@jxsuite/compiler 8.6.0 → 9.0.1

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.
@@ -1,17 +1,18 @@
1
1
  /**
2
- * Image-optimizer.js — Sharp wrapper for image resizing and format conversion.
2
+ * Image-optimizer — responsive image variants, encoded by the compiler's Rust core.
3
3
  *
4
- * Generates responsive image variants (WebP, AVIF) at configured breakpoint widths. Returns an
5
- * ImageManifest describing all generated variants with their output paths.
4
+ * Generates the variants of one source image (AVIF, JPEG, PNG, lossless WebP) at the configured
5
+ * breakpoint widths, and returns an ImageManifest describing them. The pixels never enter
6
+ * JavaScript: `@jxsuite/compiler-binding` decodes, orients, converts to sRGB, resizes and encodes
7
+ * in process, in parallel across a source's variants (compiler.md §7.2).
6
8
  */
7
9
 
8
10
  import { createHash } from "node:crypto";
9
- import { errorMessage } from "@jxsuite/schema/parse";
10
- import { existsSync, mkdirSync, readFileSync } from "node:fs";
11
+ import { readFileSync } from "node:fs";
11
12
  import { basename, extname, resolve } from "node:path";
12
- import { createRequire } from "node:module";
13
- // Sharp 0.35 only has a default export (function merged with a types namespace).
14
- import type SharpNS from "sharp";
13
+ import { imageMetadata, processImage as encodeVariants } from "@jxsuite/compiler-binding";
14
+
15
+ import type { ImageQuality } from "@jxsuite/compiler-binding";
15
16
 
16
17
  export interface ImageVariant {
17
18
  width: number; // Pixel width of the variant
@@ -23,13 +24,18 @@ export interface ImageVariant {
23
24
  export interface ImageManifest {
24
25
  variants: ImageVariant[]; // Array of generated responsive variants
25
26
  contentHash: string; // 8-char content hash for cache busting
26
- original?: { width: number; height: number }; // Original image dimensions
27
+ original?: { width: number; height: number; format?: string }; // Original image dimensions
27
28
  }
28
29
 
29
30
  export interface ImageConfig {
30
31
  optimize: boolean;
31
32
  widths: number[];
32
33
  formats: string[];
34
+ /**
35
+ * Lossy quality per format, 1 to 100. The build service reads `avif` and `jpeg`: PNG is lossless,
36
+ * and so is WebP as this compiler writes it. `webp` is still read by the Cloudflare service, as
37
+ * the quality of its transform URLs; `png` is accepted so existing projects still validate.
38
+ */
33
39
  quality: { webp?: number; avif?: number; jpeg?: number; png?: number };
34
40
  sizes: string;
35
41
  lazyLoad: boolean;
@@ -49,74 +55,19 @@ export interface ImageConfig {
49
55
  remoteDomains?: string[];
50
56
  }
51
57
 
52
- type SharpModule = typeof SharpNS;
53
- /**
54
- * Accepted output-format type, derived from the Sharp instance's own toFormat signature. Reaching
55
- * into the `SharpNS.FormatEnum` namespace instead is fragile: sharp ships as `export = sharp`, so
56
- * whether a default type-import exposes the merged namespace depends on esModuleInterop resolution
57
- * (differs local vs CI).
58
- */
59
- type SharpFormat = Parameters<ReturnType<SharpModule>["toFormat"]>[0];
60
-
61
- let _sharp: SharpModule | null = null;
62
-
63
- async function getSharp() {
64
- if (_sharp) {
65
- return _sharp;
66
- }
67
- // Primary: dynamic import — works in tests (mock.module intercepts it) and in
68
- // Production installs where @img/sharp-* native packages are adjacent to cli.js.
69
- try {
70
- const sharpMod = await import("sharp");
71
- _sharp = sharpMod.default;
72
- return _sharp;
73
- } catch {
74
- // Fall through to CJS fallback below.
75
- }
76
- // Fallback: resolve from the project being compiled. This covers symlinked
77
- // Monorepo dev environments (e.g. NixOS) where Node.js resolves import.meta.url
78
- // To the compiler package's real path, making the @img/sharp-* packages
79
- // Unreachable via the primary import path.
80
- try {
81
- const req = createRequire(resolve(process.cwd(), "package.json"));
82
- // SAFETY: sharp's CommonJS entry is `module.exports = sharp`, the value its ESM default exports.
83
- _sharp = req("sharp") as SharpModule;
84
- return _sharp;
85
- } catch (error) {
86
- throw new Error(
87
- `Sharp is required for image optimization but failed to load: ${errorMessage(error)}`,
88
- { cause: error },
89
- );
90
- }
91
- }
92
-
93
58
  const OPTIMIZED_DIR = "images/_optimized";
94
59
 
95
60
  /**
96
- * The part of sharp's metadata this module reads, with every member optional. The sharp these types
97
- * describe always reports all three, but `getSharp` may load the project's own copy instead, and
98
- * sharp before 0.34 declared each of them optional.
99
- */
100
- interface ReportedMetadata {
101
- format?: string;
102
- height?: number;
103
- width?: number;
104
- }
105
-
106
- /**
107
- * Get image metadata (dimensions and format) via Sharp.
61
+ * Get an image's dimensions and format, reading only its header.
62
+ *
63
+ * The dimensions are the ones a viewer sees: an EXIF orientation that turns the image on its side
64
+ * has already exchanged them.
108
65
  *
109
66
  * @param {string} srcPath - Absolute path to source image
110
67
  * @returns {Promise<{ width: number; height: number; format: string }>}
111
68
  */
112
69
  export async function getImageMetadata(srcPath: string) {
113
- const sharp = await getSharp();
114
- const meta: ReportedMetadata = await sharp(srcPath).metadata();
115
- return {
116
- format: meta.format ?? "unknown",
117
- height: meta.height ?? 0,
118
- width: meta.width ?? 0,
119
- };
70
+ return imageMetadata(srcPath);
120
71
  }
121
72
 
122
73
  /**
@@ -131,24 +82,41 @@ export function contentHash(srcPath: string) {
131
82
  }
132
83
 
133
84
  /**
134
- * Compute a config hash from the image optimization settings.
85
+ * Bumped whenever the pipeline produces different output for the same source and settings.
135
86
  *
136
- * @param {ImageConfig} config
137
- * @returns {string}
87
+ * It is part of two things. The cache key is settings plus source bytes, which answers "would this
88
+ * produce the same output?" only while the code between them is fixed; capping variants at the
89
+ * largest configured width changed the answer for every image already cached, and without a version
90
+ * those images kept their stale manifests. And a variant's file name carries it (`variantHash`),
91
+ * because `/images/_optimized/*` is served as immutable: the same name must always be the same
92
+ * bytes, and a new encoder writes different bytes for an unchanged source.
93
+ *
94
+ * 1 → 2: variants stop at the largest configured width (compiler.md §7.2).
95
+ *
96
+ * 2 → 3: the Rust core encodes. EXIF orientation is applied, embedded colour profiles are converted
97
+ * to sRGB, WebP is lossless, and a transparent source asked for as JPEG is PNG.
138
98
  */
99
+ const PIPELINE_VERSION = 3;
100
+
139
101
  /**
140
- * Bumped whenever the pipeline decides variants differently for the same settings.
102
+ * The hash in a variant's file name: the source's bytes and the pipeline that encoded them.
141
103
  *
142
- * The cache key is settings plus source bytes, which answers "would this produce the same output?"
143
- * only while the code between them is fixed. It is not: capping variants at the largest configured
144
- * width changed the answer for every image already cached, and without a version here those images
145
- * keep their stale manifests — including the oversized variants the change exists to stop
146
- * emitting.
147
- *
148
- * 1 → 2: variants stop at the largest configured width (compiler.md §7.2).
104
+ * @param {string} srcPath - Absolute path to source image
105
+ * @returns {string} 8-character hex hash
149
106
  */
150
- const PIPELINE_VERSION = 2;
107
+ export function variantHash(srcPath: string) {
108
+ return createHash("md5")
109
+ .update(`${contentHash(srcPath)}:${PIPELINE_VERSION}`)
110
+ .digest("hex")
111
+ .slice(0, 8);
112
+ }
151
113
 
114
+ /**
115
+ * Compute a config hash from the image optimization settings.
116
+ *
117
+ * @param {ImageConfig} config
118
+ * @returns {string}
119
+ */
152
120
  export function configHash(config: ImageConfig) {
153
121
  const key = JSON.stringify({
154
122
  formats: config.formats,
@@ -159,98 +127,51 @@ export function configHash(config: ImageConfig) {
159
127
  return createHash("md5").update(key).digest("hex").slice(0, 8);
160
128
  }
161
129
 
162
- /**
163
- * Build the output filename for a variant.
164
- *
165
- * @param {string} stem - Original filename without extension
166
- * @param {number} width
167
- * @param {string} hash8 - 8-char content hash
168
- * @param {string} format - "webp", "avif", "jpeg", "png"
169
- * @returns {string}
170
- */
171
- export function variantFilename(stem: string, width: number, hash8: string, format: string) {
172
- return `${stem}-${width}-${hash8}.${format}`;
173
- }
174
-
175
130
  /**
176
131
  * Process a single source image: resize to each configured width, encode to each format. Writes
177
132
  * variants to cacheImgDir/_optimized/ (e.g. .cache/images/_optimized/).
178
133
  *
134
+ * The width ladder is the configured one capped at the source's own width, plus the source's native
135
+ * width when it is narrower than the top rung; a source wider than the top rung stops there. A
136
+ * variant whose file already exists is not encoded again, because its name carries a hash of the
137
+ * source's bytes and the pipeline version.
138
+ *
179
139
  * @param {string} srcPath - Absolute path to source image
180
140
  * @param {string} cacheImgDir - Absolute path to the image cache directory (.cache/images/)
181
141
  * @param {ImageConfig} config
182
142
  * @returns {Promise<ImageManifest>}
183
143
  */
184
- export async function processImage(srcPath: string, cacheImgDir: string, config: ImageConfig) {
185
- const sharp = await getSharp();
186
- const meta = await getImageMetadata(srcPath);
187
- const hash8 = contentHash(srcPath);
188
- const stem = basename(srcPath, extname(srcPath));
189
-
144
+ export async function processImage(
145
+ srcPath: string,
146
+ cacheImgDir: string,
147
+ config: ImageConfig,
148
+ ): Promise<ImageManifest> {
190
149
  const optimizedDir = resolve(cacheImgDir, "_optimized");
191
- mkdirSync(optimizedDir, { recursive: true });
192
-
193
- const variants: ImageVariant[] = [];
194
-
195
- /*
196
- * The configured ladder, capped at the source's own width — upscaling only wastes bytes.
197
- *
198
- * A source SMALLER than every rung would otherwise produce no variants at all, and one that falls
199
- * between rungs would never be offered at its native resolution, so both get their own width
200
- * added. A source LARGER than the top rung does not: the largest configured width is the ceiling
201
- * the project chose, and honouring it is the point of configuring it.
202
- *
203
- * This used to add the native width unconditionally, so a 3840 px screenshot shipped a 3840 px
204
- * AVIF *and* WebP — encoded on every cold build, copied into dist, and offered as a `3840w`
205
- * candidate that no `sizes` on any real viewport would pick.
206
- */
207
- const ceiling = config.widths.length > 0 ? Math.max(...config.widths) : meta.width;
208
- const widths = config.widths.filter((w) => w <= meta.width);
209
- if (meta.width < ceiling && !widths.includes(meta.width)) {
210
- widths.push(meta.width);
150
+ const quality: ImageQuality = {};
151
+ if (config.quality.avif !== undefined) {
152
+ quality.avif = config.quality.avif;
211
153
  }
212
- if (widths.length === 0) {
213
- widths.push(meta.width);
154
+ if (config.quality.jpeg !== undefined) {
155
+ quality.jpeg = config.quality.jpeg;
214
156
  }
215
- widths.sort((a, b) => a - b);
216
-
217
- const tasks: Promise<void>[] = [];
218
-
219
- for (const width of widths) {
220
- for (const format of config.formats) {
221
- const filename = variantFilename(stem, width, hash8, format);
222
- const outputPath = `/${OPTIMIZED_DIR}/${filename}`;
223
- const absolutePath = resolve(optimizedDir, filename);
224
-
225
- variants.push({ absolutePath, format, outputPath, width });
226
-
227
- if (existsSync(absolutePath)) {
228
- continue;
229
- }
230
-
231
- /* SAFETY: `format` is a free string from project config; a name outside the four keyed
232
- qualities reads `undefined` from the lookup and takes the default of 80. */
233
- const quality = config.quality[format as keyof ImageConfig["quality"]] ?? 80;
234
- // SAFETY: toFormat checks the name itself and throws for a format sharp cannot encode.
235
- const task = sharp(srcPath)
236
- .resize(width)
237
- .toFormat(format as SharpFormat, { quality })
238
- .toFile(absolutePath)
239
- .then(() => {});
240
-
241
- tasks.push(task);
242
- }
243
- }
244
-
245
- const CONCURRENCY = 4;
246
- for (let i = 0; i < tasks.length; i += CONCURRENCY) {
247
- await Promise.all(tasks.slice(i, i + CONCURRENCY));
248
- }
249
-
157
+ const encoded = await encodeVariants({
158
+ formats: config.formats,
159
+ hash: variantHash(srcPath),
160
+ outDir: optimizedDir,
161
+ quality,
162
+ source: srcPath,
163
+ stem: basename(srcPath, extname(srcPath)),
164
+ widths: config.widths,
165
+ });
250
166
  return {
251
- contentHash: hash8,
252
- original: { format: meta.format, height: meta.height, width: meta.width },
253
- variants,
167
+ contentHash: contentHash(srcPath),
168
+ original: encoded.original,
169
+ variants: encoded.variants.map((variant) => ({
170
+ absolutePath: resolve(optimizedDir, variant.fileName),
171
+ format: variant.format,
172
+ outputPath: `/${OPTIMIZED_DIR}/${variant.fileName}`,
173
+ width: variant.width,
174
+ })),
254
175
  };
255
176
  }
256
177
 
@@ -38,6 +38,8 @@ import type { JxAttributeValue, JxDocument, JxMutableNode, JxStyle } from "@jxsu
38
38
  import type { CacheManifest } from "./image-cache.ts";
39
39
 
40
40
  const SKIP_EXTENSIONS = new Set([".svg", ".gif"]);
41
+ /** Local sources the build service leaves alone rather than re-encodes. */
42
+ const ENCODED_AS_WRITTEN = new Set([".avif"]);
41
43
  const EXTERNAL_PREFIXES = ["http://", "https://", "data:", "//"];
42
44
 
43
45
  /** Per-build memo of original image dimensions + content hash (cloudflare mode). */
@@ -46,13 +48,13 @@ export type ImageMetaCache = Map<
46
48
  { width: number | null; height: number | null; hash: string }
47
49
  >;
48
50
 
49
- let sharpWarned = false;
51
+ let dimensionsWarned = false;
50
52
 
51
53
  /**
52
54
  * 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.
55
+ * header — no variants are generated. Dimensions degrade to null when the header cannot be read (a
56
+ * format the compiler does not decode, or no native addon for this platform): srcsets are still
57
+ * emitted (fit=scale-down guards against upscaling), only the width/height attributes are skipped.
56
58
  *
57
59
  * @param {string} absoluteSrc
58
60
  * @param {ImageMetaCache} metaCache
@@ -66,8 +68,8 @@ async function resolveCfMeta(absoluteSrc: string, metaCache: ImageMetaCache) {
66
68
  const m = await getImageMetadata(absoluteSrc);
67
69
  meta = { width: m.width, height: m.height, hash };
68
70
  } catch (error) {
69
- if (!sharpWarned) {
70
- sharpWarned = true;
71
+ if (!dimensionsWarned) {
72
+ dimensionsWarned = true;
71
73
  console.warn(
72
74
  `Could not read image dimensions (${errorMessage(error)}) — ` +
73
75
  `emitting srcsets without width/height attributes.`,
@@ -497,6 +499,13 @@ async function resolveVariants(
497
499
  return { dims, sources: [], srcset };
498
500
  }
499
501
 
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). */
505
+ if (ENCODED_AS_WRITTEN.has(extname(absoluteSrc).toLowerCase())) {
506
+ return null;
507
+ }
508
+
500
509
  let manifest = imageRefs.get(absoluteSrc);
501
510
  if (!manifest) {
502
511
  manifest = await resolveManifest(absoluteSrc, src, config, projectRoot, cache!);
@@ -508,9 +517,10 @@ async function resolveVariants(
508
517
  * offered even if a stale manifest happens to hold variants of it, and one this order does not
509
518
  * know keeps the position the project gave it.
510
519
  */
520
+ const asked = writtenFormats(config.formats, manifest.variants);
511
521
  const ordered = [
512
- ...PICTURE_FORMAT_ORDER.filter((format) => config.formats.includes(format)),
513
- ...config.formats.filter((format) => !PICTURE_FORMAT_ORDER.includes(format)),
522
+ ...PICTURE_FORMAT_ORDER.filter((format) => asked.includes(format)),
523
+ ...asked.filter((format) => !PICTURE_FORMAT_ORDER.includes(format)),
514
524
  ];
515
525
  const available = ordered.flatMap((format): PictureSource[] => {
516
526
  const srcset = buildSrcset(manifest.variants, format);
@@ -529,12 +539,28 @@ async function resolveVariants(
529
539
  const wrap = config.picture !== false && available.length > 1;
530
540
  return {
531
541
  dims,
532
- fallbackSrc: fallbackVariant(manifest.variants, config.formats),
542
+ fallbackSrc: fallbackVariant(manifest.variants, asked),
533
543
  sources: wrap ? available : [],
534
544
  srcset: available[0]?.srcset ?? "",
535
545
  };
536
546
  }
537
547
 
548
+ /**
549
+ * The formats to offer for one image: the project's, with PNG added where it stands in for JPEG.
550
+ *
551
+ * 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.
554
+ */
555
+ function writtenFormats(formats: readonly string[], variants: ImageVariant[]): readonly string[] {
556
+ const standsIn =
557
+ formats.includes("jpeg") &&
558
+ !formats.includes("png") &&
559
+ variants.some((variant) => variant.format === "png") &&
560
+ !variants.some((variant) => variant.format === "jpeg");
561
+ return standsIn ? [...formats, "png"] : formats;
562
+ }
563
+
538
564
  /**
539
565
  * Formats an `<img src>` may point at without narrowing who can see the image.
540
566
  *
@@ -553,7 +579,10 @@ const UNIVERSAL_FORMATS: readonly string[] = ["jpeg", "png"];
553
579
  * smaller image nobody can decode is not an improvement.
554
580
  */
555
581
  function fallbackVariant(variants: ImageVariant[], formats: readonly string[]): string | undefined {
556
- const format = UNIVERSAL_FORMATS.find((candidate) => formats.includes(candidate));
582
+ const format = UNIVERSAL_FORMATS.find(
583
+ (candidate) =>
584
+ formats.includes(candidate) && variants.some((variant) => variant.format === candidate),
585
+ );
557
586
  if (format === undefined) {
558
587
  return undefined;
559
588
  }
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { erasedDocument } from "../erased.ts";
12
+ import { qualifiedDocument } from "./document-scripts.ts";
12
13
  import { existsSync, readFileSync } from "node:fs";
13
14
  import { parseNativeDocument } from "@jxsuite/schema/jxn";
14
15
  import { errorMessage } from "@jxsuite/schema/parse";
@@ -28,10 +29,10 @@ export function nodeLayoutLoader(projectRoot: string): (layoutRef: string) => Jx
28
29
  throw new Error(`Layout not found: ${layoutRef} (resolved to ${layoutPath})`);
29
30
  }
30
31
  try {
31
- return erasedDocument(
32
- parseNativeDocument(readFileSync(layoutPath, "utf8"), layoutPath),
33
- layoutPath,
34
- );
32
+ // Qualified here, as the layout is read, so its `#client` and the page's stay two modules
33
+ // Through the merge (spec.md §23.2).
34
+ const layout = parseNativeDocument(readFileSync(layoutPath, "utf8"), layoutPath);
35
+ return qualifiedDocument(erasedDocument(layout, layoutPath), layoutPath, projectRoot);
35
36
  } catch (error) {
36
37
  throw new Error(`Invalid layout at ${layoutPath}: ${errorMessage(error)}`, {
37
38
  cause: error,
@@ -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";
@@ -0,0 +1,63 @@
1
+ /**
2
+ * A command the project's `@jxsuite/server` holds: `jx convert` and `jx format` resolve its entry
3
+ * from the project and run it under Bun, as `jx dev` does and for the same reasons. The compiler
4
+ * cannot depend on the server, and the server ships as TypeScript this Node entry cannot load.
5
+ *
6
+ * @module server-command
7
+ * @docs framework/build/cli
8
+ */
9
+ import { spawn } from "node:child_process";
10
+ import type { ChildProcess } from "node:child_process";
11
+ import { createRequire } from "node:module";
12
+ import { join } from "node:path";
13
+ import type { ProcessLike } from "./dev-command.ts";
14
+
15
+ /**
16
+ * Resolve the entry of one of the project's server commands.
17
+ *
18
+ * @param projectRoot Absolute project root.
19
+ * @param name The command, which is the server's export of that name.
20
+ * @throws {Error} When the server package is not installed.
21
+ */
22
+ export function resolveServerEntry(projectRoot: string, name: string): string {
23
+ try {
24
+ return createRequire(join(projectRoot, "package.json")).resolve(`@jxsuite/server/${name}`);
25
+ } catch {
26
+ throw new Error(
27
+ `@jxsuite/server is not installed in ${projectRoot}. ` +
28
+ `Add it to devDependencies (e.g. \`bun add -d @jxsuite/server\`) and retry.`,
29
+ );
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Spawn one of the project's server commands under Bun.
35
+ *
36
+ * @param name The command.
37
+ * @param projectRoot Absolute project root.
38
+ * @param argv The arguments after the command.
39
+ * @param spawnImpl Injectable for tests.
40
+ * @param proc Injectable for tests.
41
+ */
42
+ export function runServerCommand(
43
+ name: string,
44
+ projectRoot: string,
45
+ argv: readonly string[],
46
+ spawnImpl: typeof spawn = spawn,
47
+ proc: ProcessLike = process,
48
+ ): ChildProcess {
49
+ const entry = resolveServerEntry(projectRoot, name);
50
+ const child = spawnImpl("bun", [entry, "--root", projectRoot, ...argv], { stdio: "inherit" });
51
+ child.on("error", (error: NodeJS.ErrnoException) => {
52
+ console.error(
53
+ error.code === "ENOENT"
54
+ ? `jx ${name} runs on Bun, which was not found on your PATH. Install it from https://bun.sh and retry.`
55
+ : `Failed to start jx ${name}: ${error.message}`,
56
+ );
57
+ proc.exitCode = 1;
58
+ });
59
+ child.on("exit", (code) => {
60
+ proc.exitCode = code ?? 0;
61
+ });
62
+ return child;
63
+ }
@@ -32,13 +32,19 @@ export const SERVICE_WORKER_PATH = "sw.js";
32
32
  /**
33
33
  * The one path family safe to serve cache-first.
34
34
  *
35
- * It is the build's only content-addressed output — `variantFilename()` embeds a digest of the
35
+ * It is the build's only content-addressed output — a variant's file name embeds a digest of the
36
36
  * source bytes, so a changed image is a changed URL and a cached one can never be wrong. Everything
37
37
  * else is named after what it contains rather than after its content (`_headers` says the same in
38
38
  * `NEVER_IMMUTABLE`), so caching it first would serve edited components from a stale entry.
39
39
  */
40
40
  export const CACHE_FIRST_PREFIX = "/images/_optimized/";
41
41
 
42
+ /**
43
+ * The subtree the site worker answers (compiler.md §6.4): sessions, table rows and server-function
44
+ * results. The emitted worker leaves every request under it alone.
45
+ */
46
+ export const DYNAMIC_PREFIX = "/_jx";
47
+
42
48
  export interface ServiceWorkerOutput {
43
49
  /** Path relative to `outDir`, or null when nothing should be emitted. */
44
50
  path: string | null;
@@ -152,6 +158,7 @@ export function buildServiceWorker(
152
158
  const cachedPrecache = precache.map((url) => withBase(base, url));
153
159
  const cacheFirst = withBase(base, CACHE_FIRST_PREFIX);
154
160
  const offlineFallback = fallback === undefined ? null : withBase(base, fallback);
161
+ const dynamic = `${withBase(base, DYNAMIC_PREFIX)}/`;
155
162
 
156
163
  const cache = `jx-${configId(config)}`;
157
164
  const source = `/*
@@ -162,6 +169,11 @@ const CACHE = ${JSON.stringify(cache)};
162
169
  const PRECACHE = ${JSON.stringify(cachedPrecache)};
163
170
  const CACHE_FIRST = ${JSON.stringify(cacheFirst)};
164
171
  const OFFLINE_FALLBACK = ${JSON.stringify(offlineFallback)};
172
+ const DYNAMIC = ${JSON.stringify(dynamic)};
173
+
174
+ // A response its server marked as one visitor's, or as not to be kept, is never written to a cache.
175
+ const storable = (res) =>
176
+ res.ok && !/\\b(?:no-store|private)\\b/i.test(res.headers.get("Cache-Control") ?? "");
165
177
 
166
178
  self.addEventListener("install", (event) => {
167
179
  // Take over as soon as possible: a half-updated pair of workers is harder to reason about than
@@ -202,6 +214,12 @@ self.addEventListener("fetch", (event) => {
202
214
  if (request.method !== "GET") return;
203
215
  const url = new URL(request.url);
204
216
  if (url.origin !== self.location.origin) return;
217
+ /*
218
+ * Sessions and application data. They are answered by the site worker for one visitor at one
219
+ * moment, so a cached copy is somebody's rows served after sign-out, or to the next person on the
220
+ * device. Not handled at all: the request goes to the network exactly as if no worker existed.
221
+ */
222
+ if (url.pathname.startsWith(DYNAMIC)) return;
205
223
 
206
224
  // Content-addressed output only: the filename embeds a digest, so a hit can never be stale.
207
225
  if (url.pathname.startsWith(CACHE_FIRST)) {
@@ -227,7 +245,7 @@ self.addEventListener("fetch", (event) => {
227
245
  (async () => {
228
246
  try {
229
247
  const res = await fetch(request);
230
- if (res.ok) {
248
+ if (storable(res)) {
231
249
  const copy = res.clone();
232
250
  caches.open(CACHE).then((c) => c.put(request, copy));
233
251
  }