@jxsuite/compiler 9.1.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,6 +32,8 @@
32
32
  */
33
33
 
34
34
  import { formatSrcset, parseSrcset, withBase } from "@jxsuite/schema/asset-paths";
35
+ import { isMappedArray, isNonNullObject, isString } from "@jxsuite/schema/guards";
36
+ import type { JxDocument, JxElement, JxMutableNode } from "@jxsuite/schema/types";
35
37
 
36
38
  /**
37
39
  * Attributes whose value is a single URL.
@@ -89,8 +91,15 @@ const URL_META_RE =
89
91
  */
90
92
  const ENTITY_QUOTE_RE = /^("|"|'|')([\s\S]*)\1$/;
91
93
 
92
- /** Rewrite every `url(...)` in a CSS fragment, in a `<style>` block or a `style` attribute. */
93
- function rewriteCssUrls(css: string, base: string): string {
94
+ /**
95
+ * Rewrite every `url(...)` in a CSS fragment: a `<style>` block, a `style` attribute, or a
96
+ * stylesheet the build writes as a file of its own.
97
+ *
98
+ * @param {string} css
99
+ * @param {string} base - From `siteBasePath`; `""` returns the text untouched
100
+ * @returns {string}
101
+ */
102
+ export function rewriteCssUrls(css: string, base: string): string {
94
103
  return css.replaceAll(CSS_URL_RE, (match, quote: string, inner: string) => {
95
104
  const raw = inner.trim();
96
105
  const escaped = ENTITY_QUOTE_RE.exec(raw);
@@ -173,3 +182,80 @@ export function rewriteHtmlBase(html: string, base: string): string {
173
182
  return rewrittenAttrs === attrs ? match : `<${tagName}${rewrittenAttrs}>`;
174
183
  });
175
184
  }
185
+
186
+ /** One element node: its `attributes`, then the element properties written beside `tagName`. */
187
+ function rebaseNode(node: JxElement | JxMutableNode, base: string): void {
188
+ const tag = isString(node.tagName) ? node.tagName.toLowerCase() : "";
189
+ const { attributes } = node;
190
+ if (isNonNullObject(attributes)) {
191
+ for (const [name, value] of Object.entries(attributes)) {
192
+ if (isString(value)) {
193
+ attributes[name] = rewriteAttrValue(tag, "", name, value, base);
194
+ }
195
+ }
196
+ }
197
+ /* An element property is written under its IDL name (`src`, `formAction`), which lowercases to
198
+ the content attribute it reflects. `style` here is a style object, never CSS text, and its
199
+ rules ship in the component's stylesheet, which is re-rooted as a file. */
200
+ for (const name of Object.keys(node)) {
201
+ const lower = name.toLowerCase();
202
+ const value = node[name];
203
+ if (isString(value) && (URL_ATTRS.has(lower) || SRCSET_ATTRS.has(lower))) {
204
+ node[name] = rewriteAttrValue(tag, "", lower, value, base);
205
+ }
206
+ }
207
+ // Markup a node carries as text is HTML like any other, optimized pictures included.
208
+ if (isString(node.innerHTML)) {
209
+ node.innerHTML = rewriteHtmlBase(node.innerHTML, base);
210
+ }
211
+ }
212
+
213
+ /** A node, then everything it can render: children, a repeater's template, `$switch` cases. */
214
+ function rebaseTree(def: JxMutableNode[string], base: string): void {
215
+ if (!isNonNullObject(def) || Array.isArray(def)) {
216
+ return;
217
+ }
218
+ if (isMappedArray(def)) {
219
+ rebaseTree(def.map, base);
220
+ return;
221
+ }
222
+ /* SAFETY: a non-array object in a document's element tree that is not a repeater is an element
223
+ node, which is all the tree holds besides strings. */
224
+ const node = def as JxMutableNode;
225
+ rebaseNode(node, base);
226
+ const { cases, children } = node;
227
+ if (Array.isArray(children)) {
228
+ for (const child of children) {
229
+ rebaseTree(child, base);
230
+ }
231
+ } else {
232
+ rebaseTree(children, base);
233
+ }
234
+ if (isNonNullObject(cases)) {
235
+ for (const caseNode of Object.values(cases)) {
236
+ rebaseTree(caseNode, base);
237
+ }
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Re-root every site-absolute URL a document's own markup writes, in place: the document-side
243
+ * counterpart of {@link rewriteHtmlBase}, for a definition compiled into a module.
244
+ *
245
+ * A component's module is JavaScript, which the HTML pass never reads, and it replaces the markup
246
+ * the page prerendered. Left alone it drew `/hero.jpg` over the prerender's `/m/site/hero.jpg`: the
247
+ * picture a visitor had already been shown 404ed the moment the element upgraded. The same
248
+ * attributes are rewritten by the same rule (`href`, `src`, `poster`, `action`, `formaction`,
249
+ * `data`, `srcset`, `imagesrcset` and `url()` in a `style` attribute), on every node the definition
250
+ * can render, so the optimizer's candidate lists are covered with the rest. A `${…}` template that
251
+ * does not open with `/`, and a value that arrives through state, are data and are left as
252
+ * written.
253
+ *
254
+ * @param {JxDocument | JxElement} doc - Mutated
255
+ * @param {string} base - From `siteBasePath`; `""` leaves the document untouched
256
+ */
257
+ export function rebaseDocument(doc: JxDocument | JxElement, base: string): void {
258
+ if (base !== "") {
259
+ rebaseTree(doc, base);
260
+ }
261
+ }
@@ -117,6 +117,8 @@ export function resolveClientRuntime(resolveDir: string = PACKAGE_DIR): ClientRu
117
117
  assetPaths.push(mod.assetPath);
118
118
  } else {
119
119
  imports[mod.specifier] = mod.fallback;
120
+ // The CDN serves the package's subpaths under the same URL, so the prefix key follows it.
121
+ imports[`${mod.specifier}/`] = `${mod.fallback}/`;
120
122
  warnings.push(
121
123
  `Could not resolve "${mod.specifier}" — the import map falls back to ${mod.fallback}. ` +
122
124
  "Interactive pages will load it from a third party, and a `default-src 'self'` policy " +
@@ -218,13 +220,8 @@ export function importMapAssetsInHtml(html: string): string[] {
218
220
  return found;
219
221
  }
220
222
 
221
- /** Render the `<script type="importmap">` block for a resolved runtime. */
222
- export function renderImportMap(imports: Record<string, string>): string {
223
- const entries = Object.entries(imports)
224
- .map(([name, url]) => ` ${JSON.stringify(name)}: ${JSON.stringify(url)}`)
225
- .join(",\n");
226
- return `<script type="importmap">\n {\n "imports": {\n${entries}\n }\n }\n </script>`;
227
- }
223
+ // The renderer lives in `shared.ts`, beside the page-template tiers that also write a map.
224
+ export { renderImportMap } from "../shared.ts";
228
225
 
229
226
  /**
230
227
  * True when a bare specifier resolves from `resolveDir` under either backend.
@@ -251,10 +248,10 @@ const MAX_SUBPATH_PASSES = 10;
251
248
  *
252
249
  * The subpath set cannot be known before the build: it is a property of whichever third-party
253
250
  * components a page happens to register. So it is discovered _from the output_ — every emitted
254
- * `.js` asset is scanned for an import of `<runtime package>/<subpath>`, each is bundled to the
255
- * directory its prefix key names, and the scan repeats over what that produced. Bundling can
256
- * introduce new subpaths (a directive importing another directive), so the pass runs to closure
257
- * rather than once.
251
+ * `.js` file (bundles, compiled component modules, page modules) is scanned for an import of
252
+ * `<runtime package>/<subpath>`, each is bundled to the directory its prefix key names, and the
253
+ * scan repeats over what that produced. Bundling can introduce new subpaths (a directive importing
254
+ * another directive), so the pass runs to closure rather than once.
258
255
  *
259
256
  * **The subpath itself must be bundled, and only the core kept external.** A package-name external
260
257
  * covers the package's subpaths too, so listing `lit-html` in `external` externalises the entry —
@@ -287,7 +284,6 @@ export async function writeRuntimeSubpaths(
287
284
  const mirrors = new Map<string, string>();
288
285
  /** Runtime package specifier → the core file the bundler resolves it to. */
289
286
  const cores = new Map<string, string | undefined>();
290
- const assetsDir = resolve(outDir, "assets");
291
287
  let written = 0;
292
288
 
293
289
  const coreOf = async (mod: RuntimeModule): Promise<string | undefined> => {
@@ -311,10 +307,13 @@ export async function writeRuntimeSubpaths(
311
307
  let discovered = 0;
312
308
  let files: string[] = [];
313
309
  try {
314
- files = readdirSync(assetsDir, { recursive: true })
310
+ /* Every module the build emitted, not only the bundles under `assets/`: a compiled component
311
+ (`components/<tag>.js`) and a page's own module import lit subpaths too, the keyed-list
312
+ directive's `repeat` among them (compiler.md §4.7). */
313
+ files = readdirSync(outDir, { recursive: true })
315
314
  .map(String)
316
315
  .filter((entry) => entry.endsWith(".js"))
317
- .map((entry) => join(assetsDir, entry));
316
+ .map((entry) => join(outDir, entry));
318
317
  } catch {
319
318
  return finish(outDir, mirrors, errors, written);
320
319
  }
@@ -27,7 +27,15 @@ import {
27
27
  import { cacheKey, getCached, getImageCacheDir, setCached } from "./image-cache.ts";
28
28
  import { imgLoadingAttrs } from "./img-loading.ts";
29
29
  import { resolveAssetUrl } from "@jxsuite/schema/asset-paths";
30
- import { isNodeObject, isNonNullObject, isString } from "@jxsuite/schema/guards";
30
+ import { reflectedAttribute } from "@jxsuite/runtime/dom-properties";
31
+ import {
32
+ isNodeObject,
33
+ isNonNullObject,
34
+ isRef,
35
+ isString,
36
+ isTemplateString,
37
+ } from "@jxsuite/schema/guards";
38
+ import { propertyAttrText } from "../shared.ts";
31
39
  import { errorMessage } from "@jxsuite/schema/parse";
32
40
  import { extractXmp, xmpFormatOf } from "@jxsuite/site/xmp-containers";
33
41
  import { readMediaRecord } from "@jxsuite/site/xmp-packet";
@@ -327,6 +335,15 @@ function applyFocalPoint(
327
335
  }
328
336
  }
329
337
 
338
+ /**
339
+ * `text` as a String.prototype.replace replacement that inserts exactly `text`: a replacement
340
+ * string reads `$1`, `$&`, `$'` and `` $` `` as patterns, and `$$` is how it spells one dollar
341
+ * sign.
342
+ */
343
+ export function literalReplacement(text: string): string {
344
+ return text.replaceAll("$", "$$$$");
345
+ }
346
+
330
347
  /**
331
348
  * Transform image nodes in a Jx document tree.
332
349
  *
@@ -399,26 +416,47 @@ async function walkAndTransform(
399
416
  );
400
417
  }
401
418
 
419
+ // Every descendant is bounded by the narrowest literal max-width or width above it.
420
+ const inner = containerWidthOf(node, containerWidth);
421
+ for (const child of templateChildren(node)) {
422
+ await walkAndTransform(child, config, projectRoot, cache, metaCache, imageRefs, mounts, inner);
423
+ }
424
+ }
425
+
426
+ /**
427
+ * The element definitions under a node: its `children`, a repeater's `map` template wherever the
428
+ * repeater sits (the whole `children` value or one child among siblings), and every `$switch` case.
429
+ * A row and a case are rendered later, by a module, from this same definition, so an `<img>` in one
430
+ * is decided here or nowhere (site-architecture.md §9.2.7).
431
+ *
432
+ * @param {JxMutableNode | JxDocument} node
433
+ * @returns {JxMutableNode[]}
434
+ */
435
+ function templateChildren(node: JxMutableNode | JxDocument): JxMutableNode[] {
436
+ const found: JxMutableNode[] = [];
437
+ const visit = (child: JxMutableNode["children"] | JxMutableNode | string | null) => {
438
+ // Text children carry no images, and a non-object child (an authored `null`) is skipped.
439
+ if (!isNodeObject(child)) {
440
+ return;
441
+ }
442
+ if (child.$prototype === "Array") {
443
+ visit(child.map);
444
+ return;
445
+ }
446
+ found.push(child);
447
+ };
402
448
  if (Array.isArray(node.children)) {
403
- // Every descendant is bounded by the narrowest literal max-width or width above it.
404
- const inner = containerWidthOf(node, containerWidth);
405
449
  for (const child of node.children) {
406
- // Text children carry no images, and a non-object child (an authored `null`) is skipped.
407
- if (!isNodeObject(child)) {
408
- continue;
409
- }
410
- await walkAndTransform(
411
- child,
412
- config,
413
- projectRoot,
414
- cache,
415
- metaCache,
416
- imageRefs,
417
- mounts,
418
- inner,
419
- );
450
+ visit(child);
420
451
  }
452
+ } else {
453
+ visit(node.children);
454
+ }
455
+ const cases: Record<string, JxMutableNode> = node.cases ?? {};
456
+ for (const branch of Object.values(cases)) {
457
+ visit(branch);
421
458
  }
459
+ return found;
422
460
  }
423
461
 
424
462
  /** A `<source>` in a generated `<picture>`: one image format, one candidate list. */
@@ -659,6 +697,53 @@ function sizesForContainer(containerWidth: number | null): string | undefined {
659
697
  return `(max-width: ${width}px) 100vw, ${width}px`;
660
698
  }
661
699
 
700
+ /**
701
+ * Move an `<img>` node's element properties into `attributes`, each under the attribute HTML
702
+ * reflects it to (spec.md §8.1).
703
+ *
704
+ * The pipeline reads and writes `attributes` only (`src` in, `srcset`, `sizes`, `width` and
705
+ * `height` out), and `wrapInPicture` moves `attributes` onto the inner `<img>`. An image written
706
+ * with properties is the same image, so it is brought to that one spelling first: `alt`, `width`
707
+ * and `role` then land on the image and not on the `<picture>` around it, and nothing is written
708
+ * twice. The node-level key is always removed. An `attributes` entry the author wrote wins. A
709
+ * literal is lifted as the static emitter would write it (`translate: false` as `"no"`), a `$ref`
710
+ * or a template as written, for the emitter to resolve. `id` and `className` stay on the node,
711
+ * where the style handle joins the class.
712
+ *
713
+ * @param {JxMutableNode | JxDocument} node - The `<img>` node, mutated
714
+ * @param {Record<string, JxAttributeValue>} attrs - The node's `attributes`
715
+ */
716
+ function liftImageProperties(
717
+ node: JxMutableNode | JxDocument,
718
+ attrs: Record<string, JxAttributeValue>,
719
+ ): void {
720
+ for (const [key, value] of Object.entries(node)) {
721
+ if (key === "id" || key === "className") {
722
+ continue;
723
+ }
724
+ const reflection = reflectedAttribute("img", key);
725
+ if (!reflection) {
726
+ continue;
727
+ }
728
+ /* SAFETY: `key` came from the node's own entries; deleting it drops one optional member. */
729
+ delete (node as Record<string, JxAttributeValue>)[key];
730
+ if (attrs[reflection.attribute] !== undefined) {
731
+ continue;
732
+ }
733
+ if (isRef(value) || isTemplateString(value)) {
734
+ attrs[reflection.attribute] = value;
735
+ continue;
736
+ }
737
+ /* SAFETY: a property's value is a document value, which is a scope value. */
738
+ const text = propertyAttrText(reflection, value as JxAttributeValue);
739
+ if (text === null) {
740
+ continue;
741
+ }
742
+ // A presence boolean lifts as `true`, which `attributes` writes bare.
743
+ attrs[reflection.attribute] = text === "" && reflection.kind !== "text" ? true : text;
744
+ }
745
+ }
746
+
662
747
  async function transformImgNode(
663
748
  node: JxMutableNode | JxDocument,
664
749
  config: ImageConfig,
@@ -673,15 +758,7 @@ async function transformImgNode(
673
758
  node.attributes = {};
674
759
  }
675
760
  const attrs = node.attributes;
676
- /*
677
- * A node-level `src` is normalized into `attributes` first. The static emitter only renders a
678
- * fixed set of node-level DOM properties and `src` is not among them, so an image written that
679
- * way used to acquire a `srcset` and lose its `src` — the fallback the srcset exists to have.
680
- */
681
- if (attrs.src === undefined && isString(node.src)) {
682
- attrs.src = node.src;
683
- delete node.src;
684
- }
761
+ liftImageProperties(node, attrs);
685
762
  applyFocalPoint(node, attrs.src, projectRoot, mounts);
686
763
 
687
764
  const variants = config.optimize
@@ -819,8 +896,10 @@ async function transformInnerHtmlImages(
819
896
  config.optimize && src !== ""
820
897
  ? await resolveVariants(
821
898
  src,
822
- // An image that already carries a candidate list is its author's.
823
- DATA_NO_OPT_RE.test(attrs) || hasAttr(attrs, "srcset"),
899
+ /* An image that already carries a candidate list is its author's, and so is one
900
+ inside a `<picture>`: its sources are the candidate list, whether an author wrote
901
+ them or the node half did while prerendering the component this markup came from. */
902
+ DATA_NO_OPT_RE.test(attrs) || hasAttr(attrs, "srcset") || insidePicture(html, m.index),
824
903
  config,
825
904
  projectRoot,
826
905
  cache,
@@ -877,11 +956,25 @@ async function transformInnerHtmlImages(
877
956
 
878
957
  let result = html;
879
958
  for (const { match, replacement } of replacements) {
880
- result = result.replace(match, replacement);
959
+ /* Escaped: `alt="$10 a month"` in a raw replacement STRING would be read as a pattern. */
960
+ result = result.replace(match, literalReplacement(replacement));
881
961
  }
882
962
  return result;
883
963
  }
884
964
 
965
+ /**
966
+ * Whether the tag starting at `index` sits inside a `<picture>`: the nearest `<picture` before it
967
+ * is not yet closed.
968
+ *
969
+ * @param {string} html
970
+ * @param {number} index
971
+ * @returns {boolean}
972
+ */
973
+ function insidePicture(html: string, index: number): boolean {
974
+ const before = html.slice(0, index).toLowerCase();
975
+ return before.lastIndexOf("<picture") > before.lastIndexOf("</picture>");
976
+ }
977
+
885
978
  /**
886
979
  * The string-surgery twin of {@link wrapInPicture}: the same markup, built from a raw attribute
887
980
  * string rather than a node. `srcset`/`sizes` stay off the `<img>` so it remains a real fallback.