@decocms/blocks 8.2.3 → 8.3.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.
@@ -1,14 +1,20 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
3
  import { paint } from "../color.ts";
3
4
  import { writeIfChanged } from "../content.ts";
4
5
  import { consoleReporter, type Reporter } from "../log.ts";
5
6
  import { CliError, type DecoPaths, decoPaths, findDecoRoot } from "../root.ts";
6
- import { generateSchema, type SchemaResult } from "./generate.ts";
7
+ import { type DecoMeta, generateSchema, type SchemaResult } from "./generate.ts";
7
8
 
8
9
  export interface SchemaOptions {
9
10
  root?: string;
10
11
  cwd?: string;
11
12
  reporter?: Reporter;
13
+ /**
14
+ * `--check`: write nothing; fail (exit 1) when `.deco/schema.gen.json`
15
+ * differs from what `deco schema` would write. For CI.
16
+ */
17
+ check?: boolean;
12
18
  }
13
19
 
14
20
  export interface WriteSchemaResult extends SchemaResult {
@@ -25,10 +31,114 @@ export async function writeSchema(paths: DecoPaths): Promise<WriteSchemaResult>
25
31
  if (result.diagnostics.some((d) => d.severity === "error")) {
26
32
  return { ...result, written: false, changed: false };
27
33
  }
28
- const changed = writeIfChanged(paths.schema, `${JSON.stringify(result.meta, null, 2)}\n`);
34
+ const changed = writeIfChanged(paths.schema, schemaText(result));
29
35
  return { ...result, written: true, changed };
30
36
  }
31
37
 
38
+ /** The file's text, as `deco schema` writes it. */
39
+ function schemaText(result: SchemaResult): string {
40
+ return `${JSON.stringify(result.meta, null, 2)}\n`;
41
+ }
42
+
43
+ export interface CheckSchemaResult extends SchemaResult {
44
+ /** `undefined` when the schema has errors, so there is nothing to compare. */
45
+ status?: "up-to-date" | "missing" | "stale";
46
+ /** For a stale file: what differs, one line each. */
47
+ differences: string[];
48
+ }
49
+
50
+ /** `deco schema --check`: compare `.deco/schema.gen.json` with what `deco schema` would write. */
51
+ export async function checkSchema(paths: DecoPaths): Promise<CheckSchemaResult> {
52
+ const result = await generateSchema(paths);
53
+ if (result.diagnostics.some((d) => d.severity === "error")) {
54
+ return { ...result, differences: [] };
55
+ }
56
+ let saved: string;
57
+ try {
58
+ saved = fs.readFileSync(paths.schema, "utf8");
59
+ } catch {
60
+ return { ...result, status: "missing", differences: [] };
61
+ }
62
+ if (saved === schemaText(result)) return { ...result, status: "up-to-date", differences: [] };
63
+ return { ...result, status: "stale", differences: describeDifferences(saved, result.meta) };
64
+ }
65
+
66
+ const LISTED = 5;
67
+
68
+ function names(list: string[]): string {
69
+ const shown = list.slice(0, LISTED).join(", ");
70
+ return list.length > LISTED ? `${shown} and ${list.length - LISTED} more` : shown;
71
+ }
72
+
73
+ /** One line per kind of change, so a CI log says what moved without a diff. */
74
+ function describeDifferences(saved: string, meta: DecoMeta): string[] {
75
+ let old: Partial<DecoMeta>;
76
+ try {
77
+ old = JSON.parse(saved);
78
+ } catch {
79
+ return ["the saved file is not valid JSON"];
80
+ }
81
+ if (old === null || typeof old !== "object") return ["the saved file is not a schema"];
82
+ const lines: string[] = [];
83
+ const oldGroups = old.manifest?.blocks ?? {};
84
+ const newGroups = meta.manifest.blocks;
85
+ for (const group of [...new Set([...Object.keys(newGroups), ...Object.keys(oldGroups)])]) {
86
+ const before = Object.keys(oldGroups[group] ?? {});
87
+ const after = Object.keys(newGroups[group] ?? {});
88
+ const added = after.filter((name) => !before.includes(name));
89
+ const removed = before.filter((name) => !after.includes(name));
90
+ if (added.length > 0) lines.push(`${group}: new in code: ${names(added)}`);
91
+ if (removed.length > 0) lines.push(`${group}: no longer in code: ${names(removed)}`);
92
+ }
93
+ const oldDefinitions = old.schema?.definitions ?? {};
94
+ const changed = Object.keys(meta.schema.definitions).filter(
95
+ (key) =>
96
+ Object.hasOwn(oldDefinitions, key) &&
97
+ JSON.stringify(oldDefinitions[key]) !== JSON.stringify(meta.schema.definitions[key]),
98
+ );
99
+ if (changed.length > 0) {
100
+ lines.push(
101
+ `${changed.length} schema definition${changed.length === 1 ? "" : "s"} changed (fields or choices)`,
102
+ );
103
+ }
104
+ if (old.version !== meta.version) {
105
+ lines.push(`written by version ${String(old.version)}; this is ${meta.version}`);
106
+ }
107
+ if (lines.length === 0) lines.push("the content is the same but the formatting differs");
108
+ return lines;
109
+ }
110
+
111
+ export function reportSchemaCheck(result: CheckSchemaResult, reporter: Reporter): number {
112
+ const c = paint(reporter.color);
113
+ for (const d of result.diagnostics) {
114
+ if (d.severity === "error") reporter.error(c.red(d.message));
115
+ else reporter.warn(`${c.yellow("warning")}: ${d.message}`);
116
+ }
117
+ const fix = "Run `deco schema` and commit .deco/schema.gen.json.";
118
+ switch (result.status) {
119
+ case undefined:
120
+ reporter.error(c.red(".deco/schema.gen.json can't be checked: fix the errors above"));
121
+ return 1;
122
+ case "missing":
123
+ reporter.error(c.red(`.deco/schema.gen.json is missing. ${fix}`));
124
+ return 1;
125
+ case "stale":
126
+ reporter.error(
127
+ [
128
+ c.red(
129
+ ".deco/schema.gen.json is out of date: the code's types have changed since it was written.",
130
+ ),
131
+ ...result.differences.map((line) => ` - ${line}`),
132
+ fix,
133
+ ].join("\n"),
134
+ );
135
+ return 1;
136
+ case "up-to-date":
137
+ reporter.info(`.deco/schema.gen.json is up to date with ${path.basename(result.blockMap)}`);
138
+ return 0;
139
+ }
140
+ }
141
+
32
142
  export function reportSchema(result: WriteSchemaResult, reporter: Reporter): number {
33
143
  const c = paint(reporter.color);
34
144
  for (const d of result.diagnostics) {
@@ -49,11 +159,12 @@ export function reportSchema(result: WriteSchemaResult, reporter: Reporter): num
49
159
  return 0;
50
160
  }
51
161
 
52
- /** `deco schema`, once. Returns the exit code. */
162
+ /** `deco schema` (or `deco schema --check`), once. Returns the exit code. */
53
163
  export async function schema(options: SchemaOptions = {}): Promise<number> {
54
164
  const reporter = options.reporter ?? consoleReporter;
55
165
  const paths = decoPaths(findDecoRoot(options));
56
166
  try {
167
+ if (options.check) return reportSchemaCheck(await checkSchema(paths), reporter);
57
168
  return reportSchema(await writeSchema(paths), reporter);
58
169
  } catch (error) {
59
170
  if (error instanceof CliError) {
package/src/v8/cms.ts CHANGED
@@ -398,7 +398,18 @@ export function resetForTests(): void {
398
398
  /** With `site`, the content is the fallback of hosted releases. */
399
399
  function contentOf(config: CMSConfig): Snapshot | Loader {
400
400
  if (!config.site) return config.content;
401
- return remoteLoader(config.content, { site: config.site, dev: config.dev });
401
+ return remoteLoader(config.content, { site: config.site, dev: config.dev ?? isDevelopment() });
402
+ }
403
+
404
+ /**
405
+ * `NODE_ENV=development`: the SDK's one environment read (an explicit `dev`
406
+ * overrides it). Guarded, so a Worker or a browser without `process` reads
407
+ * `false`; spelled `process.env.NODE_ENV` so a bundler's `define` replaces it.
408
+ */
409
+ function isDevelopment(): boolean {
410
+ return (
411
+ typeof process !== "undefined" && process.env != null && process.env.NODE_ENV === "development"
412
+ );
402
413
  }
403
414
 
404
415
  function validate(config: CMSConfig): void {
@@ -0,0 +1,325 @@
1
+ /**
2
+ * `@decocms/blocks/image`: image URLs for the Deco image CDN, srcset and
3
+ * preload data.
4
+ *
5
+ * Pure functions: no React, no framework, no module state. A site builds one
6
+ * `ImageUrl` from the providers its images come from and passes it to the
7
+ * binding's components or image loader. v7's `registerImageCdnDomain` and
8
+ * `registerImageQuality` do not come back: they were module-wide state, the
9
+ * dual-instance hazard the package split removed; their values are
10
+ * `decoCdn`'s `domain` and `quality` options.
11
+ *
12
+ * Only the Deco CDN lives here. A commerce platform's own resize syntax is a
13
+ * provider in that platform's client package (`@decocms/apps-vtex/image`,
14
+ * `@decocms/apps-shopify/image`), listed before `decoCdn`.
15
+ */
16
+
17
+ export type Fit = "contain" | "cover" | "fill";
18
+
19
+ /**
20
+ * A named tier ("low" | "medium" | "high" | "original", what the Deco image CDN
21
+ * accepts) or a number. The Deco CDN ignores numbers; a provider for another
22
+ * service says how it reads them.
23
+ */
24
+ export type Quality = "low" | "medium" | "high" | "original" | number;
25
+
26
+ /** The Deco image CDN's quality tiers. */
27
+ export type QualityTier = "low" | "medium" | "high" | "original";
28
+
29
+ export interface ResizeOptions {
30
+ width: number;
31
+ height?: number;
32
+ fit?: Fit;
33
+ quality?: Quality;
34
+ }
35
+
36
+ export interface ImageProvider {
37
+ name: string;
38
+ /** Whether this provider handles `src` (what `ImageUrl.isOptimizable` reports). */
39
+ match(src: string): boolean;
40
+ /** The resized URL, or null to leave `src` to the next provider. */
41
+ format(src: string, o: ResizeOptions): string | null;
42
+ /** Hosts the formatted URLs point at, for CSP img-src and preconnect. */
43
+ hosts?: string[];
44
+ }
45
+
46
+ export interface ImageUrl {
47
+ /** The resized URL; "" for an empty src, data: URIs and unknown sources unchanged. */
48
+ (src: string, o: ResizeOptions): string;
49
+ /** Whether a provider handles `src` (false for "", data: URIs and unknown sources). */
50
+ isOptimizable(src: string): boolean;
51
+ hosts(): string[];
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Deco image CDN
56
+ // ---------------------------------------------------------------------------
57
+
58
+ const DECO_CACHE_URL = "https://assets.decocache.com/";
59
+ const DECO_S3_URL = "https://deco-sites-assets.s3.sa-east-1.amazonaws.com/";
60
+ const LEADING_ASSET_HOST =
61
+ /^https:\/\/(?:assets\.decocache\.com|deco-sites-assets\.s3\.sa-east-1\.amazonaws\.com)\//;
62
+ /** Deco CDNs on Cloudflare: a decoims.com src= makes them fetch themselves (508), so it is stripped. */
63
+ const CLOUDFLARE_DECO_CDNS = new Set(["assets.decocms.com", "decoims.com"]);
64
+ /** Every host that serves the Deco image CDN's `/image?…&src=` endpoint. */
65
+ const DECO_IMAGE_HOSTS = [
66
+ "assets.decocms.com",
67
+ "decoims.com",
68
+ "deco-assets.edgedeco.com",
69
+ "deco-assets.decoazn.com",
70
+ ];
71
+ /** Characters an unwrapped `src` cannot carry raw in the query this provider writes. */
72
+ const QUERY_UNSAFE = /[%&#+]/g;
73
+
74
+ export interface DecoCdnOptions {
75
+ /** The CDN host. Default "assets.decocms.com"; "decoims.com", "deco-assets.edgedeco.com" also serve it. */
76
+ domain?: string;
77
+ /** Tier asked for when a call names none (a call's numeric quality is ignored). Default: none, the CDN's 60%. */
78
+ quality?: QualityTier;
79
+ /** Fit when a call names none. Default "cover", as v7's `getSrcSet` and `Image`. */
80
+ fit?: Fit;
81
+ /**
82
+ * Earlier CDN hosts whose URLs are re-served from `domain`. Default ["decoims.com"]
83
+ * on the Cloudflare CDNs, [] otherwise (the Azion CDNs fetch decoims.com URLs fine).
84
+ */
85
+ legacyHosts?: string[];
86
+ /**
87
+ * The sources this provider resizes. "deco" (default): the Deco asset hosts,
88
+ * `domain` and `legacyHosts`; others pass through. "all": every non-empty,
89
+ * non-data: source, v7's behaviour (put the provider last). Or a predicate.
90
+ */
91
+ sources?: "deco" | "all" | ((src: string) => boolean);
92
+ /**
93
+ * How the Deco asset hosts (assets.decocache.com, the S3 bucket) are removed
94
+ * from the source. "leading" (default, v7's `Image` since 7.71.4): only a
95
+ * host the source starts with. "anywhere" (older v7 `getOptimizedMediaUrl`
96
+ * copies): the first occurrence of each, wherever it is, so a source that
97
+ * merely contains an asset URL (`https://other.host/https://assets.decocache.com/…`)
98
+ * loses that part.
99
+ */
100
+ stripAssetHosts?: "anywhere" | "leading";
101
+ /**
102
+ * Query layout. "src-last" (default, v7's `getOptimizedMediaUrl`):
103
+ * `?fit=&width=[&height=][&quality=]&src=<raw path>`. "quality-last" (what
104
+ * next/image loaders built on v7's helper emit): the same URL re-serialised,
105
+ * `?fit=&width=[&height=]&src=<form-encoded path>&quality=`. Both are served
106
+ * the same way; keep the one a site uses so the CDN cache stays warm.
107
+ */
108
+ layout?: "src-last" | "quality-last";
109
+ }
110
+
111
+ function stripScheme(domain: string): string {
112
+ return domain.replace(/^https?:\/\//, "").replace(/\/+$/, "");
113
+ }
114
+
115
+ /**
116
+ * The `src` an already-resized Deco CDN URL (`https://<cdn>/image?…&src=…`)
117
+ * was made from, as the CDN reads it (query-decoded); null for any other URL.
118
+ */
119
+ function decoImageSource(src: string, hosts: Set<string>): string | null {
120
+ if (!/^https?:\/\//i.test(src) || !/\/image\?/i.test(src)) return null;
121
+ let url: URL;
122
+ try {
123
+ url = new URL(src);
124
+ } catch {
125
+ return null;
126
+ }
127
+ if (!hosts.has(url.hostname) || url.pathname !== "/image") return null;
128
+ const inner = url.searchParams.get("src");
129
+ return inner ? inner : null;
130
+ }
131
+
132
+ /**
133
+ * The Deco image CDN (`https://<domain>/image?fit=&width=…&src=`). An
134
+ * already-resized Deco CDN URL (any of its hosts' `/image?…&src=`) that this
135
+ * provider resizes (see `sources`) is re-resized from its `src`; before, it
136
+ * became `src=image` or `src=<cdn>/image`, which the CDN cannot serve.
137
+ */
138
+ export function decoCdn(o: DecoCdnOptions = {}): ImageProvider {
139
+ const domain = stripScheme(o.domain ?? "assets.decocms.com");
140
+ const legacy = (o.legacyHosts ?? (CLOUDFLARE_DECO_CDNS.has(domain) ? ["decoims.com"] : []))
141
+ .map(stripScheme)
142
+ .filter((h) => h !== domain);
143
+ const decoPrefixes = [
144
+ `https://${domain}/`,
145
+ ...legacy.map((h) => `https://${h}/`),
146
+ DECO_CACHE_URL,
147
+ DECO_S3_URL,
148
+ ];
149
+ const sources = o.sources ?? "deco";
150
+ const layout = o.layout ?? "src-last";
151
+ const imageHosts = new Set([...DECO_IMAGE_HOSTS, domain, ...legacy]);
152
+
153
+ return {
154
+ name: "deco",
155
+ hosts: [domain],
156
+ match(src) {
157
+ if (typeof sources === "function") return sources(src);
158
+ if (sources === "all") return src.length > 0 && !src.startsWith("data:");
159
+ // Only the sources resized before fix 2: a Deco CDN URL this provider
160
+ // did not match (another CDN host, http, an uppercase host) still passes
161
+ // through unchanged, as it was served fine.
162
+ return decoPrefixes.some((p) => src.startsWith(p));
163
+ },
164
+ format(src, r) {
165
+ // An already-resized Deco CDN URL is re-resized from the src it was made
166
+ // from (nested ones too); before, `src=` got the CDN URL's own path
167
+ // ("image") and the CDN answered 404.
168
+ let unwrapped = false;
169
+ for (let inner = decoImageSource(src, imageHosts), i = 0; inner !== null && i < 8; i++) {
170
+ src = inner;
171
+ unwrapped = true;
172
+ inner = decoImageSource(src, imageHosts);
173
+ }
174
+ let source =
175
+ (o.stripAssetHosts ?? "leading") === "leading"
176
+ ? src.replace(LEADING_ASSET_HOST, "")
177
+ : src.replace(DECO_CACHE_URL, "").replace(DECO_S3_URL, "");
178
+ source = source.split("?")[0];
179
+ for (const host of [...legacy, domain]) {
180
+ if (source.startsWith(`https://${host}/`)) source = source.slice(host.length + 9);
181
+ }
182
+ if (unwrapped) source = source.replace(QUERY_UNSAFE, encodeURIComponent);
183
+ const quality = typeof r.quality === "string" ? r.quality : o.quality;
184
+ const params = new URLSearchParams();
185
+ params.set("fit", r.fit ?? o.fit ?? "cover");
186
+ params.set("width", `${r.width}`);
187
+ if (r.height) params.set("height", `${r.height}`);
188
+ if (layout === "src-last") {
189
+ if (quality) params.set("quality", quality);
190
+ return `https://${domain}/image?${params}&src=${source}`;
191
+ }
192
+ const url = new URL(`https://${domain}/image?${params}&src=${source}`);
193
+ if (quality) url.searchParams.set("quality", quality);
194
+ return url.toString();
195
+ },
196
+ };
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // ImageUrl, srcset, preload
201
+ // ---------------------------------------------------------------------------
202
+
203
+ /**
204
+ * One URL builder for a site. Providers are tried in order: the first that
205
+ * matches `src` and returns a URL wins; unknown sources pass through unchanged.
206
+ */
207
+ export function createImageUrl(o: { providers: ImageProvider[] }): ImageUrl {
208
+ const providers = [...o.providers];
209
+ const usable = (src: string) =>
210
+ typeof src === "string" && src.length > 0 && !src.startsWith("data:");
211
+ const url = ((src: string, r: ResizeOptions) => {
212
+ if (typeof src !== "string" || src.length === 0) return "";
213
+ if (!usable(src)) return src;
214
+ for (const p of providers) {
215
+ if (!p.match(src)) continue;
216
+ const out = p.format(src, r);
217
+ if (out !== null) return out;
218
+ }
219
+ return src;
220
+ }) as ImageUrl;
221
+ url.isOptimizable = (src) => usable(src) && providers.some((p) => p.match(src));
222
+ url.hosts = () => [...new Set(providers.flatMap((p) => p.hosts ?? []))];
223
+ return url;
224
+ }
225
+
226
+ export interface SrcSetOptions {
227
+ /**
228
+ * Base width for `factors`. Left out, each candidate is `NaN` wide, as v7's
229
+ * `getSrcSet` wrote it for an `Image` or `Source` without a width.
230
+ */
231
+ width?: number;
232
+ /** Candidate widths; when given, `width` and `factors` are not used. */
233
+ widths?: number[];
234
+ /** Multipliers of `width` (truncated, as v7 did). Default [1, 2]. */
235
+ factors?: number[];
236
+ /** Base height for `factors`, scaled with the width. */
237
+ height?: number;
238
+ /** height / width, for a fixed frame: each candidate gets round(w * ratio). */
239
+ ratio?: number;
240
+ fit?: Fit;
241
+ quality?: Quality;
242
+ }
243
+
244
+ /** `"<url> <w>w, ..."`, or undefined for an empty src or no candidates (`widths: []`). */
245
+ export function srcSet(url: ImageUrl, src: string, o: SrcSetOptions): string | undefined {
246
+ if (typeof src !== "string" || src.length === 0) return undefined;
247
+ const sizes: { w: number; h?: number }[] = o.widths
248
+ ? o.widths.map((w) => ({ w, h: o.ratio ? Math.round(w * o.ratio) : undefined }))
249
+ : // No width: v7's NaN candidates (`width=NaN … NaNw`), kept byte for byte.
250
+ (o.factors ?? [1, 2]).map((f) => {
251
+ const w = Math.trunc(f * (o.width as number));
252
+ const h = o.height
253
+ ? Math.trunc(f * o.height)
254
+ : o.ratio
255
+ ? Math.round(w * o.ratio)
256
+ : undefined;
257
+ return { w, h };
258
+ });
259
+ const entries: string[] = [];
260
+ for (const { w, h } of sizes) {
261
+ const href = url(src, { width: w, height: h, fit: o.fit, quality: o.quality });
262
+ if (href) entries.push(`${href} ${w}w`);
263
+ }
264
+ return entries.length > 0 ? entries.join(", ") : undefined;
265
+ }
266
+
267
+ /** Candidates of a srcset attribute (URLs with commas inside are kept whole). */
268
+ export function parseSrcSet(s: string): { url: string; w?: number; x?: number }[] {
269
+ const out: { url: string; w?: number; x?: number }[] = [];
270
+ let i = 0;
271
+ while (i < s.length) {
272
+ while (i < s.length && /[\s,]/.test(s[i])) i++;
273
+ if (i >= s.length) break;
274
+ let j = i;
275
+ while (j < s.length && !/\s/.test(s[j])) j++;
276
+ let url = s.slice(i, j);
277
+ i = j;
278
+ let descriptor = "";
279
+ if (url.endsWith(",")) url = url.replace(/,+$/, "");
280
+ else {
281
+ while (i < s.length && s[i] !== ",") descriptor += s[i++];
282
+ i++;
283
+ }
284
+ const entry: { url: string; w?: number; x?: number } = { url };
285
+ const d = /^(\d+(?:\.\d+)?)([wx])$/.exec(descriptor.trim());
286
+ if (d) entry[d[2] as "w" | "x"] = Number(d[1]);
287
+ out.push(entry);
288
+ }
289
+ return out;
290
+ }
291
+
292
+ export interface PreloadOptions extends SrcSetOptions {
293
+ width: number;
294
+ sizes?: string;
295
+ media?: string;
296
+ /** Default "high". */
297
+ fetchPriority?: "high" | "low" | "auto";
298
+ }
299
+
300
+ export interface PreloadLink {
301
+ rel: "preload";
302
+ as: "image";
303
+ href: string;
304
+ imageSrcSet?: string;
305
+ imageSizes?: string;
306
+ media?: string;
307
+ fetchPriority?: string;
308
+ }
309
+
310
+ /** The attributes of a `<link rel="preload" as="image">` for an LCP image. */
311
+ export function preloadLink(url: ImageUrl, src: string, o: PreloadOptions): PreloadLink {
312
+ const link: PreloadLink = {
313
+ rel: "preload",
314
+ as: "image",
315
+ href: url(src, { width: o.width, height: o.height, fit: o.fit, quality: o.quality }),
316
+ };
317
+ const set = srcSet(url, src, o);
318
+ if (set) {
319
+ link.imageSrcSet = set;
320
+ if (o.sizes) link.imageSizes = o.sizes;
321
+ }
322
+ if (o.media) link.media = o.media;
323
+ link.fetchPriority = o.fetchPriority ?? "high";
324
+ return link;
325
+ }
@@ -25,9 +25,9 @@
25
25
  * a publish still loses to it.
26
26
  * Pointers aren't ordered among themselves, and the fallback's content is
27
27
  * never compared: only the two timestamps are.
28
- * - With `dev: true` (`createCMS({ dev })`), it never swaps, so local files win.
29
- * The SDK reads no environment variable to decide this: the site passes it
30
- * (`import.meta.env.DEV`, `process.env.NODE_ENV === "development"`).
28
+ * - With `dev: true`, it never swaps, so local files win. `createCMS` passes
29
+ * its `dev` option, or `NODE_ENV === "development"` when the site omits it;
30
+ * this loader reads no environment itself.
31
31
  * - A release larger than `MAX_SNAPSHOT_BYTES` is refused while it downloads,
32
32
  * before it's buffered whole (a Worker isolate has 128 MB).
33
33
  * - Without `site` it's a plain loader over the fallback.
@@ -7,8 +7,9 @@
7
7
  * in ./builtins/legacy) is a second key for a type, so like a function it wins
8
8
  * over a saved block of the same name; a saved block is replaced by
9
9
  * `{ ...saved, ...arguments }` and looked up again; anything else is
10
- * `UNKNOWN_BLOCK`. The built-in `lazy` is
11
- * the one special case: its `value` is not resolved first.
10
+ * `UNKNOWN_BLOCK`. Two built-ins are special cases: `lazy`, whose `value` is
11
+ * not resolved first, and `multivariate`, whose variants' rules resolve in
12
+ * order and stop at the first `true` one (later rules never run, as in v7).
12
13
  *
13
14
  * A `Resolver` belongs to one client, so its memo (results per block function
14
15
  * and canonical inputs) never outlives a request. Within the request the memo
@@ -19,6 +20,7 @@
19
20
  import { RESERVED_NAMES } from "./builtins/index.ts";
20
21
  import { isLazyBuiltin } from "./builtins/lazy.ts";
21
22
  import { LEGACY_ALIASES, wrapLegacyVariants } from "./builtins/legacy.ts";
23
+ import { isMultivariateBuiltin } from "./builtins/multivariate.ts";
22
24
  import { errors, isResolutionError } from "./errors.ts";
23
25
  import { canonicalKey, isPlainObject, type JsonObject, own } from "./json.ts";
24
26
  import type { BlockFunction, Blocks, Lazy, Snapshot } from "./types.ts";
@@ -240,7 +242,10 @@ export class Resolver {
240
242
  ): Promise<unknown> {
241
243
  // Inputs are always fresh objects: a function may mutate its props freely.
242
244
  const { __resolveType: _type, ...inputs } = node;
243
- const resolved = await this.#resolveFields(inputs, path, chain, true);
245
+ const resolved =
246
+ isMultivariateBuiltin(fn) && Array.isArray(inputs.variants)
247
+ ? await this.#resolveFirstMatch(inputs, inputs.variants, path, chain)
248
+ : await this.#resolveFields(inputs, path, chain, true);
244
249
  const start = Date.now();
245
250
  try {
246
251
  const value = await fn(resolved);
@@ -254,6 +259,38 @@ export class Resolver {
254
259
  }
255
260
  }
256
261
 
262
+ /**
263
+ * The built-in `multivariate`'s inputs: its other fields as usual, then the
264
+ * variants one at a time, each rule before the rest of its variant, up to
265
+ * the first rule that is `true`. Later variants are left out, so their
266
+ * matchers never run.
267
+ */
268
+ async #resolveFirstMatch(
269
+ inputs: JsonObject,
270
+ variants: unknown[],
271
+ path: Path,
272
+ chain: string[],
273
+ ): Promise<JsonObject> {
274
+ const { variants: _variants, ...others } = inputs;
275
+ const resolved = await this.#resolveFields(others, path, chain, true);
276
+ const kept: unknown[] = [];
277
+ for (const [i, variant] of variants.entries()) {
278
+ const at = [...path, "variants", i];
279
+ if (!isPlainObject(variant) || typeof variant.__resolveType === "string") {
280
+ const value = await this.resolve(variant, at, chain, true);
281
+ if (value === undefined) continue;
282
+ kept.push(value);
283
+ if (isPlainObject(value) && value.rule === true) break;
284
+ continue;
285
+ }
286
+ const { rule, ...rest } = variant;
287
+ const matched = await this.resolve(rule, [...at, "rule"], chain, true);
288
+ kept.push({ rule: matched, ...(await this.#resolveFields(rest, at, chain, true)) });
289
+ if (matched === true) break;
290
+ }
291
+ return { ...resolved, variants: kept };
292
+ }
293
+
257
294
  #lazy(value: unknown, path: Path, chain: string[], fromContent: boolean): Lazy<unknown> {
258
295
  let pending: Promise<unknown> | undefined;
259
296
  return () => {
package/src/v8/types.ts CHANGED
@@ -256,9 +256,10 @@ export interface CMSConfig {
256
256
  /** ms between `update()` checks of a content source that has one; minimum 60 000. */
257
257
  interval?: number;
258
258
  /**
259
- * Local development (`import.meta.env.DEV`, `process.env.NODE_ENV === "development"`):
260
- * hosted releases are never swapped in, so local files win. Drafts still load.
261
- * The SDK reads no environment variable for it; default `false`.
259
+ * Local development: hosted releases are never swapped in, so local files win.
260
+ * Drafts still load. Default: `process.env.NODE_ENV === "development"` (read
261
+ * guarded, so `false` where there is no `process`: Workers, browsers). Pass it
262
+ * to override that, e.g. `dev: import.meta.env.DEV` or `dev: false`.
262
263
  */
263
264
  dev?: boolean;
264
265
  /** Where telemetry goes; see /next/telemetry. */