@decocms/blocks 8.1.0-next.6 → 8.1.0-next.7

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 (41) hide show
  1. package/dist/v8/cli/content.d.ts +24 -3
  2. package/dist/v8/cli/content.d.ts.map +1 -1
  3. package/dist/v8/cli/content.js +70 -5
  4. package/dist/v8/cli/content.js.map +1 -1
  5. package/dist/v8/cli/run.js +1 -1
  6. package/dist/v8/cli/run.js.map +1 -1
  7. package/dist/v8/cms.d.ts.map +1 -1
  8. package/dist/v8/cms.js +16 -19
  9. package/dist/v8/cms.js.map +1 -1
  10. package/dist/v8/content.d.ts +4 -5
  11. package/dist/v8/content.d.ts.map +1 -1
  12. package/dist/v8/content.js +46 -44
  13. package/dist/v8/content.js.map +1 -1
  14. package/dist/v8/draftChanges.d.ts +37 -14
  15. package/dist/v8/draftChanges.d.ts.map +1 -1
  16. package/dist/v8/draftChanges.js +66 -44
  17. package/dist/v8/draftChanges.js.map +1 -1
  18. package/dist/v8/identity.d.ts +0 -2
  19. package/dist/v8/identity.d.ts.map +1 -1
  20. package/dist/v8/identity.js +0 -10
  21. package/dist/v8/identity.js.map +1 -1
  22. package/dist/v8/remoteLoader.d.ts +2 -4
  23. package/dist/v8/remoteLoader.d.ts.map +1 -1
  24. package/dist/v8/remoteLoader.js +106 -87
  25. package/dist/v8/remoteLoader.js.map +1 -1
  26. package/dist/v8/telemetry.d.ts +7 -7
  27. package/dist/v8/telemetry.d.ts.map +1 -1
  28. package/dist/v8/telemetry.js +24 -100
  29. package/dist/v8/telemetry.js.map +1 -1
  30. package/dist/v8/types.d.ts +47 -16
  31. package/dist/v8/types.d.ts.map +1 -1
  32. package/package.json +1 -1
  33. package/src/v8/cli/content.ts +85 -5
  34. package/src/v8/cli/run.ts +1 -1
  35. package/src/v8/cms.ts +17 -20
  36. package/src/v8/content.ts +54 -46
  37. package/src/v8/draftChanges.ts +79 -43
  38. package/src/v8/identity.ts +0 -10
  39. package/src/v8/remoteLoader.ts +111 -106
  40. package/src/v8/telemetry.ts +27 -108
  41. package/src/v8/types.ts +48 -14
@@ -2,38 +2,43 @@
2
2
  * Draft changes (see /next/content-delivery#draft-previews): what a draft
3
3
  * pointer's address answers, and how the CMS layers it over production.
4
4
  *
5
- * - The pointer's host must fall under one of the preview API domains (the
6
- * same rule as v7): by default `*.decocms.com` (Studio, its PR previews,
7
- * `local.studio.decocms.com`) and the loopback hosts; `DECO_PREVIEW_API_DOMAINS`
8
- * replaces the list. Any other host is refused before anything is fetched.
9
- * - `GET <scheme>://<host><path>&v=<version>`: the scheme comes from the
5
+ * - The pointer's host must fall under one of the draft hosts (the same rule
6
+ * as v7's preview API domains): by default `*.decocms.com` (Studio, the
7
+ * delivery CDN, `local.studio.decocms.com`) and the loopback hosts;
8
+ * `createCMS({ preview: { draftHosts } })` replaces the list. Any other host
9
+ * is refused before anything is fetched.
10
+ * - `GET <scheme>://<host><path>?v=<version>`: the scheme comes from the
10
11
  * domain that admitted the host, never from the pointer: plain `http` only
11
12
  * for loopback hosts. The pointer's `__variant` parameters are already gone (the parser
12
13
  * lifts them out), no cookies or credentials are sent, and redirects aren't
13
14
  * followed (a response that was redirected anyway is refused).
14
- * - Only a 200 is accepted, within 10 s and up to 16 MiB, shaped exactly
15
- * `{ format: 1, set: { <name>: <block JSON> }, delete: [<name>…] }` with
16
- * `set` and `delete` disjoint.
15
+ * - Every read revalidates: with a body this process already holds, it sends
16
+ * `If-None-Match` with that body's ETag, and a `304` reuses the body. Only
17
+ * a 200 or that 304 is accepted, within 10 s; a 200 is up to 16 MiB, shaped
18
+ * exactly `{ set: { <name>: <block JSON> }, delete: [<name>…] }` with `set`
19
+ * and `delete` disjoint.
17
20
  */
18
21
  import { readBoundedJson, timeoutSignal } from "./boundedJson.ts";
19
- import { readEnv } from "./identity.ts";
20
22
  import { isPlainObject } from "./json.ts";
21
23
  import type { DraftPointer, Snapshot } from "./types.ts";
22
24
 
23
25
  /** The version a pointer has when it names no draft: `deco serve`'s working tree. */
24
26
  export const LOCAL_VERSION = "local";
25
27
 
26
- const FORMAT = 1;
27
28
  const TIMEOUT_MS = 10_000;
28
29
  const MAX_BYTES = 16 * 1024 * 1024;
29
30
 
30
31
  /** What a draft changed compared with production: whole blocks, and deletions. */
31
32
  export interface DraftChanges {
32
- format: typeof FORMAT;
33
33
  set: Record<string, unknown>;
34
34
  delete: string[];
35
35
  }
36
36
 
37
+ /** A draft read: new changes (and their ETag), or `304`, the held body is current. */
38
+ export type DraftRead =
39
+ | { status: 200; changes: DraftChanges; etag: string | null }
40
+ | { status: 304 };
41
+
37
42
  /**
38
43
  * The domains a draft pointer's host may fall under, the defaults v7 shipped.
39
44
  * Deco operates every one of them, so the defaults add no SSRF surface. An
@@ -42,37 +47,48 @@ export interface DraftChanges {
42
47
  * matches that exact host. The first entry that matches decides whether a
43
48
  * port and plain `http` are allowed.
44
49
  */
45
- export const DEFAULT_PREVIEW_API_DOMAINS: readonly string[] = [
50
+ export const DEFAULT_DRAFT_HOSTS: readonly string[] = [
46
51
  "local.studio.decocms.com", // the Studio dev origin (https, with a port)
47
52
  "localhost",
48
53
  "127.0.0.1",
49
54
  ".localhost",
50
- ".decocms.com", // Studio and its preview deployments
55
+ ".decocms.com", // Studio, its preview deployments and delivery.decocms.com
51
56
  ];
52
57
 
53
- /** `DECO_PREVIEW_API_DOMAINS` (a comma list) when set, else the defaults. */
54
- function previewApiDomains(): readonly string[] {
55
- const configured = (readEnv("DECO_PREVIEW_API_DOMAINS") ?? "")
56
- .split(",")
57
- .map((domain) => domain.trim().toLowerCase())
58
- .filter(Boolean);
59
- return configured.length > 0 ? configured : DEFAULT_PREVIEW_API_DOMAINS;
58
+ /**
59
+ * `createCMS`'s `preview.draftHosts`, trimmed and lowercased, or the defaults
60
+ * when it's left out. Throws a `TypeError` on anything but a list of
61
+ * non-empty strings.
62
+ */
63
+ export function parseDraftHosts(preview: { draftHosts?: unknown } | undefined): readonly string[] {
64
+ const domains = preview?.draftHosts;
65
+ if (domains === undefined) return DEFAULT_DRAFT_HOSTS;
66
+ if (
67
+ !Array.isArray(domains) ||
68
+ domains.some((domain) => typeof domain !== "string" || domain.trim() === "")
69
+ ) {
70
+ throw new TypeError("createCMS: `preview.draftHosts` must be a list of hosts");
71
+ }
72
+ return domains.map((domain: string) => domain.trim().toLowerCase());
60
73
  }
61
74
 
62
75
  /**
63
- * The origin a pointer's host is fetched from, or `null` when no preview API
64
- * domain admits it. Loopback domains (and `local.studio.decocms.com`) may
76
+ * The origin a pointer's host is fetched from, or `null` when no draft host
77
+ * admits it. Loopback domains (and `local.studio.decocms.com`) may
65
78
  * carry a port; a public domain may not, so a pointer can't aim the fetch at
66
79
  * an odd port. Loopback hosts are `http`; everything else is `https`.
67
80
  */
68
- export function previewApiOrigin(authority: string): string | null {
81
+ export function previewApiOrigin(
82
+ authority: string,
83
+ domains: readonly string[] = DEFAULT_DRAFT_HOSTS,
84
+ ): string | null {
69
85
  const lower = authority.toLowerCase();
70
86
  const end = lower.startsWith("[") ? lower.indexOf("]") + 1 : -1;
71
87
  const host = end > 0 ? lower.slice(0, end) : lower.split(":")[0]!;
72
88
  const rest = end > 0 ? lower.slice(end) : lower.slice(host.length);
73
89
  const port = rest.startsWith(":") ? rest.slice(1) : undefined;
74
90
  if (!host) return null;
75
- const domain = previewApiDomains().find((d) =>
91
+ const domain = domains.find((d) =>
76
92
  d.startsWith(".") ? host.length > d.length && host.endsWith(d) : host === d,
77
93
  );
78
94
  if (domain === undefined) return null;
@@ -92,26 +108,39 @@ function isLoopbackDomain(domain: string): boolean {
92
108
 
93
109
  /**
94
110
  * The URL the SDK fetches for a pointer: the origin its host is admitted
95
- * under, the version as `v`. `null` when no preview API domain admits the host.
111
+ * under, the version as `v`. `null` when no draft host admits the host.
96
112
  */
97
- export function draftChangesUrl(pointer: DraftPointer): string | null {
98
- const origin = previewApiOrigin(pointer.host);
113
+ export function draftChangesUrl(
114
+ pointer: DraftPointer,
115
+ domains: readonly string[] = DEFAULT_DRAFT_HOSTS,
116
+ ): string | null {
117
+ const origin = previewApiOrigin(pointer.host, domains);
99
118
  if (origin === null) return null;
100
119
  const separator = pointer.path.includes("?") ? "&" : "?";
101
120
  return `${origin}${pointer.path}${separator}v=${encodeURIComponent(pointer.version)}`;
102
121
  }
103
122
 
104
- /** Fetches a draft's changes; rejects on a host no preview API domain admits (without fetching) or on any failure. */
105
- export async function fetchDraftChanges(pointer: DraftPointer): Promise<DraftChanges> {
106
- const url = draftChangesUrl(pointer);
123
+ /**
124
+ * Reads a draft's changes, revalidating `etag` (the ETag of the body the
125
+ * caller holds) when given. Rejects on a host no draft host admits
126
+ * (without fetching), on a `304` to a request that sent no ETag, and on any
127
+ * other failure.
128
+ */
129
+ export async function fetchDraftChanges(
130
+ pointer: DraftPointer,
131
+ options: { domains?: readonly string[]; etag?: string | null } = {},
132
+ ): Promise<DraftRead> {
133
+ const url = draftChangesUrl(pointer, options.domains);
107
134
  if (url === null) {
108
135
  throw new Error(
109
- `draft pointer names "${pointer.host}", which isn't under a preview API domain ` +
110
- "(DECO_PREVIEW_API_DOMAINS); nothing was fetched",
136
+ `draft pointer names "${pointer.host}", which isn't under a draft host ` +
137
+ "(createCMS({ preview: { draftHosts } })); nothing was fetched",
111
138
  );
112
139
  }
140
+ const headers: Record<string, string> = { accept: "application/json" };
141
+ if (options.etag) headers["if-none-match"] = options.etag;
113
142
  const response = await fetch(url, {
114
- headers: { accept: "application/json" },
143
+ headers,
115
144
  redirect: "manual",
116
145
  signal: timeoutSignal(TIMEOUT_MS),
117
146
  });
@@ -124,18 +153,24 @@ export async function fetchDraftChanges(pointer: DraftPointer): Promise<DraftCha
124
153
  await response.body?.cancel();
125
154
  throw new Error("draft changes: the pointer's address redirected; nothing was read");
126
155
  }
156
+ if (response.status === 304 && options.etag) {
157
+ await response.body?.cancel();
158
+ return { status: 304 };
159
+ }
127
160
  if (response.status !== 200) {
128
161
  await response.body?.cancel();
129
162
  throw new Error(`draft changes: HTTP ${response.status}`);
130
163
  }
131
- return parseDraftChanges(await readBoundedJson(response, "draft changes", MAX_BYTES));
164
+ const etag = response.headers.get("etag");
165
+ const changes = parseDraftChanges(await readBoundedJson(response, "draft changes", MAX_BYTES));
166
+ return { status: 200, changes, etag };
132
167
  }
133
168
 
134
- /** Validates a draft changes response; throws on an unknown format or any unexpected shape. */
169
+ /** Validates a draft changes response; throws on any unexpected shape. */
135
170
  export function parseDraftChanges(body: unknown): DraftChanges {
136
171
  const invalid = (why: string) => new Error(`draft changes: ${why}`);
137
- if (!isPlainObject(body) || body.format !== FORMAT) throw invalid("unknown format");
138
- if (Object.keys(body).some((key) => key !== "format" && key !== "set" && key !== "delete")) {
172
+ if (!isPlainObject(body)) throw invalid("expected an object");
173
+ if (Object.keys(body).some((key) => key !== "set" && key !== "delete")) {
139
174
  throw invalid("unexpected field");
140
175
  }
141
176
  const { set, delete: deleted } = body;
@@ -143,7 +178,6 @@ export function parseDraftChanges(body: unknown): DraftChanges {
143
178
  if (!Array.isArray(deleted) || deleted.some((name) => typeof name !== "string")) {
144
179
  throw invalid("delete must be a list of names");
145
180
  }
146
- if (new Set(deleted).size !== deleted.length) throw invalid("delete repeats a name");
147
181
  if (deleted.some((name) => Object.hasOwn(set, name))) throw invalid("set and delete overlap");
148
182
  return body as unknown as DraftChanges;
149
183
  }
@@ -152,9 +186,11 @@ export function parseDraftChanges(body: unknown): DraftChanges {
152
186
  * The draft as a snapshot: production's entries, with the changed ones
153
187
  * replaced whole and the deleted ones gone. A shallow copy: every unchanged
154
188
  * entry is production's own object, and production is never mutated. Its
155
- * revision is an opaque identity of the pair, never a release's.
189
+ * revision, `<base revision>~<view>`, is an opaque identity of the pair,
190
+ * never a release's; `view` names the draft body (its ETag), so each save
191
+ * re-keys what's cached by revision.
156
192
  */
157
- export function layerDraft(base: Snapshot, changes: DraftChanges, version: string): Snapshot {
193
+ export function layerDraft(base: Snapshot, changes: DraftChanges, view: string): Snapshot {
158
194
  const blocks: Record<string, unknown> = { ...base.blocks };
159
195
  for (const name of changes.delete) delete blocks[name];
160
196
  for (const [name, entry] of Object.entries(changes.set)) {
@@ -166,7 +202,7 @@ export function layerDraft(base: Snapshot, changes: DraftChanges, version: strin
166
202
  configurable: true,
167
203
  });
168
204
  }
169
- const view: Snapshot = { revision: `${base.revision}~${version}`, blocks };
170
- if (base.aliases !== undefined) view.aliases = base.aliases;
171
- return view;
205
+ const layered: Snapshot = { revision: `${base.revision}~${view}`, blocks };
206
+ if (base.aliases !== undefined) layered.aliases = base.aliases;
207
+ return layered;
172
208
  }
@@ -46,16 +46,6 @@ export function fnv1a(input: string): string {
46
46
  return (hash >>> 0).toString(16).padStart(8, "0");
47
47
  }
48
48
 
49
- /** Reads an environment variable where there is one (Node, Bun, Workers with nodejs_compat). */
50
- export function readEnv(name: string): string | undefined {
51
- try {
52
- return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process
53
- ?.env?.[name];
54
- } catch {
55
- return undefined;
56
- }
57
- }
58
-
59
49
  /** Clears every global instance whose registry key starts with `prefix`. */
60
50
  export function clearGlobals(prefix: string): void {
61
51
  const store = globalThis as unknown as Record<symbol, unknown>;
@@ -1,73 +1,82 @@
1
1
  /**
2
- * `remoteLoader`: hosted releases from the Deco API, over a fallback (the
3
- * content module, or any loader). See /next/hosted-releases-internals and
4
- * /next/hosted-publishing. Drafts aren't a loader's job: the CMS layers a
5
- * draft's changes over what `load()` returns (see ./draftChanges.ts).
2
+ * `remoteLoader`: hosted releases from `delivery.decocms.com`, over a fallback
3
+ * (the content module, or any loader). See /next/hosted-releases-internals.
4
+ * Drafts aren't a loader's job: the CMS layers a draft's changes over what
5
+ * `load()` returns (see ./draftChanges.ts).
6
6
  *
7
- * - `load()` never touches the network: it returns the newest release this
8
- * process fetched, or the fallback's content until one is fetched.
9
- * - `update()` asks the delivery API for the small production channel
10
- * manifest; the CMS calls it on first use and then every interval, at an
11
- * idle moment. A manifest older than the newest observed generation is
12
- * ignored; a revision equal to the fallback's is served from the fallback
13
- * without a download; anything else is fetched, verified against its
14
- * content hash and swapped in whole. Any error keeps memory as it was.
15
- * - In development (`NODE_ENV=development`), releases stay on the fallback so
16
- * local files win.
7
+ * - `load()` never touches the network: it returns the release this process
8
+ * last swapped in, or the fallback's content until then. Nothing persists
9
+ * across restarts: every boot starts from the fallback.
10
+ * - `update()` (the CMS calls it in the background, on first use and then
11
+ * every interval) reads `sites/<site>/latest.json`,
12
+ * `{ revision, schemaHash, publishedAt }`. Whoever is newer wins: when it
13
+ * names a revision other than the one this process last swapped in, its
14
+ * `schemaHash` equals the fallback's, and its `publishedAt` is later than
15
+ * the fallback's `committedAt` (the commit time of the git HEAD
16
+ * `deco content` built it from), it downloads
17
+ * `sites/<site>/revisions/<revision>.json`, `{ revision, schemaHash, blocks }`,
18
+ * and swaps it in whole. Otherwise, and on any error, memory stays as it is.
19
+ * A fallback without a `schemaHash` never swaps; one without a `committedAt`
20
+ * (a custom loader, an older content module, a build outside git) counts as
21
+ * the oldest. Studio writes `publishedAt` on Publish, on "Make current" (a
22
+ * rollback) and on Resync, so a rollback wins over the bundles of earlier
23
+ * commits and a deploy of a later commit wins over the rollback. Commit
24
+ * time, not build time: a slow build of an older commit that finishes after
25
+ * a publish still loses to it.
26
+ * Pointers aren't ordered among themselves, and the fallback's content is
27
+ * never compared: only the two timestamps are.
28
+ * - In development (`NODE_ENV=development`), it never swaps, so local files win.
17
29
  * - A release larger than `MAX_SNAPSHOT_BYTES` is refused while it downloads,
18
30
  * before it's buffered whole (a Worker isolate has 128 MB).
19
- * - Without `site` or `token` it's a plain loader over the fallback.
31
+ * - Without `site` it's a plain loader over the fallback.
20
32
  *
21
33
  * Instances are process-wide singletons, like `createCMS`'s.
22
34
  */
23
35
  import { readBoundedJson, timeoutSignal } from "./boundedJson.ts";
24
- import { computeContentRevision } from "./canonical.ts";
25
36
  import { isSnapshot, PEEK_RELEASE, peekRelease } from "./content.ts";
26
- import { clearGlobals, contentIdentity, fnv1a } from "./identity.ts";
37
+ import { clearGlobals, contentIdentity } from "./identity.ts";
27
38
  import { isPlainObject } from "./json.ts";
28
39
  import type { Loader, Snapshot } from "./types.ts";
29
40
 
30
- /** The hosted delivery origin: channel manifests and release assets. */
41
+ /** The hosted delivery origin: release pointers and revisions. */
31
42
  const HOSTED_DELIVERY_ORIGIN = "https://delivery.decocms.com";
43
+ /** test-only: replaces the delivery origin in local end-to-end runs. Not documented, not exported. */
44
+ const TEST_DELIVERY_ORIGIN = Symbol.for("decocms.blocks.test.deliveryOrigin");
32
45
 
33
46
  const INSTANCE_PREFIX = "decocms.blocks.remote:";
34
- const MANIFEST_FORMAT = 1;
35
47
  const FETCH_TIMEOUT_MS = 10_000;
36
48
  /** The largest release accepted, in bytes of JSON. */
37
49
  const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
50
+ // OPEN: a revision is the git commit SHA; only SHA-1 (40 hex) object names are accepted.
51
+ const REVISION = /^[0-9a-f]{40}$/;
52
+ const SCHEMA_HASH = /^[0-9a-f]{64}$/;
38
53
 
39
54
  interface RemoteLoaderOptions {
40
55
  site?: string;
41
- token?: string;
42
56
  /** ms between release checks, used when `createCMS` has no `interval` of its own. */
43
57
  interval?: number;
44
58
  }
45
59
 
46
- interface Manifest {
47
- generation: number;
60
+ /** `sites/<site>/latest.json`: the release a site serves. */
61
+ interface Latest {
48
62
  revision: string;
49
- snapshot: string;
63
+ schemaHash: string;
64
+ publishedAt: string;
50
65
  }
51
66
 
52
67
  class RemoteLoader implements Loader {
53
68
  readonly #site: string;
54
- readonly #token: string;
55
69
  /** The `interval` this loader was created with; `createCMS` reads it. */
56
70
  readonly interval: number | undefined;
57
71
  #fallback: Snapshot | Loader;
58
- #fallbackRevision: string | undefined;
59
72
  /** The fallback's content as last loaded, for a fallback that is itself a loader. */
60
73
  #fallbackSnapshot: Snapshot | undefined;
74
+ /** The release this process last swapped in; `undefined` serves the fallback. */
61
75
  #current: Snapshot | undefined;
62
- #generation = -1;
63
76
 
64
- constructor(
65
- fallback: Snapshot | Loader,
66
- options: { site: string; token: string; interval?: number },
67
- ) {
77
+ constructor(fallback: Snapshot | Loader, options: { site: string; interval?: number }) {
68
78
  this.#fallback = fallback;
69
79
  this.#site = options.site;
70
- this.#token = options.token;
71
80
  this.interval = options.interval;
72
81
  }
73
82
 
@@ -75,7 +84,6 @@ class RemoteLoader implements Loader {
75
84
  adopt(fallback: Snapshot | Loader): void {
76
85
  if (fallback === this.#fallback) return;
77
86
  this.#fallback = fallback;
78
- this.#fallbackRevision = undefined;
79
87
  this.#fallbackSnapshot = undefined;
80
88
  }
81
89
 
@@ -91,27 +99,19 @@ class RemoteLoader implements Loader {
91
99
 
92
100
  async update(): Promise<{ updated: boolean }> {
93
101
  if (isDevelopment()) return { updated: false };
94
- const manifest = await this.#manifest();
95
- if (manifest.generation < this.#generation) return { updated: false };
96
-
97
- // Best effort: a fallback that can't load (a KV key the deploy never wrote) is
98
- // fixed by downloading the release, not by failing the check.
99
- const fallbackRevision = await this.#fallbackRevisionNow().catch(() => undefined);
100
- const served = this.#current !== undefined ? this.#current.revision : fallbackRevision;
101
- if (served !== undefined && manifest.revision === served) {
102
- // A new generation of the same content (a re-promotion, a rollback to
103
- // it) still signals, so caches keyed on the release are invalidated.
104
- const changed = this.#generation !== -1 && manifest.generation > this.#generation;
105
- this.#generation = manifest.generation;
106
- return { updated: changed };
107
- }
108
- let next: Snapshot | undefined;
109
- if (fallbackRevision === undefined || manifest.revision !== fallbackRevision) {
110
- next = await this.#release(manifest);
111
- }
112
- // A slower, earlier check must not undo a newer publish or rollback.
113
- if (manifest.generation < this.#generation) return { updated: false };
114
- this.#generation = manifest.generation;
102
+ const fallback = this.#fallbackSnapshot ?? (await this.#loadFallback());
103
+ if (fallback.schemaHash === undefined) return { updated: false };
104
+ const site = encodeURIComponent(this.#site);
105
+ const latest = await this.#latest(site);
106
+ // Another schema: keep what this process serves (the fallback, or the last swap).
107
+ if (latest.schemaHash !== fallback.schemaHash) return { updated: false };
108
+ // The bundle is newer: keep what this process serves.
109
+ // OPEN: a process that already swapped a release in keeps it (memory stays as it is).
110
+ if (!isNewer(latest.publishedAt, fallback.committedAt)) return { updated: false };
111
+ if (latest.revision === this.#current?.revision) return { updated: false };
112
+ const blocks = await this.#revision(site, latest);
113
+ const next: Snapshot = { revision: latest.revision, blocks, schemaHash: latest.schemaHash };
114
+ if (fallback.aliases !== undefined) next.aliases = fallback.aliases;
115
115
  this.#current = next;
116
116
  return { updated: true };
117
117
  }
@@ -119,68 +119,54 @@ class RemoteLoader implements Loader {
119
119
  async #loadFallback(): Promise<Snapshot> {
120
120
  const fallback = this.#fallback;
121
121
  const snapshot = isSnapshot(fallback) ? fallback : await (fallback as Loader).load();
122
- if (fallback === this.#fallback) {
123
- this.#fallbackRevision = snapshot.revision;
124
- this.#fallbackSnapshot = snapshot;
125
- }
122
+ if (fallback === this.#fallback) this.#fallbackSnapshot = snapshot;
126
123
  return snapshot;
127
124
  }
128
125
 
129
- async #fallbackRevisionNow(): Promise<string> {
130
- return this.#fallbackRevision ?? (await this.#loadFallback()).revision;
131
- }
132
-
133
- async #manifest(): Promise<Manifest> {
134
- const site = encodeURIComponent(this.#site);
135
- const response = await fetchWithTimeout(
136
- `${HOSTED_DELIVERY_ORIGIN}/sites/${site}/channels/production.json`,
137
- this.#auth(),
138
- );
139
- if (!response.ok) throw new Error(`channel manifest: HTTP ${response.status}`);
126
+ async #latest(site: string): Promise<Latest> {
127
+ const response = await fetchWithTimeout(`${deliveryOrigin()}/sites/${site}/latest.json`);
128
+ if (!response.ok) {
129
+ await response.body?.cancel();
130
+ throw new Error(`latest.json: HTTP ${response.status}`);
131
+ }
140
132
  const body: unknown = await response.json();
141
- const prefix = `/sites/${site}/revisions/`;
142
133
  if (
143
134
  !isPlainObject(body) ||
144
- body.format !== MANIFEST_FORMAT ||
145
- !Number.isSafeInteger(body.generation) ||
146
135
  typeof body.revision !== "string" ||
147
- typeof body.snapshot !== "string" ||
148
- !body.snapshot.startsWith(prefix) ||
149
- !/^[\w.-]+\.json$/.test(body.snapshot.slice(prefix.length)) ||
150
- body.snapshot.includes("..")
136
+ !REVISION.test(body.revision) ||
137
+ typeof body.schemaHash !== "string" ||
138
+ !SCHEMA_HASH.test(body.schemaHash) ||
139
+ typeof body.publishedAt !== "string" ||
140
+ Number.isNaN(Date.parse(body.publishedAt))
151
141
  ) {
152
- throw new Error("channel manifest: unexpected format or snapshot path");
142
+ throw new Error("latest.json: unexpected format");
153
143
  }
154
- return body as unknown as Manifest;
144
+ return body as unknown as Latest;
155
145
  }
156
146
 
157
- async #release(manifest: Manifest): Promise<Snapshot> {
147
+ async #revision(site: string, latest: Latest): Promise<Record<string, unknown>> {
148
+ const label = `revision ${latest.revision}`;
158
149
  const response = await fetchWithTimeout(
159
- `${HOSTED_DELIVERY_ORIGIN}${manifest.snapshot}`,
160
- this.#auth(),
161
- );
162
- if (!response.ok) throw new Error(`release ${manifest.revision}: HTTP ${response.status}`);
163
- const snapshot = await readBoundedJson(
164
- response,
165
- `release ${manifest.revision}`,
166
- MAX_SNAPSHOT_BYTES,
150
+ `${deliveryOrigin()}/sites/${site}/revisions/${latest.revision}.json`,
167
151
  );
152
+ if (!response.ok) {
153
+ await response.body?.cancel();
154
+ throw new Error(`${label}: HTTP ${response.status}`);
155
+ }
156
+ const body = await readBoundedJson(response, label, MAX_SNAPSHOT_BYTES);
168
157
  if (
169
- !isSnapshot(snapshot) ||
170
- snapshot.revision !== manifest.revision ||
171
- (await computeContentRevision(snapshot.blocks)) !== manifest.revision
158
+ !isPlainObject(body) ||
159
+ body.revision !== latest.revision ||
160
+ body.schemaHash !== latest.schemaHash ||
161
+ !isPlainObject(body.blocks)
172
162
  ) {
173
- throw new Error(`release ${manifest.revision}: content doesn't match its revision`);
163
+ throw new Error(`${label}: unexpected format, or not the revision latest.json names`);
174
164
  }
175
- return snapshot;
176
- }
177
-
178
- #auth(): Record<string, string> {
179
- return { authorization: `Bearer ${this.#token}` };
165
+ return body.blocks;
180
166
  }
181
167
  }
182
168
 
183
- /** A loader over the fallback alone: `remoteLoader` without `site` or `token`. */
169
+ /** A loader over the fallback alone: `remoteLoader` without `site`. */
184
170
  class LocalLoader implements Loader {
185
171
  #fallback: Snapshot | Loader;
186
172
 
@@ -203,16 +189,14 @@ class LocalLoader implements Loader {
203
189
  }
204
190
 
205
191
  /**
206
- * Hosted releases over a fallback. `createCMS` builds it for you
207
- * when `site` and `token` are set. With either unset (a dev or test
208
- * environment without the variables), it's a loader over the fallback alone.
192
+ * Hosted releases over a fallback. `createCMS` builds it for you when `site`
193
+ * is set. Without `site`, it's a loader over the fallback alone.
209
194
  */
210
195
  export function remoteLoader(fallback: Snapshot | Loader, options: RemoteLoaderOptions): Loader {
211
- const { site, token } = options ?? {};
212
- const hosted = Boolean(site && token);
196
+ const { site } = options ?? {};
197
+ const hosted = Boolean(site);
213
198
  const key = Symbol.for(
214
- `${INSTANCE_PREFIX}${contentIdentity(fallback)}` +
215
- (hosted ? `|site:${site}|token:${fnv1a(token!)}` : "|local"),
199
+ `${INSTANCE_PREFIX}${contentIdentity(fallback)}${hosted ? `|site:${site}` : "|local"}`,
216
200
  );
217
201
  const store = globalThis as unknown as Record<symbol, RemoteLoader | LocalLoader | undefined>;
218
202
  const existing = store[key];
@@ -227,7 +211,7 @@ export function remoteLoader(fallback: Snapshot | Loader, options: RemoteLoaderO
227
211
  return existing;
228
212
  }
229
213
  const instance = hosted
230
- ? new RemoteLoader(fallback, { site: site!, token: token!, interval: options.interval })
214
+ ? new RemoteLoader(fallback, { site: site!, interval: options.interval })
231
215
  : new LocalLoader(fallback);
232
216
  store[key] = instance;
233
217
  return instance;
@@ -237,10 +221,31 @@ export function resetRemoteLoaders(): void {
237
221
  clearGlobals(INSTANCE_PREFIX);
238
222
  }
239
223
 
240
- function fetchWithTimeout(url: string, headers: Record<string, string>): Promise<Response> {
241
- return fetch(url, { headers, signal: timeoutSignal(FETCH_TIMEOUT_MS) });
224
+ /**
225
+ * Whether a release published at `publishedAt` is newer than content built
226
+ * from a commit made at `committedAt`. Content without a `committedAt` is the
227
+ * oldest.
228
+ * OPEN: a `committedAt` that doesn't parse as a date counts as missing.
229
+ */
230
+ function isNewer(publishedAt: string, committedAt: string | undefined): boolean {
231
+ const committed = committedAt === undefined ? Number.NaN : Date.parse(committedAt);
232
+ return Number.isNaN(committed) || Date.parse(publishedAt) > committed;
233
+ }
234
+
235
+ /** No credentials: delivery is public. */
236
+ function fetchWithTimeout(url: string): Promise<Response> {
237
+ return fetch(url, { signal: timeoutSignal(FETCH_TIMEOUT_MS) });
238
+ }
239
+
240
+ function deliveryOrigin(): string {
241
+ const override = (globalThis as Record<symbol, unknown>)[TEST_DELIVERY_ORIGIN];
242
+ return typeof override === "string" ? override : HOSTED_DELIVERY_ORIGIN;
242
243
  }
243
244
 
245
+ /**
246
+ * The SDK's only environment read: local development never swaps in hosted
247
+ * releases, so local files win.
248
+ */
244
249
  function isDevelopment(): boolean {
245
250
  try {
246
251
  // Written out so bundlers that define process.env.NODE_ENV replace it.