@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.
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/protocol/client.d.ts +1 -1
- package/dist/protocol/conformance/cases/reads.d.ts.map +1 -1
- package/dist/protocol/conformance/cases/reads.js +22 -6
- package/dist/protocol/conformance/cases/reads.js.map +1 -1
- package/dist/protocol/conformance/cases/writes.d.ts.map +1 -1
- package/dist/protocol/conformance/cases/writes.js +1 -0
- package/dist/protocol/conformance/cases/writes.js.map +1 -1
- package/dist/protocol/conformance/contentHashFixtures.d.ts +0 -29
- package/dist/protocol/conformance/contentHashFixtures.d.ts.map +1 -1
- package/dist/protocol/conformance/contentHashFixtures.js +0 -30
- package/dist/protocol/conformance/contentHashFixtures.js.map +1 -1
- package/dist/protocol/conformance/context.d.ts +3 -3
- package/dist/protocol/conformance/context.d.ts.map +1 -1
- package/dist/protocol/conformance/index.d.ts +1 -1
- package/dist/protocol/conformance/index.d.ts.map +1 -1
- package/dist/protocol/conformance/index.js +2 -2
- package/dist/protocol/conformance/index.js.map +1 -1
- package/dist/protocol/index.d.ts +3 -5
- package/dist/protocol/index.d.ts.map +1 -1
- package/dist/protocol/index.js +3 -5
- package/dist/protocol/index.js.map +1 -1
- package/dist/protocol/secrets.d.ts.map +1 -1
- package/dist/protocol/secrets.js +9 -2
- package/dist/protocol/secrets.js.map +1 -1
- package/dist/protocol/server/assets.d.ts +1 -1
- package/dist/protocol/server/assets.js +1 -1
- package/dist/protocol/server/methods/read.d.ts.map +1 -1
- package/dist/protocol/server/methods/read.js +5 -2
- package/dist/protocol/server/methods/read.js.map +1 -1
- package/dist/protocol/types.d.ts +23 -0
- package/dist/protocol/types.d.ts.map +1 -1
- package/dist/protocol/types.js +10 -0
- package/dist/protocol/types.js.map +1 -1
- package/dist/v8/boundedJson.d.ts +11 -0
- package/dist/v8/boundedJson.d.ts.map +1 -0
- package/dist/v8/boundedJson.js +44 -0
- package/dist/v8/boundedJson.js.map +1 -0
- package/dist/v8/builtins/data.d.ts +21 -5
- package/dist/v8/builtins/data.d.ts.map +1 -1
- package/dist/v8/builtins/data.js +47 -6
- package/dist/v8/builtins/data.js.map +1 -1
- package/dist/v8/builtins/index.d.ts.map +1 -1
- package/dist/v8/builtins/index.js +2 -3
- package/dist/v8/builtins/index.js.map +1 -1
- package/dist/v8/canonical.d.ts +0 -28
- package/dist/v8/canonical.d.ts.map +1 -1
- package/dist/v8/canonical.js +0 -19
- package/dist/v8/canonical.js.map +1 -1
- package/dist/v8/cli/check/index.d.ts +5 -0
- package/dist/v8/cli/check/index.d.ts.map +1 -1
- package/dist/v8/cli/check/index.js +34 -2
- package/dist/v8/cli/check/index.js.map +1 -1
- package/dist/v8/cli/index.d.ts +2 -1
- package/dist/v8/cli/index.d.ts.map +1 -1
- package/dist/v8/cli/index.js +2 -1
- package/dist/v8/cli/index.js.map +1 -1
- package/dist/v8/cli/run.d.ts.map +1 -1
- package/dist/v8/cli/run.js +3 -10
- package/dist/v8/cli/run.js.map +1 -1
- package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
- package/dist/v8/cli/schema/builtinSchemas.js +48 -28
- package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
- package/dist/v8/cli/schema/generate.d.ts +3 -1
- package/dist/v8/cli/schema/generate.d.ts.map +1 -1
- package/dist/v8/cli/schema/generate.js +2 -1
- package/dist/v8/cli/schema/generate.js.map +1 -1
- package/dist/v8/cli/schema/tsProgram.d.ts +10 -0
- package/dist/v8/cli/schema/tsProgram.d.ts.map +1 -1
- package/dist/v8/cli/schema/tsProgram.js +31 -0
- package/dist/v8/cli/schema/tsProgram.js.map +1 -1
- package/dist/v8/cli/schema/typeToSchema.d.ts.map +1 -1
- package/dist/v8/cli/schema/typeToSchema.js +15 -1
- package/dist/v8/cli/schema/typeToSchema.js.map +1 -1
- package/dist/v8/cli/serve/server.d.ts +1 -5
- package/dist/v8/cli/serve/server.d.ts.map +1 -1
- package/dist/v8/cli/serve/server.js +76 -62
- package/dist/v8/cli/serve/server.js.map +1 -1
- package/dist/v8/cms.d.ts +5 -2
- package/dist/v8/cms.d.ts.map +1 -1
- package/dist/v8/cms.js +187 -25
- package/dist/v8/cms.js.map +1 -1
- package/dist/v8/content.d.ts +22 -6
- package/dist/v8/content.d.ts.map +1 -1
- package/dist/v8/content.js +78 -40
- package/dist/v8/content.js.map +1 -1
- package/dist/v8/draft.d.ts +9 -12
- package/dist/v8/draft.d.ts.map +1 -1
- package/dist/v8/draft.js +30 -4
- package/dist/v8/draft.js.map +1 -1
- package/dist/v8/draftChanges.d.ts +26 -0
- package/dist/v8/draftChanges.d.ts.map +1 -0
- package/dist/v8/draftChanges.js +102 -0
- package/dist/v8/draftChanges.js.map +1 -0
- package/dist/v8/hosts.d.ts +55 -0
- package/dist/v8/hosts.d.ts.map +1 -0
- package/dist/v8/hosts.js +197 -0
- package/dist/v8/hosts.js.map +1 -0
- package/dist/v8/index.d.ts +4 -3
- package/dist/v8/index.d.ts.map +1 -1
- package/dist/v8/index.js +3 -2
- package/dist/v8/index.js.map +1 -1
- package/dist/v8/remoteLoader.d.ts +1 -1
- package/dist/v8/remoteLoader.d.ts.map +1 -1
- package/dist/v8/remoteLoader.js +32 -257
- package/dist/v8/remoteLoader.js.map +1 -1
- package/dist/v8/settings.d.ts +34 -0
- package/dist/v8/settings.d.ts.map +1 -0
- package/dist/v8/settings.js +143 -0
- package/dist/v8/settings.js.map +1 -0
- package/dist/v8/telemetry.d.ts +13 -3
- package/dist/v8/telemetry.d.ts.map +1 -1
- package/dist/v8/telemetry.js +31 -32
- package/dist/v8/telemetry.js.map +1 -1
- package/dist/v8/types.d.ts +74 -9
- package/dist/v8/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +3 -3
- package/src/protocol/client.ts +1 -1
- package/src/protocol/conformance/cases/reads.ts +24 -6
- package/src/protocol/conformance/cases/writes.ts +1 -0
- package/src/protocol/conformance/contentHashFixtures.ts +0 -57
- package/src/protocol/conformance/context.ts +3 -3
- package/src/protocol/conformance/index.ts +2 -7
- package/src/protocol/index.ts +2 -8
- package/src/protocol/secrets.ts +10 -2
- package/src/protocol/server/assets.ts +1 -1
- package/src/protocol/server/methods/read.ts +5 -2
- package/src/protocol/types.ts +21 -1
- package/src/v8/boundedJson.ts +47 -0
- package/src/v8/builtins/data.ts +56 -7
- package/src/v8/builtins/index.ts +2 -3
- package/src/v8/canonical.ts +0 -36
- package/src/v8/cli/check/index.ts +48 -2
- package/src/v8/cli/index.ts +2 -1
- package/src/v8/cli/run.ts +4 -9
- package/src/v8/cli/schema/builtinSchemas.ts +49 -28
- package/src/v8/cli/schema/generate.ts +4 -1
- package/src/v8/cli/schema/tsProgram.ts +27 -0
- package/src/v8/cli/schema/typeToSchema.ts +18 -1
- package/src/v8/cli/serve/server.ts +78 -77
- package/src/v8/cms.ts +234 -30
- package/src/v8/content.ts +87 -43
- package/src/v8/draft.ts +31 -9
- package/src/v8/draftChanges.ts +117 -0
- package/src/v8/hosts.ts +184 -0
- package/src/v8/index.ts +6 -8
- package/src/v8/remoteLoader.ts +39 -290
- package/src/v8/settings.ts +178 -0
- package/src/v8/telemetry.ts +43 -40
- package/src/v8/types.ts +68 -9
|
@@ -4,17 +4,19 @@
|
|
|
4
4
|
*
|
|
5
5
|
* The content protocol is `@decocms/blocks/protocol`'s `createContentHandler`
|
|
6
6
|
* (at `/rpc`) and `createAssetHandler` (at `/assets/<name>`) over the
|
|
7
|
-
* filesystem storage; they own
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* filesystem storage; they own `Content-Type`, size limits and upload rules.
|
|
8
|
+
* `deco serve` has no authentication and answers any origin: any website open
|
|
9
|
+
* in the browser can read and write the content through it, so it is meant
|
|
10
|
+
* to run only while editing. This file is the Node HTTP layer:
|
|
10
11
|
*
|
|
11
|
-
* - Listens on 127.0.0.1
|
|
12
|
-
*
|
|
13
|
-
* `--
|
|
14
|
-
*
|
|
12
|
+
* - Listens on loopback, 127.0.0.1 and ::1 on one port, so
|
|
13
|
+
* `http://localhost:<port>` reaches it whichever address the OS gives
|
|
14
|
+
* localhost; `--host` listens on that one address instead (with a warning
|
|
15
|
+
* beyond loopback: the network can reach it then).
|
|
16
|
+
* - CORS is answered for any `Origin` (reflected, with `Vary: Origin`), and
|
|
17
|
+
* so are Chrome's Private/Local Network Access preflights.
|
|
15
18
|
* - Every save regenerates `.deco/blocks.gen.ts`.
|
|
16
19
|
*/
|
|
17
|
-
import { randomBytes } from "node:crypto";
|
|
18
20
|
import fs from "node:fs";
|
|
19
21
|
import http from "node:http";
|
|
20
22
|
import type { AddressInfo } from "node:net";
|
|
@@ -30,18 +32,12 @@ import { readSavedBlocks, writeContent } from "../content.ts";
|
|
|
30
32
|
import { consoleReporter, type Reporter } from "../log.ts";
|
|
31
33
|
import { CliError, decoPaths, findDecoRoot, packageVersion } from "../root.ts";
|
|
32
34
|
|
|
33
|
-
/** The site editor's origins: the browser origins allowed by default. */
|
|
34
|
-
const STUDIO_ORIGINS = [
|
|
35
|
-
"https://studio.decocms.com",
|
|
36
|
-
"https://admin.decocms.com",
|
|
37
|
-
"https://admin.deco.cx",
|
|
38
|
-
];
|
|
39
|
-
|
|
40
35
|
/** Where the site editor link points. */
|
|
41
|
-
const STUDIO_ORIGIN =
|
|
36
|
+
const STUDIO_ORIGIN = "https://studio.decocms.com";
|
|
42
37
|
|
|
43
38
|
const DEFAULT_PORT = 4545;
|
|
44
|
-
|
|
39
|
+
/** Where it listens without `--host`; ::1 is skipped where IPv6 is unavailable. */
|
|
40
|
+
const DEFAULT_HOSTS = ["127.0.0.1", "::1"];
|
|
45
41
|
|
|
46
42
|
const LOOPBACK = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
|
|
47
43
|
|
|
@@ -52,19 +48,15 @@ export interface ServeOptions {
|
|
|
52
48
|
host?: string;
|
|
53
49
|
/** The local app the site editor previews: `localhost:8001` or a full loopback URL. */
|
|
54
50
|
preview?: string;
|
|
55
|
-
token?: string;
|
|
56
|
-
allowOrigins?: string[];
|
|
57
51
|
/** The upload folder, relative to the folder that contains `.deco`. */
|
|
58
52
|
assets?: string;
|
|
59
53
|
readOnly?: boolean;
|
|
60
54
|
reporter?: Reporter;
|
|
61
|
-
env?: NodeJS.ProcessEnv;
|
|
62
55
|
}
|
|
63
56
|
|
|
64
57
|
export interface RunningServer {
|
|
65
|
-
/** The content protocol endpoint, `http://
|
|
58
|
+
/** The content protocol endpoint, `http://localhost:4545/rpc`. */
|
|
66
59
|
endpoint: string;
|
|
67
|
-
token: string;
|
|
68
60
|
siteEditorUrl: string;
|
|
69
61
|
port: number;
|
|
70
62
|
close(): Promise<void>;
|
|
@@ -111,24 +103,11 @@ function previewUrl(input: string): string {
|
|
|
111
103
|
/** Start the server; resolves once it listens. */
|
|
112
104
|
export async function startServer(options: ServeOptions = {}): Promise<RunningServer> {
|
|
113
105
|
const reporter = options.reporter ?? consoleReporter;
|
|
114
|
-
const env = options.env ?? process.env;
|
|
115
106
|
const paths = decoPaths(findDecoRoot(options));
|
|
116
|
-
const host = options.host
|
|
107
|
+
const host = options.host?.toLowerCase();
|
|
117
108
|
const requestedPort = options.port ?? DEFAULT_PORT;
|
|
118
109
|
const readOnly = options.readOnly ?? false;
|
|
119
|
-
if (options.token !== undefined && options.token.trim() === "") {
|
|
120
|
-
throw new CliError("--token can't be empty: pass a token, or leave it out for a random one");
|
|
121
|
-
}
|
|
122
|
-
if (options.token === undefined && env.DECO_SERVE_TOKEN?.trim() === "") {
|
|
123
|
-
throw new CliError(
|
|
124
|
-
"DECO_SERVE_TOKEN can't be empty: set a token, or unset it for a random one",
|
|
125
|
-
);
|
|
126
|
-
}
|
|
127
|
-
const token = options.token ?? env.DECO_SERVE_TOKEN ?? randomBytes(32).toString("base64url");
|
|
128
110
|
const preview = previewUrl(options.preview ?? defaultPreviewUrl(paths.root));
|
|
129
|
-
const allowedOrigins = new Set(
|
|
130
|
-
[...STUDIO_ORIGINS, ...(options.allowOrigins ?? [])].map((o) => o.replace(/\/+$/, "")),
|
|
131
|
-
);
|
|
132
111
|
|
|
133
112
|
if (!Number.isInteger(requestedPort) || requestedPort < 0 || requestedPort > 65535) {
|
|
134
113
|
throw new CliError(`--port must be a port number, got ${requestedPort}`);
|
|
@@ -161,21 +140,13 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
|
|
|
161
140
|
},
|
|
162
141
|
};
|
|
163
142
|
const rpc = createContentHandler(storage, {
|
|
164
|
-
token,
|
|
165
143
|
server: { name: "deco-cli", version: packageVersion() },
|
|
166
144
|
preview: { url: preview },
|
|
167
145
|
onError: (error) => reporter.warn(String((error as Error)?.message ?? error)),
|
|
168
146
|
});
|
|
169
|
-
const assets = createAssetHandler(storage
|
|
170
|
-
|
|
171
|
-
let port = requestedPort;
|
|
172
|
-
const allowedHosts = () => {
|
|
173
|
-
const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
|
|
174
|
-
if (!LOOPBACK.has(host)) hosts.add(`${host.includes(":") ? `[${host}]` : host}:${port}`);
|
|
175
|
-
return hosts;
|
|
176
|
-
};
|
|
147
|
+
const assets = createAssetHandler(storage);
|
|
177
148
|
|
|
178
|
-
const
|
|
149
|
+
const handle: http.RequestListener = async (req, res) => {
|
|
179
150
|
const origin = req.headers.origin;
|
|
180
151
|
const cors: Record<string, string> = {};
|
|
181
152
|
const refuse = (status: number, code: number, message: string) => {
|
|
@@ -184,21 +155,14 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
|
|
|
184
155
|
};
|
|
185
156
|
|
|
186
157
|
try {
|
|
187
|
-
// DNS rebinding: only our own address.
|
|
188
|
-
if (!allowedHosts().has(String(req.headers.host ?? "").toLowerCase())) {
|
|
189
|
-
return refuse(403, ErrorCode.Forbidden, "unexpected Host header");
|
|
190
|
-
}
|
|
191
158
|
if (origin !== undefined) {
|
|
192
|
-
if (!allowedOrigins.has(origin)) {
|
|
193
|
-
return refuse(403, ErrorCode.Forbidden, `origin ${origin} isn't allowed`);
|
|
194
|
-
}
|
|
195
159
|
cors["access-control-allow-origin"] = origin;
|
|
196
160
|
cors.vary = "Origin";
|
|
197
161
|
}
|
|
198
162
|
if (req.method === "OPTIONS") {
|
|
199
163
|
const preflight: Record<string, string> = {
|
|
200
164
|
"access-control-allow-methods": "POST, PUT, OPTIONS",
|
|
201
|
-
"access-control-allow-headers": "
|
|
165
|
+
"access-control-allow-headers": "content-type",
|
|
202
166
|
"access-control-max-age": "600",
|
|
203
167
|
};
|
|
204
168
|
// Chrome's Local Network Access / Private Network Access preflight.
|
|
@@ -220,34 +184,30 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
|
|
|
220
184
|
} catch (error) {
|
|
221
185
|
refuse(500, ErrorCode.InternalError, (error as Error).message);
|
|
222
186
|
}
|
|
223
|
-
}
|
|
187
|
+
};
|
|
224
188
|
|
|
225
|
-
await
|
|
226
|
-
|
|
227
|
-
reject(
|
|
228
|
-
error.code === "EADDRINUSE"
|
|
229
|
-
? new CliError(`port ${requestedPort} is in use; pass --port`)
|
|
230
|
-
: error,
|
|
231
|
-
),
|
|
232
|
-
);
|
|
233
|
-
server.listen(requestedPort, host, () => resolve());
|
|
234
|
-
});
|
|
235
|
-
port = (server.address() as AddressInfo).port;
|
|
189
|
+
const servers = await listen(handle, host ? [host] : DEFAULT_HOSTS, requestedPort);
|
|
190
|
+
const port = (servers[0].address() as AddressInfo).port;
|
|
236
191
|
|
|
237
|
-
const displayHost = host.includes(":") ? `[${host}]` : host;
|
|
192
|
+
const displayHost = !host ? "localhost" : host.includes(":") ? `[${host}]` : host;
|
|
238
193
|
const endpoint = `http://${displayHost}:${port}/rpc`;
|
|
239
|
-
|
|
194
|
+
// The site editor connects only through loopback; a wildcard address
|
|
195
|
+
// listens there too, so its link uses localhost.
|
|
196
|
+
const wildcard = host === "0.0.0.0" || host === "::";
|
|
197
|
+
const linkEndpoint = wildcard ? `http://localhost:${port}/rpc` : endpoint;
|
|
198
|
+
const siteEditorUrl = `${STUDIO_ORIGIN}/site-editor#endpoint=${encodeURIComponent(linkEndpoint)}`;
|
|
240
199
|
|
|
241
|
-
if (!LOOPBACK.has(host)) {
|
|
200
|
+
if (host && !LOOPBACK.has(host)) {
|
|
242
201
|
reporter.warn(
|
|
243
|
-
`warning: listening on ${host}: other machines can reach this server
|
|
202
|
+
`warning: listening on ${host}: other machines on the network can reach this server and read and write the content` +
|
|
203
|
+
(wildcard ? "" : "; the site editor connects only through localhost"),
|
|
244
204
|
);
|
|
245
205
|
}
|
|
246
206
|
const schemaFile = fs.existsSync(paths.schema)
|
|
247
207
|
? ".deco/schema.gen.json"
|
|
248
208
|
: fs.existsSync(paths.legacySchema)
|
|
249
209
|
? ".deco/meta.gen.json"
|
|
250
|
-
: "no schema: run deco schema";
|
|
210
|
+
: "no schema yet: run deco schema for typed forms";
|
|
251
211
|
const count = Object.keys(readSavedBlocks(paths.blocks).blocks).length;
|
|
252
212
|
const description = await storage.describe();
|
|
253
213
|
const label = (name: string) => name.padEnd(21);
|
|
@@ -263,17 +223,58 @@ export async function startServer(options: ServeOptions = {}): Promise<RunningSe
|
|
|
263
223
|
|
|
264
224
|
return {
|
|
265
225
|
endpoint,
|
|
266
|
-
token,
|
|
267
226
|
siteEditorUrl,
|
|
268
227
|
port,
|
|
269
|
-
close: () =>
|
|
270
|
-
new Promise<void>((resolve) => {
|
|
271
|
-
server.closeAllConnections?.();
|
|
272
|
-
server.close(() => resolve());
|
|
273
|
-
}),
|
|
228
|
+
close: () => Promise.all(servers.map(close)).then(() => undefined),
|
|
274
229
|
};
|
|
275
230
|
}
|
|
276
231
|
|
|
232
|
+
/**
|
|
233
|
+
* One server per address, all on the port the first one gets. An address
|
|
234
|
+
* after the first that the machine doesn't have (::1 without IPv6) is
|
|
235
|
+
* skipped; with port 0, a port the next address can't take is tried again.
|
|
236
|
+
*/
|
|
237
|
+
async function listen(
|
|
238
|
+
handle: http.RequestListener,
|
|
239
|
+
hosts: string[],
|
|
240
|
+
requestedPort: number,
|
|
241
|
+
): Promise<http.Server[]> {
|
|
242
|
+
for (let attempt = 0; ; attempt++) {
|
|
243
|
+
const servers: http.Server[] = [];
|
|
244
|
+
let port = requestedPort;
|
|
245
|
+
try {
|
|
246
|
+
for (const [i, host] of hosts.entries()) {
|
|
247
|
+
const server = http.createServer(handle);
|
|
248
|
+
try {
|
|
249
|
+
await new Promise<void>((resolve, reject) => {
|
|
250
|
+
server.once("error", reject);
|
|
251
|
+
server.listen(port, host, () => resolve());
|
|
252
|
+
});
|
|
253
|
+
} catch (error) {
|
|
254
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
255
|
+
if (i > 0 && (code === "EADDRNOTAVAIL" || code === "EAFNOSUPPORT")) continue;
|
|
256
|
+
throw error;
|
|
257
|
+
}
|
|
258
|
+
servers.push(server);
|
|
259
|
+
port = (server.address() as AddressInfo).port;
|
|
260
|
+
}
|
|
261
|
+
return servers;
|
|
262
|
+
} catch (error) {
|
|
263
|
+
await Promise.all(servers.map(close));
|
|
264
|
+
if ((error as NodeJS.ErrnoException).code !== "EADDRINUSE") throw error;
|
|
265
|
+
if (requestedPort === 0 && attempt < 5) continue;
|
|
266
|
+
throw new CliError(`port ${port} is in use; pass --port`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
function close(server: http.Server): Promise<void> {
|
|
272
|
+
return new Promise((resolve) => {
|
|
273
|
+
server.closeAllConnections?.();
|
|
274
|
+
server.close(() => resolve());
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
277
278
|
/** A Node request as a fetch `Request`, its body streamed. */
|
|
278
279
|
function toRequest(req: http.IncomingMessage): Request {
|
|
279
280
|
const headers = new Headers();
|
package/src/v8/cms.ts
CHANGED
|
@@ -7,30 +7,63 @@
|
|
|
7
7
|
* cache. See /next/api-reference#one-instance-per-process.
|
|
8
8
|
*/
|
|
9
9
|
import { runInBackground } from "./background.ts";
|
|
10
|
+
import { SETTINGS_BLOCK, SETTINGS_TYPE } from "./builtins/data.ts";
|
|
10
11
|
import { builtIns } from "./builtins/index.ts";
|
|
11
12
|
import { secretBlock } from "./builtins/secret.ts";
|
|
12
13
|
import { CMSClient } from "./client.ts";
|
|
13
14
|
import { ContentStore, isLoader, isSnapshot } from "./content.ts";
|
|
14
|
-
import { parseDraftPointer } from "./draft.ts";
|
|
15
|
+
import { draftCookieFor, endsPreview, parseDraftPointer, readDraftPointer } from "./draft.ts";
|
|
16
|
+
import { allowsHost, type HostPattern, parseHostPattern } from "./hosts.ts";
|
|
15
17
|
import { clearGlobals, contentIdentity, fnv1a, readEnv } from "./identity.ts";
|
|
18
|
+
import { isPlainObject } from "./json.ts";
|
|
16
19
|
import { remoteLoader, resetRemoteLoaders } from "./remoteLoader.ts";
|
|
17
|
-
import {
|
|
18
|
-
|
|
20
|
+
import {
|
|
21
|
+
defaultSettings,
|
|
22
|
+
isStatic,
|
|
23
|
+
parseCodeHosts,
|
|
24
|
+
parseCodeSources,
|
|
25
|
+
readSettings,
|
|
26
|
+
type SettingsCaps,
|
|
27
|
+
} from "./settings.ts";
|
|
28
|
+
import {
|
|
29
|
+
resolveDestination,
|
|
30
|
+
setCurrentTelemetry,
|
|
31
|
+
TelemetryPipeline,
|
|
32
|
+
telemetryLimits,
|
|
33
|
+
} from "./telemetry.ts";
|
|
34
|
+
import type {
|
|
35
|
+
Blocks,
|
|
36
|
+
Client,
|
|
37
|
+
CMS,
|
|
38
|
+
CMSConfig,
|
|
39
|
+
EffectiveSettings,
|
|
40
|
+
Loader,
|
|
41
|
+
RequestLike,
|
|
42
|
+
Snapshot,
|
|
43
|
+
} from "./types.ts";
|
|
19
44
|
import { forceVariants } from "./variants.ts";
|
|
20
45
|
|
|
21
46
|
const INSTANCE_PREFIX = "decocms.blocks.cms:";
|
|
22
47
|
const MIN_INTERVAL = 60_000;
|
|
23
48
|
/** Each check runs one interval, plus or minus up to this much, after the previous one. */
|
|
24
49
|
const JITTER = 10_000;
|
|
50
|
+
/** How often telemetry reads its settings again when the release hasn't changed (date rules). */
|
|
51
|
+
const TELEMETRY_SETTINGS_MS = 60_000;
|
|
25
52
|
|
|
26
53
|
/** Options that must agree between two `createCMS` calls sharing an instance. */
|
|
27
54
|
interface Fingerprint {
|
|
28
55
|
interval: number;
|
|
29
56
|
telemetry: string;
|
|
57
|
+
preview: string;
|
|
30
58
|
secrets: string;
|
|
31
59
|
}
|
|
32
60
|
|
|
33
|
-
|
|
61
|
+
/**
|
|
62
|
+
* The state one content root shares across `createCMS` calls: the content
|
|
63
|
+
* store, caps, telemetry and secret key. Each call gets its own handle
|
|
64
|
+
* holding its own block map (see `CMSHandle`).
|
|
65
|
+
*/
|
|
66
|
+
class CMSInstance {
|
|
34
67
|
readonly config: Readonly<CMSConfig>;
|
|
35
68
|
readonly fingerprint: Fingerprint;
|
|
36
69
|
readonly #store: ContentStore;
|
|
@@ -39,7 +72,15 @@ class CMSInstance implements CMS {
|
|
|
39
72
|
/** The built-ins with a `secret` that holds this instance's key (the first call's). */
|
|
40
73
|
readonly #builtIns: Readonly<Blocks>;
|
|
41
74
|
readonly #telemetry: TelemetryPipeline | undefined;
|
|
42
|
-
#
|
|
75
|
+
readonly #caps: SettingsCaps;
|
|
76
|
+
/** The hosts a draft pointer may name (`preview.sources`): code only, never content. */
|
|
77
|
+
readonly #sources: readonly HostPattern[];
|
|
78
|
+
/** Settings of a `CMS` block with nothing to run, per release snapshot. */
|
|
79
|
+
#staticSettings = new WeakMap<Snapshot, EffectiveSettings>();
|
|
80
|
+
/** The release and time telemetry last read its section. */
|
|
81
|
+
#telemetryRead: { snapshot: Snapshot; at: number } | undefined;
|
|
82
|
+
/** One handle per block map, so the same config returns the same object. */
|
|
83
|
+
readonly #handles = new WeakMap<Blocks, CMS>();
|
|
43
84
|
/**
|
|
44
85
|
* When the next check is due. The first is on the first `forRelease()` or `forDraft()`, not
|
|
45
86
|
* at construction: Workers read `Date.now()` as 0 at module scope.
|
|
@@ -48,10 +89,14 @@ class CMSInstance implements CMS {
|
|
|
48
89
|
|
|
49
90
|
constructor(config: CMSConfig, interval: number) {
|
|
50
91
|
this.config = config;
|
|
51
|
-
this.#blocks = config.blocks;
|
|
52
92
|
this.#interval = interval;
|
|
53
93
|
this.#store = new ContentStore(contentOf(config));
|
|
54
94
|
this.fingerprint = fingerprintOf(config, interval);
|
|
95
|
+
this.#caps = {
|
|
96
|
+
hosts: parseCodeHosts(config.preview),
|
|
97
|
+
limits: telemetryLimits(config.telemetry),
|
|
98
|
+
};
|
|
99
|
+
this.#sources = parseCodeSources(config.preview);
|
|
55
100
|
const destination = resolveDestination(config.telemetry, config.site);
|
|
56
101
|
if (destination !== null) {
|
|
57
102
|
this.#telemetry = new TelemetryPipeline(destination);
|
|
@@ -63,34 +108,57 @@ class CMSInstance implements CMS {
|
|
|
63
108
|
this.#builtIns = Object.freeze({ ...builtIns, secret });
|
|
64
109
|
}
|
|
65
110
|
|
|
66
|
-
forRelease(): Client {
|
|
111
|
+
forRelease(blocks: Blocks): Client {
|
|
67
112
|
this.#scheduleUpdate();
|
|
68
113
|
const telemetry = this.#telemetry;
|
|
69
|
-
if (telemetry === undefined) return this.#client(() => this.#store.release());
|
|
70
|
-
return this.#client(() =>
|
|
71
|
-
this.#store.release().then((snapshot) => {
|
|
114
|
+
if (telemetry === undefined) return this.#client(blocks, () => this.#store.release());
|
|
115
|
+
return this.#client(blocks, () =>
|
|
116
|
+
this.#store.release().then(async (snapshot) => {
|
|
72
117
|
telemetry.useRelease(snapshot);
|
|
118
|
+
await this.#followTelemetrySettings(blocks, telemetry, snapshot);
|
|
73
119
|
return snapshot;
|
|
74
120
|
}),
|
|
75
121
|
);
|
|
76
122
|
}
|
|
77
123
|
|
|
78
124
|
/**
|
|
79
|
-
* The
|
|
80
|
-
*
|
|
81
|
-
*
|
|
125
|
+
* The release's settings, from memory: never a draft, never a fetch. The
|
|
126
|
+
* `CMS` block resolves on each call, so a field with variants is decided
|
|
127
|
+
* where it's called; one with nothing to run is resolved once per release.
|
|
82
128
|
*/
|
|
83
|
-
|
|
129
|
+
settings(blocks: Blocks): Promise<EffectiveSettings> {
|
|
130
|
+
return this.#settingsOf(blocks, this.#store.current());
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async draftPointer(blocks: Blocks, request: RequestLike): Promise<string | null> {
|
|
134
|
+
const pointer = readDraftPointer(request);
|
|
135
|
+
if (pointer === null) return null;
|
|
136
|
+
return (await this.#previewAllowed(blocks, request)) ? pointer : null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async draftCookie(blocks: Blocks, request: RequestLike): Promise<string | null> {
|
|
140
|
+
const cookie = draftCookieFor(request);
|
|
141
|
+
if (cookie === null) return null;
|
|
142
|
+
// Ending a preview is allowed anywhere, so a cookie set before a host was removed still goes.
|
|
143
|
+
if (endsPreview(request)) return cookie;
|
|
144
|
+
return (await this.#previewAllowed(blocks, request)) ? cookie : null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* The draft, with the variants the pointer forces (even for a `local`
|
|
149
|
+
* pointer, which names no draft). A draft client is a production client
|
|
150
|
+
* reading a draft pointer, so it schedules the release check like any other.
|
|
151
|
+
*/
|
|
152
|
+
forDraft(blocks: Blocks, pointer: string): Client {
|
|
84
153
|
this.#scheduleUpdate();
|
|
154
|
+
const load = () => this.#store.draft(pointer, this.#sources);
|
|
85
155
|
const variants = parseDraftPointer(pointer)?.variants;
|
|
86
|
-
if (variants === undefined) return this.#client(
|
|
87
|
-
return this.#client(() =>
|
|
88
|
-
this.#store.draft(pointer).then((snapshot) => forceVariants(snapshot, variants)),
|
|
89
|
-
);
|
|
156
|
+
if (variants === undefined) return this.#client(blocks, load);
|
|
157
|
+
return this.#client(blocks, () => load().then((snapshot) => forceVariants(snapshot, variants)));
|
|
90
158
|
}
|
|
91
159
|
|
|
92
|
-
forRevision(revision: string): Client {
|
|
93
|
-
return this.#client(() => this.#store.revision(revision));
|
|
160
|
+
forRevision(blocks: Blocks, revision: string): Client {
|
|
161
|
+
return this.#client(blocks, () => this.#store.revision(revision));
|
|
94
162
|
}
|
|
95
163
|
|
|
96
164
|
update(): Promise<{ updated: boolean }> {
|
|
@@ -98,16 +166,85 @@ class CMSInstance implements CMS {
|
|
|
98
166
|
return this.#store.update();
|
|
99
167
|
}
|
|
100
168
|
|
|
101
|
-
/**
|
|
169
|
+
/** The handle for a block map: this instance, resolving with that map. */
|
|
170
|
+
handle(blocks: Blocks): CMS {
|
|
171
|
+
let handle = this.#handles.get(blocks);
|
|
172
|
+
if (handle === undefined) {
|
|
173
|
+
handle = new CMSHandle(this, blocks);
|
|
174
|
+
this.#handles.set(blocks, handle);
|
|
175
|
+
}
|
|
176
|
+
return handle;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* A later `createCMS` call with the same key hands in its (possibly
|
|
181
|
+
* hot-reloaded) content. Its block map stays with its own handle: another
|
|
182
|
+
* bundle in the same process (Next's proxy) must not replace the app's.
|
|
183
|
+
*/
|
|
102
184
|
adopt(config: CMSConfig): void {
|
|
103
|
-
this.#blocks = config.blocks;
|
|
104
185
|
this.#store.replace(contentOf(config));
|
|
186
|
+
this.#staticSettings = new WeakMap();
|
|
187
|
+
this.#telemetryRead = undefined;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async #settingsOf(blocks: Blocks, snapshot: Snapshot | undefined): Promise<EffectiveSettings> {
|
|
191
|
+
if (snapshot === undefined) return defaultSettings(this.#caps);
|
|
192
|
+
const cached = this.#staticSettings.get(snapshot);
|
|
193
|
+
if (cached !== undefined) return cached;
|
|
194
|
+
const settings = await readSettings(
|
|
195
|
+
snapshot,
|
|
196
|
+
() =>
|
|
197
|
+
new CMSClient({
|
|
198
|
+
load: () => Promise.resolve(snapshot),
|
|
199
|
+
blocks,
|
|
200
|
+
builtIns: this.#builtIns,
|
|
201
|
+
onCollision: (name) => this.#warnCollision(name),
|
|
202
|
+
}),
|
|
203
|
+
this.#caps,
|
|
204
|
+
);
|
|
205
|
+
// A block map's own cms-settings function may answer differently per call.
|
|
206
|
+
const entry = snapshot.blocks[SETTINGS_BLOCK];
|
|
207
|
+
const fixed = !isPlainObject(entry) || isStatic(entry);
|
|
208
|
+
if (fixed && !Object.hasOwn(blocks, SETTINGS_TYPE)) {
|
|
209
|
+
this.#staticSettings.set(snapshot, settings);
|
|
210
|
+
}
|
|
211
|
+
return settings;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Whether the release's preview hosts allow this request's host. */
|
|
215
|
+
async #previewAllowed(blocks: Blocks, request: RequestLike): Promise<boolean> {
|
|
216
|
+
const { hosts } = (await this.settings(blocks)).preview;
|
|
217
|
+
const patterns = hosts
|
|
218
|
+
.map((raw) => parseHostPattern(raw))
|
|
219
|
+
.filter((pattern): pattern is HostPattern => pattern !== null);
|
|
220
|
+
return allowsHost(patterns, request.url);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Telemetry follows the release's `telemetry` section, read outside any
|
|
225
|
+
* request's choices: when the release changes (before its first client
|
|
226
|
+
* runs) and then at most once a minute, so date rules take effect.
|
|
227
|
+
*/
|
|
228
|
+
async #followTelemetrySettings(
|
|
229
|
+
blocks: Blocks,
|
|
230
|
+
telemetry: TelemetryPipeline,
|
|
231
|
+
snapshot: Snapshot,
|
|
232
|
+
): Promise<void> {
|
|
233
|
+
const last = this.#telemetryRead;
|
|
234
|
+
const now = Date.now();
|
|
235
|
+
if (last?.snapshot === snapshot && now - last.at < TELEMETRY_SETTINGS_MS) return;
|
|
236
|
+
this.#telemetryRead = { snapshot, at: now };
|
|
237
|
+
const read = this.#settingsOf(blocks, snapshot).then((settings) => {
|
|
238
|
+
if (this.#telemetryRead?.snapshot === snapshot) telemetry.apply(settings.telemetry);
|
|
239
|
+
});
|
|
240
|
+
// A new release waits for its rates; a periodic re-read doesn't hold up the request.
|
|
241
|
+
if (last?.snapshot !== snapshot) await read;
|
|
105
242
|
}
|
|
106
243
|
|
|
107
|
-
#client(load: () => Promise<Snapshot>): Client {
|
|
244
|
+
#client(blocks: Blocks, load: () => Promise<Snapshot>): Client {
|
|
108
245
|
return new CMSClient({
|
|
109
246
|
load,
|
|
110
|
-
blocks
|
|
247
|
+
blocks,
|
|
111
248
|
builtIns: this.#builtIns,
|
|
112
249
|
onCollision: (name) => this.#warnCollision(name),
|
|
113
250
|
telemetry: this.#telemetry?.forClient(),
|
|
@@ -139,9 +276,67 @@ class CMSInstance implements CMS {
|
|
|
139
276
|
}
|
|
140
277
|
}
|
|
141
278
|
|
|
279
|
+
/** `Symbol.for`, so a second copy of this module still reads it. */
|
|
280
|
+
const INSTANCE = Symbol.for("decocms.blocks.cms.instance");
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* What `createCMS` returns: the shared instance plus the block map of this
|
|
284
|
+
* call. Every handle on one content root shares its content, caps, telemetry
|
|
285
|
+
* and secret key; each resolves with the block map it was created with.
|
|
286
|
+
*/
|
|
287
|
+
class CMSHandle implements CMS {
|
|
288
|
+
readonly #instance: CMSInstance;
|
|
289
|
+
readonly #blocks: Blocks;
|
|
290
|
+
|
|
291
|
+
constructor(instance: CMSInstance, blocks: Blocks) {
|
|
292
|
+
this.#instance = instance;
|
|
293
|
+
this.#blocks = blocks;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The shared instance (tests use it to tell whether two handles share one). */
|
|
297
|
+
get [INSTANCE](): CMSInstance {
|
|
298
|
+
return this.#instance;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
forRelease(): Client {
|
|
302
|
+
return this.#instance.forRelease(this.#blocks);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
forDraft(pointer: string): Client {
|
|
306
|
+
return this.#instance.forDraft(this.#blocks, pointer);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
forRevision(revision: string): Client {
|
|
310
|
+
return this.#instance.forRevision(this.#blocks, revision);
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
update(): Promise<{ updated: boolean }> {
|
|
314
|
+
return this.#instance.update();
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
settings(): Promise<EffectiveSettings> {
|
|
318
|
+
return this.#instance.settings(this.#blocks);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
draftPointer(request: RequestLike): Promise<string | null> {
|
|
322
|
+
return this.#instance.draftPointer(this.#blocks, request);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
draftCookie(request: RequestLike): Promise<string | null> {
|
|
326
|
+
return this.#instance.draftCookie(this.#blocks, request);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** The shared instance behind a `createCMS` result; `undefined` for anything else. */
|
|
331
|
+
export function instanceOf(cms: CMS): object | undefined {
|
|
332
|
+
const instance = (cms as unknown as Record<symbol, unknown>)[INSTANCE];
|
|
333
|
+
return instance instanceof Object ? instance : undefined;
|
|
334
|
+
}
|
|
335
|
+
|
|
142
336
|
/**
|
|
143
|
-
* Creates the CMS
|
|
144
|
-
* Create it once, at module scope, and
|
|
337
|
+
* Creates the CMS: a handle on the one instance this content root has in the
|
|
338
|
+
* process, holding this call's block map. Create it once, at module scope, and
|
|
339
|
+
* ask it for a client per request.
|
|
145
340
|
*/
|
|
146
341
|
export function createCMS(config: CMSConfig): CMS {
|
|
147
342
|
validate(config);
|
|
@@ -151,14 +346,20 @@ export function createCMS(config: CMSConfig): CMS {
|
|
|
151
346
|
const key = Symbol.for(INSTANCE_PREFIX + identityOf(config));
|
|
152
347
|
const store = globalThis as unknown as Record<symbol, CMSInstance | undefined>;
|
|
153
348
|
const existing = store[key];
|
|
154
|
-
|
|
349
|
+
// An instance an older copy of this package stored (a dev reload across
|
|
350
|
+
// versions) has no handles: it's replaced rather than adopted.
|
|
351
|
+
if (
|
|
352
|
+
existing instanceof Object &&
|
|
353
|
+
typeof existing.adopt === "function" &&
|
|
354
|
+
typeof existing.handle === "function"
|
|
355
|
+
) {
|
|
155
356
|
warnOnConflict(existing.fingerprint, fingerprintOf(config, interval));
|
|
156
357
|
existing.adopt(config);
|
|
157
|
-
return existing;
|
|
358
|
+
return existing.handle(config.blocks);
|
|
158
359
|
}
|
|
159
360
|
const instance = new CMSInstance(config, interval);
|
|
160
361
|
store[key] = instance;
|
|
161
|
-
return instance;
|
|
362
|
+
return instance.handle(config.blocks);
|
|
162
363
|
}
|
|
163
364
|
|
|
164
365
|
/** Clears every stored CMS instance, so a test starts clean. */
|
|
@@ -168,7 +369,7 @@ export function resetForTests(): void {
|
|
|
168
369
|
setCurrentTelemetry(undefined);
|
|
169
370
|
}
|
|
170
371
|
|
|
171
|
-
/** With `site` and `token`, the content is the fallback of hosted releases
|
|
372
|
+
/** With `site` and `token`, the content is the fallback of hosted releases. */
|
|
172
373
|
function contentOf(config: CMSConfig): Snapshot | Loader {
|
|
173
374
|
if (!config.site || !config.token) return config.content;
|
|
174
375
|
return remoteLoader(config.content, { site: config.site, token: config.token });
|
|
@@ -186,6 +387,8 @@ function validate(config: CMSConfig): void {
|
|
|
186
387
|
"createCMS: `content` must be the content module ({ revision, blocks }) or a loader with load()",
|
|
187
388
|
);
|
|
188
389
|
}
|
|
390
|
+
parseCodeHosts(config.preview);
|
|
391
|
+
parseCodeSources(config.preview);
|
|
189
392
|
}
|
|
190
393
|
|
|
191
394
|
function resolveInterval(configured: number | undefined): number {
|
|
@@ -221,6 +424,7 @@ function fingerprintOf(config: CMSConfig, interval: number): Fingerprint {
|
|
|
221
424
|
return {
|
|
222
425
|
interval,
|
|
223
426
|
telemetry: stableJson(config.telemetry ?? null),
|
|
427
|
+
preview: stableJson(config.preview ?? null),
|
|
224
428
|
secrets: config.secrets?.key ? fnv1a(config.secrets.key) : "",
|
|
225
429
|
};
|
|
226
430
|
}
|