@jxsuite/compiler 9.0.1 → 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.
- package/dist/cli.js +204 -205
- package/dist/compiler.js +134 -138
- package/package.json +18 -18
- package/src/cli.ts +13 -3
- package/src/compiler.ts +25 -12
- package/src/shared.ts +560 -118
- package/src/site/bundler-backend.bun.ts +36 -2
- package/src/site/bundler-backend.node.ts +42 -2
- package/src/site/bundler-backend.ts +12 -0
- package/src/site/bundler.ts +40 -4
- package/src/site/external-class.ts +290 -0
- package/src/site/format-host.ts +49 -10
- package/src/site/headers-emitter.ts +6 -5
- package/src/site/image-cache.ts +34 -3
- package/src/site/image-optimizer.ts +51 -11
- package/src/site/image-transform.ts +100 -62
- package/src/site/pages-discovery.ts +8 -1
- package/src/site/prototype-resolver.ts +91 -195
- package/src/site/service-worker.ts +4 -3
- package/src/site/site-build.ts +179 -14
- package/src/site/site-loader.ts +9 -0
- package/src/targets/compile-class.ts +42 -3
- package/src/targets/compile-client.ts +177 -55
- package/src/targets/compile-element.ts +308 -46
- package/src/targets/compile-static.ts +21 -83
|
@@ -10,7 +10,11 @@
|
|
|
10
10
|
import { createHash } from "node:crypto";
|
|
11
11
|
import { readFileSync } from "node:fs";
|
|
12
12
|
import { basename, extname, resolve } from "node:path";
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
DEFAULT_IMAGE_QUALITY,
|
|
15
|
+
imageMetadata,
|
|
16
|
+
processImage as encodeVariants,
|
|
17
|
+
} from "@jxsuite/compiler-binding";
|
|
14
18
|
|
|
15
19
|
import type { ImageQuality } from "@jxsuite/compiler-binding";
|
|
16
20
|
|
|
@@ -37,7 +41,8 @@ export interface ImageConfig {
|
|
|
37
41
|
* the quality of its transform URLs; `png` is accepted so existing projects still validate.
|
|
38
42
|
*/
|
|
39
43
|
quality: { webp?: number; avif?: number; jpeg?: number; png?: number };
|
|
40
|
-
sizes
|
|
44
|
+
/** The project-wide fallback `sizes`. A site build always has one; a direct caller may not. */
|
|
45
|
+
sizes?: string;
|
|
41
46
|
lazyLoad: boolean;
|
|
42
47
|
/**
|
|
43
48
|
* Wrap a multi-format image in a `<picture>` with one `<source>` per format. Default true.
|
|
@@ -91,22 +96,52 @@ export function contentHash(srcPath: string) {
|
|
|
91
96
|
* because `/images/_optimized/*` is served as immutable: the same name must always be the same
|
|
92
97
|
* bytes, and a new encoder writes different bytes for an unchanged source.
|
|
93
98
|
*
|
|
94
|
-
* 1 → 2: variants stop at the largest configured width (
|
|
99
|
+
* 1 → 2: variants stop at the largest configured width (site-architecture.md §9.2.2).
|
|
95
100
|
*
|
|
96
101
|
* 2 → 3: the Rust core encodes. EXIF orientation is applied, embedded colour profiles are converted
|
|
97
102
|
* to sRGB, WebP is lossless, and a transparent source asked for as JPEG is PNG.
|
|
103
|
+
*
|
|
104
|
+
* 3 → 4: a variant's filename digest covers its format and that format's quality
|
|
105
|
+
* (site-architecture.md §9.2.5).
|
|
106
|
+
*/
|
|
107
|
+
const PIPELINE_VERSION = 4;
|
|
108
|
+
|
|
109
|
+
/** The quality recorded for a format the encoder writes losslessly and the project gave none. */
|
|
110
|
+
const LOSSLESS_QUALITY = 100;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The quality one format is encoded at: the project's, else the encoder's default for it.
|
|
114
|
+
*
|
|
115
|
+
* @param {ImageConfig["quality"]} quality
|
|
116
|
+
* @param {string} format
|
|
117
|
+
* @returns {number}
|
|
98
118
|
*/
|
|
99
|
-
|
|
119
|
+
export function qualityFor(quality: ImageConfig["quality"], format: string): number {
|
|
120
|
+
const configured = new Map<string, number | undefined>(Object.entries(quality)).get(format);
|
|
121
|
+
if (configured !== undefined) {
|
|
122
|
+
return configured;
|
|
123
|
+
}
|
|
124
|
+
const defaults = new Map<string, number>(Object.entries(DEFAULT_IMAGE_QUALITY));
|
|
125
|
+
return defaults.get(format) ?? LOSSLESS_QUALITY;
|
|
126
|
+
}
|
|
100
127
|
|
|
101
128
|
/**
|
|
102
|
-
* The hash in a variant's file name: the source's bytes
|
|
129
|
+
* The hash in a variant's file name: the source's bytes, the pipeline that encoded them, and the
|
|
130
|
+
* format and quality they were encoded at.
|
|
131
|
+
*
|
|
132
|
+
* The settings are in it because the encoder keeps a variant whose file already exists, and
|
|
133
|
+
* `/images/_optimized/*` is served as immutable. Named from the source alone, a changed quality
|
|
134
|
+
* found the old files under the same names and kept them, and a host with a cold cache shipped new
|
|
135
|
+
* bytes at a URL returning visitors held for a year.
|
|
103
136
|
*
|
|
104
137
|
* @param {string} srcPath - Absolute path to source image
|
|
138
|
+
* @param {string} format - The format the variant was asked for in
|
|
139
|
+
* @param {number} quality - The quality that format is encoded at
|
|
105
140
|
* @returns {string} 8-character hex hash
|
|
106
141
|
*/
|
|
107
|
-
export function variantHash(srcPath: string) {
|
|
142
|
+
export function variantHash(srcPath: string, format: string, quality: number) {
|
|
108
143
|
return createHash("md5")
|
|
109
|
-
.update(`${contentHash(srcPath)}:${PIPELINE_VERSION}`)
|
|
144
|
+
.update(`${contentHash(srcPath)}:${PIPELINE_VERSION}:${format}:${quality}`)
|
|
110
145
|
.digest("hex")
|
|
111
146
|
.slice(0, 8);
|
|
112
147
|
}
|
|
@@ -129,15 +164,15 @@ export function configHash(config: ImageConfig) {
|
|
|
129
164
|
|
|
130
165
|
/**
|
|
131
166
|
* Process a single source image: resize to each configured width, encode to each format. Writes
|
|
132
|
-
* variants to cacheImgDir/_optimized
|
|
167
|
+
* variants to cacheImgDir/_optimized/, the image cache (`getImageCacheDir`).
|
|
133
168
|
*
|
|
134
169
|
* The width ladder is the configured one capped at the source's own width, plus the source's native
|
|
135
170
|
* width when it is narrower than the top rung; a source wider than the top rung stops there. A
|
|
136
171
|
* variant whose file already exists is not encoded again, because its name carries a hash of the
|
|
137
|
-
* source's bytes
|
|
172
|
+
* source's bytes, the pipeline version, and its format and quality (`variantHash`).
|
|
138
173
|
*
|
|
139
174
|
* @param {string} srcPath - Absolute path to source image
|
|
140
|
-
* @param {string} cacheImgDir - Absolute path to the image cache directory
|
|
175
|
+
* @param {string} cacheImgDir - Absolute path to the image cache directory
|
|
141
176
|
* @param {ImageConfig} config
|
|
142
177
|
* @returns {Promise<ImageManifest>}
|
|
143
178
|
*/
|
|
@@ -156,7 +191,12 @@ export async function processImage(
|
|
|
156
191
|
}
|
|
157
192
|
const encoded = await encodeVariants({
|
|
158
193
|
formats: config.formats,
|
|
159
|
-
|
|
194
|
+
hashes: Object.fromEntries(
|
|
195
|
+
config.formats.map((format) => [
|
|
196
|
+
format,
|
|
197
|
+
variantHash(srcPath, format, qualityFor(config.quality, format)),
|
|
198
|
+
]),
|
|
199
|
+
),
|
|
160
200
|
outDir: optimizedDir,
|
|
161
201
|
quality,
|
|
162
202
|
source: srcPath,
|
|
@@ -37,9 +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
|
-
|
|
41
|
-
|
|
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
|
+
*/
|
|
42
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"]);
|
|
43
58
|
const EXTERNAL_PREFIXES = ["http://", "https://", "data:", "//"];
|
|
44
59
|
|
|
45
60
|
/** Per-build memo of original image dimensions + content hash (cloudflare mode). */
|
|
@@ -178,10 +193,8 @@ function shouldSkip(src: string) {
|
|
|
178
193
|
if (EXTERNAL_PREFIXES.some((p) => src.startsWith(p))) {
|
|
179
194
|
return true;
|
|
180
195
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
}
|
|
184
|
-
return false;
|
|
196
|
+
const extension = extname(src).toLowerCase();
|
|
197
|
+
return !RASTER_EXTENSIONS.has(extension) && !ENCODED_AS_WRITTEN.has(extension);
|
|
185
198
|
}
|
|
186
199
|
|
|
187
200
|
/**
|
|
@@ -210,7 +223,7 @@ function isAllowedRemote(src: string, config: ImageConfig) {
|
|
|
210
223
|
}
|
|
211
224
|
try {
|
|
212
225
|
const url = new URL(src);
|
|
213
|
-
if (
|
|
226
|
+
if (REMOTE_SKIP_EXTENSIONS.has(extname(url.pathname).toLowerCase())) {
|
|
214
227
|
return false;
|
|
215
228
|
}
|
|
216
229
|
return config.remoteDomains.includes(url.hostname);
|
|
@@ -318,8 +331,8 @@ function applyFocalPoint(
|
|
|
318
331
|
* Transform image nodes in a Jx document tree.
|
|
319
332
|
*
|
|
320
333
|
* Mutates img nodes in place, injecting srcset, sizes, width, height, loading, and decoding.
|
|
321
|
-
* Optimized variants are written to
|
|
322
|
-
*
|
|
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.
|
|
323
336
|
*
|
|
324
337
|
* @param {JxMutableNode | JxDocument} doc - The Jx document tree (mutated in place)
|
|
325
338
|
* @param {ImageConfig} config
|
|
@@ -343,15 +356,6 @@ export async function transformImageNodes(
|
|
|
343
356
|
return { imageRefs };
|
|
344
357
|
}
|
|
345
358
|
|
|
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
359
|
async function walkAndTransform(
|
|
356
360
|
node: JxMutableNode | JxDocument,
|
|
357
361
|
config: ImageConfig,
|
|
@@ -390,11 +394,13 @@ async function walkAndTransform(
|
|
|
390
394
|
metaCache,
|
|
391
395
|
imageRefs,
|
|
392
396
|
mounts,
|
|
397
|
+
// The node holding the content is the innermost container of every image in it.
|
|
398
|
+
containerWidthOf(node, containerWidth),
|
|
393
399
|
);
|
|
394
400
|
}
|
|
395
401
|
|
|
396
402
|
if (Array.isArray(node.children)) {
|
|
397
|
-
// 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.
|
|
398
404
|
const inner = containerWidthOf(node, containerWidth);
|
|
399
405
|
for (const child of node.children) {
|
|
400
406
|
// Text children carry no images, and a non-object child (an authored `null`) is skipped.
|
|
@@ -447,11 +453,11 @@ interface ResolvedVariants {
|
|
|
447
453
|
* Generate (or look up) this image's variants and describe what the markup should say.
|
|
448
454
|
*
|
|
449
455
|
* 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
|
|
451
|
-
* 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.
|
|
452
458
|
*
|
|
453
459
|
* @param {JxAttributeValue | undefined} src - The `src` as written, which may be bound or absent
|
|
454
|
-
* @param {boolean} optedOut - `data-no-optimize` is present
|
|
460
|
+
* @param {boolean} optedOut - `data-no-optimize` or an authored `srcset` is present
|
|
455
461
|
* @param {ImageConfig} config
|
|
456
462
|
* @param {string} projectRoot
|
|
457
463
|
* @param {CacheManifest | null} cache
|
|
@@ -499,9 +505,7 @@ async function resolveVariants(
|
|
|
499
505
|
return { dims, sources: [], srcset };
|
|
500
506
|
}
|
|
501
507
|
|
|
502
|
-
|
|
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). */
|
|
508
|
+
// An AVIF source is already in the best format every variant would be converted to.
|
|
505
509
|
if (ENCODED_AS_WRITTEN.has(extname(absoluteSrc).toLowerCase())) {
|
|
506
510
|
return null;
|
|
507
511
|
}
|
|
@@ -549,8 +553,9 @@ async function resolveVariants(
|
|
|
549
553
|
* The formats to offer for one image: the project's, with PNG added where it stands in for JPEG.
|
|
550
554
|
*
|
|
551
555
|
* JPEG has no alpha channel, so the encoder writes PNG wherever JPEG was asked of a source with
|
|
552
|
-
* transparency (
|
|
553
|
-
* other format the project did not list stays out even if a stale manifest holds
|
|
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.
|
|
554
559
|
*/
|
|
555
560
|
function writtenFormats(formats: readonly string[], variants: ImageVariant[]): readonly string[] {
|
|
556
561
|
const standsIn =
|
|
@@ -595,15 +600,6 @@ function fallbackVariant(variants: ImageVariant[], formats: readonly string[]):
|
|
|
595
600
|
return best && variantUrl(best.outputPath);
|
|
596
601
|
}
|
|
597
602
|
|
|
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
603
|
const CSS_LENGTH = /^(\d+(?:\.\d+)?)(px|rem)$/;
|
|
608
604
|
|
|
609
605
|
/** A CSS length in px, but only when it is a plain `px`/`rem` literal. `null` for anything else. */
|
|
@@ -620,7 +616,8 @@ function pxLength(value: JxStyle[string]): number | null {
|
|
|
620
616
|
}
|
|
621
617
|
|
|
622
618
|
/**
|
|
623
|
-
* The narrowest
|
|
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).
|
|
624
621
|
*
|
|
625
622
|
* Only literal lengths count. A `clamp()`, a percentage or a custom property is a real constraint
|
|
626
623
|
* too, but not one the build can resolve — and a wrong `sizes` is worse than none, because the
|
|
@@ -635,11 +632,13 @@ function containerWidthOf(
|
|
|
635
632
|
if (!isNonNullObject(style)) {
|
|
636
633
|
return inherited;
|
|
637
634
|
}
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
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
|
+
}
|
|
641
640
|
}
|
|
642
|
-
return
|
|
641
|
+
return narrowest;
|
|
643
642
|
}
|
|
644
643
|
|
|
645
644
|
/**
|
|
@@ -688,7 +687,8 @@ async function transformImgNode(
|
|
|
688
687
|
const variants = config.optimize
|
|
689
688
|
? await resolveVariants(
|
|
690
689
|
attrs.src,
|
|
691
|
-
|
|
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,
|
|
692
692
|
config,
|
|
693
693
|
projectRoot,
|
|
694
694
|
cache,
|
|
@@ -709,7 +709,9 @@ async function transformImgNode(
|
|
|
709
709
|
if (variants) {
|
|
710
710
|
if (variants.srcset !== "") {
|
|
711
711
|
attrs.srcset = variants.srcset;
|
|
712
|
-
|
|
712
|
+
if (resolvedSizes !== undefined) {
|
|
713
|
+
attrs.sizes = resolvedSizes;
|
|
714
|
+
}
|
|
713
715
|
if (variants.fallbackSrc !== undefined) {
|
|
714
716
|
attrs.src = variants.fallbackSrc;
|
|
715
717
|
}
|
|
@@ -740,12 +742,12 @@ async function transformImgNode(
|
|
|
740
742
|
*
|
|
741
743
|
* @param {JxMutableNode | JxDocument} node - The `<img>` node, mutated into a `<picture>`
|
|
742
744
|
* @param {PictureSource[]} sources
|
|
743
|
-
* @param {JxAttributeValue} sizes
|
|
745
|
+
* @param {JxAttributeValue | undefined} sizes - The resolved `sizes`, when anything names one
|
|
744
746
|
*/
|
|
745
747
|
function wrapInPicture(
|
|
746
748
|
node: JxMutableNode | JxDocument,
|
|
747
749
|
sources: readonly PictureSource[],
|
|
748
|
-
sizes: JxAttributeValue,
|
|
750
|
+
sizes: JxAttributeValue | undefined,
|
|
749
751
|
) {
|
|
750
752
|
const imgAttrs = { ...node.attributes };
|
|
751
753
|
const inheritedSizes = imgAttrs.sizes ?? sizes;
|
|
@@ -760,7 +762,7 @@ function wrapInPicture(
|
|
|
760
762
|
const children = sources.map((source): JxMutableNode => {
|
|
761
763
|
const attributes: Record<string, JxAttributeValue> = {};
|
|
762
764
|
// An empty `sizes` is not a neutral default — omit it and let the browser assume 100vw.
|
|
763
|
-
if (inheritedSizes !== "") {
|
|
765
|
+
if (inheritedSizes !== undefined && inheritedSizes !== "") {
|
|
764
766
|
attributes.sizes = inheritedSizes;
|
|
765
767
|
}
|
|
766
768
|
attributes.srcset = source.srcset;
|
|
@@ -775,11 +777,15 @@ function wrapInPicture(
|
|
|
775
777
|
}
|
|
776
778
|
|
|
777
779
|
const IMG_TAG_RE = /<img\b([^>]*)>/gi;
|
|
778
|
-
const SRCSET_ATTR_RE = /\bsrcset="/;
|
|
779
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;
|
|
780
783
|
|
|
781
784
|
/**
|
|
782
|
-
* 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).
|
|
783
789
|
*
|
|
784
790
|
* @param {string} html
|
|
785
791
|
* @param {ImageConfig} config
|
|
@@ -788,6 +794,7 @@ const DATA_NO_OPT_RE = /\bdata-no-optimize\b/;
|
|
|
788
794
|
* @param {ImageMetaCache} metaCache
|
|
789
795
|
* @param {Map<string, ImageManifest>} imageRefs
|
|
790
796
|
* @param {readonly AssetMount[]} mounts
|
|
797
|
+
* @param {number | null} containerWidth - The bound of the node holding this HTML
|
|
791
798
|
* @returns {Promise<string>}
|
|
792
799
|
*/
|
|
793
800
|
async function transformInnerHtmlImages(
|
|
@@ -798,6 +805,7 @@ async function transformInnerHtmlImages(
|
|
|
798
805
|
metaCache: ImageMetaCache,
|
|
799
806
|
imageRefs: Map<string, ImageManifest>,
|
|
800
807
|
mounts: readonly AssetMount[],
|
|
808
|
+
containerWidth: number | null,
|
|
801
809
|
) {
|
|
802
810
|
const replacements: { match: string; replacement: string }[] = [];
|
|
803
811
|
|
|
@@ -807,12 +815,12 @@ async function transformInnerHtmlImages(
|
|
|
807
815
|
|
|
808
816
|
// Attribute values in pre-rendered innerHTML are entity-escaped — decode for processing
|
|
809
817
|
const src = (attrValue(attrs, "src") ?? "").replaceAll("&", "&");
|
|
810
|
-
const alreadyResponsive = SRCSET_ATTR_RE.test(attrs);
|
|
811
818
|
const variants =
|
|
812
|
-
config.optimize && src !== ""
|
|
819
|
+
config.optimize && src !== ""
|
|
813
820
|
? await resolveVariants(
|
|
814
821
|
src,
|
|
815
|
-
|
|
822
|
+
// An image that already carries a candidate list is its author's.
|
|
823
|
+
DATA_NO_OPT_RE.test(attrs) || hasAttr(attrs, "srcset"),
|
|
816
824
|
config,
|
|
817
825
|
projectRoot,
|
|
818
826
|
cache,
|
|
@@ -822,11 +830,26 @@ async function transformInnerHtmlImages(
|
|
|
822
830
|
)
|
|
823
831
|
: null;
|
|
824
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;
|
|
825
838
|
let extra = "";
|
|
826
839
|
if (variants && variants.srcset !== "") {
|
|
827
|
-
extra += ` srcset="${variants.srcset}"
|
|
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
|
+
}
|
|
828
851
|
}
|
|
829
|
-
if (variants?.dims &&
|
|
852
|
+
if (variants?.dims && !hasAttr(attrs, "width") && !hasAttr(attrs, "height")) {
|
|
830
853
|
extra += ` width="${variants.dims.width}" height="${variants.dims.height}"`;
|
|
831
854
|
}
|
|
832
855
|
const loading = imgLoadingAttrs(
|
|
@@ -847,8 +870,8 @@ async function transformInnerHtmlImages(
|
|
|
847
870
|
|
|
848
871
|
const img =
|
|
849
872
|
variants && variants.sources.length > 0
|
|
850
|
-
? renderPictureTag(
|
|
851
|
-
: `<img${
|
|
873
|
+
? renderPictureTag(written, variants.sources, resolvedSizes, extra)
|
|
874
|
+
: `<img${written}${extra}>`;
|
|
852
875
|
replacements.push({ match: tag, replacement: img });
|
|
853
876
|
}
|
|
854
877
|
|
|
@@ -865,31 +888,46 @@ async function transformInnerHtmlImages(
|
|
|
865
888
|
*
|
|
866
889
|
* @param {string} attrs - The original tag's attribute string
|
|
867
890
|
* @param {readonly PictureSource[]} sources
|
|
868
|
-
* @param {string} sizes
|
|
891
|
+
* @param {string | undefined} sizes - The resolved `sizes`, the tag's own included
|
|
869
892
|
* @param {string} extra - Attributes this pass decided to add
|
|
870
893
|
* @returns {string}
|
|
871
894
|
*/
|
|
872
895
|
function renderPictureTag(
|
|
873
896
|
attrs: string,
|
|
874
897
|
sources: readonly PictureSource[],
|
|
875
|
-
sizes: string,
|
|
898
|
+
sizes: string | undefined,
|
|
876
899
|
extra: string,
|
|
877
900
|
) {
|
|
878
|
-
const
|
|
901
|
+
const imgAttrs = attrs.replace(SIZES_ATTR_RE, "");
|
|
879
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}"`;
|
|
880
905
|
const sourceTags = sources
|
|
881
|
-
.map((s) => `<source type="${s.type}" srcset="${s.srcset}"
|
|
906
|
+
.map((s) => `<source type="${s.type}" srcset="${s.srcset}"${sizesAttr}>`)
|
|
882
907
|
.join("");
|
|
883
|
-
return `<picture>${sourceTags}<img${
|
|
908
|
+
return `<picture>${sourceTags}<img${imgAttrs}${imgExtra}></picture>`;
|
|
884
909
|
}
|
|
885
910
|
|
|
886
911
|
/**
|
|
887
|
-
* 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`.
|
|
888
914
|
*
|
|
889
915
|
* @param {string} attrs
|
|
890
916
|
* @param {string} name
|
|
891
917
|
* @returns {string | undefined}
|
|
892
918
|
*/
|
|
893
919
|
function attrValue(attrs: string, name: string): string | undefined {
|
|
894
|
-
return new RegExp(
|
|
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);
|
|
895
933
|
}
|
|
@@ -576,7 +576,14 @@ async function expandPagedRoute(
|
|
|
576
576
|
);
|
|
577
577
|
return [];
|
|
578
578
|
}
|
|
579
|
-
|
|
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 [];
|