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.*;
020import static org.apache.juneau.console.freemarker.ToolkitPack.Kind.*;
021
022import java.util.*;
023import java.util.function.UnaryOperator;
024import java.util.logging.*;
025
026import org.apache.juneau.rest.server.*;
027import org.apache.juneau.console.*;
028import org.apache.juneau.rest.server.staticfile.*;
029import org.apache.juneau.terminal.region.*;
030import org.apache.juneau.console.views.*;
031import org.apache.juneau.console.widgets.*;
032
033/**
034 * Registry of named toolkit packs for the {@code <@page toolkit=...>} directive and for the packs cards require.
035 *
036 * <p>
037 * Built-in packs:
038 * <ul>
039 *    <li>{@code "jquery"}, {@code "datatables"} and {@code "datatables-buttons"} ({@link ToolkitPack.Kind#VENDOR}) &mdash;
040 *       WebJars, resolved through {@link #WEBJAR_RESOLVER} to the host's {@link WebJarsMixin} mount.
041 *       {@code "datatables"} depends on {@code "jquery"}; {@code "datatables-buttons"} on {@code "datatables"}.
042 *    <li>{@code "datatables-glue"} ({@link ToolkitPack.Kind#VENDOR}) &mdash; the first-party glue
043 *       ({@link ViewsMixin#DATATABLES_JS_PATH}, served by {@code DataTablesMixin}); depends on {@code "datatables"}.
044 *       Every {@code <@card type="datatables">} requires it.
045 *    <li>{@code "views"} ({@link ToolkitPack.Kind#RUNTIME}) &mdash; the views runtime.  JS order is a contract: bus (first), renders,
046 *       icons, search, pagestate, urlstate, ribbon, views, config, regions, terminal-view, helpers.
047 *       {@code juneau-urlstate.js} must precede {@code juneau-views.js} / {@code juneau-config.js}.
048 *    <li>{@code "calendar"} ({@link ToolkitPack.Kind#RUNTIME}) &mdash; the {@code juneau-calendar.*} runtime from
049 *       {@code juneau-console-widgets}, resolved through {@link #WIDGETS_RESOLVER}.
050 *    <li>{@code "xterm"} ({@link ToolkitPack.Kind#VENDOR}) &mdash; the xterm.js WebJar (library and stylesheet), resolved
051 *       through {@link #WEBJAR_RESOLVER}.
052 *    <li>{@code "terminal"} ({@link ToolkitPack.Kind#RUNTIME}) &mdash; the {@code juneau-terminal.*} runtime from
053 *       {@code juneau-terminal-region}, resolved through {@link TerminalMixin#terminalAssetUrl(RestRequest, String)};
054 *       depends on {@code "views"} and {@code "xterm"}.  Every {@code <@card type="terminal">} requires it, so a page
055 *       with a terminal card needs no {@code toolkit=}.
056 *    <li>{@code "charts"} ({@link ToolkitPack.Kind#RUNTIME}) &mdash; {@code juneau-charts.js} from
057 *       {@code juneau-console}, resolved through {@link ConsoleChromeMixin#consoleAssetUrl(RestRequest, String)};
058 *       depends on {@code "echarts"} and {@code "data"}.  Every {@code <@card type="chart">} requires it.
059 *    <li>{@code "joblog"} ({@link ToolkitPack.Kind#RUNTIME}) &mdash; {@code juneau-joblog.js} from
060 *       {@code juneau-console}; no dependencies.  Every {@code <@card type="job-log">} requires it.
061 *    <li>{@code "echarts"} ({@link ToolkitPack.Kind#VENDOR}) &mdash; the ECharts WebJar ({@link #ECHARTS_JS_ASSET}),
062 *       optional on the classpath: a missing jar is E-70 at startup when the app opts in
063 *       ({@code ConsoleFreemarkerMixin.Builder.requirePacks}), else at the first chart page.
064 *    <li>{@code "echarts-gl"} ({@link ToolkitPack.Kind#VENDOR}) &mdash; the echarts-gl WebJar; depends on {@code "echarts"};
065 *       a page opts in with {@code toolkit("echarts-gl")}.
066 *    <li>{@code "data"} ({@link ToolkitPack.Kind#RUNTIME}) &mdash; {@code juneau-data.js} ({@code JuneauViews.data}); depends on
067 *       {@code "views"}.
068 * </ul>
069 *
070 * <p>
071 * {@link #resolve(List, RestRequest, List, String)} expands the requested packs depth-first over
072 * {@link ToolkitPack#dependsOn()} (each pack after its dependencies, siblings in request order, each pack once), skips
073 * {@linkplain #provide(Collection) provided} packs (their dependencies still load), skips an asset whose file name the
074 * page already loads through {@code init=} or {@code css=} (with a WARN), and splits the result by kind.
075 * {@link #validate()} checks the static graph: unknown {@code dependsOn} names, cycles, and a VENDOR pack depending on
076 * a RUNTIME pack.
077 *
078 * @since 10.0.0
079 */
080@SuppressWarnings({
081   "java:S1192" // Repeated literals are contract wire keys; named constants would obscure the contract shape.
082})
083public final class ToolkitPackRegistry {
084
085   private static final Logger LOG = Logger.getLogger(ToolkitPackRegistry.class.getName());
086
087   /** The built-in views runtime pack. */
088   public static final String PACK_VIEWS = "views";
089
090   /**
091    * The built-in {@code "calendar"} pack: the already-shipping {@code juneau-calendar.*} runtime from
092    * {@code juneau-console-widgets}.  Never inferred from {@code type="calendar"}; a calendar page lists it
093    * explicitly (e.g. {@code toolkit="views,calendar"}).
094    */
095   public static final String PACK_CALENDAR = "calendar";
096
097   /** The built-in jQuery WebJar pack. */
098   public static final String PACK_JQUERY = "jquery";
099
100   /** The built-in DataTables WebJar pack (library plus default styling CSS). */
101   public static final String PACK_DATATABLES = "datatables";
102
103   /** The built-in pack holding the first-party DataTables glue. */
104   public static final String PACK_DATATABLES_GLUE = "datatables-glue";
105
106   /** The built-in DataTables Buttons WebJar pack (copy and CSV export, no JSZip or pdfmake). */
107   public static final String PACK_DATATABLES_BUTTONS = "datatables-buttons";
108
109   /** The built-in xterm.js WebJar pack (library plus stylesheet). */
110   public static final String PACK_XTERM = "xterm";
111
112   /** The built-in terminal runtime pack; depends on {@code "views"} and {@code "xterm"}. */
113   public static final String PACK_TERMINAL = "terminal";
114
115   /** The built-in chart-card runtime pack ({@code juneau-charts.js}); depends on {@code "echarts"} and {@code "data"}. */
116   public static final String PACK_CHARTS = "charts";
117
118   /** The built-in job-log card runtime pack ({@code juneau-joblog.js}); no dependencies. */
119   public static final String PACK_JOBLOG = "joblog";
120
121   /** Dashboard chrome ({@code PageSpec.dashboard}); added by the builder, never needed in {@code toolkit(...)}. */
122   public static final String PACK_DASHBOARD = "dashboard";
123
124   /** The switcher card runtime ({@code juneau-switcher.js}); depends on the views pack. */
125   public static final String PACK_SWITCHER = "switcher";
126
127   /** The built-in ECharts WebJar pack ({@code org.webjars.npm:echarts}, optional on the classpath). */
128   public static final String PACK_ECHARTS = "echarts";
129
130   /** The built-in echarts-gl WebJar pack; depends on {@code "echarts"}; never required by a card type. */
131   public static final String PACK_ECHARTS_GL = "echarts-gl";
132
133   /** The built-in DataRegistry runtime pack ({@code juneau-data.js}); depends on {@code "views"}. */
134   public static final String PACK_DATA = "data";
135
136   private static final String NPM = "org.webjars.npm";
137
138   /** The ECharts library asset id, for {@link #WEBJAR_RESOLVER}. */
139   public static final String ECHARTS_JS_ASSET = WebJarResolver.asset(NPM, "echarts", "echarts/{version}/dist/echarts.min.js");
140
141   /** The echarts-gl library asset id (path unverified against the WebJar; no module depends on it). */
142   public static final String ECHARTS_GL_JS_ASSET = WebJarResolver.asset(NPM, "echarts-gl", "echarts-gl/{version}/dist/echarts-gl.min.js");
143
144   static final String E70 = "chart cards need the ECharts WebJar org.webjars.npm:echarts, which is not on the classpath; add it to the application's pom (version property 'webjars-echarts.version')";
145   static final String E70_PACK = "toolkit pack '%s' needs the WebJar %s, which is not on the classpath; add it to the application's pom (version property '%s')";
146
147   // groupId:artifactId -> the version property the message names.
148   // echarts is not listed: it has its own message (E70) in webJarMissing.
149   private static final Map<String,String> WEBJAR_PROPERTIES = Map.of(
150      NPM + ":echarts-gl", "webjars-echarts-gl.version");
151
152   /** Resolves an asset path to an absolute, cache-busted URL against the in-flight request. */
153   @FunctionalInterface
154   public interface AssetUrlResolver {
155      /**
156       * @param req The in-flight request.
157       * @param path The asset path.
158       * @return The resolved, cache-busted URL.
159       */
160      String resolve(RestRequest req, String path);
161   }
162
163   /** The default resolver: {@link ViewsMixin#viewAssetUrl(RestRequest, String)}. */
164   public static final AssetUrlResolver VIEWS_RESOLVER = ViewsMixin::viewAssetUrl;
165
166   /** The {@code "calendar"} pack resolver: {@link WidgetsMixin#widgetAssetUrl(RestRequest, String)}. */
167   public static final AssetUrlResolver WIDGETS_RESOLVER = WidgetsMixin::widgetAssetUrl;
168
169   /** The WebJar resolver: paths are {@link WebJarResolver#asset(String, String, String)} ids. */
170   public static final AssetUrlResolver WEBJAR_RESOLVER = WebJarResolver::resolve;
171
172   /**
173    * Resolved absolute URLs, split by pack kind.
174    *
175    * @param vendorCss VENDOR CSS, emitted before the page {@code css=}.
176    * @param vendorJs VENDOR JS, emitted before the runtime JS.
177    * @param runtimeCss RUNTIME CSS, emitted after the page {@code css=}.
178    * @param runtimeJs RUNTIME JS, emitted before the {@code after-toolkit} slot.
179    */
180   public record Resolved(List<String> vendorCss, List<String> vendorJs, List<String> runtimeCss, List<String> runtimeJs) {
181      /** Nothing to load. */
182      public static final Resolved EMPTY = new Resolved(List.of(), List.of(), List.of(), List.of());
183   }
184
185   private final Map<String,ToolkitPack> packs = new LinkedHashMap<>();
186   private final Set<String> provided = new LinkedHashSet<>();
187
188   /** Constructs the registry with the built-in packs installed. */
189   public ToolkitPackRegistry() {
190      register(ToolkitPack.create(PACK_JQUERY).kind(VENDOR).resolver(WEBJAR_RESOLVER)
191         .js(WebJarResolver.asset("org.webjars", "jquery", "jquery/{version}/jquery.min.js"))
192         .build());
193      register(ToolkitPack.create(PACK_DATATABLES).kind(VENDOR).resolver(WEBJAR_RESOLVER)
194         .css(WebJarResolver.asset(NPM, "datatables.net-dt", "datatables.net-dt/{version}/css/dataTables.dataTables.min.css"))
195         .js(WebJarResolver.asset(NPM, "datatables.net", "datatables.net/{version}/js/dataTables.min.js"))
196         .dependsOn(PACK_JQUERY)
197         .build());
198      register(ToolkitPack.create(PACK_DATATABLES_GLUE).kind(VENDOR).resolver(VIEWS_RESOLVER)
199         .js(ViewsMixin.DATATABLES_JS_PATH)
200         .dependsOn(PACK_DATATABLES)
201         .build());
202      register(ToolkitPack.create(PACK_DATATABLES_BUTTONS).kind(VENDOR).resolver(WEBJAR_RESOLVER)
203         .css(WebJarResolver.asset(NPM, "datatables.net-buttons-dt", "datatables.net-buttons-dt/{version}/css/buttons.dataTables.min.css"))
204         .js(
205            WebJarResolver.asset(NPM, "datatables.net-buttons", "datatables.net-buttons/{version}/js/dataTables.buttons.min.js"),
206            WebJarResolver.asset(NPM, "datatables.net-buttons", "datatables.net-buttons/{version}/js/buttons.html5.min.js"))
207         .dependsOn(PACK_DATATABLES)
208         .build());
209      register(ToolkitPack.create(PACK_VIEWS).kind(RUNTIME).resolver(VIEWS_RESOLVER)
210         .css(ViewsMixin.VIEWS_CSS_PATH, ViewsMixin.CONFIG_CSS_PATH)
211         .js(
212            // Dependency-free and read by views, regions and the console shell: it must load first (E-JS-46).
213            ViewsMixin.BUS_JS_PATH,
214            ViewsMixin.MODEL_JS_PATH,
215            ViewsMixin.RENDERS_JS_PATH,
216            ViewsMixin.ICONS_JS_PATH,
217            ViewsMixin.SEARCH_JS_PATH,
218            ViewsMixin.PAGESTATE_JS_PATH,
219            ViewsMixin.URLSTATE_JS_PATH,
220            ViewsMixin.RIBBON_JS_PATH,
221            ViewsMixin.VIEWS_JS_PATH,
222            ViewsMixin.CONFIG_JS_PATH,
223            ViewsMixin.REGIONS_JS_PATH,
224            ViewsMixin.RUN_VIEW_JS_PATH,
225            ViewsMixin.HELPERS_JS_PATH)
226         .build());
227      // The "calendar" pack ships from juneau-console-widgets and resolves through that mixin's own
228      // cache-busting helper, not VIEWS_RESOLVER.  A page that wants it lists toolkit="views,calendar" so
229      // juneau-views.js still loads before juneau-calendar.js (shared layer stack).
230      register(ToolkitPack.create(PACK_CALENDAR).kind(RUNTIME).resolver(WIDGETS_RESOLVER)
231         .css(WidgetsMixin.CALENDAR_CSS_PATH)
232         .js(WidgetsMixin.CALENDAR_JS_PATH)
233         .build());
234      register(ToolkitPack.create(PACK_XTERM).kind(VENDOR).resolver(WEBJAR_RESOLVER)
235         .css(TerminalMixin.XTERM_CSS_ASSET)
236         .js(TerminalMixin.XTERM_JS_ASSET)
237         .build());
238      register(ToolkitPack.create(PACK_TERMINAL).kind(RUNTIME).resolver(TerminalMixin::terminalAssetUrl)
239         .css(TerminalMixin.CSS_PATH)
240         .js(TerminalMixin.JS_PATH)
241         .dependsOn(PACK_VIEWS, PACK_XTERM)
242         .build());
243      register(ToolkitPack.create(PACK_ECHARTS).kind(VENDOR).resolver(WEBJAR_RESOLVER)
244         .js(ECHARTS_JS_ASSET)
245         .build());
246      register(ToolkitPack.create(PACK_ECHARTS_GL).kind(VENDOR).resolver(WEBJAR_RESOLVER)
247         .js(ECHARTS_GL_JS_ASSET)
248         .dependsOn(PACK_ECHARTS)
249         .build());
250      register(ToolkitPack.create(PACK_DATA).kind(RUNTIME).resolver(VIEWS_RESOLVER)
251         .js(ViewsMixin.DATA_JS_PATH)
252         .dependsOn(PACK_VIEWS)
253         .build());
254      register(ToolkitPack.create(PACK_CHARTS).kind(RUNTIME).resolver(ConsoleChromeMixin::consoleAssetUrl)
255         .js(ConsoleChromeMixin.CHARTS_JS_PATH)
256         .dependsOn(PACK_ECHARTS, PACK_DATA)
257         .build());
258      register(ToolkitPack.create(PACK_JOBLOG).kind(RUNTIME).resolver(ConsoleChromeMixin::consoleAssetUrl)
259         .js(ConsoleChromeMixin.JOBLOG_JS_PATH)
260         .build());
261      register(ToolkitPack.create(PACK_DASHBOARD).kind(RUNTIME).resolver(ConsoleChromeMixin::consoleAssetUrl)
262         .js(ConsoleChromeMixin.DASHBOARD_JS_PATH)
263         .dependsOn(PACK_VIEWS, PACK_DATA)
264         .build());
265      register(ToolkitPack.create(PACK_SWITCHER).kind(RUNTIME).resolver(ConsoleChromeMixin::consoleAssetUrl)
266         .js(ConsoleChromeMixin.SWITCHER_JS_PATH)
267         .dependsOn(PACK_VIEWS)
268         .build());
269   }
270
271   /**
272    * Registers a pack, replacing any pack with the same name (all of its fields, including {@code dependsOn}).
273    *
274    * @param pack The pack.
275    */
276   public synchronized void register(ToolkitPack pack) {
277      packs.put(pack.name(), pack);
278   }
279
280   /**
281    * Marks packs as already loaded by the app: they contribute no URLs, but their dependencies still load.
282    *
283    * @param names The pack names.
284    * @return This object.
285    */
286   public synchronized ToolkitPackRegistry provide(Collection<String> names) {
287      provided.addAll(names);
288      return this;
289   }
290
291   /**
292    * @param name A pack name.
293    * @return <jk>true</jk> if a pack with that name is registered.
294    */
295   public synchronized boolean contains(String name) {
296      return packs.containsKey(name);
297   }
298
299   /**
300    * Checks the static graph: every {@code dependsOn} and provided name is registered, there is no cycle, and no
301    * VENDOR pack depends on a RUNTIME pack.
302    *
303    * @return This object.
304    * @throws IllegalArgumentException On the first problem found.
305    */
306   public synchronized ToolkitPackRegistry validate() {
307      for (var pack : packs.values()) {
308         for (var dep : pack.dependsOn()) {
309            var target = packs.get(dep);
310            if (n(target))
311               throw iaex("Unknown toolkit pack '%s' (dependsOn of pack '%s').", dep, pack.name());
312            if (pack.kind() == VENDOR && target.kind() == RUNTIME)
313               throw iaex("VENDOR toolkit pack '%s' cannot depend on RUNTIME pack '%s'.", pack.name(), dep);
314         }
315      }
316      for (var name : provided)
317         if (! packs.containsKey(name))
318            throw iaex("Unknown toolkit pack '%s' (providedPacks).", name);
319      expand(packs.keySet(), "registered");
320      return this;
321   }
322
323   /**
324    * Checks that every name is a registered pack.
325    *
326    * @param names The pack names.
327    * @param source Where the names came from, for the message (e.g. {@code <@page toolkit=>}).
328    * @throws IllegalArgumentException If a name is unknown.
329    */
330   public synchronized void requireKnown(Collection<String> names, String source) {
331      for (var name : names)
332         if (! packs.containsKey(name))
333            throw iaex("Unknown toolkit pack '%s' (%s).", name, source);
334   }
335
336   /**
337    * @param root A registered pack name.
338    * @param target A pack name.
339    * @return <jk>true</jk> if {@code target} is {@code root} or one of its transitive {@code dependsOn}.
340    */
341   public synchronized boolean reaches(String root, String target) {
342      return expand(List.of(root), "reaches").stream().anyMatch(p -> p.name().equals(target));
343   }
344
345   /**
346    * Probes, at startup, every WebJar the given packs reach: each non-provided VENDOR pack resolved through
347    * {@link #WEBJAR_RESOLVER}.
348    *
349    * @param roots Root pack names; empty probes nothing.
350    * @return This object.
351    * @throws IllegalStateException E-70 when a WebJar or its file is not on the classpath.
352    */
353   public ToolkitPackRegistry checkWebJars(Collection<String> roots) {
354      return checkWebJars(roots, WebJarResolver::resolvePath);
355   }
356
357   // Package-private: the probe is injectable because the echarts jar is on every test classpath.
358   synchronized ToolkitPackRegistry checkWebJars(Collection<String> roots, UnaryOperator<String> probe) {
359      for (var pack : expand(new LinkedHashSet<>(roots), "requirePacks")) {
360         if (provided.contains(pack.name()) || pack.kind() != VENDOR || pack.resolver() != WEBJAR_RESOLVER)
361            continue;
362         for (var asset : concat(pack.cssPaths(), pack.jsPaths())) {
363            try {
364               probe.apply(asset);
365            } catch (IllegalStateException e) {
366               var x = webJarMissing(pack, asset, e);
367               throw x != null ? x : new IllegalStateException("Pack '" + pack.name() + "' " + e.getMessage(), e);
368            }
369         }
370      }
371      return this;
372   }
373
374   private static List<String> concat(List<String> a, List<String> b) {
375      var out = new ArrayList<String>(a);
376      out.addAll(b);
377      return out;
378   }
379
380   // Distinguishes "jar absent" from "jar present, file missing" (the resolver's own message says which).
381   private static String causeSuffix(RuntimeException cause) {
382      return nn(cause.getMessage()) ? " [" + cause.getMessage() + "]" : "";
383   }
384
385   // E-70 for a WebJar the message table knows; null when the asset is not a known WebJar.
386   private static IllegalStateException webJarMissing(ToolkitPack pack, String asset, RuntimeException cause) {
387      var parts = asset.split(":", 3);
388      var coords = parts.length == 3 ? parts[0] + ":" + parts[1] : asset;
389      if (eq(coords, NPM + ":echarts"))
390         return new IllegalStateException("E-70: " + E70 + causeSuffix(cause), cause);
391      var prop = WEBJAR_PROPERTIES.get(coords);
392      if (prop == null)
393         return null;
394      return new IllegalStateException("E-70: " + f(E70_PACK, pack.name(), coords, prop) + causeSuffix(cause), cause);
395   }
396
397   /**
398    * Resolves the root packs and their dependencies to absolute URLs, split by kind.
399    *
400    * @param names The root pack names, in order.  Empty or <jk>null</jk> = nothing (no request needed).
401    * @param req The in-flight request.
402    * @param pageUrls The page's own {@code init=} and {@code css=} URLs; a pack asset with the same file name is
403    *    skipped with a WARN.
404    * @param template The page template name, for the WARN.
405    * @return The resolved URLs.
406    * @throws IllegalArgumentException On an unknown pack or a cycle.
407    * @throws IllegalStateException If the request is missing or a resolver fails (e.g. a WebJar isn't on the classpath).
408    */
409   public Resolved resolve(List<String> names, RestRequest req, List<String> pageUrls, String template) {
410      if (n(names) || names.isEmpty())
411         return Resolved.EMPTY;
412      if (n(req))
413         throw isex("<@page toolkit> needs FreemarkerRenderScope.request() (renderer wrap).");
414      List<ToolkitPack> order;
415      Set<String> skip;
416      synchronized (this) {
417         order = expand(new LinkedHashSet<>(names), "requested");
418         skip = Set.copyOf(provided);
419      }
420      var pageFiles = new LinkedHashMap<String,String>();
421      for (var url : pageUrls)
422         pageFiles.putIfAbsent(fileName(url), url);
423      var vendorCss = new ArrayList<String>();
424      var vendorJs = new ArrayList<String>();
425      var runtimeCss = new ArrayList<String>();
426      var runtimeJs = new ArrayList<String>();
427      for (var pack : order) {
428         if (skip.contains(pack.name()))
429            continue;
430         var vendor = pack.kind() == VENDOR;
431         addUrls(pack, pack.cssPaths(), vendor ? vendorCss : runtimeCss, req, pageFiles, template);
432         addUrls(pack, pack.jsPaths(), vendor ? vendorJs : runtimeJs, req, pageFiles, template);
433      }
434      return new Resolved(List.copyOf(vendorCss), List.copyOf(vendorJs), List.copyOf(runtimeCss), List.copyOf(runtimeJs));
435   }
436
437   /**
438    * The file name of a URL: the last path segment, without query or fragment, lower-cased.
439    *
440    * @param url The URL.
441    * @return The file name.
442    */
443   static String fileName(String url) {
444      var s = url;
445      var q = s.indexOf('?');
446      if (q >= 0)
447         s = s.substring(0, q);
448      var h = s.indexOf('#');
449      if (h >= 0)
450         s = s.substring(0, h);
451      return s.substring(s.lastIndexOf('/') + 1).toLowerCase(Locale.ROOT);
452   }
453
454   private static void addUrls(ToolkitPack pack, List<String> paths, List<String> out, RestRequest req, Map<String,String> pageFiles, String template) {
455      for (var path : paths) {
456         String url;
457         try {
458            url = pack.resolver().resolve(req, path);
459         } catch (IllegalStateException | IllegalArgumentException e) {
460            var x = e instanceof IllegalStateException ? webJarMissing(pack, path, e) : null;
461            throw x != null ? x : new IllegalStateException("Pack '" + pack.name() + "' " + e.getMessage(), e);
462         }
463         var dup = pageFiles.get(fileName(url));
464         if (nn(dup)) {
465            LOG.log(Level.WARNING, () -> f("Template '%s': skipped pack '%s' asset %s; the page already loads %s.", template, pack.name(), url, dup));
466            continue;
467         }
468         out.add(url);
469      }
470   }
471
472   // Caller holds the monitor.
473   private List<ToolkitPack> expand(Collection<String> roots, String source) {
474      var out = new LinkedHashMap<String,ToolkitPack>();
475      for (var name : roots)
476         visit(name, source, new ArrayList<>(), out);
477      return List.copyOf(out.values());
478   }
479
480   private void visit(String name, String source, List<String> path, Map<String,ToolkitPack> out) {
481      if (out.containsKey(name))
482         return;
483      var at = path.indexOf(name);
484      if (at >= 0) {
485         var cycle = tl(path.subList(at, path.size()));
486         cycle.add(name);
487         throw new IllegalArgumentException("Toolkit pack cycle: " + String.join(" → ", cycle) + ".");
488      }
489      var pack = packs.get(name);
490      if (n(pack))
491         throw iaex("Unknown toolkit pack '%s' (%s).", name, source);
492      path.add(name);
493      for (var dep : pack.dependsOn())
494         visit(dep, "dependsOn of pack '" + name + "'", path, out);
495      path.remove(path.size() - 1);
496      out.put(name, pack);
497   }
498}