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

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 (125) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/protocol/conformance/contentHashFixtures.d.ts +29 -0
  6. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
  7. package/dist/protocol/conformance/contentHashFixtures.js +30 -0
  8. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
  9. package/dist/protocol/conformance/index.d.ts +1 -1
  10. package/dist/protocol/conformance/index.d.ts.map +1 -1
  11. package/dist/protocol/conformance/index.js +1 -1
  12. package/dist/protocol/conformance/index.js.map +1 -1
  13. package/dist/protocol/index.d.ts +5 -2
  14. package/dist/protocol/index.d.ts.map +1 -1
  15. package/dist/protocol/index.js +5 -2
  16. package/dist/protocol/index.js.map +1 -1
  17. package/dist/protocol/secrets.d.ts.map +1 -1
  18. package/dist/protocol/secrets.js +9 -2
  19. package/dist/protocol/secrets.js.map +1 -1
  20. package/dist/protocol/server/assets.d.ts +1 -1
  21. package/dist/protocol/server/assets.js +1 -1
  22. package/dist/v8/builtins/data.d.ts +21 -5
  23. package/dist/v8/builtins/data.d.ts.map +1 -1
  24. package/dist/v8/builtins/data.js +47 -6
  25. package/dist/v8/builtins/data.js.map +1 -1
  26. package/dist/v8/builtins/index.d.ts.map +1 -1
  27. package/dist/v8/builtins/index.js +2 -3
  28. package/dist/v8/builtins/index.js.map +1 -1
  29. package/dist/v8/canonical.d.ts +28 -0
  30. package/dist/v8/canonical.d.ts.map +1 -1
  31. package/dist/v8/canonical.js +19 -0
  32. package/dist/v8/canonical.js.map +1 -1
  33. package/dist/v8/cli/check/index.d.ts.map +1 -1
  34. package/dist/v8/cli/check/index.js +13 -1
  35. package/dist/v8/cli/check/index.js.map +1 -1
  36. package/dist/v8/cli/index.d.ts +2 -1
  37. package/dist/v8/cli/index.d.ts.map +1 -1
  38. package/dist/v8/cli/index.js +2 -1
  39. package/dist/v8/cli/index.js.map +1 -1
  40. package/dist/v8/cli/run.d.ts.map +1 -1
  41. package/dist/v8/cli/run.js +2 -9
  42. package/dist/v8/cli/run.js.map +1 -1
  43. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  44. package/dist/v8/cli/schema/builtinSchemas.js +48 -28
  45. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  46. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  47. package/dist/v8/cli/schema/generate.js +2 -2
  48. package/dist/v8/cli/schema/generate.js.map +1 -1
  49. package/dist/v8/cli/schema/tsProgram.d.ts +16 -0
  50. package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -1
  51. package/dist/v8/cli/schema/tsProgram.js +48 -0
  52. package/dist/v8/cli/schema/tsProgram.js.map +1 -1
  53. package/dist/v8/cli/schema/typeToSchema.d.ts +13 -0
  54. package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
  55. package/dist/v8/cli/schema/typeToSchema.js +85 -2
  56. package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
  57. package/dist/v8/cli/serve/server.d.ts +0 -4
  58. package/dist/v8/cli/serve/server.d.ts.map +1 -1
  59. package/dist/v8/cli/serve/server.js +20 -46
  60. package/dist/v8/cli/serve/server.js.map +1 -1
  61. package/dist/v8/cms.d.ts +5 -2
  62. package/dist/v8/cms.d.ts.map +1 -1
  63. package/dist/v8/cms.js +188 -20
  64. package/dist/v8/cms.js.map +1 -1
  65. package/dist/v8/content.d.ts +32 -2
  66. package/dist/v8/content.d.ts.map +1 -1
  67. package/dist/v8/content.js +82 -19
  68. package/dist/v8/content.js.map +1 -1
  69. package/dist/v8/draft.d.ts +13 -12
  70. package/dist/v8/draft.d.ts.map +1 -1
  71. package/dist/v8/draft.js +75 -9
  72. package/dist/v8/draft.js.map +1 -1
  73. package/dist/v8/hosts.d.ts +55 -0
  74. package/dist/v8/hosts.d.ts.map +1 -0
  75. package/dist/v8/hosts.js +197 -0
  76. package/dist/v8/hosts.js.map +1 -0
  77. package/dist/v8/index.d.ts +4 -3
  78. package/dist/v8/index.d.ts.map +1 -1
  79. package/dist/v8/index.js +3 -2
  80. package/dist/v8/index.js.map +1 -1
  81. package/dist/v8/remoteLoader.d.ts.map +1 -1
  82. package/dist/v8/remoteLoader.js +222 -26
  83. package/dist/v8/remoteLoader.js.map +1 -1
  84. package/dist/v8/settings.d.ts +27 -0
  85. package/dist/v8/settings.d.ts.map +1 -0
  86. package/dist/v8/settings.js +130 -0
  87. package/dist/v8/settings.js.map +1 -0
  88. package/dist/v8/telemetry.d.ts +13 -3
  89. package/dist/v8/telemetry.d.ts.map +1 -1
  90. package/dist/v8/telemetry.js +31 -32
  91. package/dist/v8/telemetry.js.map +1 -1
  92. package/dist/v8/types.d.ts +69 -3
  93. package/dist/v8/types.d.ts.map +1 -1
  94. package/dist/v8/variants.d.ts +3 -0
  95. package/dist/v8/variants.d.ts.map +1 -0
  96. package/dist/v8/variants.js +65 -0
  97. package/dist/v8/variants.js.map +1 -0
  98. package/package.json +1 -1
  99. package/src/index.ts +3 -3
  100. package/src/protocol/conformance/contentHashFixtures.ts +57 -0
  101. package/src/protocol/conformance/index.ts +6 -1
  102. package/src/protocol/index.ts +8 -1
  103. package/src/protocol/secrets.ts +10 -2
  104. package/src/protocol/server/assets.ts +1 -1
  105. package/src/v8/builtins/data.ts +56 -7
  106. package/src/v8/builtins/index.ts +2 -3
  107. package/src/v8/canonical.ts +36 -0
  108. package/src/v8/cli/check/index.ts +23 -1
  109. package/src/v8/cli/index.ts +2 -1
  110. package/src/v8/cli/run.ts +3 -8
  111. package/src/v8/cli/schema/builtinSchemas.ts +49 -28
  112. package/src/v8/cli/schema/generate.ts +2 -1
  113. package/src/v8/cli/schema/tsProgram.ts +44 -0
  114. package/src/v8/cli/schema/typeToSchema.ts +93 -2
  115. package/src/v8/cli/serve/server.ts +20 -55
  116. package/src/v8/cms.ts +235 -23
  117. package/src/v8/content.ts +84 -18
  118. package/src/v8/draft.ts +88 -15
  119. package/src/v8/hosts.ts +184 -0
  120. package/src/v8/index.ts +6 -8
  121. package/src/v8/remoteLoader.ts +258 -23
  122. package/src/v8/settings.ts +157 -0
  123. package/src/v8/telemetry.ts +43 -40
  124. package/src/v8/types.ts +62 -3
  125. package/src/v8/variants.ts +61 -0
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 (
@@ -23,6 +29,20 @@ export function isLoader(content: unknown): content is Loader {
23
29
  );
24
30
  }
25
31
 
32
+ /**
33
+ * An internal hook a built-in loader (`remoteLoader`) has: the release it
34
+ * would return right now, from memory, or `undefined` when that takes a load.
35
+ * `cms.settings()` reads through it, so it never fetches.
36
+ */
37
+ export const PEEK_RELEASE: unique symbol = Symbol.for("decocms.blocks.peekRelease");
38
+
39
+ /** The release a source holds in memory: the snapshot itself, or what a loader can peek. */
40
+ export function peekRelease(source: Snapshot | Loader): Snapshot | undefined {
41
+ if (!isLoader(source)) return source;
42
+ const peek = (source as { [PEEK_RELEASE]?: () => Snapshot | undefined })[PEEK_RELEASE];
43
+ return typeof peek === "function" ? peek.call(source) : undefined;
44
+ }
45
+
26
46
  export function isSnapshot(content: unknown): content is Snapshot {
27
47
  return (
28
48
  isPlainObject(content) &&
@@ -36,8 +56,12 @@ export class ContentStore {
36
56
  #source: Snapshot | Loader;
37
57
  #release: Promise<Snapshot> | undefined;
38
58
  #updating: Promise<{ updated: boolean }> | undefined;
39
- readonly #drafts = new BoundedMap<string, Promise<Snapshot>>(CACHED_DRAFTS);
59
+ readonly #drafts = new BoundedMap<string, { pending: Promise<Snapshot>; at: number }>(
60
+ CACHED_DRAFTS,
61
+ );
40
62
  readonly #served = new BoundedMap<string, Snapshot>(SERVED_REVISIONS);
63
+ /** The release this store last handed a client, for a loader that can't peek. */
64
+ #latest: Snapshot | undefined;
41
65
 
42
66
  constructor(source: Snapshot | Loader) {
43
67
  this.#source = source;
@@ -70,8 +94,10 @@ export class ContentStore {
70
94
 
71
95
  /**
72
96
  * 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.
97
+ * pointer. A loader gets `load(pointer)` only for a pointer that parses,
98
+ * formatted again without its `__variant` parameters (so every variant of
99
+ * one draft shares one load); anything else is `LOADER_FAILED`, never a
100
+ * silent fallback to the release. A loaded draft is reused for a minute.
75
101
  */
76
102
  draft(pointer: string): Promise<Snapshot> {
77
103
  const source = this.#source;
@@ -80,13 +106,29 @@ export class ContentStore {
80
106
  if (parsed === null) {
81
107
  return Promise.reject(errors.loaderFailed(`invalid draft pointer "${truncate(pointer)}"`));
82
108
  }
83
- const key = formatDraftPointer(parsed);
109
+ // The draft itself, without the variants a preview forces: those apply per client.
110
+ const key = formatDraftPointer({
111
+ host: parsed.host,
112
+ path: parsed.path,
113
+ version: parsed.version,
114
+ });
84
115
  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;
116
+ if (cached !== undefined && Date.now() - cached.at < DRAFT_TTL_MS) return cached.pending;
117
+ const entry = { pending: this.#load(source, key), at: Date.now() };
118
+ this.#drafts.set(key, entry);
119
+ entry.pending.catch(() => {
120
+ if (this.#drafts.get(key) === entry) this.#drafts.delete(key);
121
+ });
122
+ return entry.pending;
123
+ }
124
+
125
+ /**
126
+ * The current release as it is in memory, without loading anything: the
127
+ * content module, what a built-in loader holds, or the release this store
128
+ * last loaded. `undefined` before a custom loader's first load.
129
+ */
130
+ current(): Snapshot | undefined {
131
+ return peekRelease(this.#source) ?? this.#latest;
90
132
  }
91
133
 
92
134
  /** A release revision this store has served, or the release when it's unknown (drafts included). */
@@ -107,6 +149,8 @@ export class ContentStore {
107
149
  const updated = result?.updated === true;
108
150
  if (updated) {
109
151
  this.#release = undefined;
152
+ // `#latest` stays: settings keep the release that was serving until
153
+ // the next one loads, never the defaults (which may allow every host).
110
154
  // A loader that ignores the pointer hands back the release as the
111
155
  // draft; that copy is as stale as the release now.
112
156
  this.#drafts.clear();
@@ -131,12 +175,16 @@ export class ContentStore {
131
175
  const previous = this.#source;
132
176
  if (source === previous) {
133
177
  // The same loader (a hosted remoteLoader that adopted new fallback content): re-read it.
178
+ // Cached drafts were layered over the old content, so they go too.
134
179
  this.#release = undefined;
180
+ this.#latest = undefined;
181
+ this.#drafts.clear();
135
182
  return;
136
183
  }
137
184
  if (isSnapshot(previous)) this.#served.delete(previous.revision);
138
185
  this.#source = source;
139
186
  this.#release = undefined;
187
+ this.#latest = undefined;
140
188
  this.#drafts.clear();
141
189
  }
142
190
 
@@ -158,6 +206,7 @@ export class ContentStore {
158
206
  }
159
207
 
160
208
  #serve(snapshot: Snapshot): Snapshot {
209
+ this.#latest = snapshot;
161
210
  this.#served.set(snapshot.revision, snapshot);
162
211
  return snapshot;
163
212
  }
@@ -167,29 +216,46 @@ function truncate(value: string): string {
167
216
  return value.length > 80 ? `${value.slice(0, 80)}…` : value;
168
217
  }
169
218
 
170
- /** A Map that forgets its least recently set entry past `limit`. */
171
- class BoundedMap<K, V> {
219
+ /**
220
+ * A Map that forgets its least recently used entries past `limit`, counted by
221
+ * `size` (one per entry unless given).
222
+ */
223
+ export class BoundedMap<K, V> {
172
224
  readonly #map = new Map<K, V>();
173
- constructor(readonly limit: number) {}
225
+ #total = 0;
226
+ constructor(
227
+ readonly limit: number,
228
+ readonly size: (value: V) => number = () => 1,
229
+ ) {}
174
230
 
175
231
  get(key: K): V | undefined {
176
- return this.#map.get(key);
232
+ const value = this.#map.get(key);
233
+ if (value !== undefined) {
234
+ this.#map.delete(key);
235
+ this.#map.set(key, value);
236
+ }
237
+ return value;
177
238
  }
178
239
 
179
240
  set(key: K, value: V): void {
180
- this.#map.delete(key);
241
+ this.delete(key);
181
242
  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);
243
+ this.#total += this.size(value);
244
+ for (const [oldest, old] of this.#map) {
245
+ if (this.#total <= this.limit || oldest === key) break;
246
+ this.#map.delete(oldest);
247
+ this.#total -= this.size(old);
185
248
  }
186
249
  }
187
250
 
188
251
  delete(key: K): void {
252
+ if (!this.#map.has(key)) return;
253
+ this.#total -= this.size(this.#map.get(key) as V);
189
254
  this.#map.delete(key);
190
255
  }
191
256
 
192
257
  clear(): void {
193
258
  this.#map.clear();
259
+ this.#total = 0;
194
260
  }
195
261
  }
package/src/v8/draft.ts CHANGED
@@ -1,12 +1,18 @@
1
1
  /**
2
2
  * Draft pointers (see /next/api-reference#draft-pointers): the string
3
- * `<host[:port]><path[?query]>@<version>` that names a draft, and the two
4
- * helpers that carry one from a `?__draft=` link into a cookie.
3
+ * `<host[:port]><path[?query]>@<version>` that names a draft, and what
4
+ * `cms.draftPointer` and `cms.draftCookie` read and write to carry one from a
5
+ * `?__draft=` link into a cookie. The host check against the preview hosts is
6
+ * the CMS's: these read the request only.
7
+ *
8
+ * The query's reserved `__variant` parameters are the variants a preview
9
+ * forces (`<block>@<path>=<index>`, URL-encoded, one per multivariate); the
10
+ * parser lifts them out of `path` into `variants`.
5
11
  */
6
- import type { DraftPointer } from "./types.ts";
12
+ import type { DraftPointer, ForcedVariant, RequestLike } from "./types.ts";
7
13
 
8
- /** The draft cookie's name, for frameworks whose cookie API has no Request (Next.js `cookies()`). */
9
- export const DRAFT_COOKIE = "deco-draft";
14
+ /** The draft cookie's name. Not exported from the package: reading it directly would skip the host check. */
15
+ const DRAFT_COOKIE = "deco-draft";
10
16
 
11
17
  const DRAFT_PARAM = "__draft";
12
18
  const DRAFT_OFF = "off";
@@ -18,6 +24,8 @@ const VERSION_RE = /^[A-Za-z0-9._-]{1,64}$/;
18
24
  /** Rooted path with an optional query; no `@`, `#`, whitespace or scheme characters. */
19
25
  const PATH_RE = /^\/[A-Za-z0-9/_.%~=&?-]*$/;
20
26
  const MAX_POINTER_LENGTH = 4096;
27
+ const VARIANT_PARAM = "__variant=";
28
+ const INDEX_RE = /^(0|[1-9][0-9]{0,3})$/;
21
29
 
22
30
  /**
23
31
  * Parses a pointer, strictly: `null` on a scheme, a stray `@`, an unrooted
@@ -39,7 +47,12 @@ export function parseDraftPointer(raw: string | null | undefined): DraftPointer
39
47
  if (!PATH_RE.test(path) || path.startsWith("//")) return null;
40
48
 
41
49
  const host = normalizeHost(location.slice(0, slash));
42
- return host === null ? null : { host, path, version };
50
+ if (host === null) return null;
51
+ const split = splitVariants(path);
52
+ if (split === null) return null;
53
+ return split.variants.length === 0
54
+ ? { host, path, version }
55
+ : { host, path: split.path, version, variants: split.variants };
43
56
  }
44
57
 
45
58
  /**
@@ -48,12 +61,70 @@ export function parseDraftPointer(raw: string | null | undefined): DraftPointer
48
61
  * bad pointer is caught where it's built rather than where it's loaded.
49
62
  */
50
63
  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) {
64
+ const variants = pointer.variants ?? [];
65
+ const params = variants.map((variant) => VARIANT_PARAM + encodeVariant(variant));
66
+ const path =
67
+ params.length === 0
68
+ ? pointer.path
69
+ : `${pointer.path}${pointer.path.includes("?") ? "&" : "?"}${params.join("&")}`;
70
+ const parsed = parseDraftPointer(`${pointer.host}${path}@${pointer.version}`);
71
+ if (
72
+ parsed === null ||
73
+ parsed.path !== pointer.path ||
74
+ parsed.version !== pointer.version ||
75
+ JSON.stringify(parsed.variants ?? []) !== JSON.stringify(variants.map(plainVariant))
76
+ ) {
54
77
  throw new TypeError(`invalid draft pointer parts: ${JSON.stringify(pointer)}`);
55
78
  }
56
- return `${parsed.host}${parsed.path}@${parsed.version}`;
79
+ return `${parsed.host}${path}@${parsed.version}`;
80
+ }
81
+
82
+ /** The path without its `__variant` parameters, and the variants they force; `null` on a bad one. */
83
+ function splitVariants(path: string): { path: string; variants: ForcedVariant[] } | null {
84
+ const q = path.indexOf("?");
85
+ if (q === -1) return { path, variants: [] };
86
+ const kept: string[] = [];
87
+ const variants: ForcedVariant[] = [];
88
+ for (const param of path.slice(q + 1).split("&")) {
89
+ if (!param.startsWith(VARIANT_PARAM)) {
90
+ kept.push(param);
91
+ continue;
92
+ }
93
+ const variant = decodeVariant(param.slice(VARIANT_PARAM.length));
94
+ if (variant === null) return null;
95
+ variants.push(variant);
96
+ }
97
+ const base = path.slice(0, q);
98
+ return { path: kept.length === 0 ? base : `${base}?${kept.join("&")}`, variants };
99
+ }
100
+
101
+ /** `<block>@<path>=<index>`: the index after the last `=`, the block before the last `@`. */
102
+ function decodeVariant(encoded: string): ForcedVariant | null {
103
+ let raw: string;
104
+ try {
105
+ raw = decodeURIComponent(encoded);
106
+ } catch {
107
+ return null;
108
+ }
109
+ const eq = raw.lastIndexOf("=");
110
+ const at = raw.lastIndexOf("@", eq);
111
+ if (eq === -1 || at <= 0) return null;
112
+ const index = raw.slice(eq + 1);
113
+ const path = raw.slice(at + 1, eq);
114
+ if (!INDEX_RE.test(index) || (path !== "" && path.split(".").includes(""))) return null;
115
+ return { block: raw.slice(0, at), path, index: Number(index) };
116
+ }
117
+
118
+ function encodeVariant({ block, path, index }: ForcedVariant): string {
119
+ // encodeURIComponent leaves !'()* as they are; the pointer's path doesn't allow them.
120
+ return encodeURIComponent(`${block}@${path}=${index}`).replace(
121
+ /[!'()*]/g,
122
+ (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
123
+ );
124
+ }
125
+
126
+ function plainVariant({ block, path, index }: ForcedVariant): ForcedVariant {
127
+ return { block, path, index };
57
128
  }
58
129
 
59
130
  function normalizeHost(authority: string): string | null {
@@ -66,15 +137,12 @@ function normalizeHost(authority: string): string | null {
66
137
  return `${host}:${port}`;
67
138
  }
68
139
 
69
- /** Anything with a `url` and `headers`: a fetch `Request`, a `NextRequest`, a framework wrapper. */
70
- export type RequestLike = Request | { url: string; headers: Headers };
71
-
72
140
  /**
73
141
  * The draft pointer a request carries: `?__draft=` from the URL first, then
74
142
  * the `deco-draft` cookie. `null` when neither is present, or when the URL
75
143
  * says `?__draft=off`. The value is returned as is; `cms.forDraft` validates it.
76
144
  */
77
- export function draftPointer(request: RequestLike): string | null {
145
+ export function readDraftPointer(request: RequestLike): string | null {
78
146
  const param = draftParam(request);
79
147
  if (param === DRAFT_OFF) return null;
80
148
  if (param) return param;
@@ -92,7 +160,7 @@ export function draftPointer(request: RequestLike): string | null {
92
160
  * is `Secure; SameSite=None; Partitioned` (CHIPS): `SameSite=Lax` would never
93
161
  * be sent there. `HttpOnly` keeps page scripts from reading the pointer.
94
162
  */
95
- export function draftCookie(request: RequestLike): string | null {
163
+ export function draftCookieFor(request: RequestLike): string | null {
96
164
  const param = draftParam(request);
97
165
  if (!param) return null;
98
166
  if (param === DRAFT_OFF) return serializeCookie("", ["Max-Age=0"]);
@@ -100,6 +168,11 @@ export function draftCookie(request: RequestLike): string | null {
100
168
  return serializeCookie(encodeURIComponent(param), []);
101
169
  }
102
170
 
171
+ /** Whether the request's URL says `?__draft=off`: the cookie that ends a preview is set on any host. */
172
+ export function endsPreview(request: RequestLike): boolean {
173
+ return draftParam(request) === DRAFT_OFF;
174
+ }
175
+
103
176
  function serializeCookie(value: string, extra: string[]): string {
104
177
  return [
105
178
  `${DRAFT_COOKIE}=${value}`,
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Host patterns (see /next/api-reference#host-patterns): the format of
3
+ * `preview.hosts`, in `createCMS` and in the `CMS` block.
4
+ *
5
+ * - Hostnames and patterns are compared lowercase, with one trailing dot
6
+ * removed; names outside ASCII in their punycode form.
7
+ * - A pattern without `*` matches that one hostname.
8
+ * - `*.name` matches a hostname that ends in `.name` with at least one more
9
+ * label in front, compared label by label from the right. `*` is only ever
10
+ * the whole leading label, and at least two labels follow it.
11
+ * - `"*"` alone matches every host.
12
+ * - A pattern without a port matches any port; one with a port matches only
13
+ * a URL that names that port.
14
+ * - IPv4, and IPv6 in brackets, match exactly and never take a wildcard.
15
+ * - Anything else (a scheme, a path, a space, an empty label) isn't a pattern.
16
+ */
17
+
18
+ /** A parsed pattern. `port` is absent when the pattern names none. */
19
+ export type HostPattern =
20
+ | { kind: "any" }
21
+ | { kind: "name"; host: string; port?: string }
22
+ | { kind: "wildcard"; suffix: string; port?: string }
23
+ | { kind: "ip"; host: string; port?: string };
24
+
25
+ /** The list that allows every host. */
26
+ export const EVERY_HOST = "*";
27
+
28
+ const LABEL_RE = /^[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?$/;
29
+ const PORT_RE = /^[0-9]{1,5}$/;
30
+ const IPV4_RE =
31
+ /^(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}$/;
32
+ const NUMERIC_LABEL_RE = /^(0x[0-9a-f]*|[0-9]+)$/;
33
+
34
+ /** Parses one pattern; `null` when it isn't one. */
35
+ export function parseHostPattern(raw: unknown): HostPattern | null {
36
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 300) return null;
37
+ if (raw === EVERY_HOST) return { kind: "any" };
38
+ if (/[\s/\\?#@]/.test(raw) || raw.includes("://")) return null;
39
+ const split = splitPort(raw);
40
+ if (split === null) return null;
41
+ const { port } = split;
42
+ let host = split.host;
43
+ if (host.startsWith("[")) {
44
+ const ip = normalizeIPv6(host);
45
+ return ip === null ? null : withPort({ kind: "ip", host: ip }, port);
46
+ }
47
+ host = host.toLowerCase();
48
+ if (host.endsWith(".")) host = host.slice(0, -1);
49
+ if (host.startsWith("*.")) {
50
+ const suffix = normalizeName(host.slice(2));
51
+ if (suffix === null || suffix.split(".").length < 2) return null;
52
+ return withPort({ kind: "wildcard", suffix }, port);
53
+ }
54
+ if (IPV4_RE.test(host)) return withPort({ kind: "ip", host }, port);
55
+ const name = normalizeName(host);
56
+ return name === null ? null : withPort({ kind: "name", host: name }, port);
57
+ }
58
+
59
+ /** Formats a parsed pattern back into its normal form. */
60
+ export function formatHostPattern(pattern: HostPattern): string {
61
+ if (pattern.kind === "any") return EVERY_HOST;
62
+ const host = pattern.kind === "wildcard" ? `*.${pattern.suffix}` : pattern.host;
63
+ return pattern.port === undefined ? host : `${host}:${pattern.port}`;
64
+ }
65
+
66
+ /**
67
+ * Whether a request URL's host is one a pattern matches. A URL that can't be
68
+ * read matches only `"*"`, and neither does a hostname with an empty label.
69
+ */
70
+ export function hostMatches(pattern: HostPattern, url: URL | null): boolean {
71
+ if (pattern.kind === "any") return true;
72
+ if (url === null) return false;
73
+ if (pattern.port !== undefined && pattern.port !== url.port) return false;
74
+ let host = url.hostname.toLowerCase();
75
+ if (host.endsWith(".")) host = host.slice(0, -1);
76
+ // An empty label (`a..example.com`) isn't a hostname any pattern names.
77
+ if (host.split(".").includes("")) return false;
78
+ switch (pattern.kind) {
79
+ case "name":
80
+ case "ip":
81
+ return host === pattern.host;
82
+ case "wildcard":
83
+ return host.length > pattern.suffix.length + 1 && host.endsWith(`.${pattern.suffix}`);
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Whether a request may preview under this list: some pattern matches its URL's
89
+ * host. A URL with a username or password (`https://public.com@staging.example.com/`,
90
+ * which a forged Host header can produce) counts as unreadable.
91
+ */
92
+ export function allowsHost(patterns: readonly HostPattern[], requestUrl: string): boolean {
93
+ let url: URL | null;
94
+ try {
95
+ url = new URL(requestUrl);
96
+ } catch {
97
+ url = null;
98
+ }
99
+ if (url !== null && (url.username !== "" || url.password !== "")) url = null;
100
+ return patterns.some((pattern) => hostMatches(pattern, url));
101
+ }
102
+
103
+ /**
104
+ * Whether every host `inner` matches is matched by `outer`: content's entry
105
+ * `inner` is within code's entry `outer`.
106
+ */
107
+ export function patternWithin(inner: HostPattern, outer: HostPattern): boolean {
108
+ if (outer.kind === "any") return true;
109
+ if (inner.kind === "any") return false;
110
+ if (outer.port !== undefined && inner.port !== outer.port) return false;
111
+ switch (outer.kind) {
112
+ case "name":
113
+ case "ip":
114
+ return inner.kind === outer.kind && inner.host === outer.host;
115
+ case "wildcard":
116
+ if (inner.kind === "name") return inner.host.endsWith(`.${outer.suffix}`);
117
+ if (inner.kind === "wildcard") {
118
+ return inner.suffix === outer.suffix || inner.suffix.endsWith(`.${outer.suffix}`);
119
+ }
120
+ return false;
121
+ }
122
+ }
123
+
124
+ function withPort<T extends HostPattern>(pattern: T, port: string | undefined): T {
125
+ return port === undefined ? pattern : { ...pattern, port };
126
+ }
127
+
128
+ /** `host[:port]`, with the port checked; `null` on an empty host or a bad port. */
129
+ function splitPort(raw: string): { host: string; port?: string } | null {
130
+ let host = raw;
131
+ let port: string | undefined;
132
+ if (raw.startsWith("[")) {
133
+ const end = raw.indexOf("]");
134
+ if (end === -1) return null;
135
+ host = raw.slice(0, end + 1);
136
+ const rest = raw.slice(end + 1);
137
+ if (rest !== "") {
138
+ if (!rest.startsWith(":")) return null;
139
+ port = rest.slice(1);
140
+ }
141
+ } else {
142
+ const colon = raw.indexOf(":");
143
+ if (colon !== -1) {
144
+ if (raw.indexOf(":", colon + 1) !== -1) return null; // an IPv6 address without brackets
145
+ host = raw.slice(0, colon);
146
+ port = raw.slice(colon + 1);
147
+ }
148
+ }
149
+ if (host === "") return null;
150
+ if (port !== undefined && (!PORT_RE.test(port) || Number(port) > 65535)) return null;
151
+ // The form a URL gives it: no leading zeros.
152
+ return port === undefined ? { host } : { host, port: String(Number(port)) };
153
+ }
154
+
155
+ /** A DNS name in its ASCII (punycode) form, lowercase; `null` if it isn't one. */
156
+ function normalizeName(name: string): string | null {
157
+ if (name === "" || name.includes("*")) return null;
158
+ let ascii = name;
159
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the ASCII range is the point
160
+ if (/[^\x00-\x7f]/.test(name)) {
161
+ try {
162
+ ascii = new URL(`http://${name}/`).hostname;
163
+ } catch {
164
+ return null;
165
+ }
166
+ }
167
+ const labels = ascii.split(".");
168
+ if (labels.some((label) => !LABEL_RE.test(label))) return null;
169
+ // A name ending in a numeric label is an IPv4 address to a URL parser: only
170
+ // the canonical dotted form above is one.
171
+ if (NUMERIC_LABEL_RE.test(labels[labels.length - 1])) return null;
172
+ return ascii.length > 253 ? null : ascii;
173
+ }
174
+
175
+ /** `[addr]` in the compressed, lowercase form a URL's hostname has. */
176
+ function normalizeIPv6(bracketed: string): string | null {
177
+ if (!/^\[[0-9a-fA-F:.]+\]$/.test(bracketed)) return null;
178
+ try {
179
+ const host = new URL(`http://${bracketed}/`).hostname;
180
+ return host.startsWith("[") ? host : null;
181
+ } catch {
182
+ return null;
183
+ }
184
+ }
package/src/v8/index.ts CHANGED
@@ -1,16 +1,11 @@
1
1
  /**
2
2
  * The next-major (v8) core SDK: `createCMS`, the clients, the built-in blocks,
3
- * `matchRoute` and the draft helpers. Re-exported from the package root, where
3
+ * `matchRoute` and the draft pointer helpers (`cms.draftPointer` and
4
+ * `cms.draftCookie` are methods: they check the preview hosts). Re-exported from the package root, where
4
5
  * these names are the documented ones; see /next/api-reference.
5
6
  */
6
7
  export { createCMS, resetForTests } from "./cms.ts";
7
- export {
8
- DRAFT_COOKIE,
9
- draftCookie,
10
- draftPointer,
11
- formatDraftPointer,
12
- parseDraftPointer,
13
- } from "./draft.ts";
8
+ export { formatDraftPointer, parseDraftPointer } from "./draft.ts";
14
9
  export { matchRoute } from "./matchRoute.ts";
15
10
  export { remoteLoader } from "./remoteLoader.ts";
16
11
  export type {
@@ -21,13 +16,16 @@ export type {
21
16
  Client,
22
17
  CMS,
23
18
  CMSError,
19
+ CMSSettings,
24
20
  DraftPointer,
21
+ EffectiveSettings,
25
22
  Lazy,
26
23
  ListOptions,
27
24
  Loader,
28
25
  Match,
29
26
  Page,
30
27
  Redirect,
28
+ RequestLike,
31
29
  Result,
32
30
  Route,
33
31
  Secret,