@decocms/blocks 8.1.0-next.2 → 8.1.0-next.3

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.
Files changed (61) hide show
  1. package/dist/protocol/conformance/contentHashFixtures.d.ts +29 -0
  2. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
  3. package/dist/protocol/conformance/contentHashFixtures.js +30 -0
  4. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
  5. package/dist/protocol/conformance/index.d.ts +1 -1
  6. package/dist/protocol/conformance/index.d.ts.map +1 -1
  7. package/dist/protocol/conformance/index.js +1 -1
  8. package/dist/protocol/conformance/index.js.map +1 -1
  9. package/dist/protocol/index.d.ts +5 -2
  10. package/dist/protocol/index.d.ts.map +1 -1
  11. package/dist/protocol/index.js +5 -2
  12. package/dist/protocol/index.js.map +1 -1
  13. package/dist/v8/canonical.d.ts +28 -0
  14. package/dist/v8/canonical.d.ts.map +1 -1
  15. package/dist/v8/canonical.js +19 -0
  16. package/dist/v8/canonical.js.map +1 -1
  17. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  18. package/dist/v8/cli/schema/generate.js +2 -2
  19. package/dist/v8/cli/schema/generate.js.map +1 -1
  20. package/dist/v8/cli/schema/tsProgram.d.ts +6 -0
  21. package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -1
  22. package/dist/v8/cli/schema/tsProgram.js +17 -0
  23. package/dist/v8/cli/schema/tsProgram.js.map +1 -1
  24. package/dist/v8/cli/schema/typeToSchema.d.ts +13 -0
  25. package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
  26. package/dist/v8/cli/schema/typeToSchema.js +71 -2
  27. package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
  28. package/dist/v8/cms.d.ts.map +1 -1
  29. package/dist/v8/cms.js +13 -2
  30. package/dist/v8/cms.js.map +1 -1
  31. package/dist/v8/content.d.ts +18 -2
  32. package/dist/v8/content.d.ts.map +1 -1
  33. package/dist/v8/content.js +54 -19
  34. package/dist/v8/content.js.map +1 -1
  35. package/dist/v8/draft.d.ts +4 -0
  36. package/dist/v8/draft.d.ts.map +1 -1
  37. package/dist/v8/draft.js +67 -5
  38. package/dist/v8/draft.js.map +1 -1
  39. package/dist/v8/remoteLoader.d.ts.map +1 -1
  40. package/dist/v8/remoteLoader.js +209 -25
  41. package/dist/v8/remoteLoader.js.map +1 -1
  42. package/dist/v8/types.d.ts +13 -1
  43. package/dist/v8/types.d.ts.map +1 -1
  44. package/dist/v8/variants.d.ts +3 -0
  45. package/dist/v8/variants.d.ts.map +1 -0
  46. package/dist/v8/variants.js +65 -0
  47. package/dist/v8/variants.js.map +1 -0
  48. package/package.json +1 -1
  49. package/src/protocol/conformance/contentHashFixtures.ts +57 -0
  50. package/src/protocol/conformance/index.ts +6 -1
  51. package/src/protocol/index.ts +8 -1
  52. package/src/v8/canonical.ts +36 -0
  53. package/src/v8/cli/schema/generate.ts +2 -1
  54. package/src/v8/cli/schema/tsProgram.ts +17 -0
  55. package/src/v8/cli/schema/typeToSchema.ts +76 -2
  56. package/src/v8/cms.ts +14 -2
  57. package/src/v8/content.ts +54 -18
  58. package/src/v8/draft.ts +75 -6
  59. package/src/v8/remoteLoader.ts +242 -22
  60. package/src/v8/types.ts +14 -1
  61. package/src/v8/variants.ts +61 -0
@@ -11,19 +11,35 @@
11
11
  * ignored; a revision equal to the fallback's is served from the fallback
12
12
  * without a download; anything else is fetched, verified against its
13
13
  * content hash and swapped in whole. Any error keeps memory as it was.
14
- * - `load(pointer)` fetches the draft a pointer names and waits for it. Only
15
- * pointers to the delivery host are fetched; anything else is refused.
14
+ * - `load(pointer)` loads a draft overlay (see /next/content-delivery#exact-draft-previews)
15
+ * and waits for it: it captures the production snapshot `load()` would
16
+ * return right now, fetches the overlay manifest the pointer's version names
17
+ * and only the changed-block assets not already cached, and layers their
18
+ * replacements and tombstones over the captured snapshot. It never fetches a
19
+ * production revision to align. An authorized manifest is cached only as long
20
+ * as its response's `max-age` (the grant's remaining life), so an expired
21
+ * grant stops working on a warm server too. Only pointers into this site's drafts on the
22
+ * delivery host are fetched; anything else is refused. Any failure rejects:
23
+ * a draft never falls back to published content.
16
24
  * - In development (`NODE_ENV=development`), releases stay on the fallback so
17
25
  * local files win; drafts still load.
18
- * - A release or draft larger than `MAX_SNAPSHOT_BYTES` is refused while it
19
- * downloads, before it's buffered whole (a Worker isolate has 128 MB).
26
+ * - A release, or any one draft asset, larger than `MAX_SNAPSHOT_BYTES` is
27
+ * refused while it downloads, before it's buffered whole (a Worker isolate
28
+ * has 128 MB); a draft whose manifest and changed blocks together exceed it
29
+ * is refused as each asset is counted.
20
30
  * - Without `site` or `token` it's a plain loader over the fallback: no
21
31
  * releases, no drafts beyond what the fallback serves.
22
32
  *
23
33
  * Instances are process-wide singletons, like `createCMS`'s.
24
34
  */
25
- import { computeContentRevision } from "./canonical.ts";
26
- import { isSnapshot } from "./content.ts";
35
+ import {
36
+ computeBlockHash,
37
+ computeContentRevision,
38
+ computeOverlayVersion,
39
+ DRAFT_OVERLAY_FORMAT,
40
+ type DraftOverlay,
41
+ } from "./canonical.ts";
42
+ import { BoundedMap, isSnapshot } from "./content.ts";
27
43
  import { parseDraftPointer } from "./draft.ts";
28
44
  import { clearGlobals, contentIdentity, fnv1a } from "./identity.ts";
29
45
  import { isPlainObject } from "./json.ts";
@@ -35,8 +51,15 @@ const HOSTED_DELIVERY_ORIGIN = "https://delivery.decocms.com";
35
51
  const INSTANCE_PREFIX = "decocms.blocks.remote:";
36
52
  const MANIFEST_FORMAT = 1;
37
53
  const FETCH_TIMEOUT_MS = 10_000;
38
- /** The largest release or draft accepted, in bytes of JSON. */
54
+ /** The largest release, or draft (manifest plus changed blocks), accepted, in bytes of JSON. */
39
55
  const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
56
+ /** Draft caches, per site: authorized overlay manifests, and changed-block bytes. */
57
+ const CACHED_OVERLAYS = 16;
58
+ const CACHED_BLOCK_BYTES = 16 * 1024 * 1024;
59
+ /** Changed-block downloads in flight at once, per draft. */
60
+ const BLOCK_FETCH_CONCURRENCY = 8;
61
+ /** Overlay versions and block hashes: SHA-256, lowercase hex. */
62
+ const HASH_RE = /^[0-9a-f]{64}$/;
40
63
 
41
64
  interface RemoteLoaderOptions {
42
65
  site?: string;
@@ -51,6 +74,17 @@ interface Manifest {
51
74
  snapshot: string;
52
75
  }
53
76
 
77
+ /** A downloaded, verified JSON asset and its size in bytes. */
78
+ interface Asset<T> {
79
+ value: T;
80
+ bytes: number;
81
+ }
82
+
83
+ /** An authorized overlay manifest, usable until its grant's `max-age` runs out. */
84
+ interface AuthorizedOverlay extends Asset<DraftOverlay> {
85
+ expiresAt: number;
86
+ }
87
+
54
88
  class RemoteLoader implements Loader {
55
89
  readonly #site: string;
56
90
  readonly #token: string;
@@ -60,6 +94,11 @@ class RemoteLoader implements Loader {
60
94
  #fallbackRevision: string | undefined;
61
95
  #current: Snapshot | undefined;
62
96
  #generation = -1;
97
+ /** Authorized manifests, by overlay version and grant: a version alone unlocks nothing. */
98
+ readonly #overlays = new BoundedMap<string, Promise<AuthorizedOverlay>>(CACHED_OVERLAYS);
99
+ /** Verified changed blocks, by block hash, bounded by their bytes. */
100
+ readonly #blocks = new BoundedMap<string, Asset<unknown>>(CACHED_BLOCK_BYTES, (b) => b.bytes);
101
+ readonly #pendingBlocks = new Map<string, Promise<Asset<unknown>>>();
63
102
 
64
103
  constructor(
65
104
  fallback: Snapshot | Loader,
@@ -152,7 +191,9 @@ class RemoteLoader implements Loader {
152
191
  this.#auth(),
153
192
  );
154
193
  if (!response.ok) throw new Error(`release ${manifest.revision}: HTTP ${response.status}`);
155
- const snapshot = await readBoundedJson(response, `release ${manifest.revision}`);
194
+ const [snapshot] = await readBoundedJson(response, `release ${manifest.revision}`, {
195
+ remaining: MAX_SNAPSHOT_BYTES,
196
+ });
156
197
  if (
157
198
  !isSnapshot(snapshot) ||
158
199
  snapshot.revision !== manifest.revision ||
@@ -169,15 +210,112 @@ class RemoteLoader implements Loader {
169
210
  if (pointer.host !== new URL(HOSTED_DELIVERY_ORIGIN).host) {
170
211
  throw new Error(`draft pointer names an unexpected host "${pointer.host}"`);
171
212
  }
172
- // If-Match: serve exactly this version or fail, never the branch's newer head.
173
- const response = await fetchWithTimeout(`https://${pointer.host}${pointer.path}`, {
174
- ...this.#auth(),
175
- "if-match": pointer.version,
213
+ const site = `/sites/${encodeURIComponent(this.#site)}`;
214
+ const query = pointer.path.indexOf("?");
215
+ const pathname = query === -1 ? pointer.path : pointer.path.slice(0, query);
216
+ if (pathname !== `${site}/drafts`) throw new Error("draft pointer names another site's drafts");
217
+ if (!HASH_RE.test(pointer.version)) throw new Error("draft pointer names no overlay version");
218
+ // The grant (the pointer's query) goes, opaque, on every draft asset read.
219
+ const grant = query === -1 ? "" : pointer.path.slice(query);
220
+
221
+ // Capture production once, before any network: this draft is layered over it.
222
+ const base = this.#current ?? (await this.#loadFallback());
223
+ const budget: Budget = { remaining: MAX_SNAPSHOT_BYTES };
224
+ const manifest = charge(
225
+ budget,
226
+ await this.#authorizedOverlay(
227
+ `${site}/drafts/${pointer.version}.json${grant}`,
228
+ pointer.version,
229
+ ),
230
+ );
231
+ const hashes = [...new Set(Object.values(manifest.set))];
232
+ const values = new Map<string, unknown>();
233
+ let next = 0;
234
+ const worker = async () => {
235
+ while (next < hashes.length) {
236
+ const hash = hashes[next++]!;
237
+ values.set(
238
+ hash,
239
+ await this.#block(`${site}/draft-blocks/${hash}.json${grant}`, hash, budget),
240
+ );
241
+ }
242
+ };
243
+ const workers = Math.min(BLOCK_FETCH_CONCURRENCY, hashes.length);
244
+ await Promise.all(Array.from({ length: workers }, worker));
245
+ return composeOverlay(base, manifest, values, pointer.version);
246
+ }
247
+
248
+ /**
249
+ * The manifest a pointer's grant authorizes: cached by version and grant
250
+ * until the response's `max-age` runs out (none, or 0, isn't cached), so an
251
+ * expired grant is asked about again. Concurrent callers share a download.
252
+ */
253
+ async #authorizedOverlay(path: string, version: string): Promise<AuthorizedOverlay> {
254
+ const asked = Date.now();
255
+ const cached = this.#overlays.get(path);
256
+ if (cached !== undefined) {
257
+ const overlay = await cached;
258
+ if (overlay.expiresAt >= asked) return overlay;
259
+ if (this.#overlays.get(path) === cached) this.#overlays.delete(path);
260
+ }
261
+ const pending = this.#overlay(path, version);
262
+ this.#overlays.set(path, pending);
263
+ const forget = () => {
264
+ if (this.#overlays.get(path) === pending) this.#overlays.delete(path);
265
+ };
266
+ pending.then((overlay) => {
267
+ if (overlay.expiresAt <= Date.now()) forget();
268
+ }, forget);
269
+ return pending;
270
+ }
271
+
272
+ async #overlay(path: string, version: string): Promise<AuthorizedOverlay> {
273
+ const response = await fetchWithTimeout(`${HOSTED_DELIVERY_ORIGIN}${path}`, this.#auth());
274
+ if (!response.ok) throw new Error(`draft overlay ${version}: HTTP ${response.status}`);
275
+ const maxAge = cacheLifetimeMs(response.headers.get("cache-control"));
276
+ const [body, bytes] = await readBoundedJson(response, `draft overlay ${version}`, {
277
+ remaining: MAX_SNAPSHOT_BYTES,
176
278
  });
177
- if (!response.ok) throw new Error(`draft: HTTP ${response.status}`);
178
- const snapshot = await readBoundedJson(response, "draft");
179
- if (!isSnapshot(snapshot)) throw new Error("draft: not a snapshot");
180
- return snapshot;
279
+ const overlay = parseOverlay(body);
280
+ if ((await computeOverlayVersion(overlay)) !== version) {
281
+ throw new Error(`draft overlay ${version}: content doesn't match its version`);
282
+ }
283
+ return { value: overlay, bytes, expiresAt: Date.now() + maxAge };
284
+ }
285
+
286
+ /**
287
+ * A changed block, charged to this draft's budget: from the cache, or
288
+ * downloaded once and verified against its hash. Concurrent drafts share
289
+ * one download, which is bounded on its own and then charged to each of
290
+ * them, so one draft's budget never fails another. Only hashes an
291
+ * authorized manifest lists get here.
292
+ */
293
+ async #block(path: string, hash: string, budget: Budget): Promise<unknown> {
294
+ const cached = this.#blocks.get(hash);
295
+ if (cached !== undefined) return charge(budget, cached);
296
+ let pending = this.#pendingBlocks.get(hash);
297
+ if (pending === undefined) {
298
+ const download = (async () => {
299
+ const response = await fetchWithTimeout(`${HOSTED_DELIVERY_ORIGIN}${path}`, this.#auth());
300
+ if (!response.ok) throw new Error(`draft block ${hash}: HTTP ${response.status}`);
301
+ const [value, bytes] = await readBoundedJson(response, `draft block ${hash}`, {
302
+ remaining: MAX_SNAPSHOT_BYTES,
303
+ });
304
+ if ((await computeBlockHash(value)) !== hash) {
305
+ throw new Error(`draft block ${hash}: content doesn't match its hash`);
306
+ }
307
+ const block = { value, bytes };
308
+ this.#blocks.set(hash, block);
309
+ return block;
310
+ })();
311
+ pending = download;
312
+ this.#pendingBlocks.set(hash, download);
313
+ void download.then(
314
+ () => this.#pendingBlocks.delete(hash),
315
+ () => this.#pendingBlocks.delete(hash),
316
+ );
317
+ }
318
+ return charge(budget, await pending);
181
319
  }
182
320
 
183
321
  #auth(): Record<string, string> {
@@ -238,14 +376,45 @@ export function resetRemoteLoaders(): void {
238
376
  clearGlobals(INSTANCE_PREFIX);
239
377
  }
240
378
 
241
- /** Parses a JSON body, refusing it as soon as it's larger than `MAX_SNAPSHOT_BYTES`. */
242
- async function readBoundedJson(response: Response, label: string): Promise<unknown> {
379
+ /** What a download may still read, in bytes; shared by every asset of one draft. */
380
+ interface Budget {
381
+ remaining: number;
382
+ }
383
+
384
+ /** Charges an asset's bytes to a draft's budget, and returns its value. */
385
+ function charge<T>(budget: Budget, asset: Asset<T>): T {
386
+ budget.remaining -= asset.bytes;
387
+ if (budget.remaining < 0) throw new Error(`draft: larger than ${MAX_SNAPSHOT_BYTES} bytes`);
388
+ return asset.value;
389
+ }
390
+
391
+ /** A response's private cache lifetime in ms: its `max-age`, or 0 without one or with `no-store`. */
392
+ function cacheLifetimeMs(header: string | null): number {
393
+ if (header === null || /(?:^|,)\s*no-store\b/i.test(header)) return 0;
394
+ const seconds = /(?:^|,)\s*max-age=(\d+)/i.exec(header)?.[1];
395
+ return seconds === undefined ? 0 : Number(seconds) * 1000;
396
+ }
397
+
398
+ /**
399
+ * Parses a JSON body and returns it with its size, refusing it as soon as it
400
+ * would exceed the budget (charged as bytes arrive, so parallel reads share it).
401
+ */
402
+ async function readBoundedJson(
403
+ response: Response,
404
+ label: string,
405
+ budget: Budget,
406
+ ): Promise<[unknown, number]> {
243
407
  const tooLarge = () => new Error(`${label}: larger than ${MAX_SNAPSHOT_BYTES} bytes`);
244
- if (Number(response.headers.get("content-length")) > MAX_SNAPSHOT_BYTES) {
408
+ if (Number(response.headers.get("content-length")) > budget.remaining) {
245
409
  await response.body?.cancel();
246
410
  throw tooLarge();
247
411
  }
248
- if (response.body === null) return response.json();
412
+ if (response.body === null) {
413
+ const text = await response.text();
414
+ budget.remaining -= text.length;
415
+ if (budget.remaining < 0) throw tooLarge();
416
+ return [JSON.parse(text), text.length];
417
+ }
249
418
  const reader = response.body.getReader();
250
419
  const decoder = new TextDecoder();
251
420
  const parts: string[] = [];
@@ -254,14 +423,65 @@ async function readBoundedJson(response: Response, label: string): Promise<unkno
254
423
  const { done, value } = await reader.read();
255
424
  if (done) break;
256
425
  size += value.byteLength;
257
- if (size > MAX_SNAPSHOT_BYTES) {
426
+ budget.remaining -= value.byteLength;
427
+ if (budget.remaining < 0) {
258
428
  await reader.cancel();
259
429
  throw tooLarge();
260
430
  }
261
431
  parts.push(decoder.decode(value, { stream: true }));
262
432
  }
263
433
  parts.push(decoder.decode());
264
- return JSON.parse(parts.join(""));
434
+ return [JSON.parse(parts.join("")), size];
435
+ }
436
+
437
+ /** Validates a draft overlay manifest; throws on an unknown format or any unexpected shape. */
438
+ function parseOverlay(body: unknown): DraftOverlay {
439
+ const invalid = (why: string) => new Error(`draft overlay: ${why}`);
440
+ if (!isPlainObject(body) || body.format !== DRAFT_OVERLAY_FORMAT) {
441
+ throw invalid("unknown format");
442
+ }
443
+ if (Object.keys(body).some((key) => key !== "format" && key !== "set" && key !== "delete")) {
444
+ throw invalid("unexpected field");
445
+ }
446
+ const { set, delete: deleted } = body;
447
+ if (!isPlainObject(set)) throw invalid("set must be an object");
448
+ for (const hash of Object.values(set)) {
449
+ if (typeof hash !== "string" || !HASH_RE.test(hash)) throw invalid("set names a bad hash");
450
+ }
451
+ if (!Array.isArray(deleted) || deleted.some((name) => typeof name !== "string")) {
452
+ throw invalid("delete must be a list of names");
453
+ }
454
+ if (new Set(deleted).size !== deleted.length) throw invalid("delete repeats a name");
455
+ if (deleted.some((name) => Object.hasOwn(set, name))) throw invalid("set and delete overlap");
456
+ return body as unknown as DraftOverlay;
457
+ }
458
+
459
+ /**
460
+ * The draft as a snapshot: the captured production entries, with the
461
+ * overlay's replacements and without its tombstones. A shallow copy: every
462
+ * unchanged entry is production's own object, and production is never
463
+ * mutated. Its revision is an opaque identity of the pair, not a content hash.
464
+ */
465
+ function composeOverlay(
466
+ base: Snapshot,
467
+ overlay: DraftOverlay,
468
+ values: Map<string, unknown>,
469
+ version: string,
470
+ ): Snapshot {
471
+ const blocks: Record<string, unknown> = { ...base.blocks };
472
+ for (const name of overlay.delete) delete blocks[name];
473
+ for (const [name, hash] of Object.entries(overlay.set)) {
474
+ // defineProperty, so an entry named "__proto__" stays an entry.
475
+ Object.defineProperty(blocks, name, {
476
+ value: values.get(hash),
477
+ enumerable: true,
478
+ writable: true,
479
+ configurable: true,
480
+ });
481
+ }
482
+ const view: Snapshot = { revision: `${base.revision}~${version}`, blocks };
483
+ if (base.aliases !== undefined) view.aliases = base.aliases;
484
+ return view;
265
485
  }
266
486
 
267
487
  function fetchWithTimeout(url: string, headers: Record<string, string>): Promise<Response> {
package/src/v8/types.ts CHANGED
@@ -47,10 +47,23 @@ export interface Loader {
47
47
  export interface DraftPointer {
48
48
  /** `host[:port]` of the content source that holds the draft. */
49
49
  host: string;
50
- /** Starts with `/`; opaque to the app. */
50
+ /** Starts with `/`; opaque to the app. Never carries the `__variant` parameters. */
51
51
  path: string;
52
52
  /** Opaque and immutable: the branch head or ETag. */
53
53
  version: string;
54
+ /** The variants this preview forces (the query's `__variant` parameters); absent when none. */
55
+ variants?: ForcedVariant[];
56
+ }
57
+
58
+ /**
59
+ * A variant a preview forces: the multivariate block at `path` (dot-separated
60
+ * keys and indexes, `""` for the saved block itself) inside the saved block
61
+ * `block` shows its variant `index` instead of evaluating rules.
62
+ */
63
+ export interface ForcedVariant {
64
+ block: string;
65
+ path: string;
66
+ index: number;
54
67
  }
55
68
 
56
69
  // ---------------------------------------------------------------------------
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Forced variants (see /next/releases-and-drafts#preview-a-variant): the
3
+ * variants a draft pointer's `__variant` parameters name, applied to a
4
+ * snapshot for one preview. Each addressed multivariate keeps only the forced
5
+ * variant, with the rule `true`, so it shows that variant's value and no other
6
+ * rule runs. The snapshot is copied along the addressed paths only; the shared
7
+ * one is never touched.
8
+ *
9
+ * An address that doesn't reach a multivariate block with that variant (a
10
+ * renamed block, a moved section, an index past the end) is ignored, so a
11
+ * stale preview link renders the content as saved.
12
+ */
13
+ import { LEGACY_ALIASES } from "./builtins/legacy.ts";
14
+ import { isPlainObject, own } from "./json.ts";
15
+ import type { ForcedVariant, Snapshot } from "./types.ts";
16
+
17
+ export function forceVariants(
18
+ snapshot: Snapshot,
19
+ variants: readonly ForcedVariant[] | undefined,
20
+ ): Snapshot {
21
+ if (variants === undefined || variants.length === 0) return snapshot;
22
+ let blocks: Record<string, unknown> | undefined;
23
+ for (const { block, path, index } of variants) {
24
+ const entry = own(blocks ?? snapshot.blocks, block);
25
+ if (entry === undefined) continue;
26
+ const keys = path === "" ? [] : path.split(".");
27
+ const next = forceAt(entry, keys, index, snapshot);
28
+ if (next === entry) continue;
29
+ blocks ??= { ...snapshot.blocks };
30
+ blocks[block] = next;
31
+ }
32
+ return blocks === undefined ? snapshot : { ...snapshot, blocks };
33
+ }
34
+
35
+ function forceAt(node: unknown, keys: string[], index: number, snapshot: Snapshot): unknown {
36
+ if (keys.length === 0) return forceNode(node, index, snapshot);
37
+ const [key, ...rest] = keys as [string, ...string[]];
38
+ if (Array.isArray(node)) {
39
+ const i = Number(key);
40
+ if (!Number.isInteger(i) || String(i) !== key || i < 0 || i >= node.length) return node;
41
+ const child = forceAt(node[i], rest, index, snapshot);
42
+ if (child === node[i]) return node;
43
+ const copy = node.slice();
44
+ copy[i] = child;
45
+ return copy;
46
+ }
47
+ if (!isPlainObject(node) || !Object.hasOwn(node, key)) return node;
48
+ const child = forceAt(node[key], rest, index, snapshot);
49
+ return child === node[key] ? node : { ...node, [key]: child };
50
+ }
51
+
52
+ /** A multivariate block (by its own name or an alias) with only `variants[index]`, ruled `true`. */
53
+ function forceNode(node: unknown, index: number, snapshot: Snapshot): unknown {
54
+ if (!isPlainObject(node) || typeof node.__resolveType !== "string") return node;
55
+ const type = node.__resolveType;
56
+ const canonical = own(snapshot.aliases, type) ?? own(LEGACY_ALIASES, type) ?? type;
57
+ if (canonical !== "multivariate" || !Array.isArray(node.variants)) return node;
58
+ const variant = node.variants[index];
59
+ if (!isPlainObject(variant)) return node;
60
+ return { ...node, variants: [{ ...variant, rule: true }] };
61
+ }