@valbuild/server 0.154.1 → 0.154.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +6 -3
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +6 -3
  4. package/browser/dist/valbuild-server-browser.esm.js +6 -3
  5. package/dist/{ValRouterCore-cfb35067.cjs.prod.js → ValOpsMemory-18337353.cjs.prod.js} +23 -2013
  6. package/dist/{ValRouterCore-361673dc.cjs.dev.js → ValOpsMemory-45ba05ad.cjs.dev.js} +23 -2013
  7. package/dist/{ValRouterCore-be314bc7.esm.js → ValOpsMemory-972616ae.esm.js} +14 -1992
  8. package/dist/ValPatchStore-2f92eced.cjs.prod.js +1128 -0
  9. package/dist/ValPatchStore-df8cdbe7.cjs.dev.js +1128 -0
  10. package/dist/ValPatchStore-e23070df.esm.js +1119 -0
  11. package/dist/ValRouterCore-5b747abb.cjs.prod.js +612 -0
  12. package/dist/ValRouterCore-73eb843d.esm.js +608 -0
  13. package/dist/ValRouterCore-86757d56.cjs.dev.js +612 -0
  14. package/dist/createPrettierFormatter-05ad7480.cjs.prod.js +692 -0
  15. package/dist/createPrettierFormatter-1edca494.esm.js +673 -0
  16. package/dist/createPrettierFormatter-851fcf99.cjs.dev.js +692 -0
  17. package/dist/createValRuntime-472df6e8.cjs.prod.js +47 -0
  18. package/dist/createValRuntime-5cebf459.cjs.dev.js +47 -0
  19. package/dist/createValRuntime-c77ee010.esm.js +45 -0
  20. package/dist/declarations/src/ValOpsMemory.d.ts +3 -73
  21. package/dist/declarations/src/ValPatchStore.d.ts +92 -0
  22. package/dist/declarations/src/ValRouter.d.ts +1 -11
  23. package/dist/declarations/src/createPrettierFormatter.d.ts +18 -3
  24. package/dist/declarations/src/createValRuntime.d.ts +12 -0
  25. package/dist/declarations/src/draftReads.d.ts +11 -3
  26. package/dist/declarations/src/index.d.ts +4 -2
  27. package/dist/declarations/src/internal/index.d.ts +28 -6
  28. package/dist/declarations/src/proposal.d.ts +13 -25
  29. package/dist/declarations/src/proposalJsonEntries.d.ts +30 -0
  30. package/dist/declarations/src/serverMode.d.ts +31 -0
  31. package/dist/{draftReads-0dcddf72.cjs.prod.js → draftReads-3f7dcda5.cjs.prod.js} +10 -2
  32. package/dist/{draftReads-df44e629.cjs.dev.js → draftReads-a300a02f.cjs.dev.js} +10 -2
  33. package/dist/{draftReads-1f29aedd.esm.js → draftReads-bca0d49c.esm.js} +10 -2
  34. package/dist/{inTabFetch-7c8a5628.esm.js → inTabFetch-0c997998.esm.js} +2 -1
  35. package/dist/{inTabFetch-56226d62.cjs.prod.js → inTabFetch-c2efa1bd.cjs.prod.js} +5 -4
  36. package/dist/{inTabFetch-5d0314a3.cjs.dev.js → inTabFetch-db6d6425.cjs.dev.js} +5 -4
  37. package/dist/jsonValuesPatch-13acc674.esm.js +276 -0
  38. package/dist/jsonValuesPatch-88bc661d.cjs.dev.js +281 -0
  39. package/dist/jsonValuesPatch-92798812.cjs.prod.js +281 -0
  40. package/dist/proposalJsonEntries-0669f027.esm.js +480 -0
  41. package/dist/proposalJsonEntries-26f397bd.cjs.dev.js +500 -0
  42. package/dist/proposalJsonEntries-9e537244.cjs.prod.js +500 -0
  43. package/dist/{publishKit-707230bc.cjs.prod.js → publishKit-38d46a51.cjs.dev.js} +20 -22
  44. package/dist/{publishKit-5a8c9a0d.cjs.dev.js → publishKit-7aca03bb.cjs.prod.js} +20 -22
  45. package/dist/{publishKit-b850045b.esm.js → publishKit-ac0af189.esm.js} +8 -9
  46. package/dist/{ValRouter-9505c550.cjs.dev.js → valRuntime-2a3cc887.cjs.prod.js} +158 -6038
  47. package/dist/{ValRouter-31f89baf.cjs.prod.js → valRuntime-70ee2dc2.cjs.dev.js} +158 -6038
  48. package/dist/{ValRouter-b7dc784d.esm.js → valRuntime-e4d26702.esm.js} +107 -5937
  49. package/dist/valbuild-server.cjs.dev.js +5146 -352
  50. package/dist/valbuild-server.cjs.prod.js +5146 -352
  51. package/dist/valbuild-server.esm.js +4902 -132
  52. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +7 -4
  53. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +7 -4
  54. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +7 -4
  55. package/internal/dist/valbuild-server-internal.cjs.dev.js +47 -31
  56. package/internal/dist/valbuild-server-internal.cjs.prod.js +47 -31
  57. package/internal/dist/valbuild-server-internal.esm.js +38 -22
  58. 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 { memoryTier, tiered, bundleTier, moduleKey, EMPTY_CHAIN, baseModuleContent, applyPatchRecord, extendChain, entryState, engineWork, resolveEntry, parseModuleKey, ChainFold, schemaVersionOf, baseVersionOf, sameModuleVersion, 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, QUICK_PREVIEW_SERVICE_WORKER_PATH, QUICK_PREVIEW_SERVICE_WORKER_SOURCE, Api } from '@valbuild/shared/internal';
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
@@ -1743,1030 +1473,15 @@ function hostName(host) {
1743
1473
  }
1744
1474
  }
1745
1475
  function isStale(parsed, schema, value) {
1746
- // The hash covers only these of what was recorded (`getValidationBasis`):
1747
- // `alt` and `hotspot` are the editor's, and change no byte.
1748
- const metadata = {
1749
- width: value.width,
1750
- height: value.height,
1751
- mimeType: value.mimeType
1752
- };
1753
- const expected = Internal.remote.getValidationHash(parsed.version, schema, getFileExt(parsed.filePath), metadata, parsed.fileHash, textEncoder);
1754
- return expected !== parsed.validationHash;
1755
- }
1756
-
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;
1476
+ // The hash covers only these of what was recorded (`getValidationBasis`):
1477
+ // `alt` and `hotspot` are the editor's, and change no byte.
1478
+ const metadata = {
1479
+ width: value.width,
1480
+ height: value.height,
1481
+ mimeType: value.mimeType
1482
+ };
1483
+ const expected = Internal.remote.getValidationHash(parsed.version, schema, getFileExt(parsed.filePath), metadata, parsed.fileHash, textEncoder);
1484
+ return expected !== parsed.validationHash;
2770
1485
  }
2771
1486
 
2772
1487
  /* eslint-disable @typescript-eslint/no-unused-vars */
@@ -6403,7 +5118,7 @@ var packageJson = {
6403
5118
  ],
6404
5119
  exports: true
6405
5120
  },
6406
- version: "0.154.1",
5121
+ version: "0.154.3",
6407
5122
  scripts: {
6408
5123
  typecheck: "tsc --noEmit",
6409
5124
  test: "jest",
@@ -12108,34 +10823,6 @@ function createMemorySketchpadStore(now = () => new Date()) {
12108
10823
  };
12109
10824
  }
12110
10825
 
12111
- /**
12112
- * One stored patch. Everything the ordered chain needs and nothing else.
12113
- */
12114
-
12115
- /**
12116
- * One pending binary file: an upload that has not been published yet.
12117
- *
12118
- * Keyed by the patch that carries it, exactly as `fs` mode keys the directory
12119
- * it writes to. The patch's own `file` op holds a hash, not the bytes, so these
12120
- * arrive on their own request and are joined up by `(patchId, filePath)`.
12121
- */
12122
-
12123
- /**
12124
- * Where pending patches live.
12125
- *
12126
- * The point of the interface: `ValOpsMemory` is not tied to memory. The default
12127
- * implementation below is explicitly NOT durable -- it dies with the process,
12128
- * or in a Worker with the isolate -- and a durable one (a Durable Object, whose
12129
- * single-threaded execution is the lock Val's fs store builds out of a file)
12130
- * is a swap rather than a rewrite.
12131
- *
12132
- * ORDER IS THE CONTRACT. `list()` returns patch ids in the order they were
12133
- * written, and that order is the chain: entry i's parent is entry i-1. This is
12134
- * the same decision `ValOpsFS` makes with `patches.log` -- the server decides
12135
- * where a patch goes, and it goes last -- and it exists for the same reason: an
12136
- * order held in the patches themselves lets a client working from a stale view
12137
- * strand every patch behind a parent that never landed.
12138
- */
12139
10826
  /**
12140
10827
  * Memory mode's `seq` (`ProjectVersion` in `@valbuild/shared/internal`), per
12141
10828
  * patch store: bumped beside `announceChange` by every write and delete, and
@@ -12162,69 +10849,6 @@ function seqOf(store) {
12162
10849
  }
12163
10850
  return counter;
12164
10851
  }
12165
- /** The default store. Not durable, deliberately and visibly. */
12166
- class InMemoryPatchStore {
12167
- order = [];
12168
- byId = new Map();
12169
- async list() {
12170
- return [...this.order];
12171
- }
12172
- async get(patchId) {
12173
- return this.byId.get(patchId) ?? null;
12174
- }
12175
- async append(patch) {
12176
- if (!this.byId.has(patch.patchId)) {
12177
- this.order.push(patch.patchId);
12178
- }
12179
- this.byId.set(patch.patchId, patch);
12180
- }
12181
- async delete(patchIds) {
12182
- for (const patchId of patchIds) {
12183
- const at = this.order.indexOf(patchId);
12184
- if (at !== -1) {
12185
- this.order.splice(at, 1);
12186
- }
12187
- this.byId.delete(patchId);
12188
- // The bytes go with the patch. They are only reachable through it, so
12189
- // keeping them would be a leak with no reader -- and these are images.
12190
- for (const key of this.files.keys()) {
12191
- if (key.startsWith(`${patchId}\u0000`)) {
12192
- this.files.delete(key);
12193
- }
12194
- }
12195
- }
12196
- }
12197
-
12198
- /*
12199
- * `\u0000` cannot occur in a patch id or a path, so the two halves of the key
12200
- * can never run together into a different pair.
12201
- *
12202
- * The PATH is normalised for the same reason `sourceFiles` is, and it is not
12203
- * cosmetic: an upload arrives as `/public/val/x.png`, and the publish step
12204
- * looks the same file up as `public/val/x.png` because that is what
12205
- * `splitRemoteRef` yields from a remote ref. `ValOpsFS` never noticed --
12206
- * `path.join` collapses the difference -- so this is another thing a
12207
- * filesystem was doing for free. Without it a remote image uploads fine,
12208
- * patches fine, and fails at publish with "No bytes held", naming a ref whose
12209
- * bytes are sitting right there under the other spelling.
12210
- */
12211
- static fileKey(patchId, filePath) {
12212
- return `${patchId}\u0000${filePath.replace(/^\//, "")}`;
12213
- }
12214
- files = new Map();
12215
- async putFile(file) {
12216
- this.files.set(InMemoryPatchStore.fileKey(file.patchId, file.filePath), file);
12217
- }
12218
- async getFile(patchId, filePath) {
12219
- return this.files.get(InMemoryPatchStore.fileKey(patchId, filePath)) ?? null;
12220
- }
12221
- async deleteFile(patchId, filePath) {
12222
- this.files.delete(InMemoryPatchStore.fileKey(patchId, filePath));
12223
- }
12224
- async filesOf(patchId) {
12225
- return [...this.files.values()].filter(file => file.patchId === patchId);
12226
- }
12227
- }
12228
10852
  /**
12229
10853
  * A `ValOps` for a host that is neither a developer's machine nor
12230
10854
  * content.val.build.
@@ -12846,606 +11470,4 @@ class ValOpsMemory extends ValOps {
12846
11470
 
12847
11471
  /** Kept exported so a host can name the error shape it may get back. */
12848
11472
 
12849
- /**
12850
- * What `redirect_to` may be on Val's routes (`/enable`, `/disable`,
12851
- * `/authorize`, `/draft/enable`, ...): a path on the site that was asked,
12852
- * which is made absolute against the request's own origin, or an absolute
12853
- * URL on that same site.
12854
- *
12855
- * A path used to go through as it was, and two things downstream need an
12856
- * absolute URL: `/authorize` reads the origin off it to build the callback,
12857
- * and Next's `NextResponse.redirect` refuses anything else. Both threw, so
12858
- * `/api/val/enable?redirect_to=/` answered 500 in a Next app.
12859
- *
12860
- * `//host/path` is a URL on another host, not a path on this one, and
12861
- * anything that is neither is refused with what is accepted instead. An
12862
- * empty value is not resolved at all: the router leaves it to the route, as
12863
- * it always was (`/logout` reads it as absent).
12864
- */
12865
-
12866
- 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).";
12867
-
12868
- /**
12869
- * `siteHosts` are the other names the request knows this site by (`Host`,
12870
- * `X-Forwarded-Host`), for a server behind a proxy whose own URL is internal.
12871
- */
12872
- function resolveRedirectTo(value, requestOrigin, siteHosts = []) {
12873
- if (value.startsWith("/") && !value.startsWith("//")) {
12874
- // A path stays on this origin. `/\host/x` also starts with one slash,
12875
- // and a URL parser reads the backslash as a second one: another host,
12876
- // not a path here.
12877
- const resolved = parsed(value, requestOrigin);
12878
- return resolved !== null && resolved.origin === new URL(requestOrigin).origin ? {
12879
- ok: true,
12880
- href: resolved.href
12881
- } : {
12882
- ok: false,
12883
- message: REDIRECT_TO_ACCEPTS
12884
- };
12885
- }
12886
- // An absolute URL, on this site only. Any URL used to pass, which made
12887
- // `/logout` and `/enable` redirect wherever a link said, and `/authorize`
12888
- // send the sign-in's code to that host: it reads the callback's origin off
12889
- // this. http(s) only: `javascript:` parses as a URL too.
12890
- const url = parsed(value);
12891
- if (url === null || url.protocol !== "https:" && url.protocol !== "http:") {
12892
- return {
12893
- ok: false,
12894
- message: REDIRECT_TO_ACCEPTS
12895
- };
12896
- }
12897
- const hosts = [new URL(requestOrigin).host, ...siteHosts].filter(host => typeof host === "string" && host !== "").map(host => host.toLowerCase());
12898
- return hosts.includes(url.host.toLowerCase()) ? {
12899
- ok: true,
12900
- href: value
12901
- } : {
12902
- ok: false,
12903
- message: REDIRECT_TO_ACCEPTS
12904
- };
12905
- }
12906
-
12907
- /**
12908
- * `value` as a URL, or null. Not `URL.canParse`: this runs in the browser
12909
- * too (demo mode), where it is missing before Safari 17 and Chrome 120.
12910
- */
12911
- function parsed(value, base) {
12912
- try {
12913
- return new URL(value, base);
12914
- } catch {
12915
- return null;
12916
- }
12917
- }
12918
-
12919
- /**
12920
- * Which requests Val's API answers in fs mode, where there is no session.
12921
- *
12922
- * fs mode reads and writes a working tree and asks nobody who they are: it is
12923
- * a developer's own machine. That holds only while the request really comes
12924
- * from that developer's Studio, and three kinds do not:
12925
- *
12926
- * - **A deployed site.** fs is the mode an app falls into when it has no
12927
- * `VAL_API_KEY` and `VAL_SECRET`, so a site deployed without them served
12928
- * this API, unauthenticated, to the internet.
12929
- * - **Another site's page**, in the developer's browser. A `text/plain` POST
12930
- * needs no preflight, and the router reads its body as JSON, so any page
12931
- * open in another tab could write to the working tree.
12932
- * - **A name that resolves to 127.0.0.1** (DNS rebinding), which makes such a
12933
- * page same-origin with the dev server as far as the browser can tell.
12934
- *
12935
- * The MCP endpoint has refused all three since it was written
12936
- * (`refuseUnsafeRequest` in `@valbuild/mcp`); this is the same rule for the
12937
- * API the Studio uses. Nothing here needs Node: `ValRouterCore` runs in a
12938
- * browser tab too, where no server is registered and nothing is refused.
12939
- */
12940
-
12941
- const guards = new WeakMap();
12942
-
12943
- /** Say how `server`'s requests are to be checked. Without it, none are. */
12944
- function setRequestGuard(server, guard) {
12945
- guards.set(server, guard);
12946
- }
12947
-
12948
- /** `VAL_ALLOWED_HOSTS`: comma separated host names, without a port. */
12949
- function parseAllowedHosts(value) {
12950
- return (value ?? "").split(",").map(host => host.trim().toLowerCase()).filter(host => host !== "");
12951
- }
12952
-
12953
- /** The refusal, or `null` when the request may go on to its route. */
12954
- function refuseUnsafeRequest(server, req, apiPath) {
12955
- var _req$method;
12956
- const guard = guards.get(server);
12957
- if (guard === undefined || guard.mode !== "fs") {
12958
- return null;
12959
- }
12960
- // Beacons are not refused: in fs mode one is checked and dropped, nothing
12961
- // is written or forwarded, and a deployed site with analytics on would fill
12962
- // every visitor's console with errors.
12963
- if (apiPath === "/analytics") {
12964
- return null;
12965
- }
12966
- if (guard.production) {
12967
- 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.");
12968
- }
12969
- const host = hostOf(req);
12970
- const forwardedHost = firstOf(req.headers.get("x-forwarded-host"));
12971
- const origin = req.headers.get("origin");
12972
- if (origin !== null) {
12973
- // `null` is the opaque origin (a sandboxed frame, a `file:` page). It
12974
- // cannot be compared with anything, so it is refused.
12975
- const originHost = origin === "null" ? null : hostOfUrl(origin);
12976
- if (originHost === null || originHost !== host && originHost !== forwardedHost) {
12977
- return refusal(`Val refused a request from another site (${origin}). In local filesystem mode the API only answers the Studio on its own address.`);
12978
- }
12979
- }
12980
- // A request with no `Origin` can still come from another site: an `<img>`,
12981
- // a script. Following a link here is not refused: sign-in comes back as
12982
- // one. A link is a GET; a form posted from another site navigates too.
12983
- const followedLink = ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === "GET" && req.headers.get("sec-fetch-mode") === "navigate";
12984
- if (req.headers.get("sec-fetch-site") === "cross-site" && !followedLink) {
12985
- return refusal("Val refused a request from another site. In local filesystem mode the API only answers the Studio on its own address.");
12986
- }
12987
- const hostname = host === null ? null : hostnameOf(host);
12988
- if (hostname === null || !isLocalName(hostname, guard.allowedHosts)) {
12989
- 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.`);
12990
- }
12991
- return null;
12992
- }
12993
- function refusal(message) {
12994
- return {
12995
- status: 403,
12996
- json: {
12997
- message
12998
- }
12999
- };
13000
- }
13001
- function firstOf(header) {
13002
- var _header$split$;
13003
- const first = header === null || header === void 0 || (_header$split$ = header.split(",")[0]) === null || _header$split$ === void 0 ? void 0 : _header$split$.trim().toLowerCase();
13004
- return first ? first : null;
13005
- }
13006
- function hostOf(req) {
13007
- const header = firstOf(req.headers.get("host"));
13008
- if (header !== null) {
13009
- return header;
13010
- }
13011
- // No Host header: the URL the framework built the request from.
13012
- return hostOfUrl(req.url);
13013
- }
13014
- function hostOfUrl(url) {
13015
- try {
13016
- return new URL(url).host.toLowerCase();
13017
- } catch {
13018
- return null;
13019
- }
13020
- }
13021
-
13022
- /** A host without its port. An IPv6 literal keeps its brackets. */
13023
- function hostnameOf(host) {
13024
- if (host.startsWith("[")) {
13025
- const end = host.indexOf("]");
13026
- return end === -1 ? host : host.slice(0, end + 1);
13027
- }
13028
- const colon = host.indexOf(":");
13029
- return colon === -1 ? host : host.slice(0, colon);
13030
- }
13031
-
13032
- /**
13033
- * localhost, an IP address, or a name the developer listed.
13034
- *
13035
- * An IP address is allowed because it cannot be rebound: a page that reaches
13036
- * this server by address is on another origin, and the `Origin` check above
13037
- * has already refused it. A phone on the same network uses one.
13038
- */
13039
- function isLocalName(hostname, allowedHosts) {
13040
- return hostname === "localhost" || hostname.endsWith(".localhost") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[") && hostname.endsWith("]") || allowedHosts.includes(hostname);
13041
- }
13042
-
13043
- /**
13044
- * Val's API as a web-standard handler: a `Request` in, a converted result out.
13045
- *
13046
- * The request handling itself -- matching a route, parsing it against `Api`,
13047
- * calling the server, checking the answer -- and nothing that needs Node, so it
13048
- * runs in a browser tab as well as on a server. That is what the demo does
13049
- * (`@valbuild/server/browser`): the Studio's own client sends its requests
13050
- * here, in the same tab, instead of over the network.
13051
- *
13052
- * `serveStatic` answers `/static/...`, the Studio's own scripts and styles.
13053
- * `createValApiRouter` passes the embedded bundle; the demo passes nothing,
13054
- * because its page loaded those from the app already.
13055
- */
13056
- function createValRequestHandler(route, valServerPromise, convert, serveStatic) {
13057
- // valServerPromise is created at module-eval time, but only awaited per request.
13058
- // Without this no-op catch, a config error (e.g. proxy mode without a project)
13059
- // rejects with no handler attached, which becomes an unhandledRejection and kills
13060
- // the dev server. The error is still reported per request by the try/catch below.
13061
- valServerPromise.catch(() => {
13062
- // handled below
13063
- });
13064
- return async req => {
13065
- let valServer;
13066
- try {
13067
- valServer = await valServerPromise;
13068
- } catch (err) {
13069
- const error = {
13070
- message: "Val: could not start the Val server",
13071
- details: err instanceof Error ? err.message : String(err)
13072
- };
13073
- Internal.log.error(error.message + ": " + error.details);
13074
- return convert({
13075
- status: 500,
13076
- json: error
13077
- });
13078
- }
13079
- const url = new URL(req.url);
13080
- if (!url.pathname.startsWith(route)) {
13081
- const error = {
13082
- message: "Val: routes are not configured correctly",
13083
- details: `Check you api routes. Expected pathname to start with "${route}", but it was: "${url.pathname}"`
13084
- };
13085
- Internal.log.error(error);
13086
- return convert({
13087
- status: 500,
13088
- json: error
13089
- });
13090
- }
13091
- const path = url.pathname.slice(route.length);
13092
- if (path === QUICK_PREVIEW_SERVICE_WORKER_PATH) {
13093
- /*
13094
- * The quick preview worker (`quickPreview.ts` in
13095
- * `@valbuild/shared`). `Service-Worker-Allowed: /` lets a script at
13096
- * this path control the whole origin, which it needs: it serves the
13097
- * page's `/_app/` files. It serves them only to a page opened as a
13098
- * quick preview, and the bridge stores them only for the site.
13099
- */
13100
- return convert({
13101
- status: 200,
13102
- headers: {
13103
- "Content-Type": "text/javascript; charset=utf-8",
13104
- "Service-Worker-Allowed": "/",
13105
- "Cache-Control": "no-cache"
13106
- },
13107
- body: QUICK_PREVIEW_SERVICE_WORKER_SOURCE
13108
- });
13109
- }
13110
- const groupQueryParams = arr => {
13111
- const map = {};
13112
- for (const [key, value] of arr) {
13113
- const list = map[key] || [];
13114
- list.push(value);
13115
- map[key] = list;
13116
- }
13117
- return map;
13118
- };
13119
- async function getValServerResponse(reqApiRoutePath, req) {
13120
- var _req$method, _anyApi$route, _anyValServer$route;
13121
- const anyApi =
13122
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
13123
- Api;
13124
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
13125
- const anyValServer = valServer;
13126
- const refused = refuseUnsafeRequest(valServer, req, reqApiRoutePath);
13127
- if (refused !== null) {
13128
- return refused;
13129
- }
13130
- const method = (_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase();
13131
- let route = null;
13132
- let path = undefined;
13133
- // An exact match wins over every prefix match, wherever it sits in
13134
- // `Api`: checked per key, in order, `/validate` took `/validate/fix`
13135
- // because it was declared first.
13136
- const exactRouteDef = Object.keys(Api).find(routeDef => routeDef === reqApiRoutePath);
13137
- for (const routeDef of exactRouteDef ? [exactRouteDef] : Object.keys(Api)) {
13138
- if (routeDef === reqApiRoutePath) {
13139
- route = routeDef;
13140
- break;
13141
- }
13142
- if (reqApiRoutePath.startsWith(routeDef)) {
13143
- var _anyApi$routeDef;
13144
- 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;
13145
- if (reqDefinition) {
13146
- route = routeDef;
13147
- if (reqDefinition.path) {
13148
- const subPath = reqApiRoutePath.slice(routeDef.length);
13149
- const pathRes = reqDefinition.path.safeParse(subPath);
13150
- if (!pathRes.success) {
13151
- return zodErrorResult(pathRes.error, `invalid path: '${subPath}' endpoint: '${routeDef}'`);
13152
- } else {
13153
- path = pathRes.data;
13154
- }
13155
- }
13156
- break;
13157
- }
13158
- }
13159
- }
13160
- if (!route) {
13161
- return {
13162
- status: 404,
13163
- json: {
13164
- message: "Route not found. Valid routes are: " + Object.keys(Api),
13165
- details: {
13166
- route,
13167
- method
13168
- }
13169
- }
13170
- };
13171
- }
13172
- const apiEndpoint = anyApi === null || anyApi === void 0 || (_anyApi$route = anyApi[route]) === null || _anyApi$route === void 0 ? void 0 : _anyApi$route[method];
13173
- const reqDefinition = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.req;
13174
- if (!reqDefinition) {
13175
- return {
13176
- status: 404,
13177
- json: {
13178
- message: `Requested method ${method} on route ${route} is not valid. Valid methods are: ${Object.keys(anyApi[route]).join(", ")}`,
13179
- details: {
13180
- route,
13181
- method
13182
- }
13183
- }
13184
- };
13185
- }
13186
- const endpointImpl = anyValServer === null || anyValServer === void 0 || (_anyValServer$route = anyValServer[route]) === null || _anyValServer$route === void 0 ? void 0 : _anyValServer$route[method];
13187
- if (!endpointImpl) {
13188
- return {
13189
- status: 500,
13190
- json: {
13191
- message: "Missing server implementation of route with method. This might be caused by a mismatch between Val package versions.",
13192
- details: {
13193
- valid: {
13194
- route: {
13195
- server: Object.keys(anyValServer || {}),
13196
- api: Object.keys(anyApi || {})
13197
- },
13198
- method: {
13199
- server: Object.keys((anyValServer === null || anyValServer === void 0 ? void 0 : anyValServer[route]) || {}),
13200
- api: Object.keys((anyApi === null || anyApi === void 0 ? void 0 : anyApi[route]) || {})
13201
- }
13202
- },
13203
- route,
13204
- method
13205
- }
13206
- }
13207
- };
13208
- }
13209
- let bodyRes;
13210
- try {
13211
- bodyRes = reqDefinition.body ? reqDefinition.body.safeParse(await readJsonBody(req)) : {
13212
- success: true,
13213
- data: {}
13214
- };
13215
- if (!bodyRes.success) {
13216
- return zodErrorResult(bodyRes.error, "invalid body data");
13217
- }
13218
- } catch (e) {
13219
- return {
13220
- status: 400,
13221
- json: {
13222
- message: "Could not parse request body",
13223
- details: {
13224
- error: JSON.stringify(e)
13225
- }
13226
- }
13227
- };
13228
- }
13229
- const cookiesRes = reqDefinition.cookies ? getCookies(req, reqDefinition.cookies) : {
13230
- success: true,
13231
- data: {}
13232
- };
13233
- if (!cookiesRes.success) {
13234
- return zodErrorResult(cookiesRes.error, "invalid cookies");
13235
- }
13236
- const headersRes = reqDefinition.headers ? getHeaders(req, reqDefinition.headers) : {
13237
- success: true,
13238
- data: {}
13239
- };
13240
- if (!headersRes.success) {
13241
- return zodErrorResult(headersRes.error, "invalid headers");
13242
- }
13243
- const actualQueryParams = groupQueryParams(Array.from(url.searchParams.entries()));
13244
- let query = {};
13245
- if (reqDefinition.query) {
13246
- const queryRules = reqDefinition.query;
13247
- const queryRes = z.object(queryRules).safeParse(actualQueryParams);
13248
- if (!queryRes.success) {
13249
- return zodErrorResult(queryRes.error, `invalid query params: (${JSON.stringify(actualQueryParams)})`);
13250
- }
13251
- query = queryRes.data;
13252
- }
13253
- // `redirect_to` is a URL or a path on this site: see `resolveRedirectTo`.
13254
- if ("redirect_to" in query && typeof query.redirect_to === "string" && query.redirect_to !== "") {
13255
- var _req$headers$get;
13256
- // Behind a proxy `url` can be an internal address: the site's own
13257
- // name is then in `Host` or `X-Forwarded-Host`.
13258
- 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()]);
13259
- if (!resolved.ok) {
13260
- return {
13261
- status: 400,
13262
- json: {
13263
- message: resolved.message
13264
- }
13265
- };
13266
- }
13267
- query = {
13268
- ...query,
13269
- redirect_to: resolved.href
13270
- };
13271
- }
13272
-
13273
- /*
13274
- * A throw from an endpoint is Val's to report, not the framework's.
13275
- *
13276
- * Nothing here used to catch, so an endpoint that threw left the router
13277
- * entirely and became whatever the host does with an unhandled error --
13278
- * and on TanStack Start that is h3, which replaces the message with the
13279
- * literal string "HTTPError" and drops the stack. Its `debug` and
13280
- * `silent` options are not reachable from out here: `requestHandler`
13281
- * calls `toResponse(value, event)` with no config, and the default is
13282
- * `{}`. So the body a caller got was
13283
- * `{"status":500,"unhandled":true,"message":"HTTPError"}` -- the same
13284
- * five words for a missing project, a bad cookie secret and a module
13285
- * that failed to link -- with the real cause only on the server's
13286
- * console.
13287
- *
13288
- * That is survivable where the console is readable. It is not in a
13289
- * Cloudflare Dynamic Worker, whose `console` reaches no tail stream: a
13290
- * link error in a lazily imported chunk (`does not provide an export
13291
- * named 'getSerovalPlugins'`) showed up as an unreadable 500 on
13292
- * `/authorize` and nowhere else at all.
13293
- *
13294
- * So every endpoint's throw becomes Val's own 500 envelope, which the
13295
- * Studio already renders and `curl` already prints. The route and method
13296
- * are named because a message rarely says which endpoint it came from.
13297
- *
13298
- * The MESSAGE travels and the STACK does not. The message is the whole
13299
- * diagnostic value -- the line above names the package, the chunk and
13300
- * the export -- while a stack is a walk through somebody's bundle, and
13301
- * `/authorize` and `/enable` are reachable without a session. So the
13302
- * stack goes to the console, where a host that can read one will find
13303
- * it, and the body carries what a caller can act on.
13304
- */
13305
- let res;
13306
- try {
13307
- res = await endpointImpl({
13308
- body: bodyRes.data,
13309
- cookies: cookiesRes.data,
13310
- headers: headersRes.data,
13311
- rawQuery: reqDefinition.rawQuery ? url.search : undefined,
13312
- query,
13313
- path
13314
- });
13315
- } catch (err) {
13316
- const error = err instanceof Error ? err : new Error(String(err));
13317
- Internal.log.error(`${method} ${route} threw: ${error.message}`, error.stack);
13318
- return {
13319
- status: 500,
13320
- json: {
13321
- message: `Val: ${method} ${route} failed: ${error.message}`,
13322
- details: {
13323
- route,
13324
- method,
13325
- error: error.message
13326
- }
13327
- }
13328
- };
13329
- }
13330
- const resDef = apiEndpoint.res;
13331
- if (res.status === 500) {
13332
- var _res$json;
13333
- /*
13334
- * A failure the route declares goes out as declared, as a success
13335
- * does below. DELETE /patches says which change was not discarded and
13336
- * which publish holds it, and collapsed to its message the Studio
13337
- * could only say "Failed to delete patches" -- not why, nor offer to
13338
- * cancel that publish. Anything undeclared is still reduced to its
13339
- * message.
13340
- */
13341
- if (resDef !== null && resDef !== void 0 && resDef.safeParse(res).success) return res;
13342
- return {
13343
- status: 500,
13344
- json: {
13345
- message: ((_res$json = res.json) === null || _res$json === void 0 ? void 0 : _res$json.message) || "Internal Server Error"
13346
- }
13347
- };
13348
- }
13349
- if (resDef) {
13350
- const responseResult = resDef.safeParse(res);
13351
- if (!responseResult.success) {
13352
- return {
13353
- status: 500,
13354
- json: {
13355
- message: "Could not validate response. This is likely a bug in Val server.",
13356
- details: {
13357
- response: res,
13358
- errors: formatZodErrorString(responseResult.error)
13359
- }
13360
- }
13361
- };
13362
- }
13363
- }
13364
- return res;
13365
- }
13366
- if (path.startsWith("/static")) {
13367
- if (!serveStatic) {
13368
- return convert({
13369
- status: 404,
13370
- json: {
13371
- message: "Val: this server does not serve the Studio's own files"
13372
- }
13373
- });
13374
- }
13375
- return convert(await serveStatic(path.slice("/static".length), url.href));
13376
- } else {
13377
- return convert(await getValServerResponse(path, req));
13378
- }
13379
- };
13380
- }
13381
- function formatZodErrorString(error) {
13382
- const errors = fromError(error).toString();
13383
- return errors.length > 640 ? `${errors.slice(0, 640)}...` : errors;
13384
- }
13385
-
13386
- /**
13387
- * The request's JSON body, or `undefined` when it has none.
13388
- *
13389
- * `req.json()` THROWS on an empty body, and the router used to call it
13390
- * unconditionally for any route that declares a body — so the moment
13391
- * `DELETE /patches` gained an optional body, every caller that sent none got
13392
- * `400 Could not parse request body`. Declaring the schema `.optional()` did
13393
- * not help: the throw happens before zod is ever consulted. Six e2e tests went
13394
- * red on a helper doing exactly what the route still permits.
13395
- *
13396
- * Told apart by the request rather than by catching, so a body that IS sent and
13397
- * is malformed still fails: absent means no content type and nothing to read,
13398
- * and anything else is parsed and allowed to throw. A route whose schema
13399
- * requires a body is unaffected — it gets `undefined` and zod refuses it, with
13400
- * the same 400 as before, now naming the field.
13401
- */
13402
- async function readJsonBody(req) {
13403
- if (req.headers.get("content-length") === "0") {
13404
- return undefined;
13405
- }
13406
- const text = await req.text();
13407
- if (text.length === 0) {
13408
- return undefined;
13409
- }
13410
- return JSON.parse(text);
13411
- }
13412
- function zodErrorResult(error, message) {
13413
- return {
13414
- status: 400,
13415
- json: {
13416
- message: "Bad Request: " + message,
13417
- details: {
13418
- errors: formatZodErrorString(error)
13419
- }
13420
- }
13421
- };
13422
- }
13423
-
13424
- // TODO: is this naive implementation is too naive?
13425
- /** The declared headers, by name; `Headers.get` is case-insensitive. */
13426
- function getHeaders(req, headersDef) {
13427
- const input = {};
13428
- for (const name of Object.keys(headersDef)) {
13429
- var _req$headers;
13430
- const value = (_req$headers = req.headers) === null || _req$headers === void 0 ? void 0 : _req$headers.get(name);
13431
- if (value !== null && value !== undefined) {
13432
- input[name] = value;
13433
- }
13434
- }
13435
- return z.object(headersDef).safeParse(input);
13436
- }
13437
- function getCookies(req, cookiesDef) {
13438
- var _req$headers2;
13439
- const input = {};
13440
- 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("; ");
13441
- for (const name of Object.keys(cookiesDef)) {
13442
- const cookie = cookieParts === null || cookieParts === void 0 ? void 0 : cookieParts.find(cookie => cookie.startsWith(`${name}=`));
13443
- const value = cookie ? decodeURIComponent(cookie === null || cookie === void 0 ? void 0 : cookie.split("=")[1]) : undefined;
13444
- if (value) {
13445
- input[name.trim()] = value;
13446
- }
13447
- }
13448
- return z.object(cookiesDef).safeParse(input);
13449
- }
13450
-
13451
- 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 };