@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.
- package/dist/v8/cli/content.d.ts +24 -3
- package/dist/v8/cli/content.d.ts.map +1 -1
- package/dist/v8/cli/content.js +70 -5
- package/dist/v8/cli/content.js.map +1 -1
- package/dist/v8/cli/run.js +1 -1
- package/dist/v8/cli/run.js.map +1 -1
- package/dist/v8/cms.d.ts.map +1 -1
- package/dist/v8/cms.js +16 -19
- package/dist/v8/cms.js.map +1 -1
- package/dist/v8/content.d.ts +4 -5
- package/dist/v8/content.d.ts.map +1 -1
- package/dist/v8/content.js +46 -44
- package/dist/v8/content.js.map +1 -1
- package/dist/v8/draftChanges.d.ts +37 -14
- package/dist/v8/draftChanges.d.ts.map +1 -1
- package/dist/v8/draftChanges.js +66 -44
- package/dist/v8/draftChanges.js.map +1 -1
- package/dist/v8/identity.d.ts +0 -2
- package/dist/v8/identity.d.ts.map +1 -1
- package/dist/v8/identity.js +0 -10
- package/dist/v8/identity.js.map +1 -1
- package/dist/v8/remoteLoader.d.ts +2 -4
- package/dist/v8/remoteLoader.d.ts.map +1 -1
- package/dist/v8/remoteLoader.js +106 -87
- package/dist/v8/remoteLoader.js.map +1 -1
- package/dist/v8/telemetry.d.ts +7 -7
- package/dist/v8/telemetry.d.ts.map +1 -1
- package/dist/v8/telemetry.js +24 -100
- package/dist/v8/telemetry.js.map +1 -1
- package/dist/v8/types.d.ts +47 -16
- package/dist/v8/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/v8/cli/content.ts +85 -5
- package/src/v8/cli/run.ts +1 -1
- package/src/v8/cms.ts +17 -20
- package/src/v8/content.ts +54 -46
- package/src/v8/draftChanges.ts +79 -43
- package/src/v8/identity.ts +0 -10
- package/src/v8/remoteLoader.ts +111 -106
- package/src/v8/telemetry.ts +27 -108
- package/src/v8/types.ts +48 -14
package/src/v8/draftChanges.ts
CHANGED
|
@@ -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
|
|
6
|
-
*
|
|
7
|
-
* `local.studio.decocms.com`) and the loopback hosts;
|
|
8
|
-
* replaces the list. Any other host
|
|
9
|
-
*
|
|
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
|
-
* -
|
|
15
|
-
* `
|
|
16
|
-
*
|
|
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
|
|
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
|
|
55
|
+
".decocms.com", // Studio, its preview deployments and delivery.decocms.com
|
|
51
56
|
];
|
|
52
57
|
|
|
53
|
-
/**
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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
|
|
64
|
-
*
|
|
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(
|
|
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 =
|
|
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
|
|
111
|
+
* under, the version as `v`. `null` when no draft host admits the host.
|
|
96
112
|
*/
|
|
97
|
-
export function draftChangesUrl(
|
|
98
|
-
|
|
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
|
-
/**
|
|
105
|
-
|
|
106
|
-
|
|
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
|
|
110
|
-
"(
|
|
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
|
|
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
|
-
|
|
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
|
|
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)
|
|
138
|
-
if (Object.keys(body).some((key) => key !== "
|
|
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,
|
|
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,
|
|
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
|
|
170
|
-
if (base.aliases !== undefined)
|
|
171
|
-
return
|
|
205
|
+
const layered: Snapshot = { revision: `${base.revision}~${view}`, blocks };
|
|
206
|
+
if (base.aliases !== undefined) layered.aliases = base.aliases;
|
|
207
|
+
return layered;
|
|
172
208
|
}
|
package/src/v8/identity.ts
CHANGED
|
@@ -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>;
|
package/src/v8/remoteLoader.ts
CHANGED
|
@@ -1,73 +1,82 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* `remoteLoader`: hosted releases from
|
|
3
|
-
* content module, or any loader). See /next/hosted-releases-internals
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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`
|
|
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
|
|
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:
|
|
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
|
-
|
|
47
|
-
|
|
60
|
+
/** `sites/<site>/latest.json`: the release a site serves. */
|
|
61
|
+
interface Latest {
|
|
48
62
|
revision: string;
|
|
49
|
-
|
|
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
|
|
95
|
-
if (
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
//
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
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 #
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
body.
|
|
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("
|
|
142
|
+
throw new Error("latest.json: unexpected format");
|
|
153
143
|
}
|
|
154
|
-
return body as unknown as
|
|
144
|
+
return body as unknown as Latest;
|
|
155
145
|
}
|
|
156
146
|
|
|
157
|
-
async #
|
|
147
|
+
async #revision(site: string, latest: Latest): Promise<Record<string, unknown>> {
|
|
148
|
+
const label = `revision ${latest.revision}`;
|
|
158
149
|
const response = await fetchWithTimeout(
|
|
159
|
-
`${
|
|
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
|
-
!
|
|
170
|
-
|
|
171
|
-
|
|
158
|
+
!isPlainObject(body) ||
|
|
159
|
+
body.revision !== latest.revision ||
|
|
160
|
+
body.schemaHash !== latest.schemaHash ||
|
|
161
|
+
!isPlainObject(body.blocks)
|
|
172
162
|
) {
|
|
173
|
-
throw new Error(
|
|
163
|
+
throw new Error(`${label}: unexpected format, or not the revision latest.json names`);
|
|
174
164
|
}
|
|
175
|
-
return
|
|
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
|
|
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
|
-
*
|
|
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
|
|
212
|
-
const hosted = Boolean(site
|
|
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!,
|
|
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
|
-
|
|
241
|
-
|
|
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.
|