001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.console.freemarker;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.io.*;
022import java.util.*;
023import java.util.regex.*;
024
025import org.apache.juneau.marshall.collections.*;
026import org.apache.juneau.marshall.json5.*;
027import org.apache.juneau.console.*;
028import org.apache.juneau.console.views.*;
029
030import freemarker.core.*;
031import freemarker.template.*;
032import freemarker.template.utility.*;
033
034/**
035 * The {@code <@card>} FreeMarker directive: adds one entry to the page contract's {@code cards[]}.
036 *
037 * <p>
038 * {@code html} (the default) and {@code terminal-view} are built in. {@code datatables}, {@code terminal} and every other
039 * well-formed type name is dispatched through the host's {@link CardTypeRegistry}: a registered
040 * {@link CardTypeHandler} validates it, and an unregistered type falls back to the generic passthrough. Every type other
041 * than {@code html} requires {@code id=}.
042 *
043 * <p>
044 * {@code type="html"} (the default) takes exactly one content source: a body (emitted as
045 * {@code <template data-card="{id}">}), {@code template=} (reuses another card's template), or {@code src=} (fetched
046 * same-origin by the shell). {@code type="datatables"} takes {@code src=} or a JSON5 catalog body and becomes the C1
047 * bridge card. {@code type="terminal-view"} takes a JSON5
048 * {@code {contractVersion: '1', terminalView: {...}}} body and becomes the terminal-view bridge card (see {@link TerminalViewDef}).
049 * {@code type="terminal"} takes a JSON5 {@code {contractVersion: '1', terminal: {...}}} body and becomes the terminal
050 * card (see {@code TerminalDef}). A card without {@code id=} gets {@code jc-card-N}. {@code <@card>} is only valid inside
051 * {@code <@page>}; markup around it becomes {@code jc-seg-N} segments, so the authored order is kept.
052 *
053 * <h2 class='section'>Example:</h2>
054 * <p class='bcode'>
055 *    &lt;@page tab="releases"&gt;
056 *      &lt;@card id="intro" title="Releases"&gt;&lt;p&gt;All releases.&lt;/p&gt;&lt;/@card&gt;
057 *      &lt;@card type="datatables" id="releases"&gt;
058 *        { dataUrl: '/rest/releases/data', columns: [ { key: 'name', label: 'Name' } ] }
059 *      &lt;/@card&gt;
060 *    &lt;/@page&gt;
061 * </p>
062 *
063 * @since 10.0.0
064 */
065@SuppressWarnings({
066   "java:S1192", // Duplicated literals read more clearly inline than as constants
067   "java:S3776" // Validation and rendering chains many independent guards; splitting them adds no clarity.
068})
069public final class CardDirectiveModel implements TemplateDirectiveModel {
070
071   /** The shared-variable name this directive registers under. */
072   public static final String NAME = "card";
073
074   static final Set<String> ATTRS = Set.of("type", "id", "title", "src", "template", "requires", "class", "ref", "subscribes", "publishes", "sanitize", "style", "dataTab");
075
076   static final Set<String> REMOVED_TYPES = Set.of("js", "json", "calendar");
077
078   private static final Pattern CLASS_TOKEN_RE = Pattern.compile("^[A-Za-z_-][A-Za-z0-9_-]*$");
079
080   private static final Pattern TYPE_RE = Pattern.compile("^[a-z][a-z0-9-]{0,31}$");
081
082   /** Contract base keys copied onto {@link CardSpec}'s own setters rather than {@link CardSpec#body}. */
083   private static final Set<String> BASE_KEYS = Set.of("id", "type", "title", "src", "template");
084
085   private final CardRequirements requirements;
086   private final CardTypeRegistry cardTypes;
087
088   CardDirectiveModel(CardRequirements requirements, CardTypeRegistry cardTypes) {
089      this.requirements = requirements;
090      this.cardTypes = cardTypes;
091   }
092
093   @Override
094   @SuppressWarnings({
095      "unchecked" // FreeMarker's raw params Map is String-keyed by contract.
096   })
097   public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
098         TemplateDirectiveBody body) throws TemplateException, IOException {
099      Map<String, TemplateModel> p = params;
100      if (p.containsKey("format"))
101         throw FtlAttrLists.reject("<@card> uses type= only; format= is not a valid attribute.");
102      FtlAttrLists.rejectUnknown(p, NAME, ATTRS);
103
104      if (p.containsKey("ref")) {
105         placeByRef(env, p, FtlAttrLists.scalar(p, "ref"), body);
106         return;
107      }
108
109      var type = FtlAttrLists.scalar(p, "type");
110      var authoredId = FtlAttrLists.scalar(p, "id");
111      var requires = FtlAttrLists.list(p, NAME, "requires");
112      var cssClass = cssClass(p, authoredId);
113      var sanitize = FtlAttrLists.strictBoolean(p, NAME, "sanitize", false);
114      var subsAttr = p.containsKey("subscribes") ? DeepUnwrap.unwrap(p.get("subscribes")) : null;
115      var pubsAttr = p.containsKey("publishes") ? DeepUnwrap.unwrap(p.get("publishes")) : null;
116      if ((subsAttr != null || pubsAttr != null) && authoredId.isEmpty())
117         throw FtlAttrLists.reject("<@card> with subscribes= or publishes= needs id=.");
118      if (REMOVED_TYPES.contains(type))
119         throw FtlAttrLists.reject(f(
120            "<@card id='%s'> type='%s' was removed in 10.0.0; use type='html' with a <template>, or a registered card type.",
121            authoredId, type));
122      if (! type.isEmpty() && ! TYPE_RE.matcher(type).matches())
123         throw FtlAttrLists.reject(f("<@card id='%s'> type='%s' must match ^[a-z][a-z0-9-]{0,31}$.", authoredId, type));
124
125      var cap = PageCapture.get(env);
126      if (n(cap) || ! cap.pageOpen)
127         throw FtlAttrLists.reject("<@card> must be nested inside <@page>.");
128      if (cap.cardOpen)
129         throw FtlAttrLists.reject("<@card> cannot be nested inside another <@card>.");
130      if (! authoredId.isEmpty())
131         FtlAttrLists.checkId(NAME, authoredId);
132
133      // Markup before this card becomes its own segment, so it stays ahead of the card.
134      cap.flushSegment();
135
136      String markup;
137      cap.cardOpen = true;
138      try {
139         markup = PageCapture.render(body);
140      } finally {
141         cap.cardOpen = false;
142      }
143
144      var title = FtlAttrLists.scalar(p, "title");
145      var src = FtlAttrLists.scalar(p, "src");
146      var template = FtlAttrLists.scalar(p, "template");
147      var cardType = type.isEmpty() ? "html" : type;
148      if (sanitize && (neq(cardType, "html") || src.isEmpty()))
149         throw FtlAttrLists.reject(f("<@card id='%s'> sanitize= applies only to an html card with src=.", authoredId));
150      var style = FtlAttrLists.scalar(p, "style");
151      if (! style.isEmpty() && neq(cardType, "switcher"))
152         throw FtlAttrLists.reject(f("<@card id='%s'> style= applies only to type=\"switcher\".", authoredId));
153      var dataTab = p.containsKey("dataTab") ? FtlAttrLists.strictBoolean(p, NAME, "dataTab", false) : null;
154      if (nn(dataTab) && neq(cardType, "chart"))
155         throw FtlAttrLists.reject(f("<@card id='%s'> dataTab= applies only to type=\"chart\".", authoredId));
156      var id = authoredId.isEmpty() && eq(cardType, "html") ? cap.nextCardId() : authoredId;
157      Map<String,Object> cardBody = Map.of();
158      if (eq(cardType, "terminal-view"))
159         terminalViewCard(cap, id, title, src, template, markup, cssClass, pubsAttr, subsAttr);
160      else if (eq(cardType, "html"))
161         htmlCard(cap, id, title, src, template, markup, cssClass, sanitize, pubsAttr, subsAttr);
162      else
163         cardBody = registryCard(cap, cardType, id, title, src, template, markup, cssClass, style, dataTab, pubsAttr, subsAttr).bodyMap();
164      recordRequirements(cap, cardType, id, requires, cardBody);
165   }
166
167   /**
168    * {@code <@card ref="id"/>}: places a PageSpec-built card at this point in the card order.  Present-but-empty
169    * {@code ref=} takes this path too and fails as an unknown card.  Guards run in order: another attribute (E-B7),
170    * then page and nesting, then a non-blank body (E-B7), then the placement checks (E-B5, E-B6).
171    */
172   private static void placeByRef(Environment env, Map<String, TemplateModel> p, String ref, TemplateDirectiveBody body)
173         throws TemplateException, IOException {
174      var other = firstOtherAttr(p);
175      if (other != null)
176         throw FtlAttrLists.reject(f("<@card ref='%s'> must not also set '%s' or a body.", ref, other));
177      var cap = PageCapture.get(env);
178      if (n(cap) || ! cap.pageOpen)
179         throw FtlAttrLists.reject("<@card> must be nested inside <@page>.");
180      if (cap.cardOpen)
181         throw FtlAttrLists.reject("<@card> cannot be nested inside another <@card>.");
182      String markup;
183      cap.cardOpen = true;
184      try {
185         markup = PageCapture.render(body);
186      } finally {
187         cap.cardOpen = false;
188      }
189      if (! markup.isBlank())
190         throw FtlAttrLists.reject(f("<@card ref='%s'> must not have a body.", ref));
191      cap.flushSegment();
192      cap.placeBuiltCard(ref);
193   }
194
195   private static String firstOtherAttr(Map<String, TemplateModel> p) {
196      for (var a : List.of("type", "id", "title", "src", "template", "requires", "class", "subscribes", "publishes", "sanitize", "style", "dataTab"))
197         if (p.containsKey(a))
198            return a;
199      return null;
200   }
201
202   /**
203    * Reads {@code class=}: a space-separated list of CSS class tokens, each matching
204    * {@code [A-Za-z_-][A-Za-z0-9_-]*}. Returns the tokens joined by single spaces, or {@code ""} when absent.
205    */
206   private static String cssClass(Map<String, TemplateModel> p, String authoredId) throws TemplateModelException {
207      var raw = FtlAttrLists.scalar(p, "class");
208      if (raw.isEmpty())
209         return "";
210      var tokens = raw.split("\\s+");
211      for (var t : tokens)
212         if (! CLASS_TOKEN_RE.matcher(t).matches())
213            throw FtlAttrLists.reject(f(
214               "<@card id='%s'> class='%s' must be a space-separated list of CSS class names matching [A-Za-z_-][A-Za-z0-9_-]*.",
215               authoredId, raw));
216      return String.join(" ", tokens);
217   }
218
219   // Lowers subscribes= / publishes= (attribute or JSON5 body) onto the card through the Subscription / TopicDecl builders.
220   private static void wire(CardSpec card, Object pubs, Object subs) throws TemplateModelException {
221      if (pubs == null && subs == null)
222         return;
223      try {
224         card.wiring(CardBusAttrs.publications(card.id(), pubs), CardBusAttrs.subscriptions(card.id(), subs));
225      } catch (IllegalArgumentException e) {
226         throw FtlAttrLists.reject(e.getMessage());
227      }
228   }
229
230   // The one place a card's packs are recorded; <@page> resolves them after its body.  The handler's body-aware packs
231   // (for example a datatables card whose detail region is a job-log region) are unioned in.
232   void recordRequirements(PageCapture cap, String type, String id, List<String> requires, Map<String,Object> body)
233         throws TemplateModelException {
234      try {
235         var handler = cardTypes.handler(type);
236         var bodyPacks = handler.requiredPacks(new JsonMap(body));
237         // Nested cards first: a container builds them as it renders, so their runtimes must load ahead of its own.
238         for (var nested : handler.nestedCards(new JsonMap(body)))
239            if (nested.get("type") instanceof String nt && nested.get("id") instanceof String ni)
240               recordRequirements(cap, nt, ni, List.of(), nested);
241         cap.require(requirements.forCard(type, id, requires, bodyPacks));
242      } catch (IllegalArgumentException e) {
243         throw FtlAttrLists.reject(e.getMessage());
244      }
245   }
246
247   @SuppressWarnings({
248      "java:S107" // Internal helper whose parameters are the render/validation context.
249   })
250   private static void htmlCard(PageCapture cap, String id, String title, String src, String template, String markup,
251         String cssClass, boolean sanitize, Object pubs, Object subs)
252         throws TemplateModelException {
253      var hasBody = ! markup.isBlank();
254      var sources = (hasBody ? 1 : 0) + (src.isEmpty() ? 0 : 1) + (template.isEmpty() ? 0 : 1);
255      if (sources == 0)
256         throw FtlAttrLists.reject(f("<@card id='%s'> type='html' requires a body or src=.", id));
257      if (sources > 1)
258         throw FtlAttrLists.reject(f(
259            "<@card id='%s'> type='html' takes exactly one of a body, template= or src=.", id));
260      var card = CardSpec.html(id);
261      if (! title.isEmpty())
262         card.title(title);
263      if (! src.isEmpty())
264         card.src(src);
265      if (! template.isEmpty())
266         card.template(template);
267      if (! cssClass.isEmpty())
268         card.cssClass(cssClass);
269      if (sanitize)
270         card.sanitize(true);
271      wire(card, pubs, subs);
272      cap.addCard(card, hasBody ? markup : null);
273   }
274
275   /** Names whichever of {@code src=} and {@code template=} is present. */
276   static String notAllowed(String src, String template) {
277      if (src.isEmpty())
278         return "template= is not allowed";
279      if (template.isEmpty())
280         return "src= is not allowed";
281      return "src= and template= are not allowed";
282   }
283
284   /**
285    * Every type other than {@code html} and {@code terminal-view}: validated and lifted by the host's
286    * {@link CardTypeRegistry} (a registered handler such as {@code datatables}, {@code terminal} or {@code job-log}, or the
287    * generic passthrough for an unregistered type).
288    */
289   @SuppressWarnings({
290      "java:S107" // Internal helper whose parameters are the render/validation context.
291   })
292   private CardSpec registryCard(PageCapture cap, String type, String id, String title, String src, String template,
293         String markup, String cssClass, String style, Boolean dataTab, Object pubs, Object subs) throws TemplateModelException {
294      if (id.isEmpty())
295         throw FtlAttrLists.reject(f("<@card type=\"%s\"> requires id=.", type));
296      var hasBody = ! markup.isBlank();
297      if (eq(type, "terminal") || eq(type, "job-log")) {
298         if (! (src.isEmpty() && template.isEmpty()))
299            throw FtlAttrLists.reject(f("<@card id='%s'> type='%s' takes its options as the body; %s.", id, type,
300               notAllowed(src, template)));
301      } else if (eq(type, "chart")) {
302         if (! template.isEmpty())
303            throw FtlAttrLists.reject(f(
304               "<@card id='%s'> type='chart' takes a JSON5 body (plus src= for remote data); template= is not allowed.", id));
305      } else if (eq(type, "datatables")) {
306         if (! template.isEmpty())
307            throw FtlAttrLists.reject(f(
308               "<@card id='%s'> type='datatables' takes src= or a JSON5 body; template= is not allowed.", id));
309      } else if ((hasBody ? 1 : 0) + (src.isEmpty() ? 0 : 1) + (template.isEmpty() ? 0 : 1) > 1) {
310         throw FtlAttrLists.reject(f(
311            "<@card id='%s'> type='%s' takes at most one of a body, template= or src=.", id, type));
312      }
313      var captured = new boolean[1];
314      var source = CardSource.create(type, id).templateSink((cid, m) -> captured[0] = true);
315      if (! title.isEmpty())
316         source.title(title);
317      if (! src.isEmpty())
318         source.src(src);
319      if (! template.isEmpty())
320         source.template(template);
321      if (hasBody)
322         source.body(markup);
323      JsonMap card;
324      try {
325         card = cardTypes.toCard(source.build());
326         if (! style.isEmpty()) {
327            SwitcherDef.validateStyle(id, style);
328            card.put("style", style);
329         }
330         if (nn(dataTab))
331            card.put("dataTab", dataTab);
332      } catch (IllegalArgumentException e) {
333         throw FtlAttrLists.reject(e.getMessage());
334      }
335      var bodySubs = card.remove("subscribes");
336      var bodyPubs = card.remove("publishes");
337      if (subs != null && bodySubs != null)
338         throw FtlAttrLists.reject(f("<@card id='%s'> body key 'subscribes' is reserved; set it as an attribute.", id));
339      if (pubs != null && bodyPubs != null)
340         throw FtlAttrLists.reject(f("<@card id='%s'> body key 'publishes' is reserved; set it as an attribute.", id));
341      var spec = toCardSpec(card);
342      if (! cssClass.isEmpty())
343         spec.cssClass(cssClass);
344      wire(spec, pubs != null ? pubs : bodyPubs, subs != null ? subs : bodySubs);
345      cap.addCard(spec, captured[0] ? markup : null);
346      return spec;
347   }
348
349   /**
350    * Lifts a card source through the registry into the {@link CardSpec} {@link PageCapture} wants; the same path
351    * {@code <@card>} takes for a registered type.  {@code subscribes} / {@code publishes} found in the handler's
352    * result (a JSON5 body) are wired onto the card, and refused when the authored card already declares them, as
353    * {@code <@card>} refuses them alongside the attribute.
354    *
355    * @param source The card source.
356    * @param authored The authored card whose wiring the result takes.
357    * @return The lifted card.
358    * @throws TemplateModelException If the registry or its handler rejects the source, or its wiring conflicts.
359    */
360   CardSpec lift(CardSource source, CardSpec authored) throws TemplateModelException {
361      JsonMap card;
362      try {
363         card = cardTypes.toCard(source);
364      } catch (IllegalArgumentException e) {
365         throw FtlAttrLists.reject(e.getMessage());
366      }
367      var id = source.id();
368      var bodySubs = card.remove("subscribes");
369      var bodyPubs = card.remove("publishes");
370      if (authored.hasSubscribes() && bodySubs != null)
371         throw FtlAttrLists.reject(f("<@card id='%s'> body key 'subscribes' is reserved; set it as an attribute.", id));
372      if (authored.hasPublishes() && bodyPubs != null)
373         throw FtlAttrLists.reject(f("<@card id='%s'> body key 'publishes' is reserved; set it as an attribute.", id));
374      var spec = toCardSpec(card);
375      wire(spec, bodyPubs, bodySubs);
376      return spec.wiringFrom(authored);
377   }
378
379   /** Converts the flat {@link CardTypeRegistry#toCard} result into the {@link CardSpec} {@link PageCapture} wants. */
380   private static CardSpec toCardSpec(JsonMap card) {
381      var spec = CardSpec.of((String)card.get("type"), (String)card.get("id"));
382      if (card.get("title") instanceof String v)
383         spec.title(v);
384      if (card.get("src") instanceof String v)
385         spec.src(v);
386      if (card.get("template") instanceof String v)
387         spec.template(v);
388      for (var e : card.entrySet())
389         if (! BASE_KEYS.contains(e.getKey()))
390            spec.body(e.getKey(), e.getValue());
391      return spec;
392   }
393
394   private static final Set<String> RUN_VIEW_BODY_KEYS = new LinkedHashSet<>(List.of("contractVersion", "terminalView"));
395
396   /**
397    * The terminal-view bridge: a JSON5 {@code {contractVersion: '1', terminalView: {...}}} body whose {@code terminalView} keys
398    * are exactly {@link TerminalViewDef#KEYS}, validated through {@link TerminalViewDef} so an unsafe URL fails the
399    * render. The shell mounts it through {@code JuneauViews.terminalView.mount}.
400    */
401   @SuppressWarnings({
402      "java:S107", // Internal helper whose parameters are the render/validation context.
403      "unchecked" // JSON5 object keys are always strings.
404   })
405   private static void terminalViewCard(PageCapture cap, String id, String title, String src, String template,
406         String markup, String cssClass, Object pubs, Object subs) throws TemplateModelException {
407      if (id.isEmpty())
408         throw FtlAttrLists.reject("<@card type=\"terminal-view\"> requires id=.");
409      if (! (src.isEmpty() && template.isEmpty()))
410         throw FtlAttrLists.reject(f("<@card id='%s'> type='terminal-view' takes its options as the body; %s.", id,
411            notAllowed(src, template)));
412      var trimmed = markup.trim();
413      if (! trimmed.startsWith("{"))
414         throw FtlAttrLists.reject(f(
415            "<@card id='%s'> type='terminal-view' requires a JSON5 body { contractVersion: '1', terminalView: {...} }.", id));
416      JsonMap envelope;
417      try {
418         envelope = Json5Parser.DEFAULT.read(trimmed, JsonMap.class);
419      } catch (org.apache.juneau.marshall.parser.ParseException ex) {
420         throw FtlAttrLists.reject("Card JSON5 is invalid: " + ex.getMessage());
421      }
422      var bodySubs = envelope.remove("subscribes");
423      var bodyPubs = envelope.remove("publishes");
424      if (subs != null && bodySubs != null)
425         throw FtlAttrLists.reject(f("<@card id='%s'> body key 'subscribes' is reserved; set it as an attribute.", id));
426      if (pubs != null && bodyPubs != null)
427         throw FtlAttrLists.reject(f("<@card id='%s'> body key 'publishes' is reserved; set it as an attribute.", id));
428      for (var k : envelope.keySet())
429         if (! RUN_VIEW_BODY_KEYS.contains(k))
430            throw FtlAttrLists.reject(f(
431               "<@card id='%s'> type='terminal-view' unknown key '%s'; allowed: contractVersion, terminalView, subscribes, publishes.", id, k));
432      var version = envelope.get("contractVersion");
433      if (neq("1", version))
434         throw FtlAttrLists.reject(f(
435            "<@card id='%s'> type='terminal-view' requires contractVersion: '1'; got '%s'.", id, version));
436      if (! (envelope.get("terminalView") instanceof Map<?,?> terminalView))
437         throw FtlAttrLists.reject(f("<@card id='%s'> type='terminal-view' requires a terminalView object.", id));
438      var def = TerminalViewDef.fromMap(id, (Map<String,?>)terminalView).validate();
439      var card = CardSpec.of("terminal-view", id);
440      if (! title.isEmpty())
441         card.title(title);
442      if (! cssClass.isEmpty())
443         card.cssClass(cssClass);
444      card.body("terminalView", def.toMap());
445      wire(card, pubs != null ? pubs : bodyPubs, subs != null ? subs : bodySubs);
446      cap.addCard(card, null);
447   }
448}