@jxsuite/compiler 8.7.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jxsuite/compiler",
3
- "version": "8.7.0",
3
+ "version": "9.0.1",
4
4
  "description": "Jx static HTML compiler, island detector, and site builder",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -54,21 +54,31 @@
54
54
  "upgrade": "bun update --latest && bun install"
55
55
  },
56
56
  "dependencies": {
57
- "@jxsuite/create": "^1.8.1",
58
- "@jxsuite/erase": "^0.3.0",
59
- "@jxsuite/runtime": "^7.0.0",
60
- "@jxsuite/schema": "^6.0.0",
61
- "@jxsuite/site": "^2.7.0",
57
+ "@jxsuite/compiler-binding": "^0.2.1",
58
+ "@jxsuite/create": "^1.8.2",
59
+ "@jxsuite/erase": "^0.3.1",
60
+ "@jxsuite/runtime": "^7.0.1",
61
+ "@jxsuite/schema": "^6.0.1",
62
+ "@jxsuite/site": "^2.7.1",
62
63
  "@vue/reactivity": "3.5.44",
63
64
  "esbuild": "^0.28.2",
64
- "lit-html": "^3.3.3",
65
- "sharp": "^0.35.5"
65
+ "lit-html": "^3.3.3"
66
66
  },
67
67
  "devDependencies": {
68
68
  "@happy-dom/global-registrator": "^21.0.4",
69
- "@jxsuite/connector": "^0.8.9",
70
- "@jxsuite/parser": "^5.0.0",
69
+ "@jxsuite/connector": "^0.8.10",
70
+ "@jxsuite/parser": "^5.0.1",
71
71
  "@jxsuite/test-support": "^0.0.0",
72
72
  "@types/mdast": "^4.0.4"
73
+ },
74
+ "optionalDependencies": {
75
+ "@jxsuite/compiler-binding-linux-x64-gnu": "0.2.1",
76
+ "@jxsuite/compiler-binding-linux-x64-musl": "0.2.1",
77
+ "@jxsuite/compiler-binding-linux-arm64-gnu": "0.2.1",
78
+ "@jxsuite/compiler-binding-linux-arm64-musl": "0.2.1",
79
+ "@jxsuite/compiler-binding-darwin-x64": "0.2.1",
80
+ "@jxsuite/compiler-binding-darwin-arm64": "0.2.1",
81
+ "@jxsuite/compiler-binding-win32-x64-msvc": "0.2.1",
82
+ "@jxsuite/compiler-binding-win32-arm64-msvc": "0.2.1"
73
83
  }
74
84
  }
@@ -31,7 +31,7 @@ export interface HeaderRuleSet {
31
31
  }
32
32
 
33
33
  /**
34
- * The only content-addressed output the build produces. `variantFilename()` embeds an 8-character
34
+ * The only content-addressed output the build produces. A variant's file name embeds an 8-character
35
35
  * digest of the source bytes, so a changed image is a changed URL and the old one can be cached
36
36
  * forever (RFC 8246).
37
37
  */
package/src/site/i18n.ts CHANGED
@@ -22,7 +22,7 @@ import { servedRoute } from "./static-host.ts";
22
22
  /*
23
23
  * `resolveI18n` and the two types beside it live in `@jxsuite/schema/locale` rather than here.
24
24
  * Studio needs the same answer and cannot import this package — there is no `./site/i18n` export,
25
- * the dependency graph carries `sharp` and `esbuild`, and Studio bundles for a browser. One
25
+ * the dependency graph carries a native addon and `esbuild`, and Studio bundles for a browser. One
26
26
  * resolution with two hosts is the only shape in which the tag Studio offers is certain to be the
27
27
  * tag the build accepts.
28
28
  *
@@ -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
  }
@@ -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";
@@ -32,7 +32,7 @@ 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.
@@ -198,6 +198,23 @@ declare module "@jxsuite/schema/format-registry" {
198
198
  const ADAPTER_REMEDY =
199
199
  'set build.adapter to "cloudflare-workers", "cloudflare-pages", "node", or "bun".';
200
200
 
201
+ /**
202
+ * The phases a build's time is divided into, in the order they run. Each is the wall-clock time
203
+ * between two points in `buildSite`, so together they account for all of `total`:
204
+ *
205
+ * - `setup`: reading the project file, the extension registry, document scripts and server mounts.
206
+ * - `content`: discovering pages, loading extension project sections (collections), asset mounts and
207
+ * expanding dynamic routes. This is extension code, not the compiler's own.
208
+ * - `components`: compiling the site's components to modules and style sheets.
209
+ * - `routes`: compiling every route, including optimizing the images each one uses.
210
+ * - `bundles`: the image cache, the server worker, client bundles and extension-emitted assets.
211
+ * - `outputs`: redirects, sitemap, copied assets, the manifest, the service worker and headers.
212
+ */
213
+ export type BuildPhase = "setup" | "content" | "components" | "routes" | "bundles" | "outputs";
214
+
215
+ /** Milliseconds per phase, and for the whole build. Measured, never estimated. */
216
+ export type BuildTimings = Record<BuildPhase | "total", number>;
217
+
201
218
  /**
202
219
  * Build an entire Jx site from a project directory.
203
220
  *
@@ -207,7 +224,7 @@ const ADAPTER_REMEDY =
207
224
  * @param {boolean} [options.verbose] - Log progress
208
225
  * @param {boolean} [options.includeHeld] - Keep entries a content type's `hold` rules match, for a
209
226
  * preview. Left off, a build leaves them out (site-architecture.md §7.6).
210
- * @returns {Promise<{ routes: number; files: number; errors: string[] }>}
227
+ * @returns {Promise<{ routes: number; files: number; errors: string[]; timings: BuildTimings }>}
211
228
  */
212
229
  export async function buildSite(
213
230
  projectRoot: string,
@@ -220,6 +237,23 @@ export async function buildSite(
220
237
  const { clean = true, includeHeld = false, verbose = false } = options;
221
238
  const errors: string[] = [];
222
239
  const log = verbose ? console.log.bind(console) : () => {};
240
+ const timings: BuildTimings = {
241
+ bundles: 0,
242
+ components: 0,
243
+ content: 0,
244
+ outputs: 0,
245
+ routes: 0,
246
+ setup: 0,
247
+ total: 0,
248
+ };
249
+ const started = performance.now();
250
+ let lap = started;
251
+ /** Close the phase that just ran: everything since the last one closed is its time. */
252
+ const closePhase = (name: BuildPhase) => {
253
+ const now = performance.now();
254
+ timings[name] = now - lap;
255
+ lap = now;
256
+ };
223
257
 
224
258
  // ── 1. Load project configuration ──────────────────────────────────────────
225
259
  log("Loading project.json...");
@@ -452,6 +486,8 @@ export async function buildSite(
452
486
  );
453
487
  }
454
488
 
489
+ closePhase("setup");
490
+
455
491
  // ── 2. Clean output directory ───────────────────────────────────────────
456
492
  if (clean && existsSync(outDir)) {
457
493
  rmSync(outDir, { force: true, recursive: true });
@@ -524,6 +560,8 @@ export async function buildSite(
524
560
 
525
561
  let fileCount = 0;
526
562
 
563
+ closePhase("content");
564
+
527
565
  // ── 5. Compile site components ──────────────────────────────────────────
528
566
  const compiledComponentTags: string[] = [];
529
567
  const componentCSS = new Map<string, string>(); // TagName → CSS text
@@ -688,11 +726,20 @@ export async function buildSite(
688
726
  }
689
727
  }
690
728
 
729
+ closePhase("components");
730
+
691
731
  // ── 6. Compile each route ───────────────────────────────────────────────
692
732
 
693
733
  const cfImages = projectConfig.images.optimize && projectConfig.images.service === "cloudflare";
694
734
  const imageCache = projectConfig.images.optimize && !cfImages ? loadCache(projectRoot) : null;
695
735
  const imageMetaCache: ImageMetaCache | null = cfImages ? new Map() : null;
736
+ if (imageCache && projectConfig.images.formats?.includes("webp")) {
737
+ console.warn(
738
+ `images.formats lists "webp", which this compiler writes losslessly: its files are several ` +
739
+ `times the size of AVIF or JPEG. Keep it only for pixel-exact output; ["avif", "jpeg"] ` +
740
+ `is the default.`,
741
+ );
742
+ }
696
743
  if (cfImages) {
697
744
  console.log(
698
745
  `images.service is "cloudflare" — srcsets use /cdn-cgi/image transform URLs. ` +
@@ -997,6 +1044,8 @@ export async function buildSite(
997
1044
  }
998
1045
  }
999
1046
 
1047
+ closePhase("routes");
1048
+
1000
1049
  // ── 6b. Save image cache and copy variants to dist ──────────────────────
1001
1050
  if (imageCache && projectConfig.images.optimize) {
1002
1051
  // Prune only on fully successful builds — a route that failed to compile never
@@ -1270,6 +1319,8 @@ export async function buildSite(
1270
1319
  }
1271
1320
  }
1272
1321
 
1322
+ closePhase("bundles");
1323
+
1273
1324
  // ── 7. Generate redirects ───────────────────────────────────────────────
1274
1325
  if (projectConfig.redirects && Object.keys(projectConfig.redirects).length > 0) {
1275
1326
  log("Generating redirects...");
@@ -1440,7 +1491,9 @@ export async function buildSite(
1440
1491
  log(` ${errors.length} error(s)`);
1441
1492
  }
1442
1493
 
1443
- return { errors, files: fileCount, routes: routes.length, serverEntries };
1494
+ closePhase("outputs");
1495
+ timings.total = performance.now() - started;
1496
+ return { errors, files: fileCount, routes: routes.length, serverEntries, timings };
1444
1497
  }
1445
1498
 
1446
1499
  /** The route `compilePage` renders: a URL and the page document that produces it. */
@@ -48,11 +48,11 @@ const DEFAULTS = {
48
48
  layout: null,
49
49
  },
50
50
  images: {
51
- formats: ["webp", "avif"],
51
+ formats: ["avif", "jpeg"],
52
52
  lazyLoad: true,
53
53
  optimize: true,
54
54
  picture: true,
55
- quality: { avif: 65, jpeg: 80, png: 80, webp: 80 },
55
+ quality: { avif: 65, jpeg: 80 },
56
56
  service: "build",
57
57
  sizes: "(max-width: 768px) 100vw, 50vw",
58
58
  widths: [320, 640, 960, 1280, 1920],