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.util.*;
022import java.util.function.*;
023import java.util.regex.*;
024import java.util.stream.*;
025
026import org.apache.juneau.commons.http.*;
027import org.apache.juneau.marshall.collections.*;
028import org.apache.juneau.rest.server.*;
029import org.apache.juneau.console.*;
030import org.apache.juneau.rest.server.view.freemarker.*;
031import org.apache.juneau.console.views.*;
032
033import freemarker.template.*;
034
035/**
036 * Java description of one console page: the active tab, toolkits, page CSS and init scripts, per-request header
037 * fields, the stock theme by name, and the page's cards (tables, html and registered custom types) and body attributes.
038 *
039 * <p>
040 * A {@code PageSpec} renders nothing itself.  Its values are seeded into the request's {@link PageCapture} before any
041 * directive runs, so a built page goes through the same {@code <@console>} chrome and emits the same
042 * {@code #juneau-page} contract and the same toolkit asset tags as an FTL page.  Chrome (brand, nav tree, footer, theme tokens) stays in the app's
043 * chrome template.
044 *
045 * <h2 class='section'>Example:</h2>
046 * <p class='bjava'>
047 *    <jk>var</jk> <jv>spec</jv> = PageSpec.<jsm>create</jsm>()
048 *       .title(<js>"SLO"</js>)
049 *       .tab(<js>"slo"</js>)
050 *       .toolkit(<js>"views"</js>)
051 *       .css(<js>"/css/slo.css"</js>)
052 *       .csrf(<jv>token</jv>, <js>"X-CSRF"</js>)
053 *       .html(<js>"intro"</js>, <js>"&lt;p&gt;Queue health&lt;/p&gt;"</js>)
054 *       .table(<jv>sloTable</jv>);
055 * </p>
056 *
057 * <h2 class='section'>Example:</h2>
058 * <p class='bjava'>
059 *    <jk>return</jk> PageSpec.<jsm>create</jsm>()
060 *       .tab(<js>"changes"</js>)
061 *       .table(ChangesView.<jsm>def</jsm>(), <jv>c</jv> -&gt; <jv>c</jv>.title(<js>"Changes"</js>))
062 *       .table(TasksView.<jsm>def</jsm>(), <jv>c</jv> -&gt; <jv>c</jv>.title(<js>"Tasks for the selected change"</js>)
063 *          .subscribes(Subscription.<jsm>to</jsm>(Topics.<jsm>selection</jsm>(<js>"changes"</js>)).as(<js>"params"</js>).map(<js>"changeId"</js>, <js>"ids.0"</js>)))
064 *       .card(ChartDef.<jsm>bar</jsm>(<js>"byOwner"</js>).title(<js>"Open changes by owner"</js>).src(<js>"/rest/changes/by-owner?q={q}"</js>)
065 *          .x(<js>"owner"</js>).series(<js>"open"</js>, <js>"Open"</js>).toCardSpec()
066 *          .subscribes(Subscription.<jsm>to</jsm>(Topics.<jsm>filter</jsm>(<js>"changes"</js>)).as(<js>"params"</js>).map(<js>"q"</js>, <js>"search"</js>)))
067 *       .view(<jv>req</jv>);
068 * </p>
069 *
070 * @since 10.0.0
071 */
072@SuppressWarnings({
073   "java:S1845", // Fluent-builder setters intentionally mirror field names (Juneau DSL convention)
074   "java:S3776", // Validation and rendering chains many independent guards; splitting them adds no clarity.
075   "javabugs:S2259" // False positive: each card.accept(c) is guarded by nn(card), which Sonar's flow analysis does not track as a null guard.
076})
077public final class PageSpec implements Handled<PageSpec> {
078
079   /** Data-model attribute that carries the spec into the render. */
080   public static final String ATTR = "jcPageSpec";
081
082   private static final Set<String> USER_MENU_KEYS = Set.of("label", "initials", "avatar", "items");
083   /**
084    * The three reserved types ({@code chart}, {@code job-log}, {@code terminal}) {@link #applyTo} lifts through their registered handler,
085    * with their own {@code <@card>} checks.  The other reserved types are seeded as written; adopter types are lifted
086    * through the registry too.
087    */
088   private static final Set<String> LIFTED_TYPES = Set.of("chart", "job-log", "terminal", "switcher");
089   private static final Pattern ATTR_NAME_RE = Pattern.compile("[A-Za-z_:][-A-Za-z0-9_:.]*");
090
091   /** One {@code header(String,String)} passthrough entry. */
092   record HeaderEntry(String name, String value) {}
093
094   private String template;
095   private String title;
096   private String tab;
097   String theme;
098   private String scheme;
099   private boolean schemeToggle;
100   private boolean themeSelector;
101   final List<String> toolkits = new ArrayList<>();
102   final List<String> css = new ArrayList<>();
103   final List<String> init = new ArrayList<>();
104   private final ModelBlock model = new ModelBlock("page", "page");
105   private boolean allowInlineHandlers;
106   private final List<TableSpec> tableSpecs = new ArrayList<>();
107   private boolean scriptUsed;
108   final Map<String,Object> attrs = new LinkedHashMap<>();
109   final List<HeaderEntry> headers = new ArrayList<>();
110   String headerSubtitle;
111   Map<String,Object> headerUserMenu;
112   final List<CardSpec> cards = new ArrayList<>();
113   /** Card id to inline markup; an absent key means no markup. */
114   final Map<String,String> cardMarkup = new LinkedHashMap<>();
115   /** Card id to the unwrapped datatables body of each {@link #table} card, handed to the card-type registry at seed time. */
116   final Map<String,Map<String,Object>> tableBodies = new LinkedHashMap<>();
117   final List<TopicDecl> topics = new ArrayList<>();
118   private final Map<String,Boolean> topicRetain = new LinkedHashMap<>();
119   final Map<String,BridgeDecl> bridges = new LinkedHashMap<>();
120   final Map<String,JsonMap> dataSources = new LinkedHashMap<>();
121   /** The {@code dashboard} contract object, or <jk>null</jk> (see {@link #dashboard(DashboardSpec)}). */
122   private Map<String,Object> dashboard;
123   /** Body attribute name to its HTML-attribute-escaped value; the last call for a name wins. */
124   final Map<String,String> bodyAttrs = new LinkedHashMap<>();
125   final List<PageCapture.PendingNavAdd> navUnders = new ArrayList<>();
126   final List<BadgeDef> badges = new ArrayList<>();
127   Map<String,Object> facts = Map.of();
128
129   private PageSpec() {}
130
131   /**
132    * Creates a new, empty spec.
133    *
134    * @return A new spec.
135    */
136   public static PageSpec create() {
137      return new PageSpec();
138   }
139
140   /**
141    * Sets the page template, overriding the mixin's configured chrome template.
142    *
143    * @param pageTemplateName The template name (no {@code .ftlh}).
144    * @return This object.
145    */
146   public PageSpec template(String pageTemplateName) {
147      template = pageTemplateName;
148      return this;
149   }
150
151   /**
152    * Adds a passthrough attribute, applied to the view this spec builds.
153    *
154    * @param key The attribute name.
155    * @param value The attribute value.
156    * @return This object.
157    */
158   public PageSpec attr(String key, Object value) {
159      if (ATTR.equals(key))
160         throw iaex("PageSpec.attr key '%s' is reserved for the spec itself.", key);
161      attrs.put(key, value);
162      return this;
163   }
164
165   /**
166    * Adds a passthrough HTTP response header, applied to the view this spec builds.
167    *
168    * @param name The header name.
169    * @param value The header value.
170    * @return This object.
171    */
172   public PageSpec header(String name, String value) {
173      headers.add(new HeaderEntry(name, value));
174      return this;
175   }
176
177   /**
178    * Sets the page title.  The spec always wins over {@code <@console title>}.
179    *
180    * @param v The title.
181    * @return This object.
182    */
183   public PageSpec title(String v) {
184      title = v;
185      return this;
186   }
187
188   /**
189    * Sets the {@code <@page tab>}-equivalent active-nav path.
190    *
191    * @param idPath A {@code '/'}-separated id path, e.g. {@code "home/skills/core"}.
192    * @return This object.
193    * @throws IllegalArgumentException If blank, or any segment is blank.
194    */
195   public PageSpec tab(String idPath) {
196      tab = checkIdPath("tab", idPath);
197      return this;
198   }
199
200   /**
201    * Validates a {@code '/'}-separated id path: the whole string and every segment must be non-blank.
202    *
203    * @param method The calling method's name, used in the error message.
204    * @param idPath The path to validate.
205    * @return {@code idPath}, unchanged.
206    * @throws IllegalArgumentException If blank, or any {@code '/'}-separated segment is blank.
207    */
208   static String checkIdPath(String method, String idPath) {
209      if (ib(idPath))
210         throw iaex("PageSpec %s path must be a non-empty '/'-separated id path; got '%s'.", method, idPath);
211      for (var segment : idPath.split("/", -1))
212         if (segment.isBlank())
213            throw iaex("PageSpec %s path must be a non-empty '/'-separated id path; got '%s'.", method, idPath);
214      return idPath;
215   }
216
217   /**
218    * Selects a stock theme by name.  Validated immediately via {@link ConsoleChromeMixin#stockTheme(String)}.
219    *
220    * @param stockName One of {@link ConsoleChromeMixin#BUILTIN_THEME_NAMES}.
221    * @return This object.
222    * @throws IllegalArgumentException If {@code stockName} is not a built-in stock-theme name.
223    */
224   public PageSpec theme(String stockName) {
225      ConsoleChromeMixin.stockTheme(stockName);
226      theme = stockName;
227      return this;
228   }
229
230   /**
231    * Pins the page's colour scheme.
232    *
233    * <p>
234    * {@code auto} (the default) follows the browser's {@code prefers-color-scheme}; {@code light} and {@code dark}
235    * pin the page. An explicit {@code <@console scheme="…">} on the page template wins over this value.
236    *
237    * @param name One of {@link ConsoleChromeMixin#SCHEMES}.
238    * @return This object.
239    * @throws IllegalArgumentException If {@code name} is not a known scheme.
240    */
241   public PageSpec scheme(String name) {
242      if (name == null || ! ConsoleChromeMixin.SCHEMES.contains(name))
243         throw iaex("Unknown scheme '%s'.  Schemes: %s.", name, String.join(", ", ConsoleChromeMixin.SCHEMES));
244      scheme = name;
245      return this;
246   }
247
248   /**
249    * Lets the visitor override the page's colour scheme with a stored choice.
250    *
251    * <p>
252    * An explicit {@code <@console schemeToggle="…">} on the page template wins over this value.
253    *
254    * @param value Whether the stored choice is honoured.
255    * @return This object.
256    */
257   public PageSpec schemeToggle(boolean value) {
258      schemeToggle = value;
259      return this;
260   }
261
262   /**
263    * Adds a header control that lets the visitor pick the stock theme palette, independent of the colour scheme.
264    *
265    * <p>
266    * The page's own theme stays the default; a stored pick overrides it.  An explicit
267    * {@code <@console themeSelector="…">} on the page template wins over this value.
268    *
269    * @param value Whether the theme selector is shown.
270    * @return This object.
271    */
272   public PageSpec themeSelector(boolean value) {
273      themeSelector = value;
274      return this;
275   }
276
277   /**
278    * Adds toolkit names, appending any not already present.
279    *
280    * @param names The toolkit names.
281    * @return This object.
282    */
283   public PageSpec toolkit(String...names) {
284      addAllDeduped(toolkits, names);
285      return this;
286   }
287
288   /**
289    * Adds page CSS URLs, appending any not already present.
290    *
291    * @param urls The CSS URLs.
292    * @return This object.
293    */
294   public PageSpec css(String...urls) {
295      addAllDeduped(css, urls);
296      return this;
297   }
298
299   /**
300    * Adds page init-script URLs, appending any not already present.
301    *
302    * @param urls The script URLs.
303    * @return This object.
304    * @throws IllegalArgumentException If a URL is not a same-origin path.
305    */
306   public PageSpec init(String...urls) {
307      for (var u : urls)
308         if (! SafePathTemplate.isSameOriginPath(u))
309            throw iaex("PageSpec script must be a same-origin path; got '%s'.", u);
310      addAllDeduped(init, urls);
311      return this;
312   }
313
314   /**
315    * Adds page scripts; an alias of {@link #init(String...)} with the same de-duplication.
316    *
317    * @param urls The script URLs.
318    * @return This object.
319    */
320   public PageSpec script(String...urls) {
321      scriptUsed = true;
322      return init(urls);
323   }
324
325   /**
326    * Allows inline handler references on this page.
327    *
328    * @param v Whether inline handlers are allowed; the default is <jk>false</jk>.
329    * @return This object.
330    */
331   public PageSpec allowInlineHandlers(boolean v) {
332      allowInlineHandlers = v;
333      return this;
334   }
335
336   @Override /* Handled */
337   public ModelBlock modelBlock() { return model; }
338
339   @Override /* Handled */
340   public PageSpec self() { return this; }
341
342   private static void addAllDeduped(List<String> target, String...values) {
343      for (var v : values)
344         if (! target.contains(v))
345            target.add(v);
346   }
347
348   /**
349    * Sets the header's {@code subtitle} and/or {@code userMenu}.  These are the only two header fields this builder
350    * may set; every other field belongs in the chrome template.
351    *
352    * @param c Mutates a scratch {@link PageCapture.HeaderSpec}.
353    * @return This object.
354    * @throws IllegalArgumentException If {@code c} sets any field other than {@code subtitle}/{@code userMenu}, or the
355    *    user menu has a key the page contract does not allow.
356    */
357   public PageSpec header(Consumer<PageCapture.HeaderSpec> c) {
358      var scratch = new PageCapture.HeaderSpec();
359      c.accept(scratch);
360      checkHeaderScratch(scratch);
361      if (scratch.subtitle != null)
362         headerSubtitle = scratch.subtitle;
363      if (scratch.userMenu != null)
364         for (var k : scratch.userMenu.keySet())
365            if (! USER_MENU_KEYS.contains(k))
366               throw iaex("PageSpec.header userMenu key '%s' is not allowed; allowed: label, initials, avatar, items.", k);
367      if (scratch.userMenu != null)
368         headerUserMenu = new LinkedHashMap<>(scratch.userMenu);
369      return this;
370   }
371
372   private static void checkHeaderScratch(PageCapture.HeaderSpec h) {
373      if (h.title != null)
374         throw headerFieldRejected("title");
375      if (h.logoSrc != null || h.logoHref != null || h.logoAlt != null)
376         throw headerFieldRejected("logo");
377      if (h.chrome)
378         throw headerFieldRejected("chrome");
379      if (! h.links.isEmpty())
380         throw headerFieldRejected("link");
381   }
382
383   private static IllegalArgumentException headerFieldRejected(String field) {
384      return iaex("PageSpec.header may set only subtitle and userMenu; '%s' belongs in the chrome template.", field);
385   }
386
387   /**
388    * Appends a card, enforcing unique ids across every spec-declared card.
389    *
390    * @param card The card.
391    * @return {@code card}, for fluent chaining by the caller.
392    * @throws IllegalArgumentException If a card with this id was already declared.
393    */
394   CardSpec addCard(CardSpec card) {
395      for (var c : cards)
396         if (c.id().equals(card.id()))
397            throw iaex("PageSpec card id '%s' is already declared.", card.id());
398      cards.add(card);
399      return card;
400   }
401
402   /**
403    * Adds a {@code datatables} card for {@code table}, with no title.
404    *
405    * @param table The table.  Validated and snapshotted immediately; later changes to it do not affect this page.
406    * @return This object.
407    */
408   public PageSpec table(TableSpec table) {
409      return table(table, (Consumer<CardSpec>)null);
410   }
411
412   /**
413    * Adds a {@code datatables} card for {@code table}, with a title.
414    *
415    * @param table The table.
416    * @param title The card title.
417    * @return This object.
418    */
419   public PageSpec table(TableSpec table, String title) {
420      return table(table, c -> c.title(title));
421   }
422
423   /**
424    * Adds a {@code datatables} card for {@code table}, letting {@code card} adjust the card.
425    *
426    * <p>
427    * The table's CSS class, if set, is carried onto the card wrapper before {@code card} runs, so {@code card} may
428    * override it.  The card body is produced by the card-type registry when the spec is seeded into a page.
429    *
430    * @param table The table.
431    * @param card Mutates the card.  May be <jk>null</jk>.
432    * @return This object.
433    */
434   public PageSpec table(TableSpec table, Consumer<CardSpec> card) {
435      table.validate();
436      var body = table.toCardBody();
437      var c = CardSpec.of("datatables", table.id());
438      if (nn(table.cssClass()))
439         c.cssClass(table.cssClass());
440      if (nn(card))
441         card.accept(c);
442      if (nn(c.src()) || nn(c.template()))
443         throw iaex("PageSpec.table id '%s' sets src or template; the table supplies the card's data.", table.id());
444      addCard(c);
445      tableBodies.put(table.id(), body);
446      tableSpecs.add(table);
447      return this;
448   }
449
450   /**
451    * Adds an {@code html} card whose body is {@code markup}, with no title.
452    *
453    * @param id The card id.
454    * @param markup The markup, emitted as {@code <template data-card=id>}.  Must not be <jk>null</jk>.
455    * @return This object.
456    * @throws IllegalArgumentException If {@code markup} is <jk>null</jk>.
457    */
458   public PageSpec html(String id, String markup) {
459      return html0(id, null, markup, null);
460   }
461
462   /**
463    * Adds an {@code html} card whose body is {@code markup}, with a title.
464    *
465    * @param id The card id.
466    * @param title The card title.
467    * @param markup The markup.  Must not be <jk>null</jk>.
468    * @return This object.
469    */
470   public PageSpec html(String id, String title, String markup) {
471      return html0(id, title, markup, null);
472   }
473
474   /**
475    * Adds an {@code html} card whose body is {@code markup}, letting {@code card} adjust the card (title, CSS
476    * class, and so on).  {@code card} must not also set {@code src} or {@code template}.
477    *
478    * @param id The card id.
479    * @param markup The markup.  Must not be <jk>null</jk>.
480    * @param card Mutates the card.  May be <jk>null</jk>.
481    * @return This object.
482    * @throws IllegalArgumentException If {@code markup} is <jk>null</jk>, or {@code card} sets {@code src} or {@code template}.
483    */
484   public PageSpec html(String id, String markup, Consumer<CardSpec> card) {
485      return html0(id, null, markup, card);
486   }
487
488   /**
489    * Adds an {@code html} card whose body is fetched from {@code src}, with a title, unsanitized.  See
490    * {@link #htmlSrc(String,String,String,boolean)} for the trust boundary.
491    *
492    * @param id The card id.
493    * @param title The card title.  May be <jk>null</jk> for no title.
494    * @param src The same-origin path of the HTML fragment endpoint.  Must not be blank.
495    * @return This object.
496    * @throws IllegalArgumentException If {@code src} is <jk>null</jk> or blank.
497    */
498   public PageSpec htmlSrc(String id, String title, String src) {
499      return htmlSrc(id, title, src, false);
500   }
501
502   /**
503    * Adds an {@code html} card whose body is fetched from {@code src}, with a title, optionally rebuilt through the
504    * views attribute-allowlist sanitizer.  The equivalent of {@code <@card type="html" src="..." sanitize=true>}.
505    *
506    * <h4 class='section'>Trust boundary:</h4>
507    * <p>
508    * With {@code sanitize} <jk>false</jk> the shell fetches {@code src} and inserts the returned HTML as-is through a
509    * raw HTML-sink assignment, <b>unsanitized</b>, the same trust level as {@code footer.text} (see
510    * {@code HtmlCardType}).  The endpoint must therefore be a trusted first-party route, must never be derived from
511    * request data, and must escape any data it embeds in the fragment.  {@code src} must be a same-origin path; an
512    * absolute URL, a scheme, {@code //}, {@code ..} or a backslash is refused when the page is built, exactly as for
513    * every other card.
514    *
515    * <p>
516    * With {@code sanitize} <jk>true</jk> the fragment is rebuilt through the views attribute-allowlist sanitizer
517    * instead: script, {@code on*} handlers, {@code javascript:} and {@code data:} URLs and every attribute off the
518    * allowlist are dropped, and benign markup (text, tables, links, images) survives.  It needs the views toolkit on
519    * the page; without the toolkit nothing is painted (the shell fails closed rather than inserting the fragment
520    * unsanitized).  The sanitizer does not remove the need to escape any data you embed in the fragment.  Turn it on when the fragment's content is not fully under your control (it embeds user-supplied or
521    * third-party markup, or comes from an endpoint you do not own); leave it off for a fragment that needs
522    * {@code class}, {@code id}, {@code style}, forms, SVG or iframes, which the allowlist drops.  The default stays off.
523    *
524    * @param id The card id.
525    * @param title The card title.  May be <jk>null</jk> for no title.
526    * @param src The same-origin path of the HTML fragment endpoint.  Must not be blank.
527    * @param sanitize Whether to rebuild the fetched fragment through the sanitizer.
528    * @return This object.
529    * @throws IllegalArgumentException If {@code src} is <jk>null</jk> or blank.
530    */
531   public PageSpec htmlSrc(String id, String title, String src, boolean sanitize) {
532      if (ib(src))
533         throw iaex("PageSpec.htmlSrc id '%s' requires a non-blank src.", id);
534      var c = CardSpec.html(id).src(src).sanitize(sanitize);
535      if (nn(title))
536         c.title(title);
537      addCard(c);
538      return this;
539   }
540
541   private PageSpec html0(String id, String title, String markup, Consumer<CardSpec> card) {
542      if (markup == null)
543         throw iaex("PageSpec.html id '%s' requires a non-null markup.", id);
544      var c = CardSpec.html(id);
545      if (nn(title))
546         c.title(title);
547      if (nn(card)) {
548         card.accept(c);
549         if (nn(c.src()) || nn(c.template()))
550            throw iaex("PageSpec.html id '%s' sets a markup body; its Consumer<CardSpec> must not also set src or template.", id);
551      }
552      addCard(c);
553      cardMarkup.put(id, markup);
554      return this;
555   }
556
557   /**
558    * Adds a custom-type card with no inline markup.
559    *
560    * <p>
561    * When the page renders, a card of an adopter type (any type that is not reserved) is built as
562    * {@code <@card>} builds it: its body map is the authored body, the type's registered {@link CardTypeHandler}
563    * validates it and returns the fragment the card carries, and an invalid body fails the render with the
564    * {@code <@card>} message.  An unregistered type takes the generic passthrough, so its body map is carried as-is.
565    *
566    * @param card The card.  Its type must not be a removed type or one with a dedicated method.
567    * @return This object.
568    */
569   public PageSpec card(CardSpec card) {
570      return card(card, null);
571   }
572
573   /**
574    * Adds a custom-type card that also takes inline markup.
575    *
576    * @param card The card.  See {@link #card(CardSpec)}.
577    * @param markupOrNull The markup, or <jk>null</jk>.  For an adopter type it is the card's body, as the content of
578    *    {@code <@card>} is: the handler parses it (JSON5) or captures it as {@code <template data-card=card.id()>}, and
579    *    {@code subscribes} / {@code publishes} keys in JSON5 markup are wired onto the card.  A card takes at most one of a
580    *    body map, non-blank markup, {@code template} or {@code src}.
581    * @return This object.
582    */
583   public PageSpec card(CardSpec card, String markupOrNull) {
584      checkCardType(card);
585      addCard(card);
586      if (nn(markupOrNull))
587         cardMarkup.put(card.id(), markupOrNull);
588      return this;
589   }
590
591   /**
592    * Adds the page's dashboard: a rail of filter sections beside a grid of card panels.
593    *
594    * <p>
595    * The panel and card-section cards built by the dashboard are added to this page as ordinary cards, and the
596    * {@code dashboard} toolkit pack is added (just before {@code charts} when that is listed).  A by-id panel
597    * ({@code panel("notes")}) must name a card added <i>before</i> this call, for example with {@link #html(String, String)}.
598    * </p>
599    *
600    * @param dashboard The dashboard.
601    * @return This object.
602    * @throws IllegalArgumentException E-77 on any dashboard problem, or if the page already has a dashboard.
603    */
604   public PageSpec dashboard(DashboardSpec dashboard) {
605      if (dashboard == null)
606         throw iaex("PageSpec.dashboard requires a dashboard.");
607      if (this.dashboard != null)
608         throw Section.e77(dashboard.id(), "a page has at most one dashboard");
609      var byId = new LinkedHashMap<String,CardSpec>();
610      for (var c : cards)
611         byId.put(c.id(), c);
612      var json = dashboard.toJson(byId);
613      for (var c : dashboard.ownedCards())
614         card(c);
615      var pack = ToolkitPackRegistry.PACK_DASHBOARD;
616      if (! toolkits.contains(pack)) {
617         var charts = toolkits.indexOf(ToolkitPackRegistry.PACK_CHARTS);
618         if (charts >= 0)
619            toolkits.add(charts, pack);
620         else
621            toolkits.add(pack);
622      }
623      this.dashboard = json;
624      return this;
625   }
626
627   private static void checkCardType(CardSpec card) {
628      if (card == null)
629         throw iaex("PageSpec.card requires a non-null card.");
630      var type = card.type();
631      if (ib(type))
632         throw iaex("PageSpec.card id '%s' requires a non-blank type.", card.id());
633      if (CardDirectiveModel.REMOVED_TYPES.contains(type))
634         throw iaex("PageSpec.card type '%s' was removed in 10.0.0; use PageSpec.html(...) with a markup/template, or a registered card type.", type);
635      if ("html".equals(type))
636         throw iaex("PageSpec.card type '%s' has a dedicated method; use PageSpec.%s(...).", type, "html");
637      if ("datatables".equals(type))
638         throw iaex("PageSpec.card type '%s' has a dedicated method; use PageSpec.%s(...).", type, "table");
639      var registry = CardTypeRegistry.standard();
640      if (CardTypeRegistry.RESERVED.contains(type) && ! registry.isRegistered(type))
641         throw iaex("PageSpec.card type '%s' is reserved and has no card-type handler; it cannot be built with PageSpec.", type);
642   }
643
644   /**
645    * Sets the CSRF body attributes: {@code data-juneau-csrf} and, if {@code headerName} is non-blank,
646    * {@code data-juneau-csrf-header}.
647    *
648    * @param token The CSRF token value.
649    * @param headerName The CSRF header name, or <jk>null</jk>/blank to omit the header attribute.
650    * @return This object.
651    */
652   public PageSpec csrf(String token, String headerName) {
653      if (token == null)
654         throw iaex("PageSpec.csrf requires a non-null token.");
655      bodyAttrs.put("data-juneau-csrf", attrEscape(token));
656      if (nn(headerName) && ! headerName.isBlank())
657         bodyAttrs.put("data-juneau-csrf-header", attrEscape(headerName));
658      return this;
659   }
660
661   /**
662    * Sets one {@code <body>} attribute.
663    *
664    * @param name The attribute name.
665    * @param value The attribute value; {@code & < > "} are escaped.
666    * @return This object.
667    */
668   public PageSpec bodyAttr(String name, String value) {
669      if (name == null || ! ATTR_NAME_RE.matcher(name).matches())
670         throw iaex("PageSpec.bodyAttr name '%s' must match [A-Za-z_:][-A-Za-z0-9_:.]*.", name);
671      bodyAttrs.put(name, attrEscape(value));
672      return this;
673   }
674
675   private static String attrEscape(String s) {
676      return s == null ? "" : s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
677   }
678
679   /** @return The declared cards, in declaration order; a snapshot. */
680   public List<CardSpec> cards() {
681      return List.copyOf(cards);
682   }
683
684   /**
685    * Looks up a declared card by id.
686    *
687    * @param id The card id.
688    * @return The card, or empty if none was declared with this id.
689    */
690   public Optional<CardSpec> card(String id) {
691      return cards.stream().filter(c -> c.id().equals(id)).findFirst();
692   }
693
694   /**
695    * Adds a header badge.  The Java twin of {@code <@badge>}.
696    *
697    * @param def The badge.  Must not be <jk>null</jk>.
698    * @return This object.
699    * @throws IllegalArgumentException If {@link BadgeDef#validate()} rejects it.
700    */
701   public PageSpec badge(BadgeDef def) {
702      def.validate();
703      badges.add(def);
704      return this;
705   }
706
707   /**
708    * Seeds page-level facts, which {@code visibleWhen} rules test on the client.  Repeated calls merge, last wins, on
709    * this side only; the strict check against chrome-supplied facts runs once, at {@code </@console>}.
710    *
711    * @param v The facts.  Leaves must be strings, numbers, booleans, string lists or maps.
712    * @return This object.
713    * @throws IllegalArgumentException On a leaf of any other type.
714    */
715   public PageSpec facts(Map<String,Object> v) {
716      checkFactTypes("", v);
717      facts = PageCapture.mergeFactsLastWins(facts, copyFacts(v));
718      return this;
719   }
720
721   // Deep, unmodifiable copy, so a caller that later mutates its maps or lists cannot change the page.
722   private static Map<String,Object> copyFacts(Map<String,Object> m) {
723      var out = new LinkedHashMap<String,Object>();
724      for (var e : m.entrySet())
725         out.put(e.getKey(), copyFact(e.getValue()));
726      return u(out);
727   }
728
729   @SuppressWarnings({
730      "unchecked" // Narrows a JSON-shaped Map<?,?> to Map<String,Object>; its keys are always strings.
731   })
732   private static Object copyFact(Object v) {
733      if (v instanceof Map<?,?> nested)
734         return copyFacts((Map<String,Object>)nested);
735      if (v instanceof List<?> list)
736         return List.copyOf(list);
737      return v;
738   }
739
740   static void checkFactTypes(String prefix, Map<?,?> m) {
741      for (var e : m.entrySet()) {
742         var path = prefix.isEmpty() ? String.valueOf(e.getKey()) : prefix + "." + e.getKey();
743         var v = e.getValue();
744         if (v instanceof Map<?,?> nested) {
745            checkFactTypes(path, nested);
746         } else if (v instanceof List<?> list) {
747            for (var item : list)
748               if (! (item instanceof String))
749                  throw badFact(path, item);
750         } else if (! (v instanceof String || v instanceof Boolean || isPlainNumber(v))) {
751            throw badFact(path, v);
752         }
753      }
754   }
755
756   private static boolean isPlainNumber(Object v) {
757      return v instanceof Integer || v instanceof Long || v instanceof Short || v instanceof Byte || v instanceof Float
758         || v instanceof Double || v instanceof java.math.BigInteger || v instanceof java.math.BigDecimal;
759   }
760
761   private static IllegalArgumentException badFact(String path, Object v) {
762      return iaex("Fact '%s' has unsupported value type '%s'; use string, number, boolean, string list or map.",
763         path, v == null ? "null" : v.getClass().getSimpleName());
764   }
765
766   /**
767    * Java twin of the {@code </@console>} card-reference check, run early when this spec's own card set is final.  The
768    * nav-node check needs the resolved chrome, so it only runs at {@code </@console>}.
769    */
770   private void checkBadgesAgainstOwnCards() {
771      var cardIds = cards.stream().map(CardSpec::id).collect(Collectors.toSet());
772      for (var b : badges) {
773         var m = b.toContractMap();
774         for (var card : PageCapture.badgeCardRefs(m))
775            if (! cardIds.contains(card))
776               throw isex(PageCapture.BADGE_CARD_MSG, m.get("id"), card);
777      }
778   }
779
780   /**
781    * Queues a child to add under an existing chrome nav node, resolved once the chrome's own nav tree exists.
782    *
783    * <p>
784    * The Java twin of {@code <@node under="...">}.
785    *
786    * @param parentIdPath A {@code '/'}-separated id path to the existing ancestor node.
787    * @param adder Receives the resolved ancestor and adds its children to it.
788    * @return This object.
789    * @throws IllegalArgumentException If the path is blank, or any {@code '/'}-separated segment is blank.
790    */
791   public PageSpec navUnder(String parentIdPath, PageCapture.NavAdder adder) {
792      navUnders.add(new PageCapture.PendingNavAdd(checkIdPath("navUnder", parentIdPath), adder));
793      return this;
794   }
795
796   /**
797    * Declares a page-level custom topic; repeatable.  Unions with FTL {@code <@topic>}.
798    *
799    * @param decl The declaration; needs {@code retain} and {@code publisher}.
800    * @return This object.
801    * @throws IllegalArgumentException E-46 if the topic is already declared with a different {@code retain} or {@code publisher}.
802    */
803   public PageSpec topic(TopicDecl decl) {
804      var m = decl.toMap();
805      var retain = (Boolean)m.get("retain");
806      var prior = topicRetain.putIfAbsent(decl.topic(), retain);
807      if (prior != null && ! prior.equals(retain))
808         throw iaex("topic '%s' is declared with retain=%s here and retain=%s at %s", decl.topic(), retain, prior, "PageSpec.topic");
809      if (prior == null) {
810         topics.add(decl);
811      } else {
812         var priorPub = topics.stream().filter(t -> t.topic().equals(decl.topic())).findFirst().get().toMap().get("publisher");
813         if (! priorPub.equals(m.get("publisher")))
814            throw iaex("topic '%s' is declared with publisher=%s here and publisher=%s at %s", decl.topic(), m.get("publisher"), priorPub, "PageSpec.topic");
815      }
816      return this;
817   }
818
819   /**
820    * Declares a server bridge; repeatable.  Unions with FTL {@code <@bridge>}.
821    *
822    * @param decl The bridge.
823    * @return This object.
824    * @throws IllegalArgumentException E-51 on a duplicate id, or from {@link BridgeDecl#toMap()}.
825    */
826   public PageSpec bridge(BridgeDecl decl) {
827      decl.toMap();   // fail at the call site, not at render
828      if (bridges.putIfAbsent(decl.id(), decl) != null)
829         throw iaex("bridge '%s': %s", decl.id(), "duplicate id");
830      return this;
831   }
832
833   /**
834    * Declares a data source, published on {@code data:<id>}; repeatable.
835    *
836    * @param def The source.
837    * @return This object.
838    * @throws IllegalArgumentException E-76 on a duplicate id or a bad declaration; also on a null definition.
839    */
840   public PageSpec data(DataSourceDef def) {
841      if (def == null)
842         throw iaex("PageSpec.data requires a non-null definition.");
843      return addData(def.toMap());   // fail at the call site, not at render
844   }
845
846   /**
847    * Declares a derived data source, published on {@code data:<as>}; repeatable.
848    *
849    * @param def The derived source.
850    * @return This object.
851    * @throws IllegalArgumentException E-76 on a duplicate id or a bad declaration; also on a null definition.
852    * @throws IllegalStateException If {@link Derived#as(String)} was not called.
853    */
854   public PageSpec data(Derived def) {
855      if (def == null)
856         throw iaex("PageSpec.data requires a non-null definition.");
857      return addData(def.toMap());
858   }
859
860   private PageSpec addData(JsonMap m) {
861      var id = (String)m.get("id");
862      if (dataSources.putIfAbsent(id, m) != null)
863         throw iaex(DataSourceDef.E76, id, "duplicate id");
864      return this;
865   }
866
867   /** @return The template name, or <jk>null</jk> if unset (the mixin's chrome template applies). */
868   public String template() {
869      return template;
870   }
871
872   /** @return The tab path, or {@code ""} if unset. */
873   public String tab() {
874      return tab == null ? "" : tab;
875   }
876
877   /** @return The toolkit names, in declaration order. */
878   public List<String> toolkits() {
879      return List.copyOf(toolkits);
880   }
881
882   /**
883    * The per-render holder {@link #view(RestRequest)} puts in the data model.  It carries this spec and records
884    * whether the render adopted it, so a spec reused across requests never shares adoption state.
885    */
886   static final class Seed implements FreemarkerView.MustConsume {
887
888      private final PageSpec spec;
889      private volatile boolean consumed;
890
891      Seed(PageSpec spec) {
892         this.spec = spec;
893      }
894
895      PageSpec spec() { return spec; }
896
897      /** Applies the spec to a fresh capture and marks it adopted. */
898      void adoptInto(PageCapture cap, CardDirectiveModel cardModel) throws TemplateModelException {
899         spec.applyTo(cap, cardModel);
900         consumed = true;
901      }
902
903      void markConsumed() { consumed = true; }
904
905      @Override /* Overridden from FreemarkerView.MustConsume */
906      public boolean consumed() { return consumed; }
907
908      @Override /* Overridden from FreemarkerView.MustConsume */
909      public String notConsumedMessage(String templateName) {
910         return f("Template '%s' was rendered with a PageSpec, but the spec was never adopted; the "
911            + "template must use <@page> or include the console chrome.", templateName);
912      }
913   }
914
915   /**
916    * Builds the view for this spec.
917    *
918    * <p>
919    * The template is {@link #template(String)} when set, else the {@code ConsoleFreemarkerMixin}'s chrome template.
920    * A built spec is not modified by rendering, so it may be cached and reused across requests.  Call
921    * {@code spec.view(req)} on each request: a reused {@link FreemarkerView} would share one adoption flag.
922    *
923    * @param req The current REST request.
924    * @return A view for the template, carrying this spec and every {@link #attr(String, Object)} /
925    *    {@link #header(String, String)} passthrough.
926    * @throws IllegalStateException If no template was set and the request has no {@code ConsoleFreemarkerMixin} bean.
927    * @throws IllegalArgumentException If this spec has no page template and its bus wiring fails R-10 / R-11.
928    */
929   public FreemarkerView view(RestRequest req) {
930      if (req == null)
931         throw iaex("PageSpec.view requires a non-null request.");
932      String templateName;
933      if (template != null) {
934         templateName = template;
935      } else {
936         var ccm = resolveConsoleMixin(req);
937         checkWiringEarly(ccm.cardTypes(), req);
938         checkBadgesAgainstOwnCards();
939         templateName = ccm.chromeTemplate();
940      }
941      var v = FreemarkerView.of(templateName).attr(ATTR, new Seed(this));
942      for (var h : headers)
943         v = v.header(h.name(), h.value());
944      for (var e : attrs.entrySet())
945         v = v.attr(e.getKey(), e.getValue());
946      return v;
947   }
948
949   // The exact-type-else-registered-subtype lookup the renderer runs, without its two-beans ambiguity check (the
950   // renderer still reports that itself at render time).
951   @SuppressWarnings({
952      "resource" // The request context owns its bean store.
953   })
954   private static ConsoleFreemarkerMixin resolveConsoleMixin(RestRequest req) {
955      var store = req.getContext().getBeanStore();
956      FreemarkerMixin found = store.getBean(FreemarkerMixin.class).orElse(null);
957      if (found == null)
958         for (var t : FreemarkerMixin.registeredSubtypes()) {
959            var b = store.getBean(t).orElse(null);
960            if (b != null) {
961               found = b;
962               break;
963            }
964         }
965      if (! (found instanceof ConsoleFreemarkerMixin ccm))
966         throw isex("PageSpec.view needs a ConsoleFreemarkerMixin bean; found '%s'.",
967            found == null ? "none" : found.getClass().getSimpleName());
968      return ccm;
969   }
970
971   /**
972    * Applies every field this spec has set to {@code cap}, via {@code cap}'s plain (non-merge-aware) setters.
973    *
974    * <p>
975    * Called once per render, on a freshly created capture before any directive has written to it, so these raw
976    * writes can never conflict with anything.  This spec is not modified: each card is copied before it is seeded.
977    * A table card, a chart, job-log or terminal card, and a card of any adopter (non-reserved) type are lifted through the
978    * card-type registry of {@code cardModel}, with the {@code <@card>} checks and messages.  Every card's required packs are recorded through {@code cardModel}.
979    *
980    * @param cap The freshly created, still-empty capture.
981    * @param cardModel The shared {@code <@card>} directive; may be <jk>null</jk> only when this spec has no cards.
982    * @throws TemplateModelException If a card is rejected.
983    */
984   void applyTo(PageCapture cap, CardDirectiveModel cardModel) throws TemplateModelException {
985      if (title != null)
986         cap.title(title);
987      if (tab != null)
988         cap.tab(tab);
989      if (theme != null)
990         cap.theme(theme);
991      if (scheme != null)
992         cap.scheme(scheme);
993      if (schemeToggle)
994         cap.schemeToggle(true);
995      if (themeSelector)
996         cap.themeSelector(true);
997      if (! toolkits.isEmpty())
998         cap.toolkit(toolkits);
999      if (! css.isEmpty())
1000         cap.css(css);
1001      if (! init.isEmpty())
1002         cap.init(init);
1003      if (! allowInlineHandlers && (model.hasInline() || tableSpecs.stream().anyMatch(TableSpec::hasInlineHandlers) || cards.stream().anyMatch(c -> c.modelBlock().hasInline())))
1004         throw new IllegalArgumentException("page: an inline handler needs allowInlineHandlers(true).");
1005      if (allowInlineHandlers)
1006         cap.allowInlineHandlers(true);
1007      cap.rootModel(model.toMap());
1008      if (scriptUsed)
1009         cap.emitScripts(true);
1010      if (headerSubtitle != null || headerUserMenu != null)
1011         cap.header(h -> {
1012            if (headerSubtitle != null)
1013               h.subtitle(headerSubtitle);
1014            if (headerUserMenu != null)
1015               h.userMenu(headerUserMenu);
1016         });
1017      if (! cards.isEmpty() && n(cardModel))
1018         throw FtlAttrLists.reject("PageSpec cards need the console card directive; the render has no ConsoleFreemarkerMixin.");
1019      for (var card : cards) {
1020         var markup = cardMarkup.get(card.id());
1021         Built built;
1022         if (tableBodies.containsKey(card.id()))
1023            built = new Built(liftTable(card, cardModel), markup);
1024         else if (LIFTED_TYPES.contains(card.type()))
1025            built = new Built(liftChecked(card, cardModel), markup);
1026         else if (CardTypeRegistry.RESERVED.contains(card.type()))
1027            built = new Built(card.copy(), markup);
1028         else
1029            built = liftCustom(card, markup, cardModel);
1030         cap.addBuiltCard(built.card(), built.markupOrNull());
1031         cardModel.recordRequirements(cap, built.card().type(), built.card().id(), List.of(), built.card().bodyMap());
1032      }
1033      try {
1034         for (var t : topics)
1035            cap.addTopic(t.toMap(), "PageSpec.topic");
1036         var req = FreemarkerRenderScope.request();
1037         for (var b : bridges.values()) {
1038            cap.addBridge(resolvedBridge(b, req));
1039         }
1040         for (var d : dataSources.values())
1041            cap.addDataSource(new JsonMap(d));
1042         if (! dataSources.isEmpty())
1043            cap.require(List.of(ToolkitPackRegistry.PACK_DATA));
1044      } catch (IllegalArgumentException e) {
1045         throw FtlAttrLists.reject(e.getMessage());
1046      }
1047      if (! bodyAttrs.isEmpty()) {
1048         var sb = new StringBuilder();
1049         for (var e : bodyAttrs.entrySet())
1050            sb.append(e.getKey()).append("=\"").append(e.getValue()).append("\" ");
1051         cap.bodyAttrs = sb.toString().stripTrailing();
1052      }
1053      for (var p : navUnders)
1054         cap.addPendingNavUnder(p.parentIdPath(), p.adder());
1055      for (var b : badges)
1056         cap.addBadge(b);
1057      if (dashboard != null)
1058         cap.dashboard(dashboard);
1059      if (! facts.isEmpty())
1060         cap.seedJavaFacts(facts);
1061   }
1062
1063   /** A card ready for {@link PageCapture#addBuiltCard}, with the markup it emits as its template, or <jk>null</jk>. */
1064   private record Built(CardSpec card, String markupOrNull) {}
1065
1066   // sanitize= is refused before any other check, as <@card> refuses it: only an html card with src= takes it.
1067   private static void checkSanitize(CardSpec card) throws TemplateModelException {
1068      if (card.sanitize())
1069         throw FtlAttrLists.reject(f("<@card id='%s'> sanitize= applies only to an html card with src=.", card.id()));
1070   }
1071
1072   private CardSpec liftTable(CardSpec card, CardDirectiveModel cardModel) throws TemplateModelException {
1073      checkSanitize(card);
1074      return liftVia(card, CardSource.create(card.type(), card.id()).bodyMap(tableBodies.get(card.id())), cardModel);
1075   }
1076
1077   private static CardSpec liftChecked(CardSpec card, CardDirectiveModel cardModel) throws TemplateModelException {
1078      checkSanitize(card);
1079      if (eq(card.type(), "terminal"))
1080         return liftTerminal(card, cardModel);
1081      if (eq(card.type(), "job-log") || eq(card.type(), "switcher"))
1082         rejectSrcAndTemplate(card);
1083      else if (nn(card.template()))
1084         throw FtlAttrLists.reject(f("<@card id='%s'> type='chart' takes a JSON5 body (plus src= for remote data); template= is not allowed.", card.id()));
1085      var source = CardSource.create(card.type(), card.id()).bodyMap(card.bodyMap());
1086      if (nn(card.src()))
1087         source.src(card.src());
1088      return liftVia(card, source, cardModel);
1089   }
1090
1091   /** Rejects {@code src=} and/or {@code template=} on a card whose options are its body, with the directive's message. */
1092   private static void rejectSrcAndTemplate(CardSpec card) throws TemplateModelException {
1093      var src = nn(card.src()) ? card.src() : "";
1094      var template = nn(card.template()) ? card.template() : "";
1095      if (! (src.isEmpty() && template.isEmpty()))
1096         throw FtlAttrLists.reject(f("<@card id='%s'> type='%s' takes its options as the body; %s.", card.id(), card.type(),
1097            CardDirectiveModel.notAllowed(src, template)));
1098   }
1099
1100   /**
1101    * A terminal card: its body map is the {@code {contractVersion: '1', terminal: {...}}} envelope {@code <@card>} takes,
1102    * with {@code contractVersion} implied, so the registered handler validates it exactly as it does for the directive.
1103    */
1104   private static CardSpec liftTerminal(CardSpec card, CardDirectiveModel cardModel) throws TemplateModelException {
1105      rejectSrcAndTemplate(card);
1106      var envelope = new LinkedHashMap<String,Object>();
1107      envelope.put("contractVersion", "1");
1108      envelope.putAll(card.bodyMap());
1109      return liftVia(card, CardSource.create(card.type(), card.id()).bodyMap(envelope), cardModel);
1110   }
1111
1112   /**
1113    * An adopter card type: the same checks {@code <@card>} runs, then its registered handler (or the generic
1114    * passthrough for an unregistered type) builds the fragment from the card's body map, or from its non-blank markup
1115    * when it has no body map.  The markup is emitted as the card's template only when the handler captures it, as
1116    * {@code <@card>} emits it; JSON5 markup a handler parses is the body, not a template.
1117    */
1118   private static Built liftCustom(CardSpec card, String markupOrNull, CardDirectiveModel cardModel) throws TemplateModelException {
1119      checkSanitize(card);
1120      var body = card.bodyMap();
1121      var hasMarkup = nn(markupOrNull) && ! markupOrNull.isBlank();
1122      if ((body.isEmpty() ? 0 : 1) + (hasMarkup ? 1 : 0) + (nn(card.src()) ? 1 : 0) + (nn(card.template()) ? 1 : 0) > 1)
1123         throw FtlAttrLists.reject(f("<@card id='%s'> type='%s' takes at most one of a body, template= or src=.", card.id(), card.type()));
1124      var captured = new boolean[1];
1125      var source = CardSource.create(card.type(), card.id()).templateSink((id, markup) -> captured[0] = true);
1126      if (nn(card.src()))
1127         source.src(card.src());
1128      if (nn(card.template()))
1129         source.template(card.template());
1130      if (! body.isEmpty())
1131         source.bodyMap(body);
1132      else if (hasMarkup)
1133         source.body(markupOrNull);
1134      var lifted = liftVia(card, source, cardModel);
1135      return new Built(lifted, captured[0] ? markupOrNull : null);
1136   }
1137
1138   private static CardSpec liftVia(CardSpec card, CardSource.Builder source, CardDirectiveModel cardModel) throws TemplateModelException {
1139      if (nn(card.title()))
1140         source.title(card.title());
1141      var lifted = cardModel.lift(source.build(), card);
1142      if (nn(card.cssClass()))
1143         lifted.cssClass(card.cssClass());
1144      if (card.bare())
1145         lifted.bare(true);
1146      return lifted;
1147   }
1148
1149   static Map<String,Object> resolvedBridge(BridgeDecl b, RestRequest req) {
1150      var m = b.toMap();
1151      var session = (String)m.get("session");
1152      if (nn(req))
1153         m.put("session", req.getUriResolver().resolve(session));
1154      else if (! session.startsWith("/"))
1155         throw iaex("BridgeDecl '%s' session '%s' needs a request to resolve.", b.id(), session);
1156      return m;
1157   }
1158
1159   /**
1160    * R-10 / R-11 over this spec alone, when it has no page template.  With a page template the FTL may add
1161    * publishers or cards, so R-10 waits for {@code </@console>}.
1162    *
1163    * @param registry The console mixin's card-type registry.
1164    * @param req The current request, used to resolve {@code servlet:} / {@code context:} bridge sessions; may be <jk>null</jk>
1165    *    only when no bridge uses one.
1166    * @throws IllegalArgumentException With the first wiring problem.
1167    */
1168   void checkWiringEarly(CardTypeRegistry registry, RestRequest req) {
1169      if (template != null)
1170         return;
1171      var early = new PageCapture();
1172      try {
1173         for (var c : cards) {
1174            var copy = c.copy();
1175            if (tableBodies.containsKey(c.id()))
1176               copy.body("table", tableBodies.get(c.id()));
1177            early.addCard(copy, null);
1178         }
1179      } catch (TemplateModelException e) {
1180         throw new IllegalArgumentException(e.getMessage(), e);
1181      }
1182      for (var t : topics)
1183         early.addTopic(t.toMap(), "PageSpec.topic");
1184      for (var b : bridges.values())
1185         early.addBridge(resolvedBridge(b, req));
1186      for (var d : dataSources.values())
1187         early.addDataSource(new JsonMap(d));
1188      if (dashboard != null)
1189         early.dashboard(dashboard);
1190      early.checkWiring(registry);
1191   }
1192}