@jxsuite/compiler 9.0.1 → 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.
@@ -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";
@@ -37,9 +45,24 @@ import type { ImageConfig, ImageManifest, ImageVariant } from "./image-optimizer
37
45
  import type { JxAttributeValue, JxDocument, JxMutableNode, JxStyle } from "@jxsuite/schema/types";
38
46
  import type { CacheManifest } from "./image-cache.ts";
39
47
 
40
- const SKIP_EXTENSIONS = new Set([".svg", ".gif"]);
41
- /** Local sources the build service leaves alone rather than re-encodes. */
48
+ /**
49
+ * The local sources the variant pass takes: the extensions of the formats the compiler's native
50
+ * core decodes (JPEG, PNG, WebP, TIFF and BMP; `crates/jx_media` in `@jxsuite/compiler-binding`).
51
+ * Anything else, or no extension at all, is left alone: a `.ico`, a `.heic` or an upload with no
52
+ * extension used to reach the encoder, fail to decode, and fail every route whose layout held it.
53
+ * Every GIF is outside it, animated or not (site-architecture.md §9.2.3).
54
+ */
55
+ const RASTER_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".webp", ".tif", ".tiff", ".bmp"]);
56
+ /**
57
+ * Local sources the build service serves as written, and the Cloudflare service still resizes: the
58
+ * native core has no AVIF decoder and nothing better to convert one to, while Cloudflare reads it.
59
+ */
42
60
  const ENCODED_AS_WRITTEN = new Set([".avif"]);
61
+ /**
62
+ * What an allowlisted remote source is refused for. A denylist, because a remote URL often has no
63
+ * extension at all and Cloudflare decodes more than the build service does.
64
+ */
65
+ const REMOTE_SKIP_EXTENSIONS = new Set([".svg", ".gif"]);
43
66
  const EXTERNAL_PREFIXES = ["http://", "https://", "data:", "//"];
44
67
 
45
68
  /** Per-build memo of original image dimensions + content hash (cloudflare mode). */
@@ -178,10 +201,8 @@ function shouldSkip(src: string) {
178
201
  if (EXTERNAL_PREFIXES.some((p) => src.startsWith(p))) {
179
202
  return true;
180
203
  }
181
- if (SKIP_EXTENSIONS.has(extname(src).toLowerCase())) {
182
- return true;
183
- }
184
- return false;
204
+ const extension = extname(src).toLowerCase();
205
+ return !RASTER_EXTENSIONS.has(extension) && !ENCODED_AS_WRITTEN.has(extension);
185
206
  }
186
207
 
187
208
  /**
@@ -210,7 +231,7 @@ function isAllowedRemote(src: string, config: ImageConfig) {
210
231
  }
211
232
  try {
212
233
  const url = new URL(src);
213
- if (SKIP_EXTENSIONS.has(extname(url.pathname).toLowerCase())) {
234
+ if (REMOTE_SKIP_EXTENSIONS.has(extname(url.pathname).toLowerCase())) {
214
235
  return false;
215
236
  }
216
237
  return config.remoteDomains.includes(url.hostname);
@@ -314,12 +335,21 @@ function applyFocalPoint(
314
335
  }
315
336
  }
316
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
+
317
347
  /**
318
348
  * Transform image nodes in a Jx document tree.
319
349
  *
320
350
  * Mutates img nodes in place, injecting srcset, sizes, width, height, loading, and decoding.
321
- * Optimized variants are written to .cache/images/_optimized/ — the caller is responsible for
322
- * copying them to the dist directory after all pages are compiled.
351
+ * Optimized variants are written to the image cache's `_optimized/` (`getImageCacheDir`), and the
352
+ * build copies the ones it used into the dist directory after all pages are compiled.
323
353
  *
324
354
  * @param {JxMutableNode | JxDocument} doc - The Jx document tree (mutated in place)
325
355
  * @param {ImageConfig} config
@@ -343,15 +373,6 @@ export async function transformImageNodes(
343
373
  return { imageRefs };
344
374
  }
345
375
 
346
- /**
347
- * @param {JxMutableNode | JxDocument} node
348
- * @param {ImageConfig} config
349
- * @param {string} projectRoot
350
- * @param {CacheManifest | null} cache
351
- * @param {ImageMetaCache} metaCache
352
- * @param {Map<string, ImageManifest>} imageRefs
353
- * @param {readonly AssetMount[]} mounts
354
- */
355
376
  async function walkAndTransform(
356
377
  node: JxMutableNode | JxDocument,
357
378
  config: ImageConfig,
@@ -390,29 +411,52 @@ async function walkAndTransform(
390
411
  metaCache,
391
412
  imageRefs,
392
413
  mounts,
414
+ // The node holding the content is the innermost container of every image in it.
415
+ containerWidthOf(node, containerWidth),
393
416
  );
394
417
  }
395
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
+ };
396
448
  if (Array.isArray(node.children)) {
397
- // Every descendant is bounded by the narrowest literal max-width above it.
398
- const inner = containerWidthOf(node, containerWidth);
399
449
  for (const child of node.children) {
400
- // Text children carry no images, and a non-object child (an authored `null`) is skipped.
401
- if (!isNodeObject(child)) {
402
- continue;
403
- }
404
- await walkAndTransform(
405
- child,
406
- config,
407
- projectRoot,
408
- cache,
409
- metaCache,
410
- imageRefs,
411
- mounts,
412
- inner,
413
- );
450
+ visit(child);
414
451
  }
452
+ } else {
453
+ visit(node.children);
415
454
  }
455
+ const cases: Record<string, JxMutableNode> = node.cases ?? {};
456
+ for (const branch of Object.values(cases)) {
457
+ visit(branch);
458
+ }
459
+ return found;
416
460
  }
417
461
 
418
462
  /** A `<source>` in a generated `<picture>`: one image format, one candidate list. */
@@ -447,11 +491,11 @@ interface ResolvedVariants {
447
491
  * Generate (or look up) this image's variants and describe what the markup should say.
448
492
  *
449
493
  * Returns null whenever the image is not ours to touch — a bound `src`, an SVG, a remote URL off
450
- * the allowlist, a missing file, an explicit `data-no-optimize`. Both callers treat null the same
451
- * way: leave the markup alone apart from the loading attributes.
494
+ * the allowlist, a missing file, an explicit `data-no-optimize`, an authored `srcset`. Both callers
495
+ * treat null the same way: leave the markup alone apart from the loading attributes.
452
496
  *
453
497
  * @param {JxAttributeValue | undefined} src - The `src` as written, which may be bound or absent
454
- * @param {boolean} optedOut - `data-no-optimize` is present
498
+ * @param {boolean} optedOut - `data-no-optimize` or an authored `srcset` is present
455
499
  * @param {ImageConfig} config
456
500
  * @param {string} projectRoot
457
501
  * @param {CacheManifest | null} cache
@@ -499,9 +543,7 @@ async function resolveVariants(
499
543
  return { dims, sources: [], srcset };
500
544
  }
501
545
 
502
- /* The build service decodes JPEG, PNG, WebP, TIFF and BMP. An AVIF source is already the format
503
- every variant would be converted to, and re-encoding it would only lose quality, so it is
504
- served as written (compiler.md §7.3). */
546
+ // An AVIF source is already in the best format every variant would be converted to.
505
547
  if (ENCODED_AS_WRITTEN.has(extname(absoluteSrc).toLowerCase())) {
506
548
  return null;
507
549
  }
@@ -549,8 +591,9 @@ async function resolveVariants(
549
591
  * The formats to offer for one image: the project's, with PNG added where it stands in for JPEG.
550
592
  *
551
593
  * JPEG has no alpha channel, so the encoder writes PNG wherever JPEG was asked of a source with
552
- * transparency (compiler.md §7.2). That PNG was asked for, under another name, and is offered; any
553
- * other format the project did not list stays out even if a stale manifest holds variants of it.
594
+ * transparency (site-architecture.md §9.2.2). That PNG was asked for, under another name, and is
595
+ * offered; any other format the project did not list stays out even if a stale manifest holds
596
+ * variants of it.
554
597
  */
555
598
  function writtenFormats(formats: readonly string[], variants: ImageVariant[]): readonly string[] {
556
599
  const standsIn =
@@ -595,15 +638,6 @@ function fallbackVariant(variants: ImageVariant[], formats: readonly string[]):
595
638
  return best && variantUrl(best.outputPath);
596
639
  }
597
640
 
598
- /**
599
- * @param {JxMutableNode | JxDocument} node
600
- * @param {ImageConfig} config
601
- * @param {string} projectRoot
602
- * @param {CacheManifest | null} cache
603
- * @param {ImageMetaCache} metaCache
604
- * @param {Map<string, ImageManifest>} imageRefs
605
- * @param {readonly AssetMount[]} mounts
606
- */
607
641
  const CSS_LENGTH = /^(\d+(?:\.\d+)?)(px|rem)$/;
608
642
 
609
643
  /** A CSS length in px, but only when it is a plain `px`/`rem` literal. `null` for anything else. */
@@ -620,7 +654,8 @@ function pxLength(value: JxStyle[string]): number | null {
620
654
  }
621
655
 
622
656
  /**
623
- * The narrowest px `max-width`/`width` an element at this point in the tree sits inside.
657
+ * The narrowest literal `max-width` or `width` this element declares in its base `style`, or the
658
+ * inherited bound when that is narrower. Nested blocks are not read (site-architecture.md §9.2.2).
624
659
  *
625
660
  * Only literal lengths count. A `clamp()`, a percentage or a custom property is a real constraint
626
661
  * too, but not one the build can resolve — and a wrong `sizes` is worse than none, because the
@@ -635,11 +670,13 @@ function containerWidthOf(
635
670
  if (!isNonNullObject(style)) {
636
671
  return inherited;
637
672
  }
638
- const declared = pxLength(style.maxWidth) ?? pxLength(style.width);
639
- if (declared === null) {
640
- return inherited;
673
+ let narrowest = inherited;
674
+ for (const declared of [pxLength(style.maxWidth), pxLength(style.width)]) {
675
+ if (declared !== null && (narrowest === null || declared < narrowest)) {
676
+ narrowest = declared;
677
+ }
641
678
  }
642
- return inherited === null ? declared : Math.min(inherited, declared);
679
+ return narrowest;
643
680
  }
644
681
 
645
682
  /**
@@ -660,6 +697,53 @@ function sizesForContainer(containerWidth: number | null): string | undefined {
660
697
  return `(max-width: ${width}px) 100vw, ${width}px`;
661
698
  }
662
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
+
663
747
  async function transformImgNode(
664
748
  node: JxMutableNode | JxDocument,
665
749
  config: ImageConfig,
@@ -674,21 +758,14 @@ async function transformImgNode(
674
758
  node.attributes = {};
675
759
  }
676
760
  const attrs = node.attributes;
677
- /*
678
- * A node-level `src` is normalized into `attributes` first. The static emitter only renders a
679
- * fixed set of node-level DOM properties and `src` is not among them, so an image written that
680
- * way used to acquire a `srcset` and lose its `src` — the fallback the srcset exists to have.
681
- */
682
- if (attrs.src === undefined && isString(node.src)) {
683
- attrs.src = node.src;
684
- delete node.src;
685
- }
761
+ liftImageProperties(node, attrs);
686
762
  applyFocalPoint(node, attrs.src, projectRoot, mounts);
687
763
 
688
764
  const variants = config.optimize
689
765
  ? await resolveVariants(
690
766
  attrs.src,
691
- attrs["data-no-optimize"] !== undefined,
767
+ // An image that already carries a candidate list is its author's, as in the innerHTML half.
768
+ attrs["data-no-optimize"] !== undefined || attrs.srcset !== undefined,
692
769
  config,
693
770
  projectRoot,
694
771
  cache,
@@ -709,7 +786,9 @@ async function transformImgNode(
709
786
  if (variants) {
710
787
  if (variants.srcset !== "") {
711
788
  attrs.srcset = variants.srcset;
712
- attrs.sizes = resolvedSizes;
789
+ if (resolvedSizes !== undefined) {
790
+ attrs.sizes = resolvedSizes;
791
+ }
713
792
  if (variants.fallbackSrc !== undefined) {
714
793
  attrs.src = variants.fallbackSrc;
715
794
  }
@@ -740,12 +819,12 @@ async function transformImgNode(
740
819
  *
741
820
  * @param {JxMutableNode | JxDocument} node - The `<img>` node, mutated into a `<picture>`
742
821
  * @param {PictureSource[]} sources
743
- * @param {JxAttributeValue} sizes
822
+ * @param {JxAttributeValue | undefined} sizes - The resolved `sizes`, when anything names one
744
823
  */
745
824
  function wrapInPicture(
746
825
  node: JxMutableNode | JxDocument,
747
826
  sources: readonly PictureSource[],
748
- sizes: JxAttributeValue,
827
+ sizes: JxAttributeValue | undefined,
749
828
  ) {
750
829
  const imgAttrs = { ...node.attributes };
751
830
  const inheritedSizes = imgAttrs.sizes ?? sizes;
@@ -760,7 +839,7 @@ function wrapInPicture(
760
839
  const children = sources.map((source): JxMutableNode => {
761
840
  const attributes: Record<string, JxAttributeValue> = {};
762
841
  // An empty `sizes` is not a neutral default — omit it and let the browser assume 100vw.
763
- if (inheritedSizes !== "") {
842
+ if (inheritedSizes !== undefined && inheritedSizes !== "") {
764
843
  attributes.sizes = inheritedSizes;
765
844
  }
766
845
  attributes.srcset = source.srcset;
@@ -775,11 +854,15 @@ function wrapInPicture(
775
854
  }
776
855
 
777
856
  const IMG_TAG_RE = /<img\b([^>]*)>/gi;
778
- const SRCSET_ATTR_RE = /\bsrcset="/;
779
857
  const DATA_NO_OPT_RE = /\bdata-no-optimize\b/;
858
+ const SRC_ATTR_RE = /(^|\s)src="[^"]*"/i;
859
+ const SIZES_ATTR_RE = /(?:^|\s)sizes="[^"]*"/i;
780
860
 
781
861
  /**
782
- * Transform `<img>` tags embedded in pre-rendered innerHTML strings.
862
+ * Transform `<img>` tags embedded in pre-rendered innerHTML strings, by the rules
863
+ * {@link transformImgNode} applies to a node: the same eligibility, the same `src` fallback, the
864
+ * same `sizes` order. A rule added to one half is added to the other (site-architecture.md
865
+ * §9.2.2).
783
866
  *
784
867
  * @param {string} html
785
868
  * @param {ImageConfig} config
@@ -788,6 +871,7 @@ const DATA_NO_OPT_RE = /\bdata-no-optimize\b/;
788
871
  * @param {ImageMetaCache} metaCache
789
872
  * @param {Map<string, ImageManifest>} imageRefs
790
873
  * @param {readonly AssetMount[]} mounts
874
+ * @param {number | null} containerWidth - The bound of the node holding this HTML
791
875
  * @returns {Promise<string>}
792
876
  */
793
877
  async function transformInnerHtmlImages(
@@ -798,6 +882,7 @@ async function transformInnerHtmlImages(
798
882
  metaCache: ImageMetaCache,
799
883
  imageRefs: Map<string, ImageManifest>,
800
884
  mounts: readonly AssetMount[],
885
+ containerWidth: number | null,
801
886
  ) {
802
887
  const replacements: { match: string; replacement: string }[] = [];
803
888
 
@@ -807,12 +892,14 @@ async function transformInnerHtmlImages(
807
892
 
808
893
  // Attribute values in pre-rendered innerHTML are entity-escaped — decode for processing
809
894
  const src = (attrValue(attrs, "src") ?? "").replaceAll("&amp;", "&");
810
- const alreadyResponsive = SRCSET_ATTR_RE.test(attrs);
811
895
  const variants =
812
- config.optimize && src !== "" && !alreadyResponsive
896
+ config.optimize && src !== ""
813
897
  ? await resolveVariants(
814
898
  src,
815
- DATA_NO_OPT_RE.test(attrs),
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),
816
903
  config,
817
904
  projectRoot,
818
905
  cache,
@@ -822,11 +909,26 @@ async function transformInnerHtmlImages(
822
909
  )
823
910
  : null;
824
911
 
912
+ // The tag, then the layout, then the project: the order the node half resolves `sizes` in.
913
+ const ownSizes = attrValue(attrs, "sizes");
914
+ const resolvedSizes = ownSizes ?? sizesForContainer(containerWidth) ?? config.sizes;
915
+
916
+ let written = attrs;
825
917
  let extra = "";
826
918
  if (variants && variants.srcset !== "") {
827
- extra += ` srcset="${variants.srcset}" sizes="${config.sizes}"`;
919
+ extra += ` srcset="${variants.srcset}"`;
920
+ if (ownSizes === undefined && resolvedSizes !== undefined && resolvedSizes !== "") {
921
+ extra += ` sizes="${resolvedSizes}"`;
922
+ }
923
+ const { fallbackSrc } = variants;
924
+ if (fallbackSrc !== undefined) {
925
+ written = attrs.replace(
926
+ SRC_ATTR_RE,
927
+ (_match, space: string) => `${space}src="${fallbackSrc}"`,
928
+ );
929
+ }
828
930
  }
829
- if (variants?.dims && !/\bwidth=/.test(attrs) && !/\bheight=/.test(attrs)) {
931
+ if (variants?.dims && !hasAttr(attrs, "width") && !hasAttr(attrs, "height")) {
830
932
  extra += ` width="${variants.dims.width}" height="${variants.dims.height}"`;
831
933
  }
832
934
  const loading = imgLoadingAttrs(
@@ -847,49 +949,78 @@ async function transformInnerHtmlImages(
847
949
 
848
950
  const img =
849
951
  variants && variants.sources.length > 0
850
- ? renderPictureTag(attrs, variants.sources, config.sizes, extra)
851
- : `<img${attrs}${extra}>`;
952
+ ? renderPictureTag(written, variants.sources, resolvedSizes, extra)
953
+ : `<img${written}${extra}>`;
852
954
  replacements.push({ match: tag, replacement: img });
853
955
  }
854
956
 
855
957
  let result = html;
856
958
  for (const { match, replacement } of replacements) {
857
- 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));
858
961
  }
859
962
  return result;
860
963
  }
861
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
+
862
978
  /**
863
979
  * The string-surgery twin of {@link wrapInPicture}: the same markup, built from a raw attribute
864
980
  * string rather than a node. `srcset`/`sizes` stay off the `<img>` so it remains a real fallback.
865
981
  *
866
982
  * @param {string} attrs - The original tag's attribute string
867
983
  * @param {readonly PictureSource[]} sources
868
- * @param {string} sizes
984
+ * @param {string | undefined} sizes - The resolved `sizes`, the tag's own included
869
985
  * @param {string} extra - Attributes this pass decided to add
870
986
  * @returns {string}
871
987
  */
872
988
  function renderPictureTag(
873
989
  attrs: string,
874
990
  sources: readonly PictureSource[],
875
- sizes: string,
991
+ sizes: string | undefined,
876
992
  extra: string,
877
993
  ) {
878
- const inheritedSizes = attrValue(attrs, "sizes") ?? sizes;
994
+ const imgAttrs = attrs.replace(SIZES_ATTR_RE, "");
879
995
  const imgExtra = extra.replace(/ srcset="[^"]*"/, "").replace(/ sizes="[^"]*"/, "");
996
+ // An empty `sizes` is not a neutral default: leave it off and the browser assumes 100vw.
997
+ const sizesAttr = sizes === undefined || sizes === "" ? "" : ` sizes="${sizes}"`;
880
998
  const sourceTags = sources
881
- .map((s) => `<source type="${s.type}" srcset="${s.srcset}" sizes="${inheritedSizes}">`)
999
+ .map((s) => `<source type="${s.type}" srcset="${s.srcset}"${sizesAttr}>`)
882
1000
  .join("");
883
- return `<picture>${sourceTags}<img${attrs}${imgExtra}></picture>`;
1001
+ return `<picture>${sourceTags}<img${imgAttrs}${imgExtra}></picture>`;
884
1002
  }
885
1003
 
886
1004
  /**
887
- * Read one double-quoted attribute out of a raw tag attribute string.
1005
+ * Read one double-quoted attribute out of a raw tag attribute string. The name is matched whole:
1006
+ * `data-src` is not `src`.
888
1007
  *
889
1008
  * @param {string} attrs
890
1009
  * @param {string} name
891
1010
  * @returns {string | undefined}
892
1011
  */
893
1012
  function attrValue(attrs: string, name: string): string | undefined {
894
- return new RegExp(`\\b${name}="([^"]*)"`, "i").exec(attrs)?.[1];
1013
+ return new RegExp(`(?:^|\\s)${name}="([^"]*)"`, "i").exec(attrs)?.[1];
1014
+ }
1015
+
1016
+ /**
1017
+ * Whether a raw tag attribute string sets an attribute. The name is matched whole: a lazy-loader's
1018
+ * `data-srcset` is not an authored `srcset`, and `data-width` is not `width`.
1019
+ *
1020
+ * @param {string} attrs
1021
+ * @param {string} name
1022
+ * @returns {boolean}
1023
+ */
1024
+ function hasAttr(attrs: string, name: string): boolean {
1025
+ return new RegExp(`(?:^|\\s)${name}=`, "i").test(attrs);
895
1026
  }
@@ -576,7 +576,14 @@ async function expandPagedRoute(
576
576
  );
577
577
  return [];
578
578
  }
579
- const items = await resolvePagedEntry(raw, paged.key, route, fixed, ctx);
579
+ let items: JsonValue | undefined;
580
+ try {
581
+ items = await resolvePagedEntry(raw, paged.key, route, fixed, ctx);
582
+ } catch (error) {
583
+ // The entry names a class the build could not resolve (compiler.md §3): its error is the route's.
584
+ ctx.report(route, errorMessage(error));
585
+ return [];
586
+ }
580
587
  if (!Array.isArray(items)) {
581
588
  ctx.report(route, `state entry "${paged.key}" did not resolve to an array at build time`);
582
589
  return [];