@valbuild/server 0.154.0 → 0.154.2
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/CHANGELOG.md +49 -0
- package/browser/dist/valbuild-server-browser.cjs.dev.js +6 -3
- package/browser/dist/valbuild-server-browser.cjs.prod.js +6 -3
- package/browser/dist/valbuild-server-browser.esm.js +6 -3
- package/dist/{ValRouterCore-fe985e4c.esm.js → ValOpsMemory-611f33d2.esm.js} +44 -1988
- package/dist/{ValRouterCore-4be8eaf1.cjs.prod.js → ValOpsMemory-6ebbb3ba.cjs.prod.js} +53 -2009
- package/dist/{ValRouterCore-0c088c9e.cjs.dev.js → ValOpsMemory-d8bf9f5d.cjs.dev.js} +53 -2009
- package/dist/ValPatchStore-2f92eced.cjs.prod.js +1128 -0
- package/dist/ValPatchStore-df8cdbe7.cjs.dev.js +1128 -0
- package/dist/ValPatchStore-e23070df.esm.js +1119 -0
- package/dist/ValRouterCore-5b747abb.cjs.prod.js +612 -0
- package/dist/ValRouterCore-73eb843d.esm.js +608 -0
- package/dist/ValRouterCore-86757d56.cjs.dev.js +612 -0
- package/dist/createPrettierFormatter-05ad7480.cjs.prod.js +692 -0
- package/dist/createPrettierFormatter-1edca494.esm.js +673 -0
- package/dist/createPrettierFormatter-851fcf99.cjs.dev.js +692 -0
- package/dist/createValRuntime-2dc83070.cjs.prod.js +47 -0
- package/dist/createValRuntime-62836dbe.esm.js +45 -0
- package/dist/createValRuntime-fd9b673d.cjs.dev.js +47 -0
- package/dist/declarations/src/ValOpsMemory.d.ts +3 -73
- package/dist/declarations/src/ValPatchStore.d.ts +92 -0
- package/dist/declarations/src/ValRouter.d.ts +1 -11
- package/dist/declarations/src/createPrettierFormatter.d.ts +18 -3
- package/dist/declarations/src/createValRuntime.d.ts +12 -0
- package/dist/declarations/src/draftReads.d.ts +11 -3
- package/dist/declarations/src/index.d.ts +4 -2
- package/dist/declarations/src/internal/index.d.ts +28 -6
- package/dist/declarations/src/proposal.d.ts +13 -25
- package/dist/declarations/src/proposalJsonEntries.d.ts +30 -0
- package/dist/declarations/src/serverMode.d.ts +31 -0
- package/dist/{draftReads-0dcddf72.cjs.prod.js → draftReads-3f7dcda5.cjs.prod.js} +10 -2
- package/dist/{draftReads-df44e629.cjs.dev.js → draftReads-a300a02f.cjs.dev.js} +10 -2
- package/dist/{draftReads-1f29aedd.esm.js → draftReads-bca0d49c.esm.js} +10 -2
- package/dist/{inTabFetch-f6694ad2.cjs.prod.js → inTabFetch-0124da2e.cjs.prod.js} +5 -4
- package/dist/{inTabFetch-c8966e73.cjs.dev.js → inTabFetch-d0c9c58a.cjs.dev.js} +5 -4
- package/dist/{inTabFetch-877e7d11.esm.js → inTabFetch-e48a801e.esm.js} +2 -1
- package/dist/jsonValuesPatch-13acc674.esm.js +276 -0
- package/dist/jsonValuesPatch-88bc661d.cjs.dev.js +281 -0
- package/dist/jsonValuesPatch-92798812.cjs.prod.js +281 -0
- package/dist/proposalJsonEntries-0669f027.esm.js +480 -0
- package/dist/proposalJsonEntries-26f397bd.cjs.dev.js +500 -0
- package/dist/proposalJsonEntries-9e537244.cjs.prod.js +500 -0
- package/dist/{publishKit-cfe1273d.cjs.dev.js → publishKit-96522d5a.cjs.prod.js} +20 -22
- package/dist/{publishKit-e7f7db7c.cjs.prod.js → publishKit-b06031dc.cjs.dev.js} +20 -22
- package/dist/{publishKit-0709423c.esm.js → publishKit-b8929fe8.esm.js} +8 -9
- package/dist/{ValRouter-1f427c38.cjs.dev.js → valRuntime-ba8ff718.cjs.prod.js} +158 -6038
- package/dist/{ValRouter-cd6e854a.cjs.prod.js → valRuntime-c8c82b24.cjs.dev.js} +158 -6038
- package/dist/{ValRouter-558dc66d.esm.js → valRuntime-ccbbbfad.esm.js} +107 -5937
- package/dist/valbuild-server.cjs.dev.js +5146 -352
- package/dist/valbuild-server.cjs.prod.js +5146 -352
- package/dist/valbuild-server.esm.js +4902 -132
- package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +7 -4
- package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +7 -4
- package/internal/browser/dist/valbuild-server-internal-browser.esm.js +7 -4
- package/internal/dist/valbuild-server-internal.cjs.dev.js +47 -31
- package/internal/dist/valbuild-server-internal.cjs.prod.js +47 -31
- package/internal/dist/valbuild-server-internal.esm.js +38 -22
- package/package.json +4 -4
|
@@ -1,283 +1,13 @@
|
|
|
1
1
|
import { Internal, extractValModules, computeValModuleShas, ImageSchema, DEFAULT_CONTENT_HOST, hasRemoteFileSchema } from '@valbuild/core';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import {
|
|
3
|
+
import { ChainFold, schemaVersionOf, baseVersionOf, EMPTY_CHAIN, sameModuleVersion, baseModuleContent, applyPatchRecord, isSchemaSourceFixError, resolveSchemaSourceFixForError, isJsonValuesRootOp, expandJsonValuesRootOp, classifyJsonValuesOp, rebaseContentOp, SerializedSchema, valClientHeaders, sketchTitle, parseSketch, SKETCHPAD_MAX_TEXT_LENGTH, checkSketch, AnalyticsBeacon, VAL_ENABLE_COOKIE_NAME, VAL_STATE_COOKIE, VAL_SESSION_COOKIE, parseJob, VAL_STUDIO_HEADER, newestCommitSha, AIToolCallSummaries, getErrorMessageFromUnknownJson } from '@valbuild/shared/internal';
|
|
4
|
+
import { p as posixPath, f as findNestedJsonValuesRecords, g as getNewJsonEntryPaths, r as resolveExistingJsonPath } from './jsonValuesPatch-13acc674.esm.js';
|
|
4
5
|
import { fromError } from 'zod-validation-error';
|
|
5
6
|
import { result } from '@valbuild/core/fp';
|
|
7
|
+
import { V as ValHead, r as recordKeysOf, i as isLastingAnswer, d as draftOverlay, I as InMemoryPatchStore } from './ValPatchStore-e23070df.esm.js';
|
|
6
8
|
import { JSONOps, PatchError, applyPatch, deepClone } from '@valbuild/core/patch';
|
|
7
9
|
import sizeOf from 'image-size';
|
|
8
10
|
|
|
9
|
-
/**
|
|
10
|
-
* `path.posix`, for the four functions the request handlers use.
|
|
11
|
-
*
|
|
12
|
-
* Node's `path` cannot be bundled for a browser, and the request handlers run
|
|
13
|
-
* in one for the demo (`@valbuild/server/browser`). These are Node's own posix
|
|
14
|
-
* algorithms, and `posixPath.test.ts` checks them against `path.posix` itself,
|
|
15
|
-
* so the two cannot differ quietly. Module paths are always posix -- `/app/
|
|
16
|
-
* page.val.ts` on Windows too -- so nothing here needs the platform's `path`.
|
|
17
|
-
*/
|
|
18
|
-
|
|
19
|
-
/** Resolves `.` and `..` segments, as Node's `normalizeString` does. */
|
|
20
|
-
function normalizeSegments(path, allowAboveRoot) {
|
|
21
|
-
let res = "";
|
|
22
|
-
let lastSegmentLength = 0;
|
|
23
|
-
let lastSlash = -1;
|
|
24
|
-
let dots = 0;
|
|
25
|
-
let code = 0;
|
|
26
|
-
for (let i = 0; i <= path.length; ++i) {
|
|
27
|
-
if (i < path.length) {
|
|
28
|
-
code = path.charCodeAt(i);
|
|
29
|
-
} else if (code === 47 /* / */) {
|
|
30
|
-
break;
|
|
31
|
-
} else {
|
|
32
|
-
code = 47;
|
|
33
|
-
}
|
|
34
|
-
if (code === 47) {
|
|
35
|
-
if (lastSlash === i - 1 || dots === 1) ; else if (dots === 2) {
|
|
36
|
-
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /* . */ || res.charCodeAt(res.length - 2) !== 46) {
|
|
37
|
-
if (res.length > 2) {
|
|
38
|
-
const lastSlashIndex = res.lastIndexOf("/");
|
|
39
|
-
if (lastSlashIndex === -1) {
|
|
40
|
-
res = "";
|
|
41
|
-
lastSegmentLength = 0;
|
|
42
|
-
} else {
|
|
43
|
-
res = res.slice(0, lastSlashIndex);
|
|
44
|
-
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
|
|
45
|
-
}
|
|
46
|
-
lastSlash = i;
|
|
47
|
-
dots = 0;
|
|
48
|
-
continue;
|
|
49
|
-
} else if (res.length !== 0) {
|
|
50
|
-
res = "";
|
|
51
|
-
lastSegmentLength = 0;
|
|
52
|
-
lastSlash = i;
|
|
53
|
-
dots = 0;
|
|
54
|
-
continue;
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
if (allowAboveRoot) {
|
|
58
|
-
res += res.length > 0 ? "/.." : "..";
|
|
59
|
-
lastSegmentLength = 2;
|
|
60
|
-
}
|
|
61
|
-
} else {
|
|
62
|
-
if (res.length > 0) {
|
|
63
|
-
res += "/" + path.slice(lastSlash + 1, i);
|
|
64
|
-
} else {
|
|
65
|
-
res = path.slice(lastSlash + 1, i);
|
|
66
|
-
}
|
|
67
|
-
lastSegmentLength = i - lastSlash - 1;
|
|
68
|
-
}
|
|
69
|
-
lastSlash = i;
|
|
70
|
-
dots = 0;
|
|
71
|
-
} else if (code === 46 && dots !== -1) {
|
|
72
|
-
++dots;
|
|
73
|
-
} else {
|
|
74
|
-
dots = -1;
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
return res;
|
|
78
|
-
}
|
|
79
|
-
function normalize(path) {
|
|
80
|
-
if (path.length === 0) return ".";
|
|
81
|
-
const isAbsolute = path.charCodeAt(0) === 47;
|
|
82
|
-
const trailingSeparator = path.charCodeAt(path.length - 1) === 47;
|
|
83
|
-
let normalized = normalizeSegments(path, !isAbsolute);
|
|
84
|
-
if (normalized.length === 0) {
|
|
85
|
-
if (isAbsolute) return "/";
|
|
86
|
-
return trailingSeparator ? "./" : ".";
|
|
87
|
-
}
|
|
88
|
-
if (trailingSeparator) normalized += "/";
|
|
89
|
-
return isAbsolute ? `/${normalized}` : normalized;
|
|
90
|
-
}
|
|
91
|
-
function join(...paths) {
|
|
92
|
-
const joined = paths.filter(path => path.length > 0).join("/");
|
|
93
|
-
return joined.length === 0 ? "." : normalize(joined);
|
|
94
|
-
}
|
|
95
|
-
function dirname(path) {
|
|
96
|
-
if (path.length === 0) return ".";
|
|
97
|
-
const hasRoot = path.charCodeAt(0) === 47;
|
|
98
|
-
let end = -1;
|
|
99
|
-
let matchedSlash = true;
|
|
100
|
-
for (let i = path.length - 1; i >= 1; --i) {
|
|
101
|
-
if (path.charCodeAt(i) === 47) {
|
|
102
|
-
if (!matchedSlash) {
|
|
103
|
-
end = i;
|
|
104
|
-
break;
|
|
105
|
-
}
|
|
106
|
-
} else {
|
|
107
|
-
matchedSlash = false;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
if (end === -1) return hasRoot ? "/" : ".";
|
|
111
|
-
if (hasRoot && end === 1) return "//";
|
|
112
|
-
return path.slice(0, end);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/**
|
|
116
|
-
* Node resolves both sides against `process.cwd()` first. When both are
|
|
117
|
-
* relative the cwd is a common prefix and drops out of the answer, so a root
|
|
118
|
-
* stands in for it; when only one is, the answer depends on a directory a
|
|
119
|
-
* browser does not have, and it is refused rather than guessed.
|
|
120
|
-
*/
|
|
121
|
-
function resolveBoth(from, to) {
|
|
122
|
-
const fromAbsolute = from.charCodeAt(0) === 47;
|
|
123
|
-
const toAbsolute = to.charCodeAt(0) === 47;
|
|
124
|
-
if (fromAbsolute !== toAbsolute) {
|
|
125
|
-
throw new Error(`posixPath.relative needs two absolute or two relative paths, got '${from}' and '${to}'.`);
|
|
126
|
-
}
|
|
127
|
-
const root = path => `/${normalizeSegments(fromAbsolute ? path : `/${path}`, false)}`;
|
|
128
|
-
return [root(from), root(to)];
|
|
129
|
-
}
|
|
130
|
-
function relative(from, to) {
|
|
131
|
-
if (from === to) return "";
|
|
132
|
-
[from, to] = resolveBoth(from, to);
|
|
133
|
-
if (from === to) return "";
|
|
134
|
-
const fromStart = 1;
|
|
135
|
-
const fromEnd = from.length;
|
|
136
|
-
const fromLen = fromEnd - fromStart;
|
|
137
|
-
const toStart = 1;
|
|
138
|
-
const toLen = to.length - toStart;
|
|
139
|
-
const length = fromLen < toLen ? fromLen : toLen;
|
|
140
|
-
let lastCommonSep = -1;
|
|
141
|
-
let i = 0;
|
|
142
|
-
for (; i < length; i++) {
|
|
143
|
-
const fromCode = from.charCodeAt(fromStart + i);
|
|
144
|
-
if (fromCode !== to.charCodeAt(toStart + i)) break;else if (fromCode === 47) lastCommonSep = i;
|
|
145
|
-
}
|
|
146
|
-
if (i === length) {
|
|
147
|
-
if (toLen > length) {
|
|
148
|
-
if (to.charCodeAt(toStart + i) === 47) {
|
|
149
|
-
return to.slice(toStart + i + 1);
|
|
150
|
-
}
|
|
151
|
-
if (i === 0) {
|
|
152
|
-
return to.slice(toStart + i);
|
|
153
|
-
}
|
|
154
|
-
} else if (fromLen > length) {
|
|
155
|
-
if (from.charCodeAt(fromStart + i) === 47) {
|
|
156
|
-
lastCommonSep = i;
|
|
157
|
-
} else if (i === 0) {
|
|
158
|
-
lastCommonSep = 0;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
let out = "";
|
|
163
|
-
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
|
|
164
|
-
if (i === fromEnd || from.charCodeAt(i) === 47) {
|
|
165
|
-
out += out.length === 0 ? ".." : "/..";
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
return `${out}${to.slice(toStart + lastCommonSep)}`;
|
|
169
|
-
}
|
|
170
|
-
const posixPath = {
|
|
171
|
-
normalize,
|
|
172
|
-
join,
|
|
173
|
-
dirname,
|
|
174
|
-
relative
|
|
175
|
-
};
|
|
176
|
-
|
|
177
|
-
/**
|
|
178
|
-
* Finds every `.jsonValues()` record in a module's schema that is NOT the
|
|
179
|
-
* module's root, returning the path to each within the module source.
|
|
180
|
-
*
|
|
181
|
-
* `.jsonValues()` is only supported on a module's ROOT record/router: the
|
|
182
|
-
* `/json` endpoint keys entries by a single string, the Studio substitutes
|
|
183
|
-
* loaded content at the top level of the module source, and
|
|
184
|
-
* `validateJsonValuesEntries` only visits a root record. A nested one would
|
|
185
|
-
* silently skip content validation and hang the Studio on a 404, so we reject
|
|
186
|
-
* it up front instead (see {@link ValOps.initSources}).
|
|
187
|
-
*/
|
|
188
|
-
function findNestedJsonValuesRecords(schema, path = []) {
|
|
189
|
-
const found = [];
|
|
190
|
-
const rec = (current, currentPath) => {
|
|
191
|
-
if (current.type === "record" && current.jsonValues && currentPath.length > 0) {
|
|
192
|
-
found.push(currentPath);
|
|
193
|
-
// Do not descend: everything below lives in the entry's `*.val.json`.
|
|
194
|
-
return;
|
|
195
|
-
}
|
|
196
|
-
switch (current.type) {
|
|
197
|
-
case "object":
|
|
198
|
-
for (const key of Object.keys(current.items)) {
|
|
199
|
-
rec(current.items[key], currentPath.concat(key));
|
|
200
|
-
}
|
|
201
|
-
return;
|
|
202
|
-
case "record":
|
|
203
|
-
rec(current.item, currentPath.concat("*"));
|
|
204
|
-
return;
|
|
205
|
-
case "array":
|
|
206
|
-
rec(current.item, currentPath.concat("*"));
|
|
207
|
-
return;
|
|
208
|
-
case "discriminated-union":
|
|
209
|
-
for (let i = 0; i < current.items.length; i++) {
|
|
210
|
-
rec(current.items[i], currentPath.concat(`union[${i}]`));
|
|
211
|
-
}
|
|
212
|
-
return;
|
|
213
|
-
default:
|
|
214
|
-
return;
|
|
215
|
-
}
|
|
216
|
-
};
|
|
217
|
-
rec(schema, path);
|
|
218
|
-
return found;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
/**
|
|
222
|
-
* The `.val.ts` suffix a module file path ends with. Stripping it yields the
|
|
223
|
-
* folder that a new entry's `*.val.json` files are nested under.
|
|
224
|
-
*/
|
|
225
|
-
const VAL_TS_SUFFIX = ".val.ts";
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Computes the `*.val.json` file path (relative to rootDir) and the `import(...)`
|
|
229
|
-
* path (relative to the module's directory) for a NEW `.jsonValues()` entry,
|
|
230
|
-
* following the locked filename convention: the file mirrors the entry key under
|
|
231
|
-
* a folder named after the `.val.ts` (its `.val.ts` suffix becomes the folder).
|
|
232
|
-
*
|
|
233
|
-
* For module `/app/support/[slug]/page.val.ts` and key `/support/faq`:
|
|
234
|
-
* - jsonPath: `/app/support/[slug]/page/support/faq.val.json`
|
|
235
|
-
* - importPath: `./page/support/faq.val.json`
|
|
236
|
-
*/
|
|
237
|
-
function getNewJsonEntryPaths(moduleFilePath, entryKey) {
|
|
238
|
-
const base = moduleFilePath.endsWith(VAL_TS_SUFFIX) ? moduleFilePath.slice(0, -VAL_TS_SUFFIX.length) : moduleFilePath;
|
|
239
|
-
const keyRel = entryKey.replace(/^\//, "");
|
|
240
|
-
const invalid = reason => result.err({
|
|
241
|
-
message: `Invalid .jsonValues() entry key '${entryKey}' in ${moduleFilePath}: ${reason}`,
|
|
242
|
-
filePath: moduleFilePath
|
|
243
|
-
});
|
|
244
|
-
// An entry key is CLIENT-SUPPLIED — it arrives as a record key in a patch op —
|
|
245
|
-
// and this path is what the commit writes to disk. Left unchecked, a key with
|
|
246
|
-
// `..` segments (or a backslash, which is a separator once the path is handed
|
|
247
|
-
// to node's `path.join` on Windows) puts that write anywhere in the project or
|
|
248
|
-
// outside it entirely, and a `move` additionally deletes the source path.
|
|
249
|
-
if (keyRel === "") {
|
|
250
|
-
return invalid("it is empty");
|
|
251
|
-
}
|
|
252
|
-
if (keyRel.includes("\\") || keyRel.includes("\0")) {
|
|
253
|
-
return invalid("it contains a backslash or a NUL byte");
|
|
254
|
-
}
|
|
255
|
-
const jsonPath = posixPath.normalize(`${base}/${keyRel}.val.json`);
|
|
256
|
-
if (!jsonPath.startsWith(`${base}/`)) {
|
|
257
|
-
return invalid(`it resolves outside '${base}/'`);
|
|
258
|
-
}
|
|
259
|
-
const moduleDir = posixPath.dirname(moduleFilePath);
|
|
260
|
-
let importPath = posixPath.relative(moduleDir, jsonPath);
|
|
261
|
-
if (!importPath.startsWith(".")) {
|
|
262
|
-
importPath = `./${importPath}`;
|
|
263
|
-
}
|
|
264
|
-
return result.ok({
|
|
265
|
-
jsonPath,
|
|
266
|
-
importPath
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/**
|
|
271
|
-
* Resolves an EXISTING entry's `*.val.json` path (relative to rootDir) from the
|
|
272
|
-
* `import(...)` path recorded in the `.val.ts` thunk (from
|
|
273
|
-
* {@link analyzeJsonValuesEntries}). Existing files may have been hand-placed,
|
|
274
|
-
* so the import path is authoritative (hybrid authoring).
|
|
275
|
-
*/
|
|
276
|
-
function resolveExistingJsonPath(moduleFilePath, importPath) {
|
|
277
|
-
const moduleDir = posixPath.dirname(moduleFilePath);
|
|
278
|
-
return posixPath.join(moduleDir, importPath);
|
|
279
|
-
}
|
|
280
|
-
|
|
281
11
|
/**
|
|
282
12
|
* The outcome of {@link validateJsonValuesEntries}: the errors found inside the
|
|
283
13
|
* entries, plus the content of every entry that could be loaded, keyed by entry
|
|
@@ -1754,1021 +1484,6 @@ function isStale(parsed, schema, value) {
|
|
|
1754
1484
|
return expected !== parsed.validationHash;
|
|
1755
1485
|
}
|
|
1756
1486
|
|
|
1757
|
-
/**
|
|
1758
|
-
* The patches a json entry render should apply, out of the whole chain:
|
|
1759
|
-
*
|
|
1760
|
-
* 1. this module's, since the chain is branch-wide;
|
|
1761
|
-
* 2. a patch published after this build is kept: this build does not have it.
|
|
1762
|
-
* One already in the build is dropped. `draftOverlay` decides which is
|
|
1763
|
-
* which, from `commits`.
|
|
1764
|
-
*/
|
|
1765
|
-
|
|
1766
|
-
/**
|
|
1767
|
-
* The patches a DRAFT applies on top of this build's own source: the pending
|
|
1768
|
-
* ones, and the ones published AFTER this build, in chain order -- with
|
|
1769
|
-
* `appliedAt` cleared on the latter, because this build has none of them.
|
|
1770
|
-
*
|
|
1771
|
-
* Content places every caller at its own build (`getApplicablePatchesAndCommits`
|
|
1772
|
-
* in valbuild/home: "the earliest the caller has not seen") and returns the
|
|
1773
|
-
* commits after it as `commits`. A patch applied at one of those was
|
|
1774
|
-
* published after this build and is not in it, so a draft has to apply it --
|
|
1775
|
-
* skipping it showed the build's old value from the publish until the next
|
|
1776
|
-
* build went live. `/sources/~` already applies them (`getSources` walks every
|
|
1777
|
-
* patch it is given); the `.jsonValues()` entry path skipped them.
|
|
1778
|
-
*
|
|
1779
|
-
* A patch applied at a commit NOT in that list is already in this build --
|
|
1780
|
-
* content returns one only because it was asked for by id -- and is dropped:
|
|
1781
|
-
* applying it again would apply it twice. Without `commits` (a store that
|
|
1782
|
-
* does not report them) every applied patch is dropped, as before. Only
|
|
1783
|
-
* `ValOpsHttp` ever reports `appliedAt`; `fs` and memory stores report `null`.
|
|
1784
|
-
*
|
|
1785
|
-
* Chain order, not published-first, because that is the order the Studio
|
|
1786
|
-
* applies them in, and a draft page starts from the server's answer and is
|
|
1787
|
-
* then kept up to date by the Studio's: the two must agree.
|
|
1788
|
-
*
|
|
1789
|
-
* For the reads that render a draft only. What to COMMIT still keys on
|
|
1790
|
-
* `appliedAt`: a published patch must never be published again.
|
|
1791
|
-
*/
|
|
1792
|
-
function draftOverlay(patches, commits) {
|
|
1793
|
-
const afterThisBuild = new Set((commits ?? []).map(commit => commit.commitSha));
|
|
1794
|
-
const overlay = [];
|
|
1795
|
-
for (const patch of patches) {
|
|
1796
|
-
if (patch.appliedAt === null) {
|
|
1797
|
-
overlay.push(patch);
|
|
1798
|
-
} else if (afterThisBuild.has(patch.appliedAt.commitSha)) {
|
|
1799
|
-
overlay.push({
|
|
1800
|
-
...patch,
|
|
1801
|
-
appliedAt: null
|
|
1802
|
-
});
|
|
1803
|
-
}
|
|
1804
|
-
}
|
|
1805
|
-
return overlay;
|
|
1806
|
-
}
|
|
1807
|
-
|
|
1808
|
-
/*
|
|
1809
|
-
* THE HEAD: the content at the newest chain, in the module store. See
|
|
1810
|
-
* `docs/plans/one-content-model.md`, "One runtime per process, and the head".
|
|
1811
|
-
*
|
|
1812
|
-
* One per data layer (`ValOps`), and so one per process for a project
|
|
1813
|
-
* (`valRuntime`): the API route, the draft readers and MCP read through the
|
|
1814
|
-
* same one, so a save moves every reader, and one head serves every editor --
|
|
1815
|
-
* draft content is not per user; the session only decides who may see it.
|
|
1816
|
-
*
|
|
1817
|
-
* In a 128 MB isolate it grows only with what was edited:
|
|
1818
|
-
*
|
|
1819
|
-
* 1. An unpatched module costs nothing: the bundle tier answers with the
|
|
1820
|
-
* bundle's own object, which the process holds for every visitor anyway.
|
|
1821
|
-
* 2. A module is materialized when it is read and has patches, never all at
|
|
1822
|
-
* once, and the next version of its chain is EXTENDED from the one before
|
|
1823
|
-
* by the new patches alone.
|
|
1824
|
-
* 3. A discard replays one module from its base through its own patches.
|
|
1825
|
-
* 4. The memory tier's byte budget ({@link HEAD_BUDGET_BYTES}) lets go of the
|
|
1826
|
-
* least recently read module, which is made again on its next read; and
|
|
1827
|
-
* it keeps the last {@link HEAD_VERSIONS_PER_MODULE} versions of each.
|
|
1828
|
-
* 5. No validation and no previews on the read path. They are their own
|
|
1829
|
-
* requests (`/validate`, the Studio's own previews).
|
|
1830
|
-
*
|
|
1831
|
-
* "Has the chain moved?" is `seq` alone (`ValOps.chainSeq`): a counter in fs
|
|
1832
|
-
* and memory mode, one small read of the content service in http mode. The
|
|
1833
|
-
* chain is fetched only when it moved.
|
|
1834
|
-
*/
|
|
1835
|
-
|
|
1836
|
-
/**
|
|
1837
|
-
* What the head may hold beyond what the build holds anyway: 16 MB, about
|
|
1838
|
-
* where a deployed isolate beside 64 MB of other heap stopped outliving a
|
|
1839
|
-
* validated whole-tree draft read (`scenarios/measure/results.md`, "The
|
|
1840
|
-
* deployed isolate").
|
|
1841
|
-
*/
|
|
1842
|
-
const HEAD_BUDGET_BYTES = 16 * 1024 * 1024;
|
|
1843
|
-
|
|
1844
|
-
/** The current version of each module and the one before it. */
|
|
1845
|
-
const HEAD_VERSIONS_PER_MODULE = 2;
|
|
1846
|
-
|
|
1847
|
-
/**
|
|
1848
|
-
* Counted work, in this process, for every head: never reset, so two readers
|
|
1849
|
-
* of it cannot disturb each other. A test takes it before and after.
|
|
1850
|
-
*/
|
|
1851
|
-
const counted = {
|
|
1852
|
-
/** "Has the chain moved?" asked. */
|
|
1853
|
-
seqReads: 0,
|
|
1854
|
-
/** The chain fetched, because it had. */
|
|
1855
|
-
chainReads: 0,
|
|
1856
|
-
/** Modules made from a base or an older version. */
|
|
1857
|
-
materialized: 0,
|
|
1858
|
-
/** Of those, made by extending the version before by the new patches alone. */
|
|
1859
|
-
extended: 0,
|
|
1860
|
-
/**
|
|
1861
|
-
* A record's whole key list walked: once per record object (a base, a
|
|
1862
|
-
* version), never per request -- see {@link recordKeysOf}.
|
|
1863
|
-
*/
|
|
1864
|
-
recordScans: 0,
|
|
1865
|
-
/** `.jsonValues()` entries resolved: once per entry and version. */
|
|
1866
|
-
entriesResolved: 0
|
|
1867
|
-
};
|
|
1868
|
-
const recordKeys = new WeakMap();
|
|
1869
|
-
|
|
1870
|
-
/**
|
|
1871
|
-
* A record's keys, in order: walked once per record OBJECT and kept beside
|
|
1872
|
-
* it. A record is immutable (a base, or a version the engine made), so the
|
|
1873
|
-
* same object has the same keys for good -- and an entry request, which only
|
|
1874
|
-
* needs the count (`total`) or a window of them, costs what it asks for,
|
|
1875
|
-
* not the size of the record. Before, every `GET /json` walked the whole
|
|
1876
|
-
* record (`Object.keys`), so reading 10,000 entries one request at a time
|
|
1877
|
-
* was 10,000 x 10,000 (phase 10's baseline).
|
|
1878
|
-
*/
|
|
1879
|
-
function recordKeysOf(record) {
|
|
1880
|
-
let keys = recordKeys.get(record);
|
|
1881
|
-
if (keys === undefined) {
|
|
1882
|
-
counted.recordScans++;
|
|
1883
|
-
keys = Object.keys(record);
|
|
1884
|
-
recordKeys.set(record, keys);
|
|
1885
|
-
}
|
|
1886
|
-
return keys;
|
|
1887
|
-
}
|
|
1888
|
-
|
|
1889
|
-
/** See {@link counted}. */
|
|
1890
|
-
function headWork() {
|
|
1891
|
-
return {
|
|
1892
|
-
...counted
|
|
1893
|
-
};
|
|
1894
|
-
}
|
|
1895
|
-
|
|
1896
|
-
/** The chain, as the head last read it. */
|
|
1897
|
-
|
|
1898
|
-
/** What the head knows about a module it made, beside its content. */
|
|
1899
|
-
|
|
1900
|
-
/** A module as the head answers it. */
|
|
1901
|
-
|
|
1902
|
-
/**
|
|
1903
|
-
* What a draft reader is given for a module: the bundle's own (read the
|
|
1904
|
-
* bundle), or the head's source in its wire shape -- `.jsonValues()` markers
|
|
1905
|
-
* without their `import()`, and the entries the draft changes in place of
|
|
1906
|
-
* theirs.
|
|
1907
|
-
*/
|
|
1908
|
-
|
|
1909
|
-
/** One entry, as `/json` and the draft readers answer it. */
|
|
1910
|
-
|
|
1911
|
-
class ValHead {
|
|
1912
|
-
memory;
|
|
1913
|
-
store;
|
|
1914
|
-
facts = new WeakMap();
|
|
1915
|
-
chain = null;
|
|
1916
|
-
fetching = null;
|
|
1917
|
-
serialized = null;
|
|
1918
|
-
wholeTree = null;
|
|
1919
|
-
constructor(ops, opts = {}) {
|
|
1920
|
-
this.ops = ops;
|
|
1921
|
-
this.memory = memoryTier({
|
|
1922
|
-
budgetBytes: opts.budgetBytes ?? HEAD_BUDGET_BYTES,
|
|
1923
|
-
lastPerModule: opts.lastPerModule ?? HEAD_VERSIONS_PER_MODULE
|
|
1924
|
-
});
|
|
1925
|
-
this.store = tiered([this.memory, bundleTier(path => this.ops.bundleModule(path)),
|
|
1926
|
-
// What the build serves where it is not the bundle: a content version,
|
|
1927
|
-
// a proposal's saves, a publish adopted in this process.
|
|
1928
|
-
bundleTier(path => this.ops.baseModule(path), "base")]);
|
|
1929
|
-
}
|
|
1930
|
-
|
|
1931
|
-
/** What the head holds now. */
|
|
1932
|
-
stats() {
|
|
1933
|
-
return this.memory.stats();
|
|
1934
|
-
}
|
|
1935
|
-
|
|
1936
|
-
// #region the chain
|
|
1937
|
-
|
|
1938
|
-
/**
|
|
1939
|
-
* The chain, re-read only when `seq` moved (or the base did: a publish
|
|
1940
|
-
* adopted). A read that finds a fetch already under way at the `seq` it
|
|
1941
|
-
* saw joins it: that fetch reads at that `seq` or later.
|
|
1942
|
-
*
|
|
1943
|
-
* Asks "has the chain moved?" once per call -- in http mode one request to
|
|
1944
|
-
* the content service. A caller that reads several modules for ONE answer
|
|
1945
|
-
* (a draft page's request) syncs once and passes the chain it got to
|
|
1946
|
-
* {@link draft}, {@link entries} and {@link changed}, so a page of thirty
|
|
1947
|
-
* modules asks once, not thirty times, and reads all of them at one chain.
|
|
1948
|
-
*/
|
|
1949
|
-
async sync() {
|
|
1950
|
-
counted.seqReads++;
|
|
1951
|
-
const [position, base] = await Promise.all([this.ops.chainPosition(), this.ops.getSourcesSha()]);
|
|
1952
|
-
const held = this.chain;
|
|
1953
|
-
if (held !== null && position !== null && held.seq === position.seq && held.epoch === position.epoch && held.base === base) {
|
|
1954
|
-
return {
|
|
1955
|
-
ok: held
|
|
1956
|
-
};
|
|
1957
|
-
}
|
|
1958
|
-
const fetching = this.fetching;
|
|
1959
|
-
if (position !== null && fetching !== null && fetching.seq === position.seq && fetching.epoch === position.epoch) {
|
|
1960
|
-
return fetching.promise;
|
|
1961
|
-
}
|
|
1962
|
-
const promise = this.fetchChain(position, base);
|
|
1963
|
-
if (position !== null) {
|
|
1964
|
-
const started = {
|
|
1965
|
-
...position,
|
|
1966
|
-
promise
|
|
1967
|
-
};
|
|
1968
|
-
this.fetching = started;
|
|
1969
|
-
// Cleared however it ends. `finally` would hand on a rejection to a
|
|
1970
|
-
// promise nobody holds: an unhandled rejection, which ends a Node
|
|
1971
|
-
// process. The caller is handed `promise` itself, and sees it.
|
|
1972
|
-
const done = () => {
|
|
1973
|
-
if (this.fetching === started) this.fetching = null;
|
|
1974
|
-
};
|
|
1975
|
-
promise.then(done, done);
|
|
1976
|
-
}
|
|
1977
|
-
return promise;
|
|
1978
|
-
}
|
|
1979
|
-
|
|
1980
|
-
/** The chain a read is answered at: the one given, or the newest. */
|
|
1981
|
-
at(chain) {
|
|
1982
|
-
return chain !== undefined ? Promise.resolve({
|
|
1983
|
-
ok: chain
|
|
1984
|
-
}) : this.sync();
|
|
1985
|
-
}
|
|
1986
|
-
async fetchChain(position, base) {
|
|
1987
|
-
counted.chainReads++;
|
|
1988
|
-
const before = await this.ops.projectVersion();
|
|
1989
|
-
const fetched = await this.ops.fetchPatches({
|
|
1990
|
-
excludePatchOps: false
|
|
1991
|
-
});
|
|
1992
|
-
if (fetched.error) {
|
|
1993
|
-
return {
|
|
1994
|
-
error: {
|
|
1995
|
-
message: fetched.error.message,
|
|
1996
|
-
...(fetched.unauthorized ? {
|
|
1997
|
-
unauthorized: true
|
|
1998
|
-
} : {}),
|
|
1999
|
-
...(fetched.networkError ? {
|
|
2000
|
-
networkError: true
|
|
2001
|
-
} : {})
|
|
2002
|
-
}
|
|
2003
|
-
};
|
|
2004
|
-
}
|
|
2005
|
-
const overlay = draftOverlay(fetched.patches, fetched.commits);
|
|
2006
|
-
const byModule = new Map();
|
|
2007
|
-
for (const patch of overlay) {
|
|
2008
|
-
const records = byModule.get(patch.path);
|
|
2009
|
-
if (records === undefined) byModule.set(patch.path, [patch]);else records.push(patch);
|
|
2010
|
-
}
|
|
2011
|
-
const versions = await this.ops.moduleVersions(overlay);
|
|
2012
|
-
const project = fetched.headVersion !== undefined ? {
|
|
2013
|
-
build: before.build,
|
|
2014
|
-
seq: fetched.headVersion
|
|
2015
|
-
} : before;
|
|
2016
|
-
const chain = {
|
|
2017
|
-
seq: fetched.headVersion ?? (position === null || position === void 0 ? void 0 : position.seq) ?? null,
|
|
2018
|
-
epoch: (position === null || position === void 0 ? void 0 : position.epoch) ?? "",
|
|
2019
|
-
base,
|
|
2020
|
-
project,
|
|
2021
|
-
fetched,
|
|
2022
|
-
overlay,
|
|
2023
|
-
byModule,
|
|
2024
|
-
versions,
|
|
2025
|
-
analysis: this.ops.analyzePatches(overlay)
|
|
2026
|
-
};
|
|
2027
|
-
// Never put back an older chain over a newer one read meanwhile. A
|
|
2028
|
-
// counter that started again (another epoch) orders nothing against
|
|
2029
|
-
// the one before it: the chain read last is the newest.
|
|
2030
|
-
if (this.chain === null || this.chain.base !== base || this.chain.epoch !== chain.epoch || this.chain.project.seq <= project.seq) {
|
|
2031
|
-
this.chain = chain;
|
|
2032
|
-
}
|
|
2033
|
-
return {
|
|
2034
|
-
ok: chain
|
|
2035
|
-
};
|
|
2036
|
-
}
|
|
2037
|
-
|
|
2038
|
-
/**
|
|
2039
|
-
* Every module's serialized schema, serialized once per data layer (a new
|
|
2040
|
-
* build is a new one): what the engine reads `.jsonValues()` records from,
|
|
2041
|
-
* and MCP's tools their schemas.
|
|
2042
|
-
*/
|
|
2043
|
-
serializedSchemas() {
|
|
2044
|
-
this.serialized ??= this.ops.getSchemas().then(schemas => {
|
|
2045
|
-
const serialized = {};
|
|
2046
|
-
for (const [path, schema] of Object.entries(schemas)) {
|
|
2047
|
-
try {
|
|
2048
|
-
serialized[path] = schema["executeSerialize"]();
|
|
2049
|
-
} catch {
|
|
2050
|
-
// Reported elsewhere; read as "no schema", as the engine does.
|
|
2051
|
-
serialized[path] = undefined;
|
|
2052
|
-
}
|
|
2053
|
-
}
|
|
2054
|
-
return serialized;
|
|
2055
|
-
});
|
|
2056
|
-
return this.serialized;
|
|
2057
|
-
}
|
|
2058
|
-
|
|
2059
|
-
// #region modules
|
|
2060
|
-
|
|
2061
|
-
/**
|
|
2062
|
-
* A module at the newest chain (or at `chain`, from {@link sync}), or
|
|
2063
|
-
* `null` when there is no such module.
|
|
2064
|
-
*/
|
|
2065
|
-
async module(path, chain) {
|
|
2066
|
-
const synced = await this.at(chain);
|
|
2067
|
-
if ("error" in synced) return synced;
|
|
2068
|
-
return {
|
|
2069
|
-
ok: await this.moduleIn(synced.ok, path)
|
|
2070
|
-
};
|
|
2071
|
-
}
|
|
2072
|
-
async moduleIn(chain, path) {
|
|
2073
|
-
const asked = versionIn(chain, path);
|
|
2074
|
-
if (asked === undefined) return null;
|
|
2075
|
-
const records = chain.byModule.get(path) ?? [];
|
|
2076
|
-
const key = moduleKey(path, asked);
|
|
2077
|
-
const found = await this.store.get(key);
|
|
2078
|
-
if (found !== null) {
|
|
2079
|
-
const facts = this.factsOf(found);
|
|
2080
|
-
return {
|
|
2081
|
-
module: found,
|
|
2082
|
-
asked,
|
|
2083
|
-
failed: facts.failed,
|
|
2084
|
-
applied: facts.applied,
|
|
2085
|
-
records
|
|
2086
|
-
};
|
|
2087
|
-
}
|
|
2088
|
-
const made = await this.make(path, asked, records);
|
|
2089
|
-
this.memory.put(key, made, made.bytes);
|
|
2090
|
-
const facts = this.factsOf(made);
|
|
2091
|
-
return {
|
|
2092
|
-
module: made,
|
|
2093
|
-
asked,
|
|
2094
|
-
failed: facts.failed,
|
|
2095
|
-
applied: facts.applied,
|
|
2096
|
-
records
|
|
2097
|
-
};
|
|
2098
|
-
}
|
|
2099
|
-
|
|
2100
|
-
/**
|
|
2101
|
-
* A module at `asked`, from the newest version held of the same base when
|
|
2102
|
-
* its chain is a start of this one (a keystroke: the new patch alone), and
|
|
2103
|
-
* from its base otherwise (a discard, a publish, an eviction).
|
|
2104
|
-
*/
|
|
2105
|
-
async make(path, asked, records) {
|
|
2106
|
-
var _await$this$ops$baseM;
|
|
2107
|
-
counted.materialized++;
|
|
2108
|
-
const schema = (await this.serializedSchemas())[path];
|
|
2109
|
-
const isRecord = (schema === null || schema === void 0 ? void 0 : schema.type) === "record" && schema.jsonValues === true;
|
|
2110
|
-
let start = null;
|
|
2111
|
-
const latest = this.memory.latest(path);
|
|
2112
|
-
if (latest !== null && latest.version.schema === asked.schema && latest.version.base === asked.base && this.factsOf(latest).failed === null && latest.patches.length <= records.length && latest.patches.every((id, i) => {
|
|
2113
|
-
var _records$i;
|
|
2114
|
-
return ((_records$i = records[i]) === null || _records$i === void 0 ? void 0 : _records$i.patchId) === id;
|
|
2115
|
-
})) {
|
|
2116
|
-
start = latest;
|
|
2117
|
-
counted.extended++;
|
|
2118
|
-
}
|
|
2119
|
-
if (start === null) {
|
|
2120
|
-
start = await this.store.get(moduleKey(path, {
|
|
2121
|
-
...asked,
|
|
2122
|
-
chain: EMPTY_CHAIN
|
|
2123
|
-
}));
|
|
2124
|
-
}
|
|
2125
|
-
if (start === null) {
|
|
2126
|
-
// No base for this version: the module as the build serves it.
|
|
2127
|
-
const base = await this.ops.baseModule(path);
|
|
2128
|
-
start = {
|
|
2129
|
-
path,
|
|
2130
|
-
version: {
|
|
2131
|
-
...asked,
|
|
2132
|
-
chain: EMPTY_CHAIN
|
|
2133
|
-
},
|
|
2134
|
-
content: baseModuleContent((base === null || base === void 0 ? void 0 : base.source) ?? null),
|
|
2135
|
-
patches: [],
|
|
2136
|
-
bytes: 0
|
|
2137
|
-
};
|
|
2138
|
-
}
|
|
2139
|
-
const startFacts = this.factsOf(start);
|
|
2140
|
-
let content = start.content;
|
|
2141
|
-
const ids = [...start.patches];
|
|
2142
|
-
let failed = null;
|
|
2143
|
-
let entryChains = startFacts.entryChains;
|
|
2144
|
-
let wholeChain = startFacts.wholeChain;
|
|
2145
|
-
for (const record of records.slice(start.patches.length)) {
|
|
2146
|
-
const res = applyPatchRecord(content, record, schema);
|
|
2147
|
-
if (res.status === "failed") {
|
|
2148
|
-
failed = {
|
|
2149
|
-
patchId: res.patchId,
|
|
2150
|
-
message: res.message
|
|
2151
|
-
};
|
|
2152
|
-
break;
|
|
2153
|
-
}
|
|
2154
|
-
if (isRecord) {
|
|
2155
|
-
const touched = touchedEntries(content, res.module);
|
|
2156
|
-
if (touched === "all") {
|
|
2157
|
-
wholeChain = extendChain(wholeChain, record.patchId);
|
|
2158
|
-
entryChains = new Map();
|
|
2159
|
-
} else if (touched.length > 0) {
|
|
2160
|
-
const next = new Map(entryChains);
|
|
2161
|
-
for (const key of touched) {
|
|
2162
|
-
next.set(key, extendChain(entryChains.get(key) ?? wholeChain, record.patchId));
|
|
2163
|
-
}
|
|
2164
|
-
entryChains = next;
|
|
2165
|
-
}
|
|
2166
|
-
}
|
|
2167
|
-
content = res.module;
|
|
2168
|
-
ids.push(record.patchId);
|
|
2169
|
-
}
|
|
2170
|
-
const base = start.patches.length === 0 ? start.content.source : ((_await$this$ops$baseM = await this.ops.baseModule(path)) === null || _await$this$ops$baseM === void 0 ? void 0 : _await$this$ops$baseM.source) ?? null;
|
|
2171
|
-
const bytes = heldBeyond(base, content.source) + entriesBytes(content);
|
|
2172
|
-
const version = failed === null ? asked : {
|
|
2173
|
-
...asked,
|
|
2174
|
-
chain: this.ops.chainAt(path, ids.length)
|
|
2175
|
-
};
|
|
2176
|
-
const made = {
|
|
2177
|
-
path,
|
|
2178
|
-
version,
|
|
2179
|
-
content,
|
|
2180
|
-
patches: ids,
|
|
2181
|
-
bytes
|
|
2182
|
-
};
|
|
2183
|
-
this.facts.set(made, {
|
|
2184
|
-
failed,
|
|
2185
|
-
applied: ids.length,
|
|
2186
|
-
entryChains,
|
|
2187
|
-
wholeChain,
|
|
2188
|
-
resolved: new Map(),
|
|
2189
|
-
draft: null
|
|
2190
|
-
});
|
|
2191
|
-
return made;
|
|
2192
|
-
}
|
|
2193
|
-
factsOf(module) {
|
|
2194
|
-
let facts = this.facts.get(module);
|
|
2195
|
-
if (facts === undefined) {
|
|
2196
|
-
facts = {
|
|
2197
|
-
failed: null,
|
|
2198
|
-
applied: module.patches.length,
|
|
2199
|
-
entryChains: new Map(),
|
|
2200
|
-
wholeChain: EMPTY_CHAIN,
|
|
2201
|
-
resolved: new Map(),
|
|
2202
|
-
draft: null
|
|
2203
|
-
};
|
|
2204
|
-
this.facts.set(module, facts);
|
|
2205
|
-
}
|
|
2206
|
-
return facts;
|
|
2207
|
-
}
|
|
2208
|
-
|
|
2209
|
-
// #region entries
|
|
2210
|
-
|
|
2211
|
-
/**
|
|
2212
|
-
* `.jsonValues()` entries at the newest chain (or at `chain`, from
|
|
2213
|
-
* {@link sync}), by key: what the module's chain made of each, and for an
|
|
2214
|
-
* entry it holds edits for but nobody has loaded, those edits on the base
|
|
2215
|
-
* entry. Made once per entry and version.
|
|
2216
|
-
*/
|
|
2217
|
-
async entries(path, keys, chain) {
|
|
2218
|
-
const synced = await this.at(chain);
|
|
2219
|
-
if ("error" in synced) {
|
|
2220
|
-
return {
|
|
2221
|
-
status: "error",
|
|
2222
|
-
message: synced.error.message
|
|
2223
|
-
};
|
|
2224
|
-
}
|
|
2225
|
-
return this.entriesIn(synced.ok, path, keys);
|
|
2226
|
-
}
|
|
2227
|
-
async entriesIn(chain, path, keys) {
|
|
2228
|
-
if (chain.fetched.errors && chain.fetched.errors.length > 0) {
|
|
2229
|
-
return {
|
|
2230
|
-
status: "error",
|
|
2231
|
-
message: `Could not fetch patches: ${JSON.stringify(chain.fetched.errors)}`
|
|
2232
|
-
};
|
|
2233
|
-
}
|
|
2234
|
-
const base = await this.ops.baseModule(path);
|
|
2235
|
-
if (base === null || base.source === null || typeof base.source !== "object" || Array.isArray(base.source)) {
|
|
2236
|
-
return {
|
|
2237
|
-
status: "not-found",
|
|
2238
|
-
message: base === null || base.source === null ? `Module not found: ${path}` : `Module is not a record: ${path}`
|
|
2239
|
-
};
|
|
2240
|
-
}
|
|
2241
|
-
const held = await this.moduleIn(chain, path);
|
|
2242
|
-
if (held === null) {
|
|
2243
|
-
return {
|
|
2244
|
-
status: "not-found",
|
|
2245
|
-
message: `Module not found: ${path}`
|
|
2246
|
-
};
|
|
2247
|
-
}
|
|
2248
|
-
const record = base.source;
|
|
2249
|
-
const facts = this.factsOf(held.module);
|
|
2250
|
-
const value = {
|
|
2251
|
-
entries: [],
|
|
2252
|
-
missing: [],
|
|
2253
|
-
errors: [],
|
|
2254
|
-
total: recordKeysOf(record).length,
|
|
2255
|
-
version: held.module.version,
|
|
2256
|
-
entryVersions: {}
|
|
2257
|
-
};
|
|
2258
|
-
const reads = new Map();
|
|
2259
|
-
await Promise.all(keys.map(async key => {
|
|
2260
|
-
reads.set(key, await this.resolved(path, record, held.module, key));
|
|
2261
|
-
}));
|
|
2262
|
-
for (const key of keys) {
|
|
2263
|
-
const marker = record[key];
|
|
2264
|
-
if (marker !== undefined && !Internal.isJson(marker)) {
|
|
2265
|
-
// Not a jsonValues entry: the value inlined in the module, as is.
|
|
2266
|
-
value.entries.push({
|
|
2267
|
-
key,
|
|
2268
|
-
content: marker
|
|
2269
|
-
});
|
|
2270
|
-
continue;
|
|
2271
|
-
}
|
|
2272
|
-
const read = reads.get(key);
|
|
2273
|
-
if (read === undefined || read.kind === "missing") {
|
|
2274
|
-
value.missing.push(key);
|
|
2275
|
-
} else if (read.kind === "error") {
|
|
2276
|
-
value.errors.push({
|
|
2277
|
-
key,
|
|
2278
|
-
message: read.message
|
|
2279
|
-
});
|
|
2280
|
-
} else {
|
|
2281
|
-
value.entries.push({
|
|
2282
|
-
key,
|
|
2283
|
-
content: read.content
|
|
2284
|
-
});
|
|
2285
|
-
value.entryVersions[key] = {
|
|
2286
|
-
...held.module.version,
|
|
2287
|
-
key,
|
|
2288
|
-
chain: facts.entryChains.get(key) ?? facts.wholeChain
|
|
2289
|
-
};
|
|
2290
|
-
}
|
|
2291
|
-
}
|
|
2292
|
-
return {
|
|
2293
|
-
status: "success",
|
|
2294
|
-
value
|
|
2295
|
-
};
|
|
2296
|
-
}
|
|
2297
|
-
|
|
2298
|
-
/**
|
|
2299
|
-
* An entry on `module`, resolved once and kept on it -- unless it could
|
|
2300
|
-
* not be read (`transient`): that is tried again on the next read rather
|
|
2301
|
-
* than kept for the version's life.
|
|
2302
|
-
*/
|
|
2303
|
-
async resolved(path, baseRecord, module, key) {
|
|
2304
|
-
const facts = this.factsOf(module);
|
|
2305
|
-
const kept = facts.resolved.get(key);
|
|
2306
|
-
if (kept !== undefined) return kept;
|
|
2307
|
-
const read = await this.resolve(path, baseRecord, module, key);
|
|
2308
|
-
if (!(read.kind === "error" && read.transient === true)) {
|
|
2309
|
-
facts.resolved.set(key, read);
|
|
2310
|
-
}
|
|
2311
|
-
return read;
|
|
2312
|
-
}
|
|
2313
|
-
async resolve(path, baseRecord, module, key) {
|
|
2314
|
-
counted.entriesResolved++;
|
|
2315
|
-
const state = entryState(module.content, key);
|
|
2316
|
-
let from = {
|
|
2317
|
-
content: undefined
|
|
2318
|
-
};
|
|
2319
|
-
if ((state === null || state === void 0 ? void 0 : state.kind) === "waiting") {
|
|
2320
|
-
from = await this.ops.baseJsonEntry(path, baseRecord, state.from);
|
|
2321
|
-
if ("message" in from) {
|
|
2322
|
-
return {
|
|
2323
|
-
kind: "error",
|
|
2324
|
-
message: from.message,
|
|
2325
|
-
transient: true
|
|
2326
|
-
};
|
|
2327
|
-
}
|
|
2328
|
-
}
|
|
2329
|
-
const copiedBefore = engineWork().cloneBytes;
|
|
2330
|
-
const read = resolveEntry(key, state, () => "content" in from ? from.content : undefined);
|
|
2331
|
-
if (read.kind === "content" && (state === null || state === void 0 ? void 0 : state.kind) === "waiting" && state.ops) {
|
|
2332
|
-
// Held edits made a new entry: the head holds it now.
|
|
2333
|
-
this.memory.charge(moduleKey(path, module.version), engineWork().cloneBytes - copiedBefore);
|
|
2334
|
-
}
|
|
2335
|
-
return read;
|
|
2336
|
-
}
|
|
2337
|
-
|
|
2338
|
-
// #region drafts
|
|
2339
|
-
|
|
2340
|
-
/**
|
|
2341
|
-
* A module as a draft reader is given it ({@link Draft}): `bundle` when the
|
|
2342
|
-
* newest version is the bundle's own -- the reader's bundle answers, and
|
|
2343
|
-
* nothing is read -- and otherwise the head's, made once per version.
|
|
2344
|
-
*/
|
|
2345
|
-
async draft(path, chain) {
|
|
2346
|
-
const synced = await this.at(chain);
|
|
2347
|
-
if ("error" in synced) return synced;
|
|
2348
|
-
const asked = versionIn(synced.ok, path);
|
|
2349
|
-
if (asked === undefined) return {
|
|
2350
|
-
ok: null
|
|
2351
|
-
};
|
|
2352
|
-
const bundle = await this.ops.bundleModule(path);
|
|
2353
|
-
if (bundle !== null && asked.chain === EMPTY_CHAIN && bundle.version.schema === asked.schema && bundle.version.base === asked.base) {
|
|
2354
|
-
return {
|
|
2355
|
-
ok: {
|
|
2356
|
-
kind: "bundle",
|
|
2357
|
-
version: asked
|
|
2358
|
-
}
|
|
2359
|
-
};
|
|
2360
|
-
}
|
|
2361
|
-
const held = await this.moduleIn(synced.ok, path);
|
|
2362
|
-
if (held === null) return {
|
|
2363
|
-
ok: null
|
|
2364
|
-
};
|
|
2365
|
-
const facts = this.factsOf(held.module);
|
|
2366
|
-
if (facts.draft !== null) return {
|
|
2367
|
-
ok: facts.draft
|
|
2368
|
-
};
|
|
2369
|
-
const made = await this.makeDraft(synced.ok, path, held);
|
|
2370
|
-
// Kept for the version, unless its entries could not be read: the next
|
|
2371
|
-
// read tries them again rather than serving markers for the version's
|
|
2372
|
-
// life.
|
|
2373
|
-
if (made.kind !== "draft" || !made.entriesFailed) facts.draft = made;
|
|
2374
|
-
return {
|
|
2375
|
-
ok: made
|
|
2376
|
-
};
|
|
2377
|
-
}
|
|
2378
|
-
|
|
2379
|
-
/**
|
|
2380
|
-
* The draft of `held`, its entries read at `chain` -- the chain `held` was
|
|
2381
|
-
* made at, so the entries are the same version's even when the chain has
|
|
2382
|
-
* moved since.
|
|
2383
|
-
*/
|
|
2384
|
-
async makeDraft(chain, path, held) {
|
|
2385
|
-
const source = held.module.content.source;
|
|
2386
|
-
const version = held.module.version;
|
|
2387
|
-
if (!isRecordOfMarkers(source)) {
|
|
2388
|
-
return {
|
|
2389
|
-
kind: "draft",
|
|
2390
|
-
version,
|
|
2391
|
-
source,
|
|
2392
|
-
changed: held.records.length > 0,
|
|
2393
|
-
entriesFailed: false
|
|
2394
|
-
};
|
|
2395
|
-
}
|
|
2396
|
-
// The entries a draft changes: the ones the chain touched, and the ones
|
|
2397
|
-
// a publish wrote that the bundle has not got (a marker with a
|
|
2398
|
-
// `patch_id`). Every other one is the bundle's, behind its marker.
|
|
2399
|
-
const wire = {};
|
|
2400
|
-
const fill = [];
|
|
2401
|
-
const touched = held.module.content.entries;
|
|
2402
|
-
let fromServer = false;
|
|
2403
|
-
for (const [key, value] of Object.entries(source)) {
|
|
2404
|
-
if (Internal.isJson(value)) {
|
|
2405
|
-
wire[key] = transportMarker(value);
|
|
2406
|
-
const published = Internal.isJsonFromServer(value);
|
|
2407
|
-
fromServer ||= published;
|
|
2408
|
-
if (published || touched.has(key)) fill.push(key);
|
|
2409
|
-
} else {
|
|
2410
|
-
wire[key] = value;
|
|
2411
|
-
}
|
|
2412
|
-
}
|
|
2413
|
-
let entriesFailed = false;
|
|
2414
|
-
if (fill.length > 0) {
|
|
2415
|
-
const read = await this.entriesIn(chain, path, fill);
|
|
2416
|
-
if (read.status !== "success" || read.value.errors.length > 0 || read.value.missing.length > 0) {
|
|
2417
|
-
entriesFailed = true;
|
|
2418
|
-
} else {
|
|
2419
|
-
for (const {
|
|
2420
|
-
key,
|
|
2421
|
-
content
|
|
2422
|
-
} of read.value.entries) {
|
|
2423
|
-
wire[key] = content;
|
|
2424
|
-
}
|
|
2425
|
-
}
|
|
2426
|
-
}
|
|
2427
|
-
return {
|
|
2428
|
-
kind: "draft",
|
|
2429
|
-
version,
|
|
2430
|
-
source: entriesFailed ? stripped(source) : wire,
|
|
2431
|
-
changed: held.records.length > 0 || fromServer,
|
|
2432
|
-
entriesFailed
|
|
2433
|
-
};
|
|
2434
|
-
}
|
|
2435
|
-
|
|
2436
|
-
/**
|
|
2437
|
-
* The modules a draft changes: a patch in their chain, or an entry a
|
|
2438
|
-
* publish wrote that the bundle has not got. What `fetchValDraft` sends.
|
|
2439
|
-
*/
|
|
2440
|
-
async changed(at) {
|
|
2441
|
-
var _made;
|
|
2442
|
-
const synced = await this.at(at);
|
|
2443
|
-
if ("error" in synced) return synced;
|
|
2444
|
-
const chain = synced.ok;
|
|
2445
|
-
let made = this.changedIn;
|
|
2446
|
-
if (((_made = made) === null || _made === void 0 ? void 0 : _made.chain) !== chain) {
|
|
2447
|
-
made = {
|
|
2448
|
-
chain,
|
|
2449
|
-
paths: this.changedOf(chain)
|
|
2450
|
-
};
|
|
2451
|
-
this.changedIn = made;
|
|
2452
|
-
}
|
|
2453
|
-
return {
|
|
2454
|
-
ok: [...(await made.paths)]
|
|
2455
|
-
};
|
|
2456
|
-
}
|
|
2457
|
-
|
|
2458
|
-
/** {@link changed}, made once per chain: it looks at every record's markers. */
|
|
2459
|
-
changedIn = null;
|
|
2460
|
-
async changedOf(chain) {
|
|
2461
|
-
const changed = new Set(chain.byModule.keys());
|
|
2462
|
-
for (const path of Object.keys(chain.versions)) {
|
|
2463
|
-
if (changed.has(path)) continue;
|
|
2464
|
-
const base = await this.ops.baseModule(path);
|
|
2465
|
-
if (base !== null && hasMarkersFromServer(base.source)) changed.add(path);
|
|
2466
|
-
}
|
|
2467
|
-
return [...changed];
|
|
2468
|
-
}
|
|
2469
|
-
|
|
2470
|
-
// #region the whole tree
|
|
2471
|
-
|
|
2472
|
-
/**
|
|
2473
|
-
* Every module at the newest chain: the patched ones made (once per
|
|
2474
|
-
* version), the rest the base's own objects. What `PUT /sources/~` and
|
|
2475
|
-
* MCP read; made once per chain.
|
|
2476
|
-
*/
|
|
2477
|
-
async tree() {
|
|
2478
|
-
var _this$wholeTree;
|
|
2479
|
-
const synced = await this.sync();
|
|
2480
|
-
if ("error" in synced) return synced;
|
|
2481
|
-
const chain = synced.ok;
|
|
2482
|
-
if (((_this$wholeTree = this.wholeTree) === null || _this$wholeTree === void 0 ? void 0 : _this$wholeTree.chain) !== chain) {
|
|
2483
|
-
this.wholeTree = {
|
|
2484
|
-
chain,
|
|
2485
|
-
promise: this.makeTree(chain)
|
|
2486
|
-
};
|
|
2487
|
-
}
|
|
2488
|
-
return this.wholeTree.promise;
|
|
2489
|
-
}
|
|
2490
|
-
async makeTree(chain) {
|
|
2491
|
-
const base = await this.ops.getBaseSources();
|
|
2492
|
-
const sources = {
|
|
2493
|
-
...base
|
|
2494
|
-
};
|
|
2495
|
-
const errors = {};
|
|
2496
|
-
const stopped = {};
|
|
2497
|
-
const versions = {
|
|
2498
|
-
...chain.versions
|
|
2499
|
-
};
|
|
2500
|
-
for (const patch of chain.overlay) {
|
|
2501
|
-
if (base[patch.path] === undefined && errors[patch.path] === undefined) {
|
|
2502
|
-
errors[patch.path] = [];
|
|
2503
|
-
}
|
|
2504
|
-
}
|
|
2505
|
-
for (const [path, records] of chain.byModule) {
|
|
2506
|
-
if (base[path] === undefined) {
|
|
2507
|
-
Internal.log.error("Module not found", path);
|
|
2508
|
-
errors[path] = records.map(record => ({
|
|
2509
|
-
patchId: record.patchId,
|
|
2510
|
-
skipped: true,
|
|
2511
|
-
error: {
|
|
2512
|
-
message: "Module not found"
|
|
2513
|
-
}
|
|
2514
|
-
}));
|
|
2515
|
-
continue;
|
|
2516
|
-
}
|
|
2517
|
-
const held = await this.moduleIn(chain, path);
|
|
2518
|
-
if (held === null) continue;
|
|
2519
|
-
sources[path] = held.module.content.source;
|
|
2520
|
-
versions[path] = held.module.version;
|
|
2521
|
-
if (held.failed !== null) {
|
|
2522
|
-
Internal.log.error("Could not apply patch", {
|
|
2523
|
-
path,
|
|
2524
|
-
patchId: held.failed.patchId,
|
|
2525
|
-
error: held.failed.message
|
|
2526
|
-
});
|
|
2527
|
-
stopped[path] = held.applied;
|
|
2528
|
-
errors[path] = [{
|
|
2529
|
-
patchId: held.failed.patchId,
|
|
2530
|
-
skipped: false,
|
|
2531
|
-
error: {
|
|
2532
|
-
message: held.failed.message
|
|
2533
|
-
}
|
|
2534
|
-
}, ...records.slice(held.applied + 1).map(record => ({
|
|
2535
|
-
patchId: record.patchId,
|
|
2536
|
-
skipped: true,
|
|
2537
|
-
error: {
|
|
2538
|
-
message: "Cannot apply patch: previous errors exists"
|
|
2539
|
-
}
|
|
2540
|
-
}))];
|
|
2541
|
-
}
|
|
2542
|
-
}
|
|
2543
|
-
for (const [path, list] of Object.entries(errors)) {
|
|
2544
|
-
if (list.length === 0) delete errors[path];
|
|
2545
|
-
}
|
|
2546
|
-
return {
|
|
2547
|
-
ok: {
|
|
2548
|
-
chain,
|
|
2549
|
-
sources,
|
|
2550
|
-
errors,
|
|
2551
|
-
stopped,
|
|
2552
|
-
versions
|
|
2553
|
-
}
|
|
2554
|
-
};
|
|
2555
|
-
}
|
|
2556
|
-
|
|
2557
|
-
// #region the module endpoint
|
|
2558
|
-
|
|
2559
|
-
/**
|
|
2560
|
-
* `GET /modules`: one module at a version. `v` the version wanted (by
|
|
2561
|
-
* default the newest); `have` the version the caller holds, from which the
|
|
2562
|
-
* answer is a delta -- the patches from it -- when the caller's chain is a
|
|
2563
|
-
* start of this one under the same schema and base.
|
|
2564
|
-
*/
|
|
2565
|
-
async answer(path, opts) {
|
|
2566
|
-
const synced = await this.sync();
|
|
2567
|
-
if ("error" in synced) return synced;
|
|
2568
|
-
const chain = synced.ok;
|
|
2569
|
-
const current = await this.moduleIn(chain, path);
|
|
2570
|
-
if (current === null) return {
|
|
2571
|
-
ok: null
|
|
2572
|
-
};
|
|
2573
|
-
let target = current.module;
|
|
2574
|
-
let isCurrent = true;
|
|
2575
|
-
if (opts.v !== undefined) {
|
|
2576
|
-
const wanted = parseModuleKey(opts.v);
|
|
2577
|
-
if (wanted === null || wanted.path !== path) {
|
|
2578
|
-
return {
|
|
2579
|
-
ok: {
|
|
2580
|
-
kind: "not-held",
|
|
2581
|
-
current: current.module.version
|
|
2582
|
-
}
|
|
2583
|
-
};
|
|
2584
|
-
}
|
|
2585
|
-
const currentKeys = [moduleKey(path, current.module.version), moduleKey(path, current.asked)];
|
|
2586
|
-
if (!currentKeys.includes(opts.v)) {
|
|
2587
|
-
const held = await this.store.get(opts.v);
|
|
2588
|
-
if (held === null) {
|
|
2589
|
-
return {
|
|
2590
|
-
ok: {
|
|
2591
|
-
kind: "not-held",
|
|
2592
|
-
current: current.module.version
|
|
2593
|
-
}
|
|
2594
|
-
};
|
|
2595
|
-
}
|
|
2596
|
-
target = held;
|
|
2597
|
-
isCurrent = false;
|
|
2598
|
-
}
|
|
2599
|
-
}
|
|
2600
|
-
const have = opts.have !== undefined ? parseModuleKey(opts.have) : null;
|
|
2601
|
-
if (isCurrent && have !== null && have.path === path && have.version.schema === target.version.schema && have.version.base === target.version.base) {
|
|
2602
|
-
const facts = this.factsOf(target);
|
|
2603
|
-
for (let n = facts.applied; n >= 0; n--) {
|
|
2604
|
-
if (this.ops.chainAt(path, n) === have.version.chain) {
|
|
2605
|
-
return {
|
|
2606
|
-
ok: {
|
|
2607
|
-
kind: "delta",
|
|
2608
|
-
from: have.version,
|
|
2609
|
-
to: target.version,
|
|
2610
|
-
patches: current.records.slice(n, facts.applied).map(({
|
|
2611
|
-
patchId,
|
|
2612
|
-
patch
|
|
2613
|
-
}) => ({
|
|
2614
|
-
patchId,
|
|
2615
|
-
patch
|
|
2616
|
-
}))
|
|
2617
|
-
}
|
|
2618
|
-
};
|
|
2619
|
-
}
|
|
2620
|
-
}
|
|
2621
|
-
}
|
|
2622
|
-
const facts = this.factsOf(target);
|
|
2623
|
-
const source = target.content.source;
|
|
2624
|
-
const entries = {};
|
|
2625
|
-
if (isRecordOfMarkers(source)) {
|
|
2626
|
-
const baseModule = await this.ops.baseModule(path);
|
|
2627
|
-
const baseRecord = baseModule !== null && typeof baseModule.source === "object" && baseModule.source !== null && !Array.isArray(baseModule.source) ? baseModule.source : {};
|
|
2628
|
-
for (const key of target.content.entries.keys()) {
|
|
2629
|
-
const read = await this.resolved(path, baseRecord, target, key);
|
|
2630
|
-
const version = {
|
|
2631
|
-
...target.version,
|
|
2632
|
-
key,
|
|
2633
|
-
chain: facts.entryChains.get(key) ?? facts.wholeChain
|
|
2634
|
-
};
|
|
2635
|
-
entries[key] = read.kind === "content" ? {
|
|
2636
|
-
content: read.content,
|
|
2637
|
-
version
|
|
2638
|
-
} : read.kind === "missing" ? {
|
|
2639
|
-
deleted: true,
|
|
2640
|
-
version
|
|
2641
|
-
} : {
|
|
2642
|
-
error: read.message,
|
|
2643
|
-
...(read.patchId !== undefined ? {
|
|
2644
|
-
patchId: read.patchId
|
|
2645
|
-
} : {}),
|
|
2646
|
-
version
|
|
2647
|
-
};
|
|
2648
|
-
}
|
|
2649
|
-
}
|
|
2650
|
-
return {
|
|
2651
|
-
ok: {
|
|
2652
|
-
kind: "module",
|
|
2653
|
-
version: target.version,
|
|
2654
|
-
source: isRecordOfMarkers(source) ? stripped(source) : source,
|
|
2655
|
-
entries,
|
|
2656
|
-
patches: [...target.patches],
|
|
2657
|
-
...(facts.failed !== null ? {
|
|
2658
|
-
failed: facts.failed
|
|
2659
|
-
} : {})
|
|
2660
|
-
}
|
|
2661
|
-
};
|
|
2662
|
-
}
|
|
2663
|
-
}
|
|
2664
|
-
|
|
2665
|
-
/** What {@link ValHead.entries} answers. */
|
|
2666
|
-
|
|
2667
|
-
/**
|
|
2668
|
-
* A module's version at `chain`. `versions` is keyed by module path, and a
|
|
2669
|
-
* path comes from a request: `~constructor` is not a module.
|
|
2670
|
-
*/
|
|
2671
|
-
function versionIn(chain, path) {
|
|
2672
|
-
return Object.hasOwn(chain.versions, path) ? chain.versions[path] : undefined;
|
|
2673
|
-
}
|
|
2674
|
-
|
|
2675
|
-
/**
|
|
2676
|
-
* Whether an answer of {@link ValHead.answer} is the same for good, so an
|
|
2677
|
-
* answer for an asked version may be cached as immutable: not when an
|
|
2678
|
-
* entry's content could not be READ (it carries no `patchId`; its base's
|
|
2679
|
-
* `import()` failed, and the next read may succeed). An entry a patch could
|
|
2680
|
-
* not be applied to names that patch, and is the version's for good.
|
|
2681
|
-
*/
|
|
2682
|
-
function isLastingAnswer(answer) {
|
|
2683
|
-
if (answer.kind !== "module") return true;
|
|
2684
|
-
return Object.values(answer.entries).every(entry => !("error" in entry) || entry.patchId !== undefined);
|
|
2685
|
-
}
|
|
2686
|
-
|
|
2687
|
-
/** What {@link ValHead.tree} answers. */
|
|
2688
|
-
|
|
2689
|
-
/** What `GET /modules` answers: see `ModuleAnswer` in the plan. */
|
|
2690
|
-
|
|
2691
|
-
/**
|
|
2692
|
-
* The entries a patch touched: the ones whose state it replaced, or `all`
|
|
2693
|
-
* when it replaced the record (every entry went, or the map was reset).
|
|
2694
|
-
*/
|
|
2695
|
-
function touchedEntries(before, after) {
|
|
2696
|
-
if (after.entries === before.entries) return [];
|
|
2697
|
-
if (after.entries.size < before.entries.size) return "all";
|
|
2698
|
-
const touched = [];
|
|
2699
|
-
for (const [key, state] of after.entries) {
|
|
2700
|
-
if (before.entries.get(key) !== state) touched.push(key);
|
|
2701
|
-
}
|
|
2702
|
-
return touched;
|
|
2703
|
-
}
|
|
2704
|
-
|
|
2705
|
-
/**
|
|
2706
|
-
* What `next` holds that `base` does not: every container copy-on-write made
|
|
2707
|
-
* (8 bytes a slot, as the engine counts them) and every string a patch
|
|
2708
|
-
* brought, walking only where the two differ -- a subtree the patches did not
|
|
2709
|
-
* touch is the base's own object, which the build holds anyway. A child that
|
|
2710
|
-
* is one of the base container's own children (moved, or shifted by an
|
|
2711
|
-
* insert) costs nothing. What the head's byte budget is measured in.
|
|
2712
|
-
*/
|
|
2713
|
-
function heldBeyond(base, next) {
|
|
2714
|
-
if (base === next) return 0;
|
|
2715
|
-
if (typeof next === "string") return next.length;
|
|
2716
|
-
if (typeof next !== "object" || next === null) return 8;
|
|
2717
|
-
const shared = new Set(typeof base === "object" && base !== null ? Object.values(base) : []);
|
|
2718
|
-
let bytes = 0;
|
|
2719
|
-
if (Array.isArray(next)) {
|
|
2720
|
-
bytes += 8 * next.length;
|
|
2721
|
-
for (const [index, child] of next.entries()) {
|
|
2722
|
-
if (shared.has(child)) continue;
|
|
2723
|
-
bytes += heldBeyond(Array.isArray(base) ? base[index] : undefined, child);
|
|
2724
|
-
}
|
|
2725
|
-
return bytes;
|
|
2726
|
-
}
|
|
2727
|
-
const record = base;
|
|
2728
|
-
for (const [key, child] of Object.entries(next)) {
|
|
2729
|
-
bytes += 8;
|
|
2730
|
-
if (shared.has(child)) continue;
|
|
2731
|
-
bytes += heldBeyond(typeof record === "object" && record !== null && !Array.isArray(record) ? record[key] : undefined, child);
|
|
2732
|
-
}
|
|
2733
|
-
return bytes;
|
|
2734
|
-
}
|
|
2735
|
-
|
|
2736
|
-
/** What the entries a chain wrote hold: their content, which patches brought. */
|
|
2737
|
-
function entriesBytes(content) {
|
|
2738
|
-
let bytes = 8 * content.entries.size;
|
|
2739
|
-
for (const state of content.entries.values()) {
|
|
2740
|
-
if (state.kind === "content") bytes += heldBeyond(undefined, state.content);
|
|
2741
|
-
}
|
|
2742
|
-
return bytes;
|
|
2743
|
-
}
|
|
2744
|
-
function isRecordOfMarkers(source) {
|
|
2745
|
-
return typeof source === "object" && source !== null && !Array.isArray(source) && Object.values(source).some(value => Internal.isJson(value));
|
|
2746
|
-
}
|
|
2747
|
-
function hasMarkersFromServer(source) {
|
|
2748
|
-
return isRecordOfMarkers(source) && Object.values(source).some(value => Internal.isJsonFromServer(value));
|
|
2749
|
-
}
|
|
2750
|
-
|
|
2751
|
-
/** A marker as it travels: without the `import()` only this process can run. */
|
|
2752
|
-
function transportMarker(marker) {
|
|
2753
|
-
if (typeof marker !== "object" || marker === null || Array.isArray(marker)) {
|
|
2754
|
-
return marker;
|
|
2755
|
-
}
|
|
2756
|
-
const copy = {};
|
|
2757
|
-
for (const [key, value] of Object.entries(marker)) {
|
|
2758
|
-
if (typeof value !== "function") copy[key] = value;
|
|
2759
|
-
}
|
|
2760
|
-
return copy;
|
|
2761
|
-
}
|
|
2762
|
-
|
|
2763
|
-
/** A record of markers, as it travels. */
|
|
2764
|
-
function stripped(source) {
|
|
2765
|
-
const wire = {};
|
|
2766
|
-
for (const [key, value] of Object.entries(source)) {
|
|
2767
|
-
wire[key] = Internal.isJson(value) ? transportMarker(value) : value;
|
|
2768
|
-
}
|
|
2769
|
-
return wire;
|
|
2770
|
-
}
|
|
2771
|
-
|
|
2772
1487
|
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
2773
1488
|
const jsonOps = new JSONOps();
|
|
2774
1489
|
/**
|
|
@@ -6403,7 +5118,7 @@ var packageJson = {
|
|
|
6403
5118
|
],
|
|
6404
5119
|
exports: true
|
|
6405
5120
|
},
|
|
6406
|
-
version: "0.154.
|
|
5121
|
+
version: "0.154.2",
|
|
6407
5122
|
scripts: {
|
|
6408
5123
|
typecheck: "tsc --noEmit",
|
|
6409
5124
|
test: "jest",
|
|
@@ -7960,10 +6675,26 @@ const ValServer = (valModules, options, callbacks, platform) => {
|
|
|
7960
6675
|
changedAt: codeMode.changedAt
|
|
7961
6676
|
}
|
|
7962
6677
|
}
|
|
7963
|
-
};
|
|
6678
|
+
};
|
|
6679
|
+
}
|
|
6680
|
+
const saved = await saveBeforeCodeOutcome(cookies, "Saved before the code was changed");
|
|
6681
|
+
if ("saved" in saved) {
|
|
6682
|
+
const savedFirst = saved.saved;
|
|
6683
|
+
const staged = await proxyProposalsApi(path, "POST", profileId, JSON.stringify(body ?? {}));
|
|
6684
|
+
/*
|
|
6685
|
+
* `savedFirst` goes with content's answer: the tab that staged holds
|
|
6686
|
+
* the proposal's files (`projectSnapshot.ts` in `@valbuild/ui`), and a
|
|
6687
|
+
* save made here wrote `.val.ts` files it did not write itself.
|
|
6688
|
+
*/
|
|
6689
|
+
return staged.status === 200 && isJsonObject(staged.json) ? {
|
|
6690
|
+
status: 200,
|
|
6691
|
+
json: {
|
|
6692
|
+
...staged.json,
|
|
6693
|
+
savedFirst
|
|
6694
|
+
}
|
|
6695
|
+
} : staged;
|
|
7964
6696
|
}
|
|
7965
|
-
|
|
7966
|
-
return saved === null ? null : {
|
|
6697
|
+
return {
|
|
7967
6698
|
status: saved.status,
|
|
7968
6699
|
json: {
|
|
7969
6700
|
message: `The code was not changed, because the changes waiting to be saved could not be saved first: ${saved.message}`,
|
|
@@ -7979,6 +6710,17 @@ const ValServer = (valModules, options, callbacks, platform) => {
|
|
|
7979
6710
|
* `null` when there was nothing to save or it was saved, otherwise why not.
|
|
7980
6711
|
*/
|
|
7981
6712
|
const saveBeforeCode = async (cookies, message) => {
|
|
6713
|
+
const outcome = await saveBeforeCodeOutcome(cookies, message);
|
|
6714
|
+
return "saved" in outcome ? null : outcome;
|
|
6715
|
+
};
|
|
6716
|
+
|
|
6717
|
+
/**
|
|
6718
|
+
* {@link saveBeforeCode}, saying whether anything was saved: `saved: false`
|
|
6719
|
+
* when nothing was pending. What a staging's answer tells the tab
|
|
6720
|
+
* (`savedFirst`), which holds the proposal's files and has to know whether
|
|
6721
|
+
* a save changed a `.val.ts` under them.
|
|
6722
|
+
*/
|
|
6723
|
+
const saveBeforeCodeOutcome = async (cookies, message) => {
|
|
7982
6724
|
const chain = await serverOps.fetchPatches({
|
|
7983
6725
|
excludePatchOps: true
|
|
7984
6726
|
});
|
|
@@ -7989,12 +6731,16 @@ const ValServer = (valModules, options, callbacks, platform) => {
|
|
|
7989
6731
|
};
|
|
7990
6732
|
}
|
|
7991
6733
|
const pending = chain.patches.filter(patch => patch.appliedAt === null).map(patch => patch.patchId);
|
|
7992
|
-
if (pending.length === 0) return
|
|
6734
|
+
if (pending.length === 0) return {
|
|
6735
|
+
saved: false
|
|
6736
|
+
};
|
|
7993
6737
|
const saved = await saveChanges(cookies, {
|
|
7994
6738
|
patchIds: pending,
|
|
7995
6739
|
message
|
|
7996
6740
|
});
|
|
7997
|
-
if (saved.status === 200) return
|
|
6741
|
+
if (saved.status === 200) return {
|
|
6742
|
+
saved: true
|
|
6743
|
+
};
|
|
7998
6744
|
const said = "message" in saved.json && typeof saved.json.message === "string" ? saved.json.message : `the save answered ${saved.status}`;
|
|
7999
6745
|
/*
|
|
8000
6746
|
* Why, in the words of each module that could not be saved: "Failed to
|
|
@@ -11900,6 +10646,9 @@ function sourceFilePatchErrorsOf(json) {
|
|
|
11900
10646
|
}
|
|
11901
10647
|
return messages;
|
|
11902
10648
|
}
|
|
10649
|
+
function isJsonObject(value) {
|
|
10650
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10651
|
+
}
|
|
11903
10652
|
|
|
11904
10653
|
async function uploadRemoteFile(contentHost, project, bucket, fileHash, fileExt, fileBuffer, auth) {
|
|
11905
10654
|
const authHeader = "apiKey" in auth ? {
|
|
@@ -12074,34 +10823,6 @@ function createMemorySketchpadStore(now = () => new Date()) {
|
|
|
12074
10823
|
};
|
|
12075
10824
|
}
|
|
12076
10825
|
|
|
12077
|
-
/**
|
|
12078
|
-
* One stored patch. Everything the ordered chain needs and nothing else.
|
|
12079
|
-
*/
|
|
12080
|
-
|
|
12081
|
-
/**
|
|
12082
|
-
* One pending binary file: an upload that has not been published yet.
|
|
12083
|
-
*
|
|
12084
|
-
* Keyed by the patch that carries it, exactly as `fs` mode keys the directory
|
|
12085
|
-
* it writes to. The patch's own `file` op holds a hash, not the bytes, so these
|
|
12086
|
-
* arrive on their own request and are joined up by `(patchId, filePath)`.
|
|
12087
|
-
*/
|
|
12088
|
-
|
|
12089
|
-
/**
|
|
12090
|
-
* Where pending patches live.
|
|
12091
|
-
*
|
|
12092
|
-
* The point of the interface: `ValOpsMemory` is not tied to memory. The default
|
|
12093
|
-
* implementation below is explicitly NOT durable -- it dies with the process,
|
|
12094
|
-
* or in a Worker with the isolate -- and a durable one (a Durable Object, whose
|
|
12095
|
-
* single-threaded execution is the lock Val's fs store builds out of a file)
|
|
12096
|
-
* is a swap rather than a rewrite.
|
|
12097
|
-
*
|
|
12098
|
-
* ORDER IS THE CONTRACT. `list()` returns patch ids in the order they were
|
|
12099
|
-
* written, and that order is the chain: entry i's parent is entry i-1. This is
|
|
12100
|
-
* the same decision `ValOpsFS` makes with `patches.log` -- the server decides
|
|
12101
|
-
* where a patch goes, and it goes last -- and it exists for the same reason: an
|
|
12102
|
-
* order held in the patches themselves lets a client working from a stale view
|
|
12103
|
-
* strand every patch behind a parent that never landed.
|
|
12104
|
-
*/
|
|
12105
10826
|
/**
|
|
12106
10827
|
* Memory mode's `seq` (`ProjectVersion` in `@valbuild/shared/internal`), per
|
|
12107
10828
|
* patch store: bumped beside `announceChange` by every write and delete, and
|
|
@@ -12128,69 +10849,6 @@ function seqOf(store) {
|
|
|
12128
10849
|
}
|
|
12129
10850
|
return counter;
|
|
12130
10851
|
}
|
|
12131
|
-
/** The default store. Not durable, deliberately and visibly. */
|
|
12132
|
-
class InMemoryPatchStore {
|
|
12133
|
-
order = [];
|
|
12134
|
-
byId = new Map();
|
|
12135
|
-
async list() {
|
|
12136
|
-
return [...this.order];
|
|
12137
|
-
}
|
|
12138
|
-
async get(patchId) {
|
|
12139
|
-
return this.byId.get(patchId) ?? null;
|
|
12140
|
-
}
|
|
12141
|
-
async append(patch) {
|
|
12142
|
-
if (!this.byId.has(patch.patchId)) {
|
|
12143
|
-
this.order.push(patch.patchId);
|
|
12144
|
-
}
|
|
12145
|
-
this.byId.set(patch.patchId, patch);
|
|
12146
|
-
}
|
|
12147
|
-
async delete(patchIds) {
|
|
12148
|
-
for (const patchId of patchIds) {
|
|
12149
|
-
const at = this.order.indexOf(patchId);
|
|
12150
|
-
if (at !== -1) {
|
|
12151
|
-
this.order.splice(at, 1);
|
|
12152
|
-
}
|
|
12153
|
-
this.byId.delete(patchId);
|
|
12154
|
-
// The bytes go with the patch. They are only reachable through it, so
|
|
12155
|
-
// keeping them would be a leak with no reader -- and these are images.
|
|
12156
|
-
for (const key of this.files.keys()) {
|
|
12157
|
-
if (key.startsWith(`${patchId}\u0000`)) {
|
|
12158
|
-
this.files.delete(key);
|
|
12159
|
-
}
|
|
12160
|
-
}
|
|
12161
|
-
}
|
|
12162
|
-
}
|
|
12163
|
-
|
|
12164
|
-
/*
|
|
12165
|
-
* `\u0000` cannot occur in a patch id or a path, so the two halves of the key
|
|
12166
|
-
* can never run together into a different pair.
|
|
12167
|
-
*
|
|
12168
|
-
* The PATH is normalised for the same reason `sourceFiles` is, and it is not
|
|
12169
|
-
* cosmetic: an upload arrives as `/public/val/x.png`, and the publish step
|
|
12170
|
-
* looks the same file up as `public/val/x.png` because that is what
|
|
12171
|
-
* `splitRemoteRef` yields from a remote ref. `ValOpsFS` never noticed --
|
|
12172
|
-
* `path.join` collapses the difference -- so this is another thing a
|
|
12173
|
-
* filesystem was doing for free. Without it a remote image uploads fine,
|
|
12174
|
-
* patches fine, and fails at publish with "No bytes held", naming a ref whose
|
|
12175
|
-
* bytes are sitting right there under the other spelling.
|
|
12176
|
-
*/
|
|
12177
|
-
static fileKey(patchId, filePath) {
|
|
12178
|
-
return `${patchId}\u0000${filePath.replace(/^\//, "")}`;
|
|
12179
|
-
}
|
|
12180
|
-
files = new Map();
|
|
12181
|
-
async putFile(file) {
|
|
12182
|
-
this.files.set(InMemoryPatchStore.fileKey(file.patchId, file.filePath), file);
|
|
12183
|
-
}
|
|
12184
|
-
async getFile(patchId, filePath) {
|
|
12185
|
-
return this.files.get(InMemoryPatchStore.fileKey(patchId, filePath)) ?? null;
|
|
12186
|
-
}
|
|
12187
|
-
async deleteFile(patchId, filePath) {
|
|
12188
|
-
this.files.delete(InMemoryPatchStore.fileKey(patchId, filePath));
|
|
12189
|
-
}
|
|
12190
|
-
async filesOf(patchId) {
|
|
12191
|
-
return [...this.files.values()].filter(file => file.patchId === patchId);
|
|
12192
|
-
}
|
|
12193
|
-
}
|
|
12194
10852
|
/**
|
|
12195
10853
|
* A `ValOps` for a host that is neither a developer's machine nor
|
|
12196
10854
|
* content.val.build.
|
|
@@ -12812,606 +11470,4 @@ class ValOpsMemory extends ValOps {
|
|
|
12812
11470
|
|
|
12813
11471
|
/** Kept exported so a host can name the error shape it may get back. */
|
|
12814
11472
|
|
|
12815
|
-
|
|
12816
|
-
* What `redirect_to` may be on Val's routes (`/enable`, `/disable`,
|
|
12817
|
-
* `/authorize`, `/draft/enable`, ...): a path on the site that was asked,
|
|
12818
|
-
* which is made absolute against the request's own origin, or an absolute
|
|
12819
|
-
* URL on that same site.
|
|
12820
|
-
*
|
|
12821
|
-
* A path used to go through as it was, and two things downstream need an
|
|
12822
|
-
* absolute URL: `/authorize` reads the origin off it to build the callback,
|
|
12823
|
-
* and Next's `NextResponse.redirect` refuses anything else. Both threw, so
|
|
12824
|
-
* `/api/val/enable?redirect_to=/` answered 500 in a Next app.
|
|
12825
|
-
*
|
|
12826
|
-
* `//host/path` is a URL on another host, not a path on this one, and
|
|
12827
|
-
* anything that is neither is refused with what is accepted instead. An
|
|
12828
|
-
* empty value is not resolved at all: the router leaves it to the route, as
|
|
12829
|
-
* it always was (`/logout` reads it as absent).
|
|
12830
|
-
*/
|
|
12831
|
-
|
|
12832
|
-
const REDIRECT_TO_ACCEPTS = "redirect_to must be a path on this site starting with / (/page), or an absolute URL on this site (https://this-site.example/page).";
|
|
12833
|
-
|
|
12834
|
-
/**
|
|
12835
|
-
* `siteHosts` are the other names the request knows this site by (`Host`,
|
|
12836
|
-
* `X-Forwarded-Host`), for a server behind a proxy whose own URL is internal.
|
|
12837
|
-
*/
|
|
12838
|
-
function resolveRedirectTo(value, requestOrigin, siteHosts = []) {
|
|
12839
|
-
if (value.startsWith("/") && !value.startsWith("//")) {
|
|
12840
|
-
// A path stays on this origin. `/\host/x` also starts with one slash,
|
|
12841
|
-
// and a URL parser reads the backslash as a second one: another host,
|
|
12842
|
-
// not a path here.
|
|
12843
|
-
const resolved = parsed(value, requestOrigin);
|
|
12844
|
-
return resolved !== null && resolved.origin === new URL(requestOrigin).origin ? {
|
|
12845
|
-
ok: true,
|
|
12846
|
-
href: resolved.href
|
|
12847
|
-
} : {
|
|
12848
|
-
ok: false,
|
|
12849
|
-
message: REDIRECT_TO_ACCEPTS
|
|
12850
|
-
};
|
|
12851
|
-
}
|
|
12852
|
-
// An absolute URL, on this site only. Any URL used to pass, which made
|
|
12853
|
-
// `/logout` and `/enable` redirect wherever a link said, and `/authorize`
|
|
12854
|
-
// send the sign-in's code to that host: it reads the callback's origin off
|
|
12855
|
-
// this. http(s) only: `javascript:` parses as a URL too.
|
|
12856
|
-
const url = parsed(value);
|
|
12857
|
-
if (url === null || url.protocol !== "https:" && url.protocol !== "http:") {
|
|
12858
|
-
return {
|
|
12859
|
-
ok: false,
|
|
12860
|
-
message: REDIRECT_TO_ACCEPTS
|
|
12861
|
-
};
|
|
12862
|
-
}
|
|
12863
|
-
const hosts = [new URL(requestOrigin).host, ...siteHosts].filter(host => typeof host === "string" && host !== "").map(host => host.toLowerCase());
|
|
12864
|
-
return hosts.includes(url.host.toLowerCase()) ? {
|
|
12865
|
-
ok: true,
|
|
12866
|
-
href: value
|
|
12867
|
-
} : {
|
|
12868
|
-
ok: false,
|
|
12869
|
-
message: REDIRECT_TO_ACCEPTS
|
|
12870
|
-
};
|
|
12871
|
-
}
|
|
12872
|
-
|
|
12873
|
-
/**
|
|
12874
|
-
* `value` as a URL, or null. Not `URL.canParse`: this runs in the browser
|
|
12875
|
-
* too (demo mode), where it is missing before Safari 17 and Chrome 120.
|
|
12876
|
-
*/
|
|
12877
|
-
function parsed(value, base) {
|
|
12878
|
-
try {
|
|
12879
|
-
return new URL(value, base);
|
|
12880
|
-
} catch {
|
|
12881
|
-
return null;
|
|
12882
|
-
}
|
|
12883
|
-
}
|
|
12884
|
-
|
|
12885
|
-
/**
|
|
12886
|
-
* Which requests Val's API answers in fs mode, where there is no session.
|
|
12887
|
-
*
|
|
12888
|
-
* fs mode reads and writes a working tree and asks nobody who they are: it is
|
|
12889
|
-
* a developer's own machine. That holds only while the request really comes
|
|
12890
|
-
* from that developer's Studio, and three kinds do not:
|
|
12891
|
-
*
|
|
12892
|
-
* - **A deployed site.** fs is the mode an app falls into when it has no
|
|
12893
|
-
* `VAL_API_KEY` and `VAL_SECRET`, so a site deployed without them served
|
|
12894
|
-
* this API, unauthenticated, to the internet.
|
|
12895
|
-
* - **Another site's page**, in the developer's browser. A `text/plain` POST
|
|
12896
|
-
* needs no preflight, and the router reads its body as JSON, so any page
|
|
12897
|
-
* open in another tab could write to the working tree.
|
|
12898
|
-
* - **A name that resolves to 127.0.0.1** (DNS rebinding), which makes such a
|
|
12899
|
-
* page same-origin with the dev server as far as the browser can tell.
|
|
12900
|
-
*
|
|
12901
|
-
* The MCP endpoint has refused all three since it was written
|
|
12902
|
-
* (`refuseUnsafeRequest` in `@valbuild/mcp`); this is the same rule for the
|
|
12903
|
-
* API the Studio uses. Nothing here needs Node: `ValRouterCore` runs in a
|
|
12904
|
-
* browser tab too, where no server is registered and nothing is refused.
|
|
12905
|
-
*/
|
|
12906
|
-
|
|
12907
|
-
const guards = new WeakMap();
|
|
12908
|
-
|
|
12909
|
-
/** Say how `server`'s requests are to be checked. Without it, none are. */
|
|
12910
|
-
function setRequestGuard(server, guard) {
|
|
12911
|
-
guards.set(server, guard);
|
|
12912
|
-
}
|
|
12913
|
-
|
|
12914
|
-
/** `VAL_ALLOWED_HOSTS`: comma separated host names, without a port. */
|
|
12915
|
-
function parseAllowedHosts(value) {
|
|
12916
|
-
return (value ?? "").split(",").map(host => host.trim().toLowerCase()).filter(host => host !== "");
|
|
12917
|
-
}
|
|
12918
|
-
|
|
12919
|
-
/** The refusal, or `null` when the request may go on to its route. */
|
|
12920
|
-
function refuseUnsafeRequest(server, req, apiPath) {
|
|
12921
|
-
var _req$method;
|
|
12922
|
-
const guard = guards.get(server);
|
|
12923
|
-
if (guard === undefined || guard.mode !== "fs") {
|
|
12924
|
-
return null;
|
|
12925
|
-
}
|
|
12926
|
-
// Beacons are not refused: in fs mode one is checked and dropped, nothing
|
|
12927
|
-
// is written or forwarded, and a deployed site with analytics on would fill
|
|
12928
|
-
// every visitor's console with errors.
|
|
12929
|
-
if (apiPath === "/analytics") {
|
|
12930
|
-
return null;
|
|
12931
|
-
}
|
|
12932
|
-
if (guard.production) {
|
|
12933
|
-
return refusal("Val is not set up for a deployed site here: without VAL_API_KEY and VAL_SECRET it runs in local filesystem mode, which has no sign-in and is only served by a development server. Set both (and VAL_PROJECT) on this deployment to use Val on it.");
|
|
12934
|
-
}
|
|
12935
|
-
const host = hostOf(req);
|
|
12936
|
-
const forwardedHost = firstOf(req.headers.get("x-forwarded-host"));
|
|
12937
|
-
const origin = req.headers.get("origin");
|
|
12938
|
-
if (origin !== null) {
|
|
12939
|
-
// `null` is the opaque origin (a sandboxed frame, a `file:` page). It
|
|
12940
|
-
// cannot be compared with anything, so it is refused.
|
|
12941
|
-
const originHost = origin === "null" ? null : hostOfUrl(origin);
|
|
12942
|
-
if (originHost === null || originHost !== host && originHost !== forwardedHost) {
|
|
12943
|
-
return refusal(`Val refused a request from another site (${origin}). In local filesystem mode the API only answers the Studio on its own address.`);
|
|
12944
|
-
}
|
|
12945
|
-
}
|
|
12946
|
-
// A request with no `Origin` can still come from another site: an `<img>`,
|
|
12947
|
-
// a script. Following a link here is not refused: sign-in comes back as
|
|
12948
|
-
// one. A link is a GET; a form posted from another site navigates too.
|
|
12949
|
-
const followedLink = ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === "GET" && req.headers.get("sec-fetch-mode") === "navigate";
|
|
12950
|
-
if (req.headers.get("sec-fetch-site") === "cross-site" && !followedLink) {
|
|
12951
|
-
return refusal("Val refused a request from another site. In local filesystem mode the API only answers the Studio on its own address.");
|
|
12952
|
-
}
|
|
12953
|
-
const hostname = host === null ? null : hostnameOf(host);
|
|
12954
|
-
if (hostname === null || !isLocalName(hostname, guard.allowedHosts)) {
|
|
12955
|
-
return refusal(`Val refused a request addressed to ${host ?? "an unknown host"}. In local filesystem mode the API answers on localhost and on IP addresses, because any other name can be made to point at this machine by the site that owns it. If this is the address you develop on, add its host name to the VAL_ALLOWED_HOSTS environment variable (comma separated) and restart the dev server.`);
|
|
12956
|
-
}
|
|
12957
|
-
return null;
|
|
12958
|
-
}
|
|
12959
|
-
function refusal(message) {
|
|
12960
|
-
return {
|
|
12961
|
-
status: 403,
|
|
12962
|
-
json: {
|
|
12963
|
-
message
|
|
12964
|
-
}
|
|
12965
|
-
};
|
|
12966
|
-
}
|
|
12967
|
-
function firstOf(header) {
|
|
12968
|
-
var _header$split$;
|
|
12969
|
-
const first = header === null || header === void 0 || (_header$split$ = header.split(",")[0]) === null || _header$split$ === void 0 ? void 0 : _header$split$.trim().toLowerCase();
|
|
12970
|
-
return first ? first : null;
|
|
12971
|
-
}
|
|
12972
|
-
function hostOf(req) {
|
|
12973
|
-
const header = firstOf(req.headers.get("host"));
|
|
12974
|
-
if (header !== null) {
|
|
12975
|
-
return header;
|
|
12976
|
-
}
|
|
12977
|
-
// No Host header: the URL the framework built the request from.
|
|
12978
|
-
return hostOfUrl(req.url);
|
|
12979
|
-
}
|
|
12980
|
-
function hostOfUrl(url) {
|
|
12981
|
-
try {
|
|
12982
|
-
return new URL(url).host.toLowerCase();
|
|
12983
|
-
} catch {
|
|
12984
|
-
return null;
|
|
12985
|
-
}
|
|
12986
|
-
}
|
|
12987
|
-
|
|
12988
|
-
/** A host without its port. An IPv6 literal keeps its brackets. */
|
|
12989
|
-
function hostnameOf(host) {
|
|
12990
|
-
if (host.startsWith("[")) {
|
|
12991
|
-
const end = host.indexOf("]");
|
|
12992
|
-
return end === -1 ? host : host.slice(0, end + 1);
|
|
12993
|
-
}
|
|
12994
|
-
const colon = host.indexOf(":");
|
|
12995
|
-
return colon === -1 ? host : host.slice(0, colon);
|
|
12996
|
-
}
|
|
12997
|
-
|
|
12998
|
-
/**
|
|
12999
|
-
* localhost, an IP address, or a name the developer listed.
|
|
13000
|
-
*
|
|
13001
|
-
* An IP address is allowed because it cannot be rebound: a page that reaches
|
|
13002
|
-
* this server by address is on another origin, and the `Origin` check above
|
|
13003
|
-
* has already refused it. A phone on the same network uses one.
|
|
13004
|
-
*/
|
|
13005
|
-
function isLocalName(hostname, allowedHosts) {
|
|
13006
|
-
return hostname === "localhost" || hostname.endsWith(".localhost") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[") && hostname.endsWith("]") || allowedHosts.includes(hostname);
|
|
13007
|
-
}
|
|
13008
|
-
|
|
13009
|
-
/**
|
|
13010
|
-
* Val's API as a web-standard handler: a `Request` in, a converted result out.
|
|
13011
|
-
*
|
|
13012
|
-
* The request handling itself -- matching a route, parsing it against `Api`,
|
|
13013
|
-
* calling the server, checking the answer -- and nothing that needs Node, so it
|
|
13014
|
-
* runs in a browser tab as well as on a server. That is what the demo does
|
|
13015
|
-
* (`@valbuild/server/browser`): the Studio's own client sends its requests
|
|
13016
|
-
* here, in the same tab, instead of over the network.
|
|
13017
|
-
*
|
|
13018
|
-
* `serveStatic` answers `/static/...`, the Studio's own scripts and styles.
|
|
13019
|
-
* `createValApiRouter` passes the embedded bundle; the demo passes nothing,
|
|
13020
|
-
* because its page loaded those from the app already.
|
|
13021
|
-
*/
|
|
13022
|
-
function createValRequestHandler(route, valServerPromise, convert, serveStatic) {
|
|
13023
|
-
// valServerPromise is created at module-eval time, but only awaited per request.
|
|
13024
|
-
// Without this no-op catch, a config error (e.g. proxy mode without a project)
|
|
13025
|
-
// rejects with no handler attached, which becomes an unhandledRejection and kills
|
|
13026
|
-
// the dev server. The error is still reported per request by the try/catch below.
|
|
13027
|
-
valServerPromise.catch(() => {
|
|
13028
|
-
// handled below
|
|
13029
|
-
});
|
|
13030
|
-
return async req => {
|
|
13031
|
-
let valServer;
|
|
13032
|
-
try {
|
|
13033
|
-
valServer = await valServerPromise;
|
|
13034
|
-
} catch (err) {
|
|
13035
|
-
const error = {
|
|
13036
|
-
message: "Val: could not start the Val server",
|
|
13037
|
-
details: err instanceof Error ? err.message : String(err)
|
|
13038
|
-
};
|
|
13039
|
-
Internal.log.error(error.message + ": " + error.details);
|
|
13040
|
-
return convert({
|
|
13041
|
-
status: 500,
|
|
13042
|
-
json: error
|
|
13043
|
-
});
|
|
13044
|
-
}
|
|
13045
|
-
const url = new URL(req.url);
|
|
13046
|
-
if (!url.pathname.startsWith(route)) {
|
|
13047
|
-
const error = {
|
|
13048
|
-
message: "Val: routes are not configured correctly",
|
|
13049
|
-
details: `Check you api routes. Expected pathname to start with "${route}", but it was: "${url.pathname}"`
|
|
13050
|
-
};
|
|
13051
|
-
Internal.log.error(error);
|
|
13052
|
-
return convert({
|
|
13053
|
-
status: 500,
|
|
13054
|
-
json: error
|
|
13055
|
-
});
|
|
13056
|
-
}
|
|
13057
|
-
const path = url.pathname.slice(route.length);
|
|
13058
|
-
if (path === QUICK_PREVIEW_SERVICE_WORKER_PATH) {
|
|
13059
|
-
/*
|
|
13060
|
-
* The quick preview worker (`quickPreview.ts` in
|
|
13061
|
-
* `@valbuild/shared`). `Service-Worker-Allowed: /` lets a script at
|
|
13062
|
-
* this path control the whole origin, which it needs: it serves the
|
|
13063
|
-
* page's `/_app/` files. It serves them only to a page opened as a
|
|
13064
|
-
* quick preview, and the bridge stores them only for the site.
|
|
13065
|
-
*/
|
|
13066
|
-
return convert({
|
|
13067
|
-
status: 200,
|
|
13068
|
-
headers: {
|
|
13069
|
-
"Content-Type": "text/javascript; charset=utf-8",
|
|
13070
|
-
"Service-Worker-Allowed": "/",
|
|
13071
|
-
"Cache-Control": "no-cache"
|
|
13072
|
-
},
|
|
13073
|
-
body: QUICK_PREVIEW_SERVICE_WORKER_SOURCE
|
|
13074
|
-
});
|
|
13075
|
-
}
|
|
13076
|
-
const groupQueryParams = arr => {
|
|
13077
|
-
const map = {};
|
|
13078
|
-
for (const [key, value] of arr) {
|
|
13079
|
-
const list = map[key] || [];
|
|
13080
|
-
list.push(value);
|
|
13081
|
-
map[key] = list;
|
|
13082
|
-
}
|
|
13083
|
-
return map;
|
|
13084
|
-
};
|
|
13085
|
-
async function getValServerResponse(reqApiRoutePath, req) {
|
|
13086
|
-
var _req$method, _anyApi$route, _anyValServer$route;
|
|
13087
|
-
const anyApi =
|
|
13088
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
13089
|
-
Api;
|
|
13090
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
13091
|
-
const anyValServer = valServer;
|
|
13092
|
-
const refused = refuseUnsafeRequest(valServer, req, reqApiRoutePath);
|
|
13093
|
-
if (refused !== null) {
|
|
13094
|
-
return refused;
|
|
13095
|
-
}
|
|
13096
|
-
const method = (_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase();
|
|
13097
|
-
let route = null;
|
|
13098
|
-
let path = undefined;
|
|
13099
|
-
// An exact match wins over every prefix match, wherever it sits in
|
|
13100
|
-
// `Api`: checked per key, in order, `/validate` took `/validate/fix`
|
|
13101
|
-
// because it was declared first.
|
|
13102
|
-
const exactRouteDef = Object.keys(Api).find(routeDef => routeDef === reqApiRoutePath);
|
|
13103
|
-
for (const routeDef of exactRouteDef ? [exactRouteDef] : Object.keys(Api)) {
|
|
13104
|
-
if (routeDef === reqApiRoutePath) {
|
|
13105
|
-
route = routeDef;
|
|
13106
|
-
break;
|
|
13107
|
-
}
|
|
13108
|
-
if (reqApiRoutePath.startsWith(routeDef)) {
|
|
13109
|
-
var _anyApi$routeDef;
|
|
13110
|
-
const reqDefinition = anyApi === null || anyApi === void 0 || (_anyApi$routeDef = anyApi[routeDef]) === null || _anyApi$routeDef === void 0 || (_anyApi$routeDef = _anyApi$routeDef[method]) === null || _anyApi$routeDef === void 0 ? void 0 : _anyApi$routeDef.req;
|
|
13111
|
-
if (reqDefinition) {
|
|
13112
|
-
route = routeDef;
|
|
13113
|
-
if (reqDefinition.path) {
|
|
13114
|
-
const subPath = reqApiRoutePath.slice(routeDef.length);
|
|
13115
|
-
const pathRes = reqDefinition.path.safeParse(subPath);
|
|
13116
|
-
if (!pathRes.success) {
|
|
13117
|
-
return zodErrorResult(pathRes.error, `invalid path: '${subPath}' endpoint: '${routeDef}'`);
|
|
13118
|
-
} else {
|
|
13119
|
-
path = pathRes.data;
|
|
13120
|
-
}
|
|
13121
|
-
}
|
|
13122
|
-
break;
|
|
13123
|
-
}
|
|
13124
|
-
}
|
|
13125
|
-
}
|
|
13126
|
-
if (!route) {
|
|
13127
|
-
return {
|
|
13128
|
-
status: 404,
|
|
13129
|
-
json: {
|
|
13130
|
-
message: "Route not found. Valid routes are: " + Object.keys(Api),
|
|
13131
|
-
details: {
|
|
13132
|
-
route,
|
|
13133
|
-
method
|
|
13134
|
-
}
|
|
13135
|
-
}
|
|
13136
|
-
};
|
|
13137
|
-
}
|
|
13138
|
-
const apiEndpoint = anyApi === null || anyApi === void 0 || (_anyApi$route = anyApi[route]) === null || _anyApi$route === void 0 ? void 0 : _anyApi$route[method];
|
|
13139
|
-
const reqDefinition = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.req;
|
|
13140
|
-
if (!reqDefinition) {
|
|
13141
|
-
return {
|
|
13142
|
-
status: 404,
|
|
13143
|
-
json: {
|
|
13144
|
-
message: `Requested method ${method} on route ${route} is not valid. Valid methods are: ${Object.keys(anyApi[route]).join(", ")}`,
|
|
13145
|
-
details: {
|
|
13146
|
-
route,
|
|
13147
|
-
method
|
|
13148
|
-
}
|
|
13149
|
-
}
|
|
13150
|
-
};
|
|
13151
|
-
}
|
|
13152
|
-
const endpointImpl = anyValServer === null || anyValServer === void 0 || (_anyValServer$route = anyValServer[route]) === null || _anyValServer$route === void 0 ? void 0 : _anyValServer$route[method];
|
|
13153
|
-
if (!endpointImpl) {
|
|
13154
|
-
return {
|
|
13155
|
-
status: 500,
|
|
13156
|
-
json: {
|
|
13157
|
-
message: "Missing server implementation of route with method. This might be caused by a mismatch between Val package versions.",
|
|
13158
|
-
details: {
|
|
13159
|
-
valid: {
|
|
13160
|
-
route: {
|
|
13161
|
-
server: Object.keys(anyValServer || {}),
|
|
13162
|
-
api: Object.keys(anyApi || {})
|
|
13163
|
-
},
|
|
13164
|
-
method: {
|
|
13165
|
-
server: Object.keys((anyValServer === null || anyValServer === void 0 ? void 0 : anyValServer[route]) || {}),
|
|
13166
|
-
api: Object.keys((anyApi === null || anyApi === void 0 ? void 0 : anyApi[route]) || {})
|
|
13167
|
-
}
|
|
13168
|
-
},
|
|
13169
|
-
route,
|
|
13170
|
-
method
|
|
13171
|
-
}
|
|
13172
|
-
}
|
|
13173
|
-
};
|
|
13174
|
-
}
|
|
13175
|
-
let bodyRes;
|
|
13176
|
-
try {
|
|
13177
|
-
bodyRes = reqDefinition.body ? reqDefinition.body.safeParse(await readJsonBody(req)) : {
|
|
13178
|
-
success: true,
|
|
13179
|
-
data: {}
|
|
13180
|
-
};
|
|
13181
|
-
if (!bodyRes.success) {
|
|
13182
|
-
return zodErrorResult(bodyRes.error, "invalid body data");
|
|
13183
|
-
}
|
|
13184
|
-
} catch (e) {
|
|
13185
|
-
return {
|
|
13186
|
-
status: 400,
|
|
13187
|
-
json: {
|
|
13188
|
-
message: "Could not parse request body",
|
|
13189
|
-
details: {
|
|
13190
|
-
error: JSON.stringify(e)
|
|
13191
|
-
}
|
|
13192
|
-
}
|
|
13193
|
-
};
|
|
13194
|
-
}
|
|
13195
|
-
const cookiesRes = reqDefinition.cookies ? getCookies(req, reqDefinition.cookies) : {
|
|
13196
|
-
success: true,
|
|
13197
|
-
data: {}
|
|
13198
|
-
};
|
|
13199
|
-
if (!cookiesRes.success) {
|
|
13200
|
-
return zodErrorResult(cookiesRes.error, "invalid cookies");
|
|
13201
|
-
}
|
|
13202
|
-
const headersRes = reqDefinition.headers ? getHeaders(req, reqDefinition.headers) : {
|
|
13203
|
-
success: true,
|
|
13204
|
-
data: {}
|
|
13205
|
-
};
|
|
13206
|
-
if (!headersRes.success) {
|
|
13207
|
-
return zodErrorResult(headersRes.error, "invalid headers");
|
|
13208
|
-
}
|
|
13209
|
-
const actualQueryParams = groupQueryParams(Array.from(url.searchParams.entries()));
|
|
13210
|
-
let query = {};
|
|
13211
|
-
if (reqDefinition.query) {
|
|
13212
|
-
const queryRules = reqDefinition.query;
|
|
13213
|
-
const queryRes = z.object(queryRules).safeParse(actualQueryParams);
|
|
13214
|
-
if (!queryRes.success) {
|
|
13215
|
-
return zodErrorResult(queryRes.error, `invalid query params: (${JSON.stringify(actualQueryParams)})`);
|
|
13216
|
-
}
|
|
13217
|
-
query = queryRes.data;
|
|
13218
|
-
}
|
|
13219
|
-
// `redirect_to` is a URL or a path on this site: see `resolveRedirectTo`.
|
|
13220
|
-
if ("redirect_to" in query && typeof query.redirect_to === "string" && query.redirect_to !== "") {
|
|
13221
|
-
var _req$headers$get;
|
|
13222
|
-
// Behind a proxy `url` can be an internal address: the site's own
|
|
13223
|
-
// name is then in `Host` or `X-Forwarded-Host`.
|
|
13224
|
-
const resolved = resolveRedirectTo(query.redirect_to, url.origin, [req.headers.get("host"), (_req$headers$get = req.headers.get("x-forwarded-host")) === null || _req$headers$get === void 0 || (_req$headers$get = _req$headers$get.split(",")[0]) === null || _req$headers$get === void 0 ? void 0 : _req$headers$get.trim()]);
|
|
13225
|
-
if (!resolved.ok) {
|
|
13226
|
-
return {
|
|
13227
|
-
status: 400,
|
|
13228
|
-
json: {
|
|
13229
|
-
message: resolved.message
|
|
13230
|
-
}
|
|
13231
|
-
};
|
|
13232
|
-
}
|
|
13233
|
-
query = {
|
|
13234
|
-
...query,
|
|
13235
|
-
redirect_to: resolved.href
|
|
13236
|
-
};
|
|
13237
|
-
}
|
|
13238
|
-
|
|
13239
|
-
/*
|
|
13240
|
-
* A throw from an endpoint is Val's to report, not the framework's.
|
|
13241
|
-
*
|
|
13242
|
-
* Nothing here used to catch, so an endpoint that threw left the router
|
|
13243
|
-
* entirely and became whatever the host does with an unhandled error --
|
|
13244
|
-
* and on TanStack Start that is h3, which replaces the message with the
|
|
13245
|
-
* literal string "HTTPError" and drops the stack. Its `debug` and
|
|
13246
|
-
* `silent` options are not reachable from out here: `requestHandler`
|
|
13247
|
-
* calls `toResponse(value, event)` with no config, and the default is
|
|
13248
|
-
* `{}`. So the body a caller got was
|
|
13249
|
-
* `{"status":500,"unhandled":true,"message":"HTTPError"}` -- the same
|
|
13250
|
-
* five words for a missing project, a bad cookie secret and a module
|
|
13251
|
-
* that failed to link -- with the real cause only on the server's
|
|
13252
|
-
* console.
|
|
13253
|
-
*
|
|
13254
|
-
* That is survivable where the console is readable. It is not in a
|
|
13255
|
-
* Cloudflare Dynamic Worker, whose `console` reaches no tail stream: a
|
|
13256
|
-
* link error in a lazily imported chunk (`does not provide an export
|
|
13257
|
-
* named 'getSerovalPlugins'`) showed up as an unreadable 500 on
|
|
13258
|
-
* `/authorize` and nowhere else at all.
|
|
13259
|
-
*
|
|
13260
|
-
* So every endpoint's throw becomes Val's own 500 envelope, which the
|
|
13261
|
-
* Studio already renders and `curl` already prints. The route and method
|
|
13262
|
-
* are named because a message rarely says which endpoint it came from.
|
|
13263
|
-
*
|
|
13264
|
-
* The MESSAGE travels and the STACK does not. The message is the whole
|
|
13265
|
-
* diagnostic value -- the line above names the package, the chunk and
|
|
13266
|
-
* the export -- while a stack is a walk through somebody's bundle, and
|
|
13267
|
-
* `/authorize` and `/enable` are reachable without a session. So the
|
|
13268
|
-
* stack goes to the console, where a host that can read one will find
|
|
13269
|
-
* it, and the body carries what a caller can act on.
|
|
13270
|
-
*/
|
|
13271
|
-
let res;
|
|
13272
|
-
try {
|
|
13273
|
-
res = await endpointImpl({
|
|
13274
|
-
body: bodyRes.data,
|
|
13275
|
-
cookies: cookiesRes.data,
|
|
13276
|
-
headers: headersRes.data,
|
|
13277
|
-
rawQuery: reqDefinition.rawQuery ? url.search : undefined,
|
|
13278
|
-
query,
|
|
13279
|
-
path
|
|
13280
|
-
});
|
|
13281
|
-
} catch (err) {
|
|
13282
|
-
const error = err instanceof Error ? err : new Error(String(err));
|
|
13283
|
-
Internal.log.error(`${method} ${route} threw: ${error.message}`, error.stack);
|
|
13284
|
-
return {
|
|
13285
|
-
status: 500,
|
|
13286
|
-
json: {
|
|
13287
|
-
message: `Val: ${method} ${route} failed: ${error.message}`,
|
|
13288
|
-
details: {
|
|
13289
|
-
route,
|
|
13290
|
-
method,
|
|
13291
|
-
error: error.message
|
|
13292
|
-
}
|
|
13293
|
-
}
|
|
13294
|
-
};
|
|
13295
|
-
}
|
|
13296
|
-
const resDef = apiEndpoint.res;
|
|
13297
|
-
if (res.status === 500) {
|
|
13298
|
-
var _res$json;
|
|
13299
|
-
/*
|
|
13300
|
-
* A failure the route declares goes out as declared, as a success
|
|
13301
|
-
* does below. DELETE /patches says which change was not discarded and
|
|
13302
|
-
* which publish holds it, and collapsed to its message the Studio
|
|
13303
|
-
* could only say "Failed to delete patches" -- not why, nor offer to
|
|
13304
|
-
* cancel that publish. Anything undeclared is still reduced to its
|
|
13305
|
-
* message.
|
|
13306
|
-
*/
|
|
13307
|
-
if (resDef !== null && resDef !== void 0 && resDef.safeParse(res).success) return res;
|
|
13308
|
-
return {
|
|
13309
|
-
status: 500,
|
|
13310
|
-
json: {
|
|
13311
|
-
message: ((_res$json = res.json) === null || _res$json === void 0 ? void 0 : _res$json.message) || "Internal Server Error"
|
|
13312
|
-
}
|
|
13313
|
-
};
|
|
13314
|
-
}
|
|
13315
|
-
if (resDef) {
|
|
13316
|
-
const responseResult = resDef.safeParse(res);
|
|
13317
|
-
if (!responseResult.success) {
|
|
13318
|
-
return {
|
|
13319
|
-
status: 500,
|
|
13320
|
-
json: {
|
|
13321
|
-
message: "Could not validate response. This is likely a bug in Val server.",
|
|
13322
|
-
details: {
|
|
13323
|
-
response: res,
|
|
13324
|
-
errors: formatZodErrorString(responseResult.error)
|
|
13325
|
-
}
|
|
13326
|
-
}
|
|
13327
|
-
};
|
|
13328
|
-
}
|
|
13329
|
-
}
|
|
13330
|
-
return res;
|
|
13331
|
-
}
|
|
13332
|
-
if (path.startsWith("/static")) {
|
|
13333
|
-
if (!serveStatic) {
|
|
13334
|
-
return convert({
|
|
13335
|
-
status: 404,
|
|
13336
|
-
json: {
|
|
13337
|
-
message: "Val: this server does not serve the Studio's own files"
|
|
13338
|
-
}
|
|
13339
|
-
});
|
|
13340
|
-
}
|
|
13341
|
-
return convert(await serveStatic(path.slice("/static".length), url.href));
|
|
13342
|
-
} else {
|
|
13343
|
-
return convert(await getValServerResponse(path, req));
|
|
13344
|
-
}
|
|
13345
|
-
};
|
|
13346
|
-
}
|
|
13347
|
-
function formatZodErrorString(error) {
|
|
13348
|
-
const errors = fromError(error).toString();
|
|
13349
|
-
return errors.length > 640 ? `${errors.slice(0, 640)}...` : errors;
|
|
13350
|
-
}
|
|
13351
|
-
|
|
13352
|
-
/**
|
|
13353
|
-
* The request's JSON body, or `undefined` when it has none.
|
|
13354
|
-
*
|
|
13355
|
-
* `req.json()` THROWS on an empty body, and the router used to call it
|
|
13356
|
-
* unconditionally for any route that declares a body — so the moment
|
|
13357
|
-
* `DELETE /patches` gained an optional body, every caller that sent none got
|
|
13358
|
-
* `400 Could not parse request body`. Declaring the schema `.optional()` did
|
|
13359
|
-
* not help: the throw happens before zod is ever consulted. Six e2e tests went
|
|
13360
|
-
* red on a helper doing exactly what the route still permits.
|
|
13361
|
-
*
|
|
13362
|
-
* Told apart by the request rather than by catching, so a body that IS sent and
|
|
13363
|
-
* is malformed still fails: absent means no content type and nothing to read,
|
|
13364
|
-
* and anything else is parsed and allowed to throw. A route whose schema
|
|
13365
|
-
* requires a body is unaffected — it gets `undefined` and zod refuses it, with
|
|
13366
|
-
* the same 400 as before, now naming the field.
|
|
13367
|
-
*/
|
|
13368
|
-
async function readJsonBody(req) {
|
|
13369
|
-
if (req.headers.get("content-length") === "0") {
|
|
13370
|
-
return undefined;
|
|
13371
|
-
}
|
|
13372
|
-
const text = await req.text();
|
|
13373
|
-
if (text.length === 0) {
|
|
13374
|
-
return undefined;
|
|
13375
|
-
}
|
|
13376
|
-
return JSON.parse(text);
|
|
13377
|
-
}
|
|
13378
|
-
function zodErrorResult(error, message) {
|
|
13379
|
-
return {
|
|
13380
|
-
status: 400,
|
|
13381
|
-
json: {
|
|
13382
|
-
message: "Bad Request: " + message,
|
|
13383
|
-
details: {
|
|
13384
|
-
errors: formatZodErrorString(error)
|
|
13385
|
-
}
|
|
13386
|
-
}
|
|
13387
|
-
};
|
|
13388
|
-
}
|
|
13389
|
-
|
|
13390
|
-
// TODO: is this naive implementation is too naive?
|
|
13391
|
-
/** The declared headers, by name; `Headers.get` is case-insensitive. */
|
|
13392
|
-
function getHeaders(req, headersDef) {
|
|
13393
|
-
const input = {};
|
|
13394
|
-
for (const name of Object.keys(headersDef)) {
|
|
13395
|
-
var _req$headers;
|
|
13396
|
-
const value = (_req$headers = req.headers) === null || _req$headers === void 0 ? void 0 : _req$headers.get(name);
|
|
13397
|
-
if (value !== null && value !== undefined) {
|
|
13398
|
-
input[name] = value;
|
|
13399
|
-
}
|
|
13400
|
-
}
|
|
13401
|
-
return z.object(headersDef).safeParse(input);
|
|
13402
|
-
}
|
|
13403
|
-
function getCookies(req, cookiesDef) {
|
|
13404
|
-
var _req$headers2;
|
|
13405
|
-
const input = {};
|
|
13406
|
-
const cookieParts = (_req$headers2 = req.headers) === null || _req$headers2 === void 0 || (_req$headers2 = _req$headers2.get("Cookie")) === null || _req$headers2 === void 0 ? void 0 : _req$headers2.split("; ");
|
|
13407
|
-
for (const name of Object.keys(cookiesDef)) {
|
|
13408
|
-
const cookie = cookieParts === null || cookieParts === void 0 ? void 0 : cookieParts.find(cookie => cookie.startsWith(`${name}=`));
|
|
13409
|
-
const value = cookie ? decodeURIComponent(cookie === null || cookie === void 0 ? void 0 : cookie.split("=")[1]) : undefined;
|
|
13410
|
-
if (value) {
|
|
13411
|
-
input[name.trim()] = value;
|
|
13412
|
-
}
|
|
13413
|
-
}
|
|
13414
|
-
return z.object(cookiesDef).safeParse(input);
|
|
13415
|
-
}
|
|
13416
|
-
|
|
13417
|
-
export { isHlsMasterPlaylist as A, sumHlsSegmentDurations as B, parseHlsMasterVariants as C, DEFAULT_ANALYTICS_INGEST_URL as D, largestHlsVariant as E, fallbackRefOf as F, mapHlsUris as G, movedRemoteHost as H, InMemoryPatchStore as I, needsHostCheck as J, rewriteRefHost as K, fallbackRemoteHost as L, MEDIA_FILE_PATH_ACCEPTS as M, checkRemoteFiles as N, ValServer as O, setRequestGuard as P, parseAllowedHosts as Q, createValRequestHandler as R, bytesToBase64 as S, ValHead as T, headWork as U, VAL_CLIENT_HEADERS as V, HEAD_BUDGET_BYTES as W, HEAD_VERSIONS_PER_MODULE as X, bytesToUtf8 as Y, posixPath as Z, formatPatchSourceError as a, askOncePerHost as b, getSettings as c, getFileExt as d, ValOpsMemory as e, findNestedJsonValuesRecords as f, getNewJsonEntryPaths as g, byUpdatedAt as h, isSketchpadId as i, applySketchpadChange as j, ValOps as k, isSafePatchId as l, matchesFilter as m, newSketchpad as n, isMediaFilePath as o, bufferFromDataUrl as p, getFieldsForType as q, resolveExistingJsonPath as r, summaryOf as s, isPublicFilePath as t, uploadRemoteFile as u, validateJsonValuesEntries as v, guessMimeTypeFromPath as w, createMetadataFromBuffer as x, sessionAuth as y, isHttpOps as z };
|
|
11473
|
+
export { ValOps as A, isSafePatchId as B, isMediaFilePath as C, bufferFromDataUrl as D, isPublicFilePath as E, guessMimeTypeFromPath as F, createMetadataFromBuffer as G, DEFAULT_ANALYTICS_INGEST_URL as H, sessionAuth as I, isHttpOps as J, bytesToBase64 as K, bytesToUtf8 as L, MEDIA_FILE_PATH_ACCEPTS as M, ValServer as V, movedRemoteHost as a, fallbackRemoteHost as b, checkRemoteFiles as c, getFieldsForType as d, formatPatchSourceError as e, fallbackRefOf as f, getFileExt as g, VAL_CLIENT_HEADERS as h, isHlsMasterPlaylist as i, askOncePerHost as j, getSettings as k, largestHlsVariant as l, mapHlsUris as m, needsHostCheck as n, ValOpsMemory as o, parseHlsMasterVariants as p, summaryOf as q, rewriteRefHost as r, sumHlsSegmentDurations as s, matchesFilter as t, uploadRemoteFile as u, validateJsonValuesEntries as v, byUpdatedAt as w, newSketchpad as x, isSketchpadId as y, applySketchpadChange as z };
|