@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
@@ -115,3 +115,39 @@ export const APPLY_DIGEST_DOMAIN = "deco-content/blocks.apply@1\n";
115
115
  export function applyRequestDigest(params: object): Promise<string> {
116
116
  return sha256Hex(APPLY_DIGEST_DOMAIN + canonicalJson(params));
117
117
  }
118
+
119
+ /** The version of the draft overlay manifest format below. */
120
+ export const DRAFT_OVERLAY_FORMAT = 1;
121
+
122
+ /**
123
+ * A draft overlay manifest (see /next/content-delivery#exact-draft-previews):
124
+ * the complete, cumulative set of a draft's changes, never a patch over an
125
+ * earlier version. `set` maps each changed entry's name to the block hash of
126
+ * its JSON; `delete` names the entries the draft removed (tombstones). The two
127
+ * are disjoint. There is no base revision: a preview server layers it over the
128
+ * production content it already has.
129
+ */
130
+ export interface DraftOverlay {
131
+ format: typeof DRAFT_OVERLAY_FORMAT;
132
+ set: Record<string, string>;
133
+ delete: string[];
134
+ }
135
+
136
+ /**
137
+ * The block hash of one changed entry: SHA-256 over its canonical JSON,
138
+ * lowercase hex. A draft block asset is stored under it
139
+ * (`/sites/<site>/draft-blocks/<block-hash>.json`), and the SDK checks every
140
+ * asset it downloads hashes to its name.
141
+ */
142
+ export function computeBlockHash(entry: unknown): Promise<string> {
143
+ return sha256Hex(canonicalJson(entry));
144
+ }
145
+
146
+ /**
147
+ * The overlay version: SHA-256 over the manifest's canonical JSON, lowercase
148
+ * hex. The manifest is stored under it (`/sites/<site>/drafts/<version>.json`)
149
+ * and a draft pointer names it after its `@`.
150
+ */
151
+ export function computeOverlayVersion(overlay: DraftOverlay): Promise<string> {
152
+ return sha256Hex(canonicalJson(overlay));
153
+ }
@@ -27,6 +27,7 @@ import {
27
27
  awaitedOf,
28
28
  getJsDocTags,
29
29
  isDescriptorType,
30
+ isFreeFormMap,
30
31
  isJsxType,
31
32
  nonNullable,
32
33
  RESOLVABLE_KEY,
@@ -283,7 +284,7 @@ export async function generateSchema(paths: DecoPaths): Promise<SchemaResult> {
283
284
  root,
284
285
  fitting(type) {
285
286
  const target = nonNullable(type);
286
- if (target.isAny() || target.isUnknown()) return [];
287
+ if (target.isAny() || target.isUnknown() || isFreeFormMap(target)) return [];
287
288
  const cached = fitCache.get(target.compilerType);
288
289
  if (cached) return cached;
289
290
  const keys = candidates
@@ -321,6 +321,23 @@ export class TsNode {
321
321
  return t && typeof t === "object" && "kind" in t ? this.ctx.node(t) : undefined;
322
322
  }
323
323
 
324
+ /**
325
+ * The declarations of the type aliases a type annotation names, as written:
326
+ * `Kind` and `Kind | null` both give `Kind`'s. The checker drops the alias
327
+ * from `Kind | undefined`, so this is how a field finds its alias.
328
+ */
329
+ getAliasDeclarationTexts(): string[] {
330
+ const ts = this.ctx.ts;
331
+ const node = this.compilerNode as TS.TypeNode;
332
+ const members = ts.isUnionTypeNode(node) ? node.types : [node];
333
+ const texts: string[] = [];
334
+ for (const member of members) {
335
+ const decl = this.ctx.checker.getTypeFromTypeNode(member).aliasSymbol?.declarations?.[0];
336
+ if (decl) texts.push(decl.getText(decl.getSourceFile()));
337
+ }
338
+ return texts;
339
+ }
340
+
324
341
  /** Whether `other` is this node or inside it. */
325
342
  contains(other: TsNode): boolean {
326
343
  const a = this.compilerNode;
@@ -123,9 +123,20 @@ function parseOptions(raw: string): { values: (string | number)[]; labels?: stri
123
123
  return labelled ? { values, labels } : { values };
124
124
  }
125
125
 
126
+ /**
127
+ * `@format` spellings that name a standard format under another name, kept
128
+ * from v7: `@format datetime` (Eitri's vocabulary) is the `date-time` picker,
129
+ * and `deco check` validates it as one.
130
+ */
131
+ const FORMAT_ALIASES: Record<string, string> = { datetime: "date-time" };
132
+
126
133
  function applyJsDocToSchema(schema: any, tags: Record<string, string>): void {
127
134
  for (const [tag, value] of Object.entries(tags)) {
128
135
  if (tag === "ignore") continue;
136
+ if (tag === "format") {
137
+ schema.format = FORMAT_ALIASES[value] ?? value;
138
+ continue;
139
+ }
129
140
  if (tag === "hide") {
130
141
  schema.hide = "true";
131
142
  continue;
@@ -324,6 +335,19 @@ export function nonNullable(type: Type): Type {
324
335
  return parts.length === 1 ? parts[0] : type.getNonNullableType();
325
336
  }
326
337
 
338
+ /**
339
+ * `Record<string, any>` and friends: a map of anything, which every block's
340
+ * output fits. It's a free-form value, not a place for a block, so the field
341
+ * doesn't offer the saved-block picker or list every block as a choice.
342
+ */
343
+ export function isFreeFormMap(type: Type): boolean {
344
+ const t = nonNullable(type);
345
+ if (!t.isObject() || t.getProperties().length > 0 || t.getCallSignatures().length > 0)
346
+ return false;
347
+ const value = t.getStringIndexType() ?? t.getNumberIndexType();
348
+ return value !== undefined && (value.isAny() || value.isUnknown());
349
+ }
350
+
327
351
  /** Types a block can fill: objects, arrays and intersections of objects, not primitives. */
328
352
  function isObjectLike(type: Type): boolean {
329
353
  const t = nonNullable(type);
@@ -434,10 +458,51 @@ function fieldSchema(
434
458
  }
435
459
 
436
460
  const schema = typeToJsonSchema(propType, new Set(visited), ctx);
461
+ orderEnumByHint(schema, typeHint);
437
462
  applyWidgetFormat(schema, typeHint);
438
463
  return schema;
439
464
  }
440
465
 
466
+ /**
467
+ * Literal values in the order `text` (the declaration as written) spells them.
468
+ * The checker orders a union's members by when it first met each literal,
469
+ * which another file can change, so `"a" | "b"` could come out as `["b", "a"]`.
470
+ * Values `text` doesn't spell all of keep the checker's order.
471
+ */
472
+ export function inDeclaredOrder<T extends string | number>(values: T[], text: string): T[] {
473
+ const at = values.map((value) => {
474
+ const spelled =
475
+ typeof value === "string"
476
+ ? [`"${value}"`, `'${value}'`, `\`${value}\``]
477
+ .map((q) => text.indexOf(q))
478
+ .filter((i) => i >= 0)
479
+ : [
480
+ ...text.matchAll(
481
+ new RegExp(`(?<![\\w.])${String(value).replace(".", "\\.")}(?![\\w.])`, "g"),
482
+ ),
483
+ ].map((m) => m.index ?? -1);
484
+ return spelled.length > 0 ? Math.min(...spelled) : -1;
485
+ });
486
+ if (at.some((i) => i < 0)) return values;
487
+ return values
488
+ .map((value, i) => ({ value, at: at[i] }))
489
+ .sort((a, b) => a.at - b.at)
490
+ .map((e) => e.value);
491
+ }
492
+
493
+ /** Reorder a literal select (or a list of them) by the field's annotation. */
494
+ function orderEnumByHint(schema: any, typeHint: string): void {
495
+ if (Array.isArray(schema?.enum)) schema.enum = inDeclaredOrder(schema.enum, typeHint);
496
+ else if (Array.isArray(schema?.items?.enum)) {
497
+ schema.items.enum = inDeclaredOrder(schema.items.enum, typeHint);
498
+ }
499
+ }
500
+
501
+ /** The declaration text of a type alias, for ordering its literal members. */
502
+ function aliasDeclarationText(type: Type): string {
503
+ return type.getAliasSymbol()?.getDeclarations()[0]?.getText() ?? "";
504
+ }
505
+
441
506
  /** The "plain value" branch of a field that blocks can fill. */
442
507
  function inlineSchema(type: Type, ctx: SchemaContext, visited: Set<string>): any {
443
508
  if (type.isArray()) {
@@ -514,12 +579,20 @@ export function typeToJsonSchema(
514
579
  }
515
580
  // String-literal unions and string enums: a select, written into the schema.
516
581
  if (nonNull.every((t) => t.isStringLiteral())) {
517
- const result: any = { type: "string", enum: nonNull.map((t) => t.getLiteralValue()) };
582
+ const values = nonNull.map((t) => t.getLiteralValue() as string);
583
+ const result: any = {
584
+ type: "string",
585
+ enum: inDeclaredOrder(values, aliasDeclarationText(type)),
586
+ };
518
587
  if (isNullable) result.nullable = true;
519
588
  return result;
520
589
  }
521
590
  if (nonNull.every((t) => t.isNumberLiteral())) {
522
- const result: any = { type: "number", enum: nonNull.map((t) => t.getLiteralValue()) };
591
+ const values = nonNull.map((t) => t.getLiteralValue() as number);
592
+ const result: any = {
593
+ type: "number",
594
+ enum: inDeclaredOrder(values, aliasDeclarationText(type)),
595
+ };
523
596
  if (isNullable) result.nullable = true;
524
597
  return result;
525
598
  }
@@ -630,6 +703,7 @@ export function typeToJsonSchema(
630
703
  }
631
704
 
632
705
  const schema = fieldSchema(propType, typeHint, ctx, visited);
706
+ if (typeNode) orderEnumByHint(schema, typeNode.getAliasDeclarationTexts().join("\n"));
633
707
  if (schema.anyOf && schema.anyOf[0]?.$ref === resolvableRef().$ref) {
634
708
  // A block-ref field: nullability lives on the wrapper.
635
709
  if (isNullableHint(optional, typeHint)) schema.nullable = true;
package/src/v8/cms.ts CHANGED
@@ -11,10 +11,12 @@ import { builtIns } from "./builtins/index.ts";
11
11
  import { secretBlock } from "./builtins/secret.ts";
12
12
  import { CMSClient } from "./client.ts";
13
13
  import { ContentStore, isLoader, isSnapshot } from "./content.ts";
14
+ import { parseDraftPointer } from "./draft.ts";
14
15
  import { clearGlobals, contentIdentity, fnv1a, readEnv } from "./identity.ts";
15
16
  import { remoteLoader, resetRemoteLoaders } from "./remoteLoader.ts";
16
17
  import { resolveDestination, setCurrentTelemetry, TelemetryPipeline } from "./telemetry.ts";
17
18
  import type { Blocks, Client, CMS, CMSConfig, Loader, Snapshot } from "./types.ts";
19
+ import { forceVariants } from "./variants.ts";
18
20
 
19
21
  const INSTANCE_PREFIX = "decocms.blocks.cms:";
20
22
  const MIN_INTERVAL = 60_000;
@@ -39,7 +41,7 @@ class CMSInstance implements CMS {
39
41
  readonly #telemetry: TelemetryPipeline | undefined;
40
42
  #blocks: Blocks;
41
43
  /**
42
- * When the next check is due. The first is on the first `forRelease()`, not
44
+ * When the next check is due. The first is on the first `forRelease()` or `forDraft()`, not
43
45
  * at construction: Workers read `Date.now()` as 0 at module scope.
44
46
  */
45
47
  #nextCheck: number | undefined;
@@ -73,8 +75,18 @@ class CMSInstance implements CMS {
73
75
  );
74
76
  }
75
77
 
78
+ /**
79
+ * The draft, with the variants the pointer forces (even over a source with no
80
+ * drafts). A draft inherits local production, so it schedules the same
81
+ * background release check `forRelease()` does (never in front of the draft).
82
+ */
76
83
  forDraft(pointer: string): Client {
77
- return this.#client(() => this.#store.draft(pointer));
84
+ this.#scheduleUpdate();
85
+ const variants = parseDraftPointer(pointer)?.variants;
86
+ if (variants === undefined) return this.#client(() => this.#store.draft(pointer));
87
+ return this.#client(() =>
88
+ this.#store.draft(pointer).then((snapshot) => forceVariants(snapshot, variants)),
89
+ );
78
90
  }
79
91
 
80
92
  forRevision(revision: string): Client {
package/src/v8/content.ts CHANGED
@@ -13,7 +13,13 @@ import { isPlainObject } from "./json.ts";
13
13
  import type { Loader, Snapshot } from "./types.ts";
14
14
 
15
15
  const SERVED_REVISIONS = 16;
16
- const CACHED_DRAFTS = 32;
16
+ /** Composed drafts kept per CMS (see /next/studio-implementation's initial limits). */
17
+ const CACHED_DRAFTS = 3;
18
+ /**
19
+ * How long a loaded draft is reused before `load(pointer)` runs again, so a
20
+ * loader's own checks (a hosted grant's expiry) apply on a warm server too.
21
+ */
22
+ const DRAFT_TTL_MS = 60_000;
17
23
 
18
24
  export function isLoader(content: unknown): content is Loader {
19
25
  return (
@@ -36,7 +42,9 @@ export class ContentStore {
36
42
  #source: Snapshot | Loader;
37
43
  #release: Promise<Snapshot> | undefined;
38
44
  #updating: Promise<{ updated: boolean }> | undefined;
39
- readonly #drafts = new BoundedMap<string, Promise<Snapshot>>(CACHED_DRAFTS);
45
+ readonly #drafts = new BoundedMap<string, { pending: Promise<Snapshot>; at: number }>(
46
+ CACHED_DRAFTS,
47
+ );
40
48
  readonly #served = new BoundedMap<string, Snapshot>(SERVED_REVISIONS);
41
49
 
42
50
  constructor(source: Snapshot | Loader) {
@@ -70,8 +78,10 @@ export class ContentStore {
70
78
 
71
79
  /**
72
80
  * The draft a pointer names. A snapshot has no drafts and ignores the
73
- * pointer. A loader gets `load(pointer)` only for a pointer that parses;
74
- * anything else is `LOADER_FAILED`, never a silent fallback to the release.
81
+ * pointer. A loader gets `load(pointer)` only for a pointer that parses,
82
+ * formatted again without its `__variant` parameters (so every variant of
83
+ * one draft shares one load); anything else is `LOADER_FAILED`, never a
84
+ * silent fallback to the release. A loaded draft is reused for a minute.
75
85
  */
76
86
  draft(pointer: string): Promise<Snapshot> {
77
87
  const source = this.#source;
@@ -80,13 +90,20 @@ export class ContentStore {
80
90
  if (parsed === null) {
81
91
  return Promise.reject(errors.loaderFailed(`invalid draft pointer "${truncate(pointer)}"`));
82
92
  }
83
- const key = formatDraftPointer(parsed);
93
+ // The draft itself, without the variants a preview forces: those apply per client.
94
+ const key = formatDraftPointer({
95
+ host: parsed.host,
96
+ path: parsed.path,
97
+ version: parsed.version,
98
+ });
84
99
  const cached = this.#drafts.get(key);
85
- if (cached !== undefined) return cached;
86
- const pending = this.#load(source, pointer);
87
- this.#drafts.set(key, pending);
88
- pending.catch(() => this.#drafts.delete(key));
89
- return pending;
100
+ if (cached !== undefined && Date.now() - cached.at < DRAFT_TTL_MS) return cached.pending;
101
+ const entry = { pending: this.#load(source, key), at: Date.now() };
102
+ this.#drafts.set(key, entry);
103
+ entry.pending.catch(() => {
104
+ if (this.#drafts.get(key) === entry) this.#drafts.delete(key);
105
+ });
106
+ return entry.pending;
90
107
  }
91
108
 
92
109
  /** A release revision this store has served, or the release when it's unknown (drafts included). */
@@ -131,7 +148,9 @@ export class ContentStore {
131
148
  const previous = this.#source;
132
149
  if (source === previous) {
133
150
  // The same loader (a hosted remoteLoader that adopted new fallback content): re-read it.
151
+ // Cached drafts were layered over the old content, so they go too.
134
152
  this.#release = undefined;
153
+ this.#drafts.clear();
135
154
  return;
136
155
  }
137
156
  if (isSnapshot(previous)) this.#served.delete(previous.revision);
@@ -167,29 +186,46 @@ function truncate(value: string): string {
167
186
  return value.length > 80 ? `${value.slice(0, 80)}…` : value;
168
187
  }
169
188
 
170
- /** A Map that forgets its least recently set entry past `limit`. */
171
- class BoundedMap<K, V> {
189
+ /**
190
+ * A Map that forgets its least recently used entries past `limit`, counted by
191
+ * `size` (one per entry unless given).
192
+ */
193
+ export class BoundedMap<K, V> {
172
194
  readonly #map = new Map<K, V>();
173
- constructor(readonly limit: number) {}
195
+ #total = 0;
196
+ constructor(
197
+ readonly limit: number,
198
+ readonly size: (value: V) => number = () => 1,
199
+ ) {}
174
200
 
175
201
  get(key: K): V | undefined {
176
- return this.#map.get(key);
202
+ const value = this.#map.get(key);
203
+ if (value !== undefined) {
204
+ this.#map.delete(key);
205
+ this.#map.set(key, value);
206
+ }
207
+ return value;
177
208
  }
178
209
 
179
210
  set(key: K, value: V): void {
180
- this.#map.delete(key);
211
+ this.delete(key);
181
212
  this.#map.set(key, value);
182
- if (this.#map.size > this.limit) {
183
- const oldest = this.#map.keys().next();
184
- if (!oldest.done) this.#map.delete(oldest.value);
213
+ this.#total += this.size(value);
214
+ for (const [oldest, old] of this.#map) {
215
+ if (this.#total <= this.limit || oldest === key) break;
216
+ this.#map.delete(oldest);
217
+ this.#total -= this.size(old);
185
218
  }
186
219
  }
187
220
 
188
221
  delete(key: K): void {
222
+ if (!this.#map.has(key)) return;
223
+ this.#total -= this.size(this.#map.get(key) as V);
189
224
  this.#map.delete(key);
190
225
  }
191
226
 
192
227
  clear(): void {
193
228
  this.#map.clear();
229
+ this.#total = 0;
194
230
  }
195
231
  }
package/src/v8/draft.ts CHANGED
@@ -2,8 +2,12 @@
2
2
  * Draft pointers (see /next/api-reference#draft-pointers): the string
3
3
  * `<host[:port]><path[?query]>@<version>` that names a draft, and the two
4
4
  * helpers that carry one from a `?__draft=` link into a cookie.
5
+ *
6
+ * The query's reserved `__variant` parameters are the variants a preview
7
+ * forces (`<block>@<path>=<index>`, URL-encoded, one per multivariate); the
8
+ * parser lifts them out of `path` into `variants`.
5
9
  */
6
- import type { DraftPointer } from "./types.ts";
10
+ import type { DraftPointer, ForcedVariant } from "./types.ts";
7
11
 
8
12
  /** The draft cookie's name, for frameworks whose cookie API has no Request (Next.js `cookies()`). */
9
13
  export const DRAFT_COOKIE = "deco-draft";
@@ -18,6 +22,8 @@ const VERSION_RE = /^[A-Za-z0-9._-]{1,64}$/;
18
22
  /** Rooted path with an optional query; no `@`, `#`, whitespace or scheme characters. */
19
23
  const PATH_RE = /^\/[A-Za-z0-9/_.%~=&?-]*$/;
20
24
  const MAX_POINTER_LENGTH = 4096;
25
+ const VARIANT_PARAM = "__variant=";
26
+ const INDEX_RE = /^(0|[1-9][0-9]{0,3})$/;
21
27
 
22
28
  /**
23
29
  * Parses a pointer, strictly: `null` on a scheme, a stray `@`, an unrooted
@@ -39,7 +45,12 @@ export function parseDraftPointer(raw: string | null | undefined): DraftPointer
39
45
  if (!PATH_RE.test(path) || path.startsWith("//")) return null;
40
46
 
41
47
  const host = normalizeHost(location.slice(0, slash));
42
- return host === null ? null : { host, path, version };
48
+ if (host === null) return null;
49
+ const split = splitVariants(path);
50
+ if (split === null) return null;
51
+ return split.variants.length === 0
52
+ ? { host, path, version }
53
+ : { host, path: split.path, version, variants: split.variants };
43
54
  }
44
55
 
45
56
  /**
@@ -48,12 +59,70 @@ export function parseDraftPointer(raw: string | null | undefined): DraftPointer
48
59
  * bad pointer is caught where it's built rather than where it's loaded.
49
60
  */
50
61
  export function formatDraftPointer(pointer: DraftPointer): string {
51
- const raw = `${pointer.host}${pointer.path}@${pointer.version}`;
52
- const parsed = parseDraftPointer(raw);
53
- if (parsed === null || parsed.path !== pointer.path || parsed.version !== pointer.version) {
62
+ const variants = pointer.variants ?? [];
63
+ const params = variants.map((variant) => VARIANT_PARAM + encodeVariant(variant));
64
+ const path =
65
+ params.length === 0
66
+ ? pointer.path
67
+ : `${pointer.path}${pointer.path.includes("?") ? "&" : "?"}${params.join("&")}`;
68
+ const parsed = parseDraftPointer(`${pointer.host}${path}@${pointer.version}`);
69
+ if (
70
+ parsed === null ||
71
+ parsed.path !== pointer.path ||
72
+ parsed.version !== pointer.version ||
73
+ JSON.stringify(parsed.variants ?? []) !== JSON.stringify(variants.map(plainVariant))
74
+ ) {
54
75
  throw new TypeError(`invalid draft pointer parts: ${JSON.stringify(pointer)}`);
55
76
  }
56
- return `${parsed.host}${parsed.path}@${parsed.version}`;
77
+ return `${parsed.host}${path}@${parsed.version}`;
78
+ }
79
+
80
+ /** The path without its `__variant` parameters, and the variants they force; `null` on a bad one. */
81
+ function splitVariants(path: string): { path: string; variants: ForcedVariant[] } | null {
82
+ const q = path.indexOf("?");
83
+ if (q === -1) return { path, variants: [] };
84
+ const kept: string[] = [];
85
+ const variants: ForcedVariant[] = [];
86
+ for (const param of path.slice(q + 1).split("&")) {
87
+ if (!param.startsWith(VARIANT_PARAM)) {
88
+ kept.push(param);
89
+ continue;
90
+ }
91
+ const variant = decodeVariant(param.slice(VARIANT_PARAM.length));
92
+ if (variant === null) return null;
93
+ variants.push(variant);
94
+ }
95
+ const base = path.slice(0, q);
96
+ return { path: kept.length === 0 ? base : `${base}?${kept.join("&")}`, variants };
97
+ }
98
+
99
+ /** `<block>@<path>=<index>`: the index after the last `=`, the block before the last `@`. */
100
+ function decodeVariant(encoded: string): ForcedVariant | null {
101
+ let raw: string;
102
+ try {
103
+ raw = decodeURIComponent(encoded);
104
+ } catch {
105
+ return null;
106
+ }
107
+ const eq = raw.lastIndexOf("=");
108
+ const at = raw.lastIndexOf("@", eq);
109
+ if (eq === -1 || at <= 0) return null;
110
+ const index = raw.slice(eq + 1);
111
+ const path = raw.slice(at + 1, eq);
112
+ if (!INDEX_RE.test(index) || (path !== "" && path.split(".").includes(""))) return null;
113
+ return { block: raw.slice(0, at), path, index: Number(index) };
114
+ }
115
+
116
+ function encodeVariant({ block, path, index }: ForcedVariant): string {
117
+ // encodeURIComponent leaves !'()* as they are; the pointer's path doesn't allow them.
118
+ return encodeURIComponent(`${block}@${path}=${index}`).replace(
119
+ /[!'()*]/g,
120
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
121
+ );
122
+ }
123
+
124
+ function plainVariant({ block, path, index }: ForcedVariant): ForcedVariant {
125
+ return { block, path, index };
57
126
  }
58
127
 
59
128
  function normalizeHost(authority: string): string | null {