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

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 (154) 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/client.d.ts +1 -1
  6. package/dist/protocol/conformance/cases/reads.d.ts.map +1 -1
  7. package/dist/protocol/conformance/cases/reads.js +22 -6
  8. package/dist/protocol/conformance/cases/reads.js.map +1 -1
  9. package/dist/protocol/conformance/cases/writes.d.ts.map +1 -1
  10. package/dist/protocol/conformance/cases/writes.js +1 -0
  11. package/dist/protocol/conformance/cases/writes.js.map +1 -1
  12. package/dist/protocol/conformance/contentHashFixtures.d.ts +0 -29
  13. package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
  14. package/dist/protocol/conformance/contentHashFixtures.js +0 -30
  15. package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
  16. package/dist/protocol/conformance/context.d.ts +3 -3
  17. package/dist/protocol/conformance/context.d.ts.map +1 -1
  18. package/dist/protocol/conformance/index.d.ts +1 -1
  19. package/dist/protocol/conformance/index.d.ts.map +1 -1
  20. package/dist/protocol/conformance/index.js +2 -2
  21. package/dist/protocol/conformance/index.js.map +1 -1
  22. package/dist/protocol/index.d.ts +3 -5
  23. package/dist/protocol/index.d.ts.map +1 -1
  24. package/dist/protocol/index.js +3 -5
  25. package/dist/protocol/index.js.map +1 -1
  26. package/dist/protocol/secrets.d.ts.map +1 -1
  27. package/dist/protocol/secrets.js +9 -2
  28. package/dist/protocol/secrets.js.map +1 -1
  29. package/dist/protocol/server/assets.d.ts +1 -1
  30. package/dist/protocol/server/assets.js +1 -1
  31. package/dist/protocol/server/methods/read.d.ts.map +1 -1
  32. package/dist/protocol/server/methods/read.js +5 -2
  33. package/dist/protocol/server/methods/read.js.map +1 -1
  34. package/dist/protocol/types.d.ts +23 -0
  35. package/dist/protocol/types.d.ts.map +1 -1
  36. package/dist/protocol/types.js +10 -0
  37. package/dist/protocol/types.js.map +1 -1
  38. package/dist/v8/boundedJson.d.ts +11 -0
  39. package/dist/v8/boundedJson.d.ts.map +1 -0
  40. package/dist/v8/boundedJson.js +44 -0
  41. package/dist/v8/boundedJson.js.map +1 -0
  42. package/dist/v8/builtins/data.d.ts +21 -5
  43. package/dist/v8/builtins/data.d.ts.map +1 -1
  44. package/dist/v8/builtins/data.js +47 -6
  45. package/dist/v8/builtins/data.js.map +1 -1
  46. package/dist/v8/builtins/index.d.ts.map +1 -1
  47. package/dist/v8/builtins/index.js +2 -3
  48. package/dist/v8/builtins/index.js.map +1 -1
  49. package/dist/v8/canonical.d.ts +0 -28
  50. package/dist/v8/canonical.d.ts.map +1 -1
  51. package/dist/v8/canonical.js +0 -19
  52. package/dist/v8/canonical.js.map +1 -1
  53. package/dist/v8/cli/check/index.d.ts +5 -0
  54. package/dist/v8/cli/check/index.d.ts.map +1 -1
  55. package/dist/v8/cli/check/index.js +34 -2
  56. package/dist/v8/cli/check/index.js.map +1 -1
  57. package/dist/v8/cli/index.d.ts +2 -1
  58. package/dist/v8/cli/index.d.ts.map +1 -1
  59. package/dist/v8/cli/index.js +2 -1
  60. package/dist/v8/cli/index.js.map +1 -1
  61. package/dist/v8/cli/run.d.ts.map +1 -1
  62. package/dist/v8/cli/run.js +3 -10
  63. package/dist/v8/cli/run.js.map +1 -1
  64. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  65. package/dist/v8/cli/schema/builtinSchemas.js +48 -28
  66. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  67. package/dist/v8/cli/schema/generate.d.ts +3 -1
  68. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  69. package/dist/v8/cli/schema/generate.js +2 -1
  70. package/dist/v8/cli/schema/generate.js.map +1 -1
  71. package/dist/v8/cli/schema/tsProgram.d.ts +10 -0
  72. package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -1
  73. package/dist/v8/cli/schema/tsProgram.js +31 -0
  74. package/dist/v8/cli/schema/tsProgram.js.map +1 -1
  75. package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
  76. package/dist/v8/cli/schema/typeToSchema.js +15 -1
  77. package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
  78. package/dist/v8/cli/serve/server.d.ts +1 -5
  79. package/dist/v8/cli/serve/server.d.ts.map +1 -1
  80. package/dist/v8/cli/serve/server.js +76 -62
  81. package/dist/v8/cli/serve/server.js.map +1 -1
  82. package/dist/v8/cms.d.ts +5 -2
  83. package/dist/v8/cms.d.ts.map +1 -1
  84. package/dist/v8/cms.js +187 -25
  85. package/dist/v8/cms.js.map +1 -1
  86. package/dist/v8/content.d.ts +22 -6
  87. package/dist/v8/content.d.ts.map +1 -1
  88. package/dist/v8/content.js +78 -40
  89. package/dist/v8/content.js.map +1 -1
  90. package/dist/v8/draft.d.ts +9 -12
  91. package/dist/v8/draft.d.ts.map +1 -1
  92. package/dist/v8/draft.js +30 -4
  93. package/dist/v8/draft.js.map +1 -1
  94. package/dist/v8/draftChanges.d.ts +26 -0
  95. package/dist/v8/draftChanges.d.ts.map +1 -0
  96. package/dist/v8/draftChanges.js +102 -0
  97. package/dist/v8/draftChanges.js.map +1 -0
  98. package/dist/v8/hosts.d.ts +55 -0
  99. package/dist/v8/hosts.d.ts.map +1 -0
  100. package/dist/v8/hosts.js +197 -0
  101. package/dist/v8/hosts.js.map +1 -0
  102. package/dist/v8/index.d.ts +4 -3
  103. package/dist/v8/index.d.ts.map +1 -1
  104. package/dist/v8/index.js +3 -2
  105. package/dist/v8/index.js.map +1 -1
  106. package/dist/v8/remoteLoader.d.ts +1 -1
  107. package/dist/v8/remoteLoader.d.ts.map +1 -1
  108. package/dist/v8/remoteLoader.js +32 -257
  109. package/dist/v8/remoteLoader.js.map +1 -1
  110. package/dist/v8/settings.d.ts +34 -0
  111. package/dist/v8/settings.d.ts.map +1 -0
  112. package/dist/v8/settings.js +143 -0
  113. package/dist/v8/settings.js.map +1 -0
  114. package/dist/v8/telemetry.d.ts +13 -3
  115. package/dist/v8/telemetry.d.ts.map +1 -1
  116. package/dist/v8/telemetry.js +31 -32
  117. package/dist/v8/telemetry.js.map +1 -1
  118. package/dist/v8/types.d.ts +74 -9
  119. package/dist/v8/types.d.ts.map +1 -1
  120. package/package.json +1 -1
  121. package/src/index.ts +3 -3
  122. package/src/protocol/client.ts +1 -1
  123. package/src/protocol/conformance/cases/reads.ts +24 -6
  124. package/src/protocol/conformance/cases/writes.ts +1 -0
  125. package/src/protocol/conformance/contentHashFixtures.ts +0 -57
  126. package/src/protocol/conformance/context.ts +3 -3
  127. package/src/protocol/conformance/index.ts +2 -7
  128. package/src/protocol/index.ts +2 -8
  129. package/src/protocol/secrets.ts +10 -2
  130. package/src/protocol/server/assets.ts +1 -1
  131. package/src/protocol/server/methods/read.ts +5 -2
  132. package/src/protocol/types.ts +21 -1
  133. package/src/v8/boundedJson.ts +47 -0
  134. package/src/v8/builtins/data.ts +56 -7
  135. package/src/v8/builtins/index.ts +2 -3
  136. package/src/v8/canonical.ts +0 -36
  137. package/src/v8/cli/check/index.ts +48 -2
  138. package/src/v8/cli/index.ts +2 -1
  139. package/src/v8/cli/run.ts +4 -9
  140. package/src/v8/cli/schema/builtinSchemas.ts +49 -28
  141. package/src/v8/cli/schema/generate.ts +4 -1
  142. package/src/v8/cli/schema/tsProgram.ts +27 -0
  143. package/src/v8/cli/schema/typeToSchema.ts +18 -1
  144. package/src/v8/cli/serve/server.ts +78 -77
  145. package/src/v8/cms.ts +234 -30
  146. package/src/v8/content.ts +87 -43
  147. package/src/v8/draft.ts +31 -9
  148. package/src/v8/draftChanges.ts +117 -0
  149. package/src/v8/hosts.ts +184 -0
  150. package/src/v8/index.ts +6 -8
  151. package/src/v8/remoteLoader.ts +39 -290
  152. package/src/v8/settings.ts +178 -0
  153. package/src/v8/telemetry.ts +43 -40
  154. package/src/v8/types.ts +68 -9
package/src/v8/content.ts CHANGED
@@ -3,24 +3,32 @@
3
3
  * the caches every client shares, and the release revisions this process has
4
4
  * served. Clients only ever see whole `{ revision, blocks }` snapshots.
5
5
  *
6
- * Drafts are never recorded as served: `forRevision(revision)` takes a
7
- * revision string a client may hand back, so it must only ever reach published
8
- * content, never a draft someone loaded with a pointer.
6
+ * A draft is the release with a draft's changes layered over it (see
7
+ * ./draftChanges.ts). Drafts are never recorded as served:
8
+ * `forRevision(revision)` takes a revision string a client may hand back, so
9
+ * it must only ever reach published content, never a draft someone loaded
10
+ * with a pointer.
9
11
  */
10
12
  import { formatDraftPointer, parseDraftPointer } from "./draft.ts";
13
+ import { type DraftChanges, fetchDraftChanges, LOCAL_VERSION, layerDraft } from "./draftChanges.ts";
11
14
  import { errors, isResolutionError } from "./errors.ts";
15
+ import type { HostPattern } from "./hosts.ts";
12
16
  import { isPlainObject } from "./json.ts";
13
17
  import type { Loader, Snapshot } from "./types.ts";
14
18
 
15
19
  const SERVED_REVISIONS = 16;
16
- /** Composed drafts kept per CMS (see /next/studio-implementation's initial limits). */
20
+ /** Fetched drafts kept per CMS. */
17
21
  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
+ /** How long a fetched draft is reused before it's fetched again, so its token is checked again. */
22
23
  const DRAFT_TTL_MS = 60_000;
23
24
 
25
+ /** A fetched draft, and the views of it over each release it was layered on. */
26
+ interface CachedDraft {
27
+ changes: Promise<DraftChanges>;
28
+ at: number;
29
+ views: WeakMap<Snapshot, Snapshot>;
30
+ }
31
+
24
32
  export function isLoader(content: unknown): content is Loader {
25
33
  return (
26
34
  (typeof content === "object" || typeof content === "function") &&
@@ -29,6 +37,20 @@ export function isLoader(content: unknown): content is Loader {
29
37
  );
30
38
  }
31
39
 
40
+ /**
41
+ * An internal hook a built-in loader (`remoteLoader`) has: the release it
42
+ * would return right now, from memory, or `undefined` when that takes a load.
43
+ * `cms.settings()` reads through it, so it never fetches.
44
+ */
45
+ export const PEEK_RELEASE: unique symbol = Symbol.for("decocms.blocks.peekRelease");
46
+
47
+ /** The release a source holds in memory: the snapshot itself, or what a loader can peek. */
48
+ export function peekRelease(source: Snapshot | Loader): Snapshot | undefined {
49
+ if (!isLoader(source)) return source;
50
+ const peek = (source as { [PEEK_RELEASE]?: () => Snapshot | undefined })[PEEK_RELEASE];
51
+ return typeof peek === "function" ? peek.call(source) : undefined;
52
+ }
53
+
32
54
  export function isSnapshot(content: unknown): content is Snapshot {
33
55
  return (
34
56
  isPlainObject(content) &&
@@ -42,10 +64,10 @@ export class ContentStore {
42
64
  #source: Snapshot | Loader;
43
65
  #release: Promise<Snapshot> | undefined;
44
66
  #updating: Promise<{ updated: boolean }> | undefined;
45
- readonly #drafts = new BoundedMap<string, { pending: Promise<Snapshot>; at: number }>(
46
- CACHED_DRAFTS,
47
- );
67
+ readonly #drafts = new BoundedMap<string, CachedDraft>(CACHED_DRAFTS);
48
68
  readonly #served = new BoundedMap<string, Snapshot>(SERVED_REVISIONS);
69
+ /** The release this store last handed a client, for a loader that can't peek. */
70
+ #latest: Snapshot | undefined;
49
71
 
50
72
  constructor(source: Snapshot | Loader) {
51
73
  this.#source = source;
@@ -64,9 +86,9 @@ export class ContentStore {
64
86
  release(): Promise<Snapshot> {
65
87
  const source = this.#source;
66
88
  if (!isLoader(source)) return Promise.resolve(this.#serve(source));
67
- if (!this.updatable) return this.#load(source, null).then((snapshot) => this.#serve(snapshot));
89
+ if (!this.updatable) return this.#load(source).then((snapshot) => this.#serve(snapshot));
68
90
  if (this.#release === undefined) {
69
- const pending = this.#load(source, null).then((snapshot) => this.#serve(snapshot));
91
+ const pending = this.#load(source).then((snapshot) => this.#serve(snapshot));
70
92
  this.#release = pending;
71
93
  // A failed load isn't cached: the next client tries again.
72
94
  pending.catch(() => {
@@ -77,33 +99,55 @@ export class ContentStore {
77
99
  }
78
100
 
79
101
  /**
80
- * The draft a pointer names. A snapshot has no drafts and ignores the
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.
102
+ * The draft a pointer names: its changes, fetched from a host in `sources`,
103
+ * layered over the release. A pointer that doesn't parse, or any failure, is
104
+ * `LOADER_FAILED`, never a silent fallback to the release. A pointer whose
105
+ * version is `local` names no draft: the release, with nothing fetched. The
106
+ * changes are keyed by the pointer without its `__variant` parameters (every
107
+ * variant of one draft shares one fetch) and reused for a minute.
85
108
  */
86
- draft(pointer: string): Promise<Snapshot> {
87
- const source = this.#source;
88
- if (!isLoader(source)) return this.release();
109
+ draft(pointer: string, sources: readonly HostPattern[]): Promise<Snapshot> {
89
110
  const parsed = parseDraftPointer(pointer);
90
111
  if (parsed === null) {
91
112
  return Promise.reject(errors.loaderFailed(`invalid draft pointer "${truncate(pointer)}"`));
92
113
  }
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
- });
99
- const cached = this.#drafts.get(key);
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);
114
+ if (parsed.version === LOCAL_VERSION) return this.release();
115
+ const { host, path, version } = parsed;
116
+ const key = formatDraftPointer({ host, path, version });
117
+ let entry = this.#drafts.get(key);
118
+ if (entry === undefined || Date.now() - entry.at >= DRAFT_TTL_MS) {
119
+ const fetched: CachedDraft = {
120
+ changes: fetchDraftChanges(parsed, sources).catch((error: unknown) => {
121
+ throw errors.loaderFailed("the draft's changes couldn't be fetched", error);
122
+ }),
123
+ at: Date.now(),
124
+ views: new WeakMap(),
125
+ };
126
+ this.#drafts.set(key, fetched);
127
+ // A failure isn't reused: the next client fetches again.
128
+ fetched.changes.catch(() => {
129
+ if (this.#drafts.get(key) === fetched) this.#drafts.delete(key);
130
+ });
131
+ entry = fetched;
132
+ }
133
+ const { changes, views } = entry;
134
+ return Promise.all([this.release(), changes]).then(([base, draft]) => {
135
+ let view = views.get(base);
136
+ if (view === undefined) {
137
+ view = layerDraft(base, draft, version);
138
+ views.set(base, view);
139
+ }
140
+ return view;
105
141
  });
106
- return entry.pending;
142
+ }
143
+
144
+ /**
145
+ * The current release as it is in memory, without loading anything: the
146
+ * content module, what a built-in loader holds, or the release this store
147
+ * last loaded. `undefined` before a custom loader's first load.
148
+ */
149
+ current(): Snapshot | undefined {
150
+ return peekRelease(this.#source) ?? this.#latest;
107
151
  }
108
152
 
109
153
  /** A release revision this store has served, or the release when it's unknown (drafts included). */
@@ -124,8 +168,9 @@ export class ContentStore {
124
168
  const updated = result?.updated === true;
125
169
  if (updated) {
126
170
  this.#release = undefined;
127
- // A loader that ignores the pointer hands back the release as the
128
- // draft; that copy is as stale as the release now.
171
+ // `#latest` stays: settings keep the release that was serving until
172
+ // the next one loads, never the defaults (which may allow every host).
173
+ // Drafts are fetched again, so a preview follows the release too.
129
174
  this.#drafts.clear();
130
175
  }
131
176
  return { updated };
@@ -148,27 +193,25 @@ export class ContentStore {
148
193
  const previous = this.#source;
149
194
  if (source === previous) {
150
195
  // 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.
152
196
  this.#release = undefined;
197
+ this.#latest = undefined;
153
198
  this.#drafts.clear();
154
199
  return;
155
200
  }
156
201
  if (isSnapshot(previous)) this.#served.delete(previous.revision);
157
202
  this.#source = source;
158
203
  this.#release = undefined;
204
+ this.#latest = undefined;
159
205
  this.#drafts.clear();
160
206
  }
161
207
 
162
- async #load(loader: Loader, pointer: string | null): Promise<Snapshot> {
208
+ async #load(loader: Loader): Promise<Snapshot> {
163
209
  let snapshot: unknown;
164
210
  try {
165
- snapshot = pointer === null ? await loader.load() : await loader.load(pointer);
211
+ snapshot = await loader.load();
166
212
  } catch (error) {
167
213
  if (isResolutionError(error)) throw error;
168
- throw errors.loaderFailed(
169
- pointer === null ? "the content loader failed" : "the draft couldn't load",
170
- error,
171
- );
214
+ throw errors.loaderFailed("the content loader failed", error);
172
215
  }
173
216
  if (!isSnapshot(snapshot)) {
174
217
  throw errors.loaderFailed("the content loader returned something other than a snapshot");
@@ -177,6 +220,7 @@ export class ContentStore {
177
220
  }
178
221
 
179
222
  #serve(snapshot: Snapshot): Snapshot {
223
+ this.#latest = snapshot;
180
224
  this.#served.set(snapshot.revision, snapshot);
181
225
  return snapshot;
182
226
  }
package/src/v8/draft.ts CHANGED
@@ -1,16 +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.
5
7
  *
6
8
  * The query's reserved `__variant` parameters are the variants a preview
7
9
  * forces (`<block>@<path>=<index>`, URL-encoded, one per multivariate); the
8
10
  * parser lifts them out of `path` into `variants`.
9
11
  */
10
- import type { DraftPointer, ForcedVariant } from "./types.ts";
12
+ import type { DraftPointer, ForcedVariant, RequestLike } from "./types.ts";
11
13
 
12
- /** The draft cookie's name, for frameworks whose cookie API has no Request (Next.js `cookies()`). */
13
- 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";
14
16
 
15
17
  const DRAFT_PARAM = "__draft";
16
18
  const DRAFT_OFF = "off";
@@ -126,6 +128,7 @@ function plainVariant({ block, path, index }: ForcedVariant): ForcedVariant {
126
128
  }
127
129
 
128
130
  function normalizeHost(authority: string): string | null {
131
+ if (authority.startsWith("[")) return normalizeIPv6Host(authority);
129
132
  const parts = authority.toLowerCase().split(":");
130
133
  if (parts.length > 2) return null;
131
134
  const [host, port] = parts;
@@ -135,15 +138,29 @@ function normalizeHost(authority: string): string | null {
135
138
  return `${host}:${port}`;
136
139
  }
137
140
 
138
- /** Anything with a `url` and `headers`: a fetch `Request`, a `NextRequest`, a framework wrapper. */
139
- export type RequestLike = Request | { url: string; headers: Headers };
141
+ /** `[addr]` or `[addr]:port`, the address in the compressed, lowercase form a URL gives it. */
142
+ function normalizeIPv6Host(authority: string): string | null {
143
+ const end = authority.indexOf("]");
144
+ const address = authority.slice(0, end + 1);
145
+ const rest = authority.slice(end + 1);
146
+ if (end === -1 || !/^\[[0-9a-fA-F:.]+\]$/.test(address)) return null;
147
+ if (rest !== "" && (!rest.startsWith(":") || !PORT_RE.test(rest.slice(1)))) return null;
148
+ if (rest !== "" && Number(rest.slice(1)) > 65535) return null;
149
+ let host: string;
150
+ try {
151
+ host = new URL(`http://${address}/`).hostname;
152
+ } catch {
153
+ return null;
154
+ }
155
+ return `${host}${rest}`;
156
+ }
140
157
 
141
158
  /**
142
159
  * The draft pointer a request carries: `?__draft=` from the URL first, then
143
160
  * the `deco-draft` cookie. `null` when neither is present, or when the URL
144
161
  * says `?__draft=off`. The value is returned as is; `cms.forDraft` validates it.
145
162
  */
146
- export function draftPointer(request: RequestLike): string | null {
163
+ export function readDraftPointer(request: RequestLike): string | null {
147
164
  const param = draftParam(request);
148
165
  if (param === DRAFT_OFF) return null;
149
166
  if (param) return param;
@@ -161,7 +178,7 @@ export function draftPointer(request: RequestLike): string | null {
161
178
  * is `Secure; SameSite=None; Partitioned` (CHIPS): `SameSite=Lax` would never
162
179
  * be sent there. `HttpOnly` keeps page scripts from reading the pointer.
163
180
  */
164
- export function draftCookie(request: RequestLike): string | null {
181
+ export function draftCookieFor(request: RequestLike): string | null {
165
182
  const param = draftParam(request);
166
183
  if (!param) return null;
167
184
  if (param === DRAFT_OFF) return serializeCookie("", ["Max-Age=0"]);
@@ -169,6 +186,11 @@ export function draftCookie(request: RequestLike): string | null {
169
186
  return serializeCookie(encodeURIComponent(param), []);
170
187
  }
171
188
 
189
+ /** Whether the request's URL says `?__draft=off`: the cookie that ends a preview is set on any host. */
190
+ export function endsPreview(request: RequestLike): boolean {
191
+ return draftParam(request) === DRAFT_OFF;
192
+ }
193
+
172
194
  function serializeCookie(value: string, extra: string[]): string {
173
195
  return [
174
196
  `${DRAFT_COOKIE}=${value}`,
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Draft changes (see /next/content-delivery#draft-previews): what a draft
3
+ * pointer's address answers, and how the CMS layers it over production.
4
+ *
5
+ * - The pointer's host must be one of `preview.sources` (code only, default
6
+ * `studio.decocms.com`); any other host is refused before anything is fetched.
7
+ * - `GET https://<host><path>&v=<version>`: plain `http` only for loopback
8
+ * hosts. The pointer's `__variant` parameters are already gone (the parser
9
+ * lifts them out), no cookies or credentials are sent, and redirects aren't
10
+ * followed (a response that was redirected anyway is refused).
11
+ * - Only a 200 is accepted, within 10 s and up to 16 MiB, shaped exactly
12
+ * `{ format: 1, set: { <name>: <block JSON> }, delete: [<name>…] }` with
13
+ * `set` and `delete` disjoint.
14
+ */
15
+ import { readBoundedJson, timeoutSignal } from "./boundedJson.ts";
16
+ import { allowsHost, type HostPattern } from "./hosts.ts";
17
+ import { isPlainObject } from "./json.ts";
18
+ import type { DraftPointer, Snapshot } from "./types.ts";
19
+
20
+ /** The version a pointer has when it names no draft: `deco serve`'s working tree. */
21
+ export const LOCAL_VERSION = "local";
22
+
23
+ const FORMAT = 1;
24
+ const TIMEOUT_MS = 10_000;
25
+ const MAX_BYTES = 16 * 1024 * 1024;
26
+
27
+ /** What a draft changed compared with production: whole blocks, and deletions. */
28
+ export interface DraftChanges {
29
+ format: typeof FORMAT;
30
+ set: Record<string, unknown>;
31
+ delete: string[];
32
+ }
33
+
34
+ /** The URL the SDK fetches for a pointer: the scheme from its host, the version as `v`. */
35
+ export function draftChangesUrl(pointer: DraftPointer): string {
36
+ const scheme = isLoopback(pointer.host) ? "http" : "https";
37
+ const separator = pointer.path.includes("?") ? "&" : "?";
38
+ return `${scheme}://${pointer.host}${pointer.path}${separator}v=${encodeURIComponent(pointer.version)}`;
39
+ }
40
+
41
+ /** Fetches a draft's changes; rejects on a host outside `sources` (without fetching) or on any failure. */
42
+ export async function fetchDraftChanges(
43
+ pointer: DraftPointer,
44
+ sources: readonly HostPattern[],
45
+ ): Promise<DraftChanges> {
46
+ const url = draftChangesUrl(pointer);
47
+ if (!allowsHost(sources, url)) {
48
+ throw new Error(
49
+ `draft pointer names "${pointer.host}", which isn't in preview.sources; nothing was fetched`,
50
+ );
51
+ }
52
+ const response = await fetch(url, {
53
+ headers: { accept: "application/json" },
54
+ redirect: "manual",
55
+ signal: timeoutSignal(TIMEOUT_MS),
56
+ });
57
+ // Some fetch polyfills (React Native, whatwg-fetch) ignore `redirect: "manual"`
58
+ // and follow anyway: refuse a response that came from anywhere else.
59
+ if (response.redirected || (response.url && !allowsHost(sources, response.url))) {
60
+ await response.body?.cancel();
61
+ throw new Error("draft changes: the pointer's address redirected; nothing was read");
62
+ }
63
+ if (response.status !== 200) {
64
+ await response.body?.cancel();
65
+ throw new Error(`draft changes: HTTP ${response.status}`);
66
+ }
67
+ return parseDraftChanges(await readBoundedJson(response, "draft changes", MAX_BYTES));
68
+ }
69
+
70
+ /** Validates a draft changes response; throws on an unknown format or any unexpected shape. */
71
+ export function parseDraftChanges(body: unknown): DraftChanges {
72
+ const invalid = (why: string) => new Error(`draft changes: ${why}`);
73
+ if (!isPlainObject(body) || body.format !== FORMAT) throw invalid("unknown format");
74
+ if (Object.keys(body).some((key) => key !== "format" && key !== "set" && key !== "delete")) {
75
+ throw invalid("unexpected field");
76
+ }
77
+ const { set, delete: deleted } = body;
78
+ if (!isPlainObject(set)) throw invalid("set must be an object");
79
+ if (!Array.isArray(deleted) || deleted.some((name) => typeof name !== "string")) {
80
+ throw invalid("delete must be a list of names");
81
+ }
82
+ if (new Set(deleted).size !== deleted.length) throw invalid("delete repeats a name");
83
+ if (deleted.some((name) => Object.hasOwn(set, name))) throw invalid("set and delete overlap");
84
+ return body as unknown as DraftChanges;
85
+ }
86
+
87
+ /**
88
+ * The draft as a snapshot: production's entries, with the changed ones
89
+ * replaced whole and the deleted ones gone. A shallow copy: every unchanged
90
+ * entry is production's own object, and production is never mutated. Its
91
+ * revision is an opaque identity of the pair, never a release's.
92
+ */
93
+ export function layerDraft(base: Snapshot, changes: DraftChanges, version: string): Snapshot {
94
+ const blocks: Record<string, unknown> = { ...base.blocks };
95
+ for (const name of changes.delete) delete blocks[name];
96
+ for (const [name, entry] of Object.entries(changes.set)) {
97
+ // defineProperty, so an entry named "__proto__" stays an entry.
98
+ Object.defineProperty(blocks, name, {
99
+ value: entry,
100
+ enumerable: true,
101
+ writable: true,
102
+ configurable: true,
103
+ });
104
+ }
105
+ const view: Snapshot = { revision: `${base.revision}~${version}`, blocks };
106
+ if (base.aliases !== undefined) view.aliases = base.aliases;
107
+ return view;
108
+ }
109
+
110
+ function isLoopback(authority: string): boolean {
111
+ const host = authority.startsWith("[")
112
+ ? authority.slice(0, authority.indexOf("]") + 1)
113
+ : authority.split(":")[0]!;
114
+ return (
115
+ host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]"
116
+ );
117
+ }
@@ -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,