@jxsuite/compiler 8.7.0 → 9.1.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.
@@ -37,7 +37,24 @@ import type { ImageConfig, ImageManifest, ImageVariant } from "./image-optimizer
37
37
  import type { JxAttributeValue, JxDocument, JxMutableNode, JxStyle } from "@jxsuite/schema/types";
38
38
  import type { CacheManifest } from "./image-cache.ts";
39
39
 
40
- const SKIP_EXTENSIONS = new Set([".svg", ".gif"]);
40
+ /**
41
+ * The local sources the variant pass takes: the extensions of the formats the compiler's native
42
+ * core decodes (JPEG, PNG, WebP, TIFF and BMP; `crates/jx_media` in `@jxsuite/compiler-binding`).
43
+ * Anything else, or no extension at all, is left alone: a `.ico`, a `.heic` or an upload with no
44
+ * extension used to reach the encoder, fail to decode, and fail every route whose layout held it.
45
+ * Every GIF is outside it, animated or not (site-architecture.md §9.2.3).
46
+ */
47
+ const RASTER_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".webp", ".tif", ".tiff", ".bmp"]);
48
+ /**
49
+ * Local sources the build service serves as written, and the Cloudflare service still resizes: the
50
+ * native core has no AVIF decoder and nothing better to convert one to, while Cloudflare reads it.
51
+ */
52
+ const ENCODED_AS_WRITTEN = new Set([".avif"]);
53
+ /**
54
+ * What an allowlisted remote source is refused for. A denylist, because a remote URL often has no
55
+ * extension at all and Cloudflare decodes more than the build service does.
56
+ */
57
+ const REMOTE_SKIP_EXTENSIONS = new Set([".svg", ".gif"]);
41
58
  const EXTERNAL_PREFIXES = ["http://", "https://", "data:", "//"];
42
59
 
43
60
  /** Per-build memo of original image dimensions + content hash (cloudflare mode). */
@@ -46,13 +63,13 @@ export type ImageMetaCache = Map<
46
63
  { width: number | null; height: number | null; hash: string }
47
64
  >;
48
65
 
49
- let sharpWarned = false;
66
+ let dimensionsWarned = false;
50
67
 
51
68
  /**
52
69
  * Resolve original image dimensions and content hash for cloudflare mode. Reads only the image
53
- * header via Sharp — no variants are generated. Dimensions degrade to null when Sharp is
54
- * unavailable (e.g. native binary won't load): srcsets are still emitted (fit=scale-down guards
55
- * against upscaling), only the width/height attributes are skipped.
70
+ * header — no variants are generated. Dimensions degrade to null when the header cannot be read (a
71
+ * format the compiler does not decode, or no native addon for this platform): srcsets are still
72
+ * emitted (fit=scale-down guards against upscaling), only the width/height attributes are skipped.
56
73
  *
57
74
  * @param {string} absoluteSrc
58
75
  * @param {ImageMetaCache} metaCache
@@ -66,8 +83,8 @@ async function resolveCfMeta(absoluteSrc: string, metaCache: ImageMetaCache) {
66
83
  const m = await getImageMetadata(absoluteSrc);
67
84
  meta = { width: m.width, height: m.height, hash };
68
85
  } catch (error) {
69
- if (!sharpWarned) {
70
- sharpWarned = true;
86
+ if (!dimensionsWarned) {
87
+ dimensionsWarned = true;
71
88
  console.warn(
72
89
  `Could not read image dimensions (${errorMessage(error)}) — ` +
73
90
  `emitting srcsets without width/height attributes.`,
@@ -176,10 +193,8 @@ function shouldSkip(src: string) {
176
193
  if (EXTERNAL_PREFIXES.some((p) => src.startsWith(p))) {
177
194
  return true;
178
195
  }
179
- if (SKIP_EXTENSIONS.has(extname(src).toLowerCase())) {
180
- return true;
181
- }
182
- return false;
196
+ const extension = extname(src).toLowerCase();
197
+ return !RASTER_EXTENSIONS.has(extension) && !ENCODED_AS_WRITTEN.has(extension);
183
198
  }
184
199
 
185
200
  /**
@@ -208,7 +223,7 @@ function isAllowedRemote(src: string, config: ImageConfig) {
208
223
  }
209
224
  try {
210
225
  const url = new URL(src);
211
- if (SKIP_EXTENSIONS.has(extname(url.pathname).toLowerCase())) {
226
+ if (REMOTE_SKIP_EXTENSIONS.has(extname(url.pathname).toLowerCase())) {
212
227
  return false;
213
228
  }
214
229
  return config.remoteDomains.includes(url.hostname);
@@ -316,8 +331,8 @@ function applyFocalPoint(
316
331
  * Transform image nodes in a Jx document tree.
317
332
  *
318
333
  * Mutates img nodes in place, injecting srcset, sizes, width, height, loading, and decoding.
319
- * Optimized variants are written to .cache/images/_optimized/ — the caller is responsible for
320
- * copying them to the dist directory after all pages are compiled.
334
+ * Optimized variants are written to the image cache's `_optimized/` (`getImageCacheDir`), and the
335
+ * build copies the ones it used into the dist directory after all pages are compiled.
321
336
  *
322
337
  * @param {JxMutableNode | JxDocument} doc - The Jx document tree (mutated in place)
323
338
  * @param {ImageConfig} config
@@ -341,15 +356,6 @@ export async function transformImageNodes(
341
356
  return { imageRefs };
342
357
  }
343
358
 
344
- /**
345
- * @param {JxMutableNode | JxDocument} node
346
- * @param {ImageConfig} config
347
- * @param {string} projectRoot
348
- * @param {CacheManifest | null} cache
349
- * @param {ImageMetaCache} metaCache
350
- * @param {Map<string, ImageManifest>} imageRefs
351
- * @param {readonly AssetMount[]} mounts
352
- */
353
359
  async function walkAndTransform(
354
360
  node: JxMutableNode | JxDocument,
355
361
  config: ImageConfig,
@@ -388,11 +394,13 @@ async function walkAndTransform(
388
394
  metaCache,
389
395
  imageRefs,
390
396
  mounts,
397
+ // The node holding the content is the innermost container of every image in it.
398
+ containerWidthOf(node, containerWidth),
391
399
  );
392
400
  }
393
401
 
394
402
  if (Array.isArray(node.children)) {
395
- // Every descendant is bounded by the narrowest literal max-width above it.
403
+ // Every descendant is bounded by the narrowest literal max-width or width above it.
396
404
  const inner = containerWidthOf(node, containerWidth);
397
405
  for (const child of node.children) {
398
406
  // Text children carry no images, and a non-object child (an authored `null`) is skipped.
@@ -445,11 +453,11 @@ interface ResolvedVariants {
445
453
  * Generate (or look up) this image's variants and describe what the markup should say.
446
454
  *
447
455
  * Returns null whenever the image is not ours to touch — a bound `src`, an SVG, a remote URL off
448
- * the allowlist, a missing file, an explicit `data-no-optimize`. Both callers treat null the same
449
- * way: leave the markup alone apart from the loading attributes.
456
+ * the allowlist, a missing file, an explicit `data-no-optimize`, an authored `srcset`. Both callers
457
+ * treat null the same way: leave the markup alone apart from the loading attributes.
450
458
  *
451
459
  * @param {JxAttributeValue | undefined} src - The `src` as written, which may be bound or absent
452
- * @param {boolean} optedOut - `data-no-optimize` is present
460
+ * @param {boolean} optedOut - `data-no-optimize` or an authored `srcset` is present
453
461
  * @param {ImageConfig} config
454
462
  * @param {string} projectRoot
455
463
  * @param {CacheManifest | null} cache
@@ -497,6 +505,11 @@ async function resolveVariants(
497
505
  return { dims, sources: [], srcset };
498
506
  }
499
507
 
508
+ // An AVIF source is already in the best format every variant would be converted to.
509
+ if (ENCODED_AS_WRITTEN.has(extname(absoluteSrc).toLowerCase())) {
510
+ return null;
511
+ }
512
+
500
513
  let manifest = imageRefs.get(absoluteSrc);
501
514
  if (!manifest) {
502
515
  manifest = await resolveManifest(absoluteSrc, src, config, projectRoot, cache!);
@@ -508,9 +521,10 @@ async function resolveVariants(
508
521
  * offered even if a stale manifest happens to hold variants of it, and one this order does not
509
522
  * know keeps the position the project gave it.
510
523
  */
524
+ const asked = writtenFormats(config.formats, manifest.variants);
511
525
  const ordered = [
512
- ...PICTURE_FORMAT_ORDER.filter((format) => config.formats.includes(format)),
513
- ...config.formats.filter((format) => !PICTURE_FORMAT_ORDER.includes(format)),
526
+ ...PICTURE_FORMAT_ORDER.filter((format) => asked.includes(format)),
527
+ ...asked.filter((format) => !PICTURE_FORMAT_ORDER.includes(format)),
514
528
  ];
515
529
  const available = ordered.flatMap((format): PictureSource[] => {
516
530
  const srcset = buildSrcset(manifest.variants, format);
@@ -529,12 +543,29 @@ async function resolveVariants(
529
543
  const wrap = config.picture !== false && available.length > 1;
530
544
  return {
531
545
  dims,
532
- fallbackSrc: fallbackVariant(manifest.variants, config.formats),
546
+ fallbackSrc: fallbackVariant(manifest.variants, asked),
533
547
  sources: wrap ? available : [],
534
548
  srcset: available[0]?.srcset ?? "",
535
549
  };
536
550
  }
537
551
 
552
+ /**
553
+ * The formats to offer for one image: the project's, with PNG added where it stands in for JPEG.
554
+ *
555
+ * JPEG has no alpha channel, so the encoder writes PNG wherever JPEG was asked of a source with
556
+ * transparency (site-architecture.md §9.2.2). That PNG was asked for, under another name, and is
557
+ * offered; any other format the project did not list stays out even if a stale manifest holds
558
+ * variants of it.
559
+ */
560
+ function writtenFormats(formats: readonly string[], variants: ImageVariant[]): readonly string[] {
561
+ const standsIn =
562
+ formats.includes("jpeg") &&
563
+ !formats.includes("png") &&
564
+ variants.some((variant) => variant.format === "png") &&
565
+ !variants.some((variant) => variant.format === "jpeg");
566
+ return standsIn ? [...formats, "png"] : formats;
567
+ }
568
+
538
569
  /**
539
570
  * Formats an `<img src>` may point at without narrowing who can see the image.
540
571
  *
@@ -553,7 +584,10 @@ const UNIVERSAL_FORMATS: readonly string[] = ["jpeg", "png"];
553
584
  * smaller image nobody can decode is not an improvement.
554
585
  */
555
586
  function fallbackVariant(variants: ImageVariant[], formats: readonly string[]): string | undefined {
556
- const format = UNIVERSAL_FORMATS.find((candidate) => formats.includes(candidate));
587
+ const format = UNIVERSAL_FORMATS.find(
588
+ (candidate) =>
589
+ formats.includes(candidate) && variants.some((variant) => variant.format === candidate),
590
+ );
557
591
  if (format === undefined) {
558
592
  return undefined;
559
593
  }
@@ -566,15 +600,6 @@ function fallbackVariant(variants: ImageVariant[], formats: readonly string[]):
566
600
  return best && variantUrl(best.outputPath);
567
601
  }
568
602
 
569
- /**
570
- * @param {JxMutableNode | JxDocument} node
571
- * @param {ImageConfig} config
572
- * @param {string} projectRoot
573
- * @param {CacheManifest | null} cache
574
- * @param {ImageMetaCache} metaCache
575
- * @param {Map<string, ImageManifest>} imageRefs
576
- * @param {readonly AssetMount[]} mounts
577
- */
578
603
  const CSS_LENGTH = /^(\d+(?:\.\d+)?)(px|rem)$/;
579
604
 
580
605
  /** A CSS length in px, but only when it is a plain `px`/`rem` literal. `null` for anything else. */
@@ -591,7 +616,8 @@ function pxLength(value: JxStyle[string]): number | null {
591
616
  }
592
617
 
593
618
  /**
594
- * The narrowest px `max-width`/`width` an element at this point in the tree sits inside.
619
+ * The narrowest literal `max-width` or `width` this element declares in its base `style`, or the
620
+ * inherited bound when that is narrower. Nested blocks are not read (site-architecture.md §9.2.2).
595
621
  *
596
622
  * Only literal lengths count. A `clamp()`, a percentage or a custom property is a real constraint
597
623
  * too, but not one the build can resolve — and a wrong `sizes` is worse than none, because the
@@ -606,11 +632,13 @@ function containerWidthOf(
606
632
  if (!isNonNullObject(style)) {
607
633
  return inherited;
608
634
  }
609
- const declared = pxLength(style.maxWidth) ?? pxLength(style.width);
610
- if (declared === null) {
611
- return inherited;
635
+ let narrowest = inherited;
636
+ for (const declared of [pxLength(style.maxWidth), pxLength(style.width)]) {
637
+ if (declared !== null && (narrowest === null || declared < narrowest)) {
638
+ narrowest = declared;
639
+ }
612
640
  }
613
- return inherited === null ? declared : Math.min(inherited, declared);
641
+ return narrowest;
614
642
  }
615
643
 
616
644
  /**
@@ -659,7 +687,8 @@ async function transformImgNode(
659
687
  const variants = config.optimize
660
688
  ? await resolveVariants(
661
689
  attrs.src,
662
- attrs["data-no-optimize"] !== undefined,
690
+ // An image that already carries a candidate list is its author's, as in the innerHTML half.
691
+ attrs["data-no-optimize"] !== undefined || attrs.srcset !== undefined,
663
692
  config,
664
693
  projectRoot,
665
694
  cache,
@@ -680,7 +709,9 @@ async function transformImgNode(
680
709
  if (variants) {
681
710
  if (variants.srcset !== "") {
682
711
  attrs.srcset = variants.srcset;
683
- attrs.sizes = resolvedSizes;
712
+ if (resolvedSizes !== undefined) {
713
+ attrs.sizes = resolvedSizes;
714
+ }
684
715
  if (variants.fallbackSrc !== undefined) {
685
716
  attrs.src = variants.fallbackSrc;
686
717
  }
@@ -711,12 +742,12 @@ async function transformImgNode(
711
742
  *
712
743
  * @param {JxMutableNode | JxDocument} node - The `<img>` node, mutated into a `<picture>`
713
744
  * @param {PictureSource[]} sources
714
- * @param {JxAttributeValue} sizes
745
+ * @param {JxAttributeValue | undefined} sizes - The resolved `sizes`, when anything names one
715
746
  */
716
747
  function wrapInPicture(
717
748
  node: JxMutableNode | JxDocument,
718
749
  sources: readonly PictureSource[],
719
- sizes: JxAttributeValue,
750
+ sizes: JxAttributeValue | undefined,
720
751
  ) {
721
752
  const imgAttrs = { ...node.attributes };
722
753
  const inheritedSizes = imgAttrs.sizes ?? sizes;
@@ -731,7 +762,7 @@ function wrapInPicture(
731
762
  const children = sources.map((source): JxMutableNode => {
732
763
  const attributes: Record<string, JxAttributeValue> = {};
733
764
  // An empty `sizes` is not a neutral default — omit it and let the browser assume 100vw.
734
- if (inheritedSizes !== "") {
765
+ if (inheritedSizes !== undefined && inheritedSizes !== "") {
735
766
  attributes.sizes = inheritedSizes;
736
767
  }
737
768
  attributes.srcset = source.srcset;
@@ -746,11 +777,15 @@ function wrapInPicture(
746
777
  }
747
778
 
748
779
  const IMG_TAG_RE = /<img\b([^>]*)>/gi;
749
- const SRCSET_ATTR_RE = /\bsrcset="/;
750
780
  const DATA_NO_OPT_RE = /\bdata-no-optimize\b/;
781
+ const SRC_ATTR_RE = /(^|\s)src="[^"]*"/i;
782
+ const SIZES_ATTR_RE = /(?:^|\s)sizes="[^"]*"/i;
751
783
 
752
784
  /**
753
- * Transform `<img>` tags embedded in pre-rendered innerHTML strings.
785
+ * Transform `<img>` tags embedded in pre-rendered innerHTML strings, by the rules
786
+ * {@link transformImgNode} applies to a node: the same eligibility, the same `src` fallback, the
787
+ * same `sizes` order. A rule added to one half is added to the other (site-architecture.md
788
+ * §9.2.2).
754
789
  *
755
790
  * @param {string} html
756
791
  * @param {ImageConfig} config
@@ -759,6 +794,7 @@ const DATA_NO_OPT_RE = /\bdata-no-optimize\b/;
759
794
  * @param {ImageMetaCache} metaCache
760
795
  * @param {Map<string, ImageManifest>} imageRefs
761
796
  * @param {readonly AssetMount[]} mounts
797
+ * @param {number | null} containerWidth - The bound of the node holding this HTML
762
798
  * @returns {Promise<string>}
763
799
  */
764
800
  async function transformInnerHtmlImages(
@@ -769,6 +805,7 @@ async function transformInnerHtmlImages(
769
805
  metaCache: ImageMetaCache,
770
806
  imageRefs: Map<string, ImageManifest>,
771
807
  mounts: readonly AssetMount[],
808
+ containerWidth: number | null,
772
809
  ) {
773
810
  const replacements: { match: string; replacement: string }[] = [];
774
811
 
@@ -778,12 +815,12 @@ async function transformInnerHtmlImages(
778
815
 
779
816
  // Attribute values in pre-rendered innerHTML are entity-escaped — decode for processing
780
817
  const src = (attrValue(attrs, "src") ?? "").replaceAll("&amp;", "&");
781
- const alreadyResponsive = SRCSET_ATTR_RE.test(attrs);
782
818
  const variants =
783
- config.optimize && src !== "" && !alreadyResponsive
819
+ config.optimize && src !== ""
784
820
  ? await resolveVariants(
785
821
  src,
786
- DATA_NO_OPT_RE.test(attrs),
822
+ // An image that already carries a candidate list is its author's.
823
+ DATA_NO_OPT_RE.test(attrs) || hasAttr(attrs, "srcset"),
787
824
  config,
788
825
  projectRoot,
789
826
  cache,
@@ -793,11 +830,26 @@ async function transformInnerHtmlImages(
793
830
  )
794
831
  : null;
795
832
 
833
+ // The tag, then the layout, then the project: the order the node half resolves `sizes` in.
834
+ const ownSizes = attrValue(attrs, "sizes");
835
+ const resolvedSizes = ownSizes ?? sizesForContainer(containerWidth) ?? config.sizes;
836
+
837
+ let written = attrs;
796
838
  let extra = "";
797
839
  if (variants && variants.srcset !== "") {
798
- extra += ` srcset="${variants.srcset}" sizes="${config.sizes}"`;
840
+ extra += ` srcset="${variants.srcset}"`;
841
+ if (ownSizes === undefined && resolvedSizes !== undefined && resolvedSizes !== "") {
842
+ extra += ` sizes="${resolvedSizes}"`;
843
+ }
844
+ const { fallbackSrc } = variants;
845
+ if (fallbackSrc !== undefined) {
846
+ written = attrs.replace(
847
+ SRC_ATTR_RE,
848
+ (_match, space: string) => `${space}src="${fallbackSrc}"`,
849
+ );
850
+ }
799
851
  }
800
- if (variants?.dims && !/\bwidth=/.test(attrs) && !/\bheight=/.test(attrs)) {
852
+ if (variants?.dims && !hasAttr(attrs, "width") && !hasAttr(attrs, "height")) {
801
853
  extra += ` width="${variants.dims.width}" height="${variants.dims.height}"`;
802
854
  }
803
855
  const loading = imgLoadingAttrs(
@@ -818,8 +870,8 @@ async function transformInnerHtmlImages(
818
870
 
819
871
  const img =
820
872
  variants && variants.sources.length > 0
821
- ? renderPictureTag(attrs, variants.sources, config.sizes, extra)
822
- : `<img${attrs}${extra}>`;
873
+ ? renderPictureTag(written, variants.sources, resolvedSizes, extra)
874
+ : `<img${written}${extra}>`;
823
875
  replacements.push({ match: tag, replacement: img });
824
876
  }
825
877
 
@@ -836,31 +888,46 @@ async function transformInnerHtmlImages(
836
888
  *
837
889
  * @param {string} attrs - The original tag's attribute string
838
890
  * @param {readonly PictureSource[]} sources
839
- * @param {string} sizes
891
+ * @param {string | undefined} sizes - The resolved `sizes`, the tag's own included
840
892
  * @param {string} extra - Attributes this pass decided to add
841
893
  * @returns {string}
842
894
  */
843
895
  function renderPictureTag(
844
896
  attrs: string,
845
897
  sources: readonly PictureSource[],
846
- sizes: string,
898
+ sizes: string | undefined,
847
899
  extra: string,
848
900
  ) {
849
- const inheritedSizes = attrValue(attrs, "sizes") ?? sizes;
901
+ const imgAttrs = attrs.replace(SIZES_ATTR_RE, "");
850
902
  const imgExtra = extra.replace(/ srcset="[^"]*"/, "").replace(/ sizes="[^"]*"/, "");
903
+ // An empty `sizes` is not a neutral default: leave it off and the browser assumes 100vw.
904
+ const sizesAttr = sizes === undefined || sizes === "" ? "" : ` sizes="${sizes}"`;
851
905
  const sourceTags = sources
852
- .map((s) => `<source type="${s.type}" srcset="${s.srcset}" sizes="${inheritedSizes}">`)
906
+ .map((s) => `<source type="${s.type}" srcset="${s.srcset}"${sizesAttr}>`)
853
907
  .join("");
854
- return `<picture>${sourceTags}<img${attrs}${imgExtra}></picture>`;
908
+ return `<picture>${sourceTags}<img${imgAttrs}${imgExtra}></picture>`;
855
909
  }
856
910
 
857
911
  /**
858
- * Read one double-quoted attribute out of a raw tag attribute string.
912
+ * Read one double-quoted attribute out of a raw tag attribute string. The name is matched whole:
913
+ * `data-src` is not `src`.
859
914
  *
860
915
  * @param {string} attrs
861
916
  * @param {string} name
862
917
  * @returns {string | undefined}
863
918
  */
864
919
  function attrValue(attrs: string, name: string): string | undefined {
865
- return new RegExp(`\\b${name}="([^"]*)"`, "i").exec(attrs)?.[1];
920
+ return new RegExp(`(?:^|\\s)${name}="([^"]*)"`, "i").exec(attrs)?.[1];
921
+ }
922
+
923
+ /**
924
+ * Whether a raw tag attribute string sets an attribute. The name is matched whole: a lazy-loader's
925
+ * `data-srcset` is not an authored `srcset`, and `data-width` is not `width`.
926
+ *
927
+ * @param {string} attrs
928
+ * @param {string} name
929
+ * @returns {boolean}
930
+ */
931
+ function hasAttr(attrs: string, name: string): boolean {
932
+ return new RegExp(`(?:^|\\s)${name}=`, "i").test(attrs);
866
933
  }
@@ -12,8 +12,8 @@
12
12
  *
13
13
  * The conventions themselves live in `@jxsuite/site/routes`, not here. The studio and the cloud
14
14
  * preview both have to answer "what URL is this file" and neither can import this package — its
15
- * dependency graph carries `sharp` and `esbuild` — so what remains in this file is the part that
16
- * genuinely needs a filesystem: the walk, the `$layout` peek, and `$paths` expansion.
15
+ * dependency graph carries a native addon and `esbuild` — so what remains in this file is the part
16
+ * that genuinely needs a filesystem: the walk, the `$layout` peek, and `$paths` expansion.
17
17
  */
18
18
 
19
19
  import { erasedDocument } from "../erased.ts";
@@ -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 [];