@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
@@ -3,8 +3,10 @@
3
3
  var core = require('@valbuild/core');
4
4
  var z = require('zod');
5
5
  var internal = require('@valbuild/shared/internal');
6
+ var jsonValuesPatch = require('./jsonValuesPatch-88bc661d.cjs.dev.js');
6
7
  var zodValidationError = require('zod-validation-error');
7
8
  var fp = require('@valbuild/core/fp');
9
+ var ValPatchStore = require('./ValPatchStore-df8cdbe7.cjs.dev.js');
8
10
  var patch = require('@valbuild/core/patch');
9
11
  var sizeOf = require('image-size');
10
12
 
@@ -12,278 +14,6 @@ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e };
12
14
 
13
15
  var sizeOf__default = /*#__PURE__*/_interopDefault(sizeOf);
14
16
 
15
- /**
16
- * `path.posix`, for the four functions the request handlers use.
17
- *
18
- * Node's `path` cannot be bundled for a browser, and the request handlers run
19
- * in one for the demo (`@valbuild/server/browser`). These are Node's own posix
20
- * algorithms, and `posixPath.test.ts` checks them against `path.posix` itself,
21
- * so the two cannot differ quietly. Module paths are always posix -- `/app/
22
- * page.val.ts` on Windows too -- so nothing here needs the platform's `path`.
23
- */
24
-
25
- /** Resolves `.` and `..` segments, as Node's `normalizeString` does. */
26
- function normalizeSegments(path, allowAboveRoot) {
27
- let res = "";
28
- let lastSegmentLength = 0;
29
- let lastSlash = -1;
30
- let dots = 0;
31
- let code = 0;
32
- for (let i = 0; i <= path.length; ++i) {
33
- if (i < path.length) {
34
- code = path.charCodeAt(i);
35
- } else if (code === 47 /* / */) {
36
- break;
37
- } else {
38
- code = 47;
39
- }
40
- if (code === 47) {
41
- if (lastSlash === i - 1 || dots === 1) ; else if (dots === 2) {
42
- if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /* . */ || res.charCodeAt(res.length - 2) !== 46) {
43
- if (res.length > 2) {
44
- const lastSlashIndex = res.lastIndexOf("/");
45
- if (lastSlashIndex === -1) {
46
- res = "";
47
- lastSegmentLength = 0;
48
- } else {
49
- res = res.slice(0, lastSlashIndex);
50
- lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
51
- }
52
- lastSlash = i;
53
- dots = 0;
54
- continue;
55
- } else if (res.length !== 0) {
56
- res = "";
57
- lastSegmentLength = 0;
58
- lastSlash = i;
59
- dots = 0;
60
- continue;
61
- }
62
- }
63
- if (allowAboveRoot) {
64
- res += res.length > 0 ? "/.." : "..";
65
- lastSegmentLength = 2;
66
- }
67
- } else {
68
- if (res.length > 0) {
69
- res += "/" + path.slice(lastSlash + 1, i);
70
- } else {
71
- res = path.slice(lastSlash + 1, i);
72
- }
73
- lastSegmentLength = i - lastSlash - 1;
74
- }
75
- lastSlash = i;
76
- dots = 0;
77
- } else if (code === 46 && dots !== -1) {
78
- ++dots;
79
- } else {
80
- dots = -1;
81
- }
82
- }
83
- return res;
84
- }
85
- function normalize(path) {
86
- if (path.length === 0) return ".";
87
- const isAbsolute = path.charCodeAt(0) === 47;
88
- const trailingSeparator = path.charCodeAt(path.length - 1) === 47;
89
- let normalized = normalizeSegments(path, !isAbsolute);
90
- if (normalized.length === 0) {
91
- if (isAbsolute) return "/";
92
- return trailingSeparator ? "./" : ".";
93
- }
94
- if (trailingSeparator) normalized += "/";
95
- return isAbsolute ? `/${normalized}` : normalized;
96
- }
97
- function join(...paths) {
98
- const joined = paths.filter(path => path.length > 0).join("/");
99
- return joined.length === 0 ? "." : normalize(joined);
100
- }
101
- function dirname(path) {
102
- if (path.length === 0) return ".";
103
- const hasRoot = path.charCodeAt(0) === 47;
104
- let end = -1;
105
- let matchedSlash = true;
106
- for (let i = path.length - 1; i >= 1; --i) {
107
- if (path.charCodeAt(i) === 47) {
108
- if (!matchedSlash) {
109
- end = i;
110
- break;
111
- }
112
- } else {
113
- matchedSlash = false;
114
- }
115
- }
116
- if (end === -1) return hasRoot ? "/" : ".";
117
- if (hasRoot && end === 1) return "//";
118
- return path.slice(0, end);
119
- }
120
-
121
- /**
122
- * Node resolves both sides against `process.cwd()` first. When both are
123
- * relative the cwd is a common prefix and drops out of the answer, so a root
124
- * stands in for it; when only one is, the answer depends on a directory a
125
- * browser does not have, and it is refused rather than guessed.
126
- */
127
- function resolveBoth(from, to) {
128
- const fromAbsolute = from.charCodeAt(0) === 47;
129
- const toAbsolute = to.charCodeAt(0) === 47;
130
- if (fromAbsolute !== toAbsolute) {
131
- throw new Error(`posixPath.relative needs two absolute or two relative paths, got '${from}' and '${to}'.`);
132
- }
133
- const root = path => `/${normalizeSegments(fromAbsolute ? path : `/${path}`, false)}`;
134
- return [root(from), root(to)];
135
- }
136
- function relative(from, to) {
137
- if (from === to) return "";
138
- [from, to] = resolveBoth(from, to);
139
- if (from === to) return "";
140
- const fromStart = 1;
141
- const fromEnd = from.length;
142
- const fromLen = fromEnd - fromStart;
143
- const toStart = 1;
144
- const toLen = to.length - toStart;
145
- const length = fromLen < toLen ? fromLen : toLen;
146
- let lastCommonSep = -1;
147
- let i = 0;
148
- for (; i < length; i++) {
149
- const fromCode = from.charCodeAt(fromStart + i);
150
- if (fromCode !== to.charCodeAt(toStart + i)) break;else if (fromCode === 47) lastCommonSep = i;
151
- }
152
- if (i === length) {
153
- if (toLen > length) {
154
- if (to.charCodeAt(toStart + i) === 47) {
155
- return to.slice(toStart + i + 1);
156
- }
157
- if (i === 0) {
158
- return to.slice(toStart + i);
159
- }
160
- } else if (fromLen > length) {
161
- if (from.charCodeAt(fromStart + i) === 47) {
162
- lastCommonSep = i;
163
- } else if (i === 0) {
164
- lastCommonSep = 0;
165
- }
166
- }
167
- }
168
- let out = "";
169
- for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
170
- if (i === fromEnd || from.charCodeAt(i) === 47) {
171
- out += out.length === 0 ? ".." : "/..";
172
- }
173
- }
174
- return `${out}${to.slice(toStart + lastCommonSep)}`;
175
- }
176
- const posixPath = {
177
- normalize,
178
- join,
179
- dirname,
180
- relative
181
- };
182
-
183
- /**
184
- * Finds every `.jsonValues()` record in a module's schema that is NOT the
185
- * module's root, returning the path to each within the module source.
186
- *
187
- * `.jsonValues()` is only supported on a module's ROOT record/router: the
188
- * `/json` endpoint keys entries by a single string, the Studio substitutes
189
- * loaded content at the top level of the module source, and
190
- * `validateJsonValuesEntries` only visits a root record. A nested one would
191
- * silently skip content validation and hang the Studio on a 404, so we reject
192
- * it up front instead (see {@link ValOps.initSources}).
193
- */
194
- function findNestedJsonValuesRecords(schema, path = []) {
195
- const found = [];
196
- const rec = (current, currentPath) => {
197
- if (current.type === "record" && current.jsonValues && currentPath.length > 0) {
198
- found.push(currentPath);
199
- // Do not descend: everything below lives in the entry's `*.val.json`.
200
- return;
201
- }
202
- switch (current.type) {
203
- case "object":
204
- for (const key of Object.keys(current.items)) {
205
- rec(current.items[key], currentPath.concat(key));
206
- }
207
- return;
208
- case "record":
209
- rec(current.item, currentPath.concat("*"));
210
- return;
211
- case "array":
212
- rec(current.item, currentPath.concat("*"));
213
- return;
214
- case "discriminated-union":
215
- for (let i = 0; i < current.items.length; i++) {
216
- rec(current.items[i], currentPath.concat(`union[${i}]`));
217
- }
218
- return;
219
- default:
220
- return;
221
- }
222
- };
223
- rec(schema, path);
224
- return found;
225
- }
226
-
227
- /**
228
- * The `.val.ts` suffix a module file path ends with. Stripping it yields the
229
- * folder that a new entry's `*.val.json` files are nested under.
230
- */
231
- const VAL_TS_SUFFIX = ".val.ts";
232
-
233
- /**
234
- * Computes the `*.val.json` file path (relative to rootDir) and the `import(...)`
235
- * path (relative to the module's directory) for a NEW `.jsonValues()` entry,
236
- * following the locked filename convention: the file mirrors the entry key under
237
- * a folder named after the `.val.ts` (its `.val.ts` suffix becomes the folder).
238
- *
239
- * For module `/app/support/[slug]/page.val.ts` and key `/support/faq`:
240
- * - jsonPath: `/app/support/[slug]/page/support/faq.val.json`
241
- * - importPath: `./page/support/faq.val.json`
242
- */
243
- function getNewJsonEntryPaths(moduleFilePath, entryKey) {
244
- const base = moduleFilePath.endsWith(VAL_TS_SUFFIX) ? moduleFilePath.slice(0, -VAL_TS_SUFFIX.length) : moduleFilePath;
245
- const keyRel = entryKey.replace(/^\//, "");
246
- const invalid = reason => fp.result.err({
247
- message: `Invalid .jsonValues() entry key '${entryKey}' in ${moduleFilePath}: ${reason}`,
248
- filePath: moduleFilePath
249
- });
250
- // An entry key is CLIENT-SUPPLIED — it arrives as a record key in a patch op —
251
- // and this path is what the commit writes to disk. Left unchecked, a key with
252
- // `..` segments (or a backslash, which is a separator once the path is handed
253
- // to node's `path.join` on Windows) puts that write anywhere in the project or
254
- // outside it entirely, and a `move` additionally deletes the source path.
255
- if (keyRel === "") {
256
- return invalid("it is empty");
257
- }
258
- if (keyRel.includes("\\") || keyRel.includes("\0")) {
259
- return invalid("it contains a backslash or a NUL byte");
260
- }
261
- const jsonPath = posixPath.normalize(`${base}/${keyRel}.val.json`);
262
- if (!jsonPath.startsWith(`${base}/`)) {
263
- return invalid(`it resolves outside '${base}/'`);
264
- }
265
- const moduleDir = posixPath.dirname(moduleFilePath);
266
- let importPath = posixPath.relative(moduleDir, jsonPath);
267
- if (!importPath.startsWith(".")) {
268
- importPath = `./${importPath}`;
269
- }
270
- return fp.result.ok({
271
- jsonPath,
272
- importPath
273
- });
274
- }
275
-
276
- /**
277
- * Resolves an EXISTING entry's `*.val.json` path (relative to rootDir) from the
278
- * `import(...)` path recorded in the `.val.ts` thunk (from
279
- * {@link analyzeJsonValuesEntries}). Existing files may have been hand-placed,
280
- * so the import path is authoritative (hybrid authoring).
281
- */
282
- function resolveExistingJsonPath(moduleFilePath, importPath) {
283
- const moduleDir = posixPath.dirname(moduleFilePath);
284
- return posixPath.join(moduleDir, importPath);
285
- }
286
-
287
17
  /**
288
18
  * The outcome of {@link validateJsonValuesEntries}: the errors found inside the
289
19
  * entries, plus the content of every entry that could be loaded, keyed by entry
@@ -1025,7 +755,7 @@ function rewriteUri(uri, {
1025
755
  return uri;
1026
756
  }
1027
757
  // `join` from an absolute directory stays absolute: `..` stops at the root.
1028
- const resolved = posixPath.join(posixPath.dirname(playlistPath), relative);
758
+ const resolved = jsonValuesPatch.posixPath.join(jsonValuesPatch.posixPath.dirname(playlistPath), relative);
1029
759
  return `/api/val/files${resolved}?patch_id=${patchId}${remote ? "&remote=true" : ""}`;
1030
760
  }
1031
761
 
@@ -1749,1030 +1479,15 @@ function hostName(host) {
1749
1479
  }
1750
1480
  }
1751
1481
  function isStale(parsed, schema, value) {
1752
- // The hash covers only these of what was recorded (`getValidationBasis`):
1753
- // `alt` and `hotspot` are the editor's, and change no byte.
1754
- const metadata = {
1755
- width: value.width,
1756
- height: value.height,
1757
- mimeType: value.mimeType
1758
- };
1759
- const expected = core.Internal.remote.getValidationHash(parsed.version, schema, getFileExt(parsed.filePath), metadata, parsed.fileHash, textEncoder);
1760
- return expected !== parsed.validationHash;
1761
- }
1762
-
1763
- /**
1764
- * The patches a json entry render should apply, out of the whole chain:
1765
- *
1766
- * 1. this module's, since the chain is branch-wide;
1767
- * 2. a patch published after this build is kept: this build does not have it.
1768
- * One already in the build is dropped. `draftOverlay` decides which is
1769
- * which, from `commits`.
1770
- */
1771
-
1772
- /**
1773
- * The patches a DRAFT applies on top of this build's own source: the pending
1774
- * ones, and the ones published AFTER this build, in chain order -- with
1775
- * `appliedAt` cleared on the latter, because this build has none of them.
1776
- *
1777
- * Content places every caller at its own build (`getApplicablePatchesAndCommits`
1778
- * in valbuild/home: "the earliest the caller has not seen") and returns the
1779
- * commits after it as `commits`. A patch applied at one of those was
1780
- * published after this build and is not in it, so a draft has to apply it --
1781
- * skipping it showed the build's old value from the publish until the next
1782
- * build went live. `/sources/~` already applies them (`getSources` walks every
1783
- * patch it is given); the `.jsonValues()` entry path skipped them.
1784
- *
1785
- * A patch applied at a commit NOT in that list is already in this build --
1786
- * content returns one only because it was asked for by id -- and is dropped:
1787
- * applying it again would apply it twice. Without `commits` (a store that
1788
- * does not report them) every applied patch is dropped, as before. Only
1789
- * `ValOpsHttp` ever reports `appliedAt`; `fs` and memory stores report `null`.
1790
- *
1791
- * Chain order, not published-first, because that is the order the Studio
1792
- * applies them in, and a draft page starts from the server's answer and is
1793
- * then kept up to date by the Studio's: the two must agree.
1794
- *
1795
- * For the reads that render a draft only. What to COMMIT still keys on
1796
- * `appliedAt`: a published patch must never be published again.
1797
- */
1798
- function draftOverlay(patches, commits) {
1799
- const afterThisBuild = new Set((commits ?? []).map(commit => commit.commitSha));
1800
- const overlay = [];
1801
- for (const patch of patches) {
1802
- if (patch.appliedAt === null) {
1803
- overlay.push(patch);
1804
- } else if (afterThisBuild.has(patch.appliedAt.commitSha)) {
1805
- overlay.push({
1806
- ...patch,
1807
- appliedAt: null
1808
- });
1809
- }
1810
- }
1811
- return overlay;
1812
- }
1813
-
1814
- /*
1815
- * THE HEAD: the content at the newest chain, in the module store. See
1816
- * `docs/plans/one-content-model.md`, "One runtime per process, and the head".
1817
- *
1818
- * One per data layer (`ValOps`), and so one per process for a project
1819
- * (`valRuntime`): the API route, the draft readers and MCP read through the
1820
- * same one, so a save moves every reader, and one head serves every editor --
1821
- * draft content is not per user; the session only decides who may see it.
1822
- *
1823
- * In a 128 MB isolate it grows only with what was edited:
1824
- *
1825
- * 1. An unpatched module costs nothing: the bundle tier answers with the
1826
- * bundle's own object, which the process holds for every visitor anyway.
1827
- * 2. A module is materialized when it is read and has patches, never all at
1828
- * once, and the next version of its chain is EXTENDED from the one before
1829
- * by the new patches alone.
1830
- * 3. A discard replays one module from its base through its own patches.
1831
- * 4. The memory tier's byte budget ({@link HEAD_BUDGET_BYTES}) lets go of the
1832
- * least recently read module, which is made again on its next read; and
1833
- * it keeps the last {@link HEAD_VERSIONS_PER_MODULE} versions of each.
1834
- * 5. No validation and no previews on the read path. They are their own
1835
- * requests (`/validate`, the Studio's own previews).
1836
- *
1837
- * "Has the chain moved?" is `seq` alone (`ValOps.chainSeq`): a counter in fs
1838
- * and memory mode, one small read of the content service in http mode. The
1839
- * chain is fetched only when it moved.
1840
- */
1841
-
1842
- /**
1843
- * What the head may hold beyond what the build holds anyway: 16 MB, about
1844
- * where a deployed isolate beside 64 MB of other heap stopped outliving a
1845
- * validated whole-tree draft read (`scenarios/measure/results.md`, "The
1846
- * deployed isolate").
1847
- */
1848
- const HEAD_BUDGET_BYTES = 16 * 1024 * 1024;
1849
-
1850
- /** The current version of each module and the one before it. */
1851
- const HEAD_VERSIONS_PER_MODULE = 2;
1852
-
1853
- /**
1854
- * Counted work, in this process, for every head: never reset, so two readers
1855
- * of it cannot disturb each other. A test takes it before and after.
1856
- */
1857
- const counted = {
1858
- /** "Has the chain moved?" asked. */
1859
- seqReads: 0,
1860
- /** The chain fetched, because it had. */
1861
- chainReads: 0,
1862
- /** Modules made from a base or an older version. */
1863
- materialized: 0,
1864
- /** Of those, made by extending the version before by the new patches alone. */
1865
- extended: 0,
1866
- /**
1867
- * A record's whole key list walked: once per record object (a base, a
1868
- * version), never per request -- see {@link recordKeysOf}.
1869
- */
1870
- recordScans: 0,
1871
- /** `.jsonValues()` entries resolved: once per entry and version. */
1872
- entriesResolved: 0
1873
- };
1874
- const recordKeys = new WeakMap();
1875
-
1876
- /**
1877
- * A record's keys, in order: walked once per record OBJECT and kept beside
1878
- * it. A record is immutable (a base, or a version the engine made), so the
1879
- * same object has the same keys for good -- and an entry request, which only
1880
- * needs the count (`total`) or a window of them, costs what it asks for,
1881
- * not the size of the record. Before, every `GET /json` walked the whole
1882
- * record (`Object.keys`), so reading 10,000 entries one request at a time
1883
- * was 10,000 x 10,000 (phase 10's baseline).
1884
- */
1885
- function recordKeysOf(record) {
1886
- let keys = recordKeys.get(record);
1887
- if (keys === undefined) {
1888
- counted.recordScans++;
1889
- keys = Object.keys(record);
1890
- recordKeys.set(record, keys);
1891
- }
1892
- return keys;
1893
- }
1894
-
1895
- /** See {@link counted}. */
1896
- function headWork() {
1897
- return {
1898
- ...counted
1899
- };
1900
- }
1901
-
1902
- /** The chain, as the head last read it. */
1903
-
1904
- /** What the head knows about a module it made, beside its content. */
1905
-
1906
- /** A module as the head answers it. */
1907
-
1908
- /**
1909
- * What a draft reader is given for a module: the bundle's own (read the
1910
- * bundle), or the head's source in its wire shape -- `.jsonValues()` markers
1911
- * without their `import()`, and the entries the draft changes in place of
1912
- * theirs.
1913
- */
1914
-
1915
- /** One entry, as `/json` and the draft readers answer it. */
1916
-
1917
- class ValHead {
1918
- memory;
1919
- store;
1920
- facts = new WeakMap();
1921
- chain = null;
1922
- fetching = null;
1923
- serialized = null;
1924
- wholeTree = null;
1925
- constructor(ops, opts = {}) {
1926
- this.ops = ops;
1927
- this.memory = internal.memoryTier({
1928
- budgetBytes: opts.budgetBytes ?? HEAD_BUDGET_BYTES,
1929
- lastPerModule: opts.lastPerModule ?? HEAD_VERSIONS_PER_MODULE
1930
- });
1931
- this.store = internal.tiered([this.memory, internal.bundleTier(path => this.ops.bundleModule(path)),
1932
- // What the build serves where it is not the bundle: a content version,
1933
- // a proposal's saves, a publish adopted in this process.
1934
- internal.bundleTier(path => this.ops.baseModule(path), "base")]);
1935
- }
1936
-
1937
- /** What the head holds now. */
1938
- stats() {
1939
- return this.memory.stats();
1940
- }
1941
-
1942
- // #region the chain
1943
-
1944
- /**
1945
- * The chain, re-read only when `seq` moved (or the base did: a publish
1946
- * adopted). A read that finds a fetch already under way at the `seq` it
1947
- * saw joins it: that fetch reads at that `seq` or later.
1948
- *
1949
- * Asks "has the chain moved?" once per call -- in http mode one request to
1950
- * the content service. A caller that reads several modules for ONE answer
1951
- * (a draft page's request) syncs once and passes the chain it got to
1952
- * {@link draft}, {@link entries} and {@link changed}, so a page of thirty
1953
- * modules asks once, not thirty times, and reads all of them at one chain.
1954
- */
1955
- async sync() {
1956
- counted.seqReads++;
1957
- const [position, base] = await Promise.all([this.ops.chainPosition(), this.ops.getSourcesSha()]);
1958
- const held = this.chain;
1959
- if (held !== null && position !== null && held.seq === position.seq && held.epoch === position.epoch && held.base === base) {
1960
- return {
1961
- ok: held
1962
- };
1963
- }
1964
- const fetching = this.fetching;
1965
- if (position !== null && fetching !== null && fetching.seq === position.seq && fetching.epoch === position.epoch) {
1966
- return fetching.promise;
1967
- }
1968
- const promise = this.fetchChain(position, base);
1969
- if (position !== null) {
1970
- const started = {
1971
- ...position,
1972
- promise
1973
- };
1974
- this.fetching = started;
1975
- // Cleared however it ends. `finally` would hand on a rejection to a
1976
- // promise nobody holds: an unhandled rejection, which ends a Node
1977
- // process. The caller is handed `promise` itself, and sees it.
1978
- const done = () => {
1979
- if (this.fetching === started) this.fetching = null;
1980
- };
1981
- promise.then(done, done);
1982
- }
1983
- return promise;
1984
- }
1985
-
1986
- /** The chain a read is answered at: the one given, or the newest. */
1987
- at(chain) {
1988
- return chain !== undefined ? Promise.resolve({
1989
- ok: chain
1990
- }) : this.sync();
1991
- }
1992
- async fetchChain(position, base) {
1993
- counted.chainReads++;
1994
- const before = await this.ops.projectVersion();
1995
- const fetched = await this.ops.fetchPatches({
1996
- excludePatchOps: false
1997
- });
1998
- if (fetched.error) {
1999
- return {
2000
- error: {
2001
- message: fetched.error.message,
2002
- ...(fetched.unauthorized ? {
2003
- unauthorized: true
2004
- } : {}),
2005
- ...(fetched.networkError ? {
2006
- networkError: true
2007
- } : {})
2008
- }
2009
- };
2010
- }
2011
- const overlay = draftOverlay(fetched.patches, fetched.commits);
2012
- const byModule = new Map();
2013
- for (const patch of overlay) {
2014
- const records = byModule.get(patch.path);
2015
- if (records === undefined) byModule.set(patch.path, [patch]);else records.push(patch);
2016
- }
2017
- const versions = await this.ops.moduleVersions(overlay);
2018
- const project = fetched.headVersion !== undefined ? {
2019
- build: before.build,
2020
- seq: fetched.headVersion
2021
- } : before;
2022
- const chain = {
2023
- seq: fetched.headVersion ?? (position === null || position === void 0 ? void 0 : position.seq) ?? null,
2024
- epoch: (position === null || position === void 0 ? void 0 : position.epoch) ?? "",
2025
- base,
2026
- project,
2027
- fetched,
2028
- overlay,
2029
- byModule,
2030
- versions,
2031
- analysis: this.ops.analyzePatches(overlay)
2032
- };
2033
- // Never put back an older chain over a newer one read meanwhile. A
2034
- // counter that started again (another epoch) orders nothing against
2035
- // the one before it: the chain read last is the newest.
2036
- if (this.chain === null || this.chain.base !== base || this.chain.epoch !== chain.epoch || this.chain.project.seq <= project.seq) {
2037
- this.chain = chain;
2038
- }
2039
- return {
2040
- ok: chain
2041
- };
2042
- }
2043
-
2044
- /**
2045
- * Every module's serialized schema, serialized once per data layer (a new
2046
- * build is a new one): what the engine reads `.jsonValues()` records from,
2047
- * and MCP's tools their schemas.
2048
- */
2049
- serializedSchemas() {
2050
- this.serialized ??= this.ops.getSchemas().then(schemas => {
2051
- const serialized = {};
2052
- for (const [path, schema] of Object.entries(schemas)) {
2053
- try {
2054
- serialized[path] = schema["executeSerialize"]();
2055
- } catch {
2056
- // Reported elsewhere; read as "no schema", as the engine does.
2057
- serialized[path] = undefined;
2058
- }
2059
- }
2060
- return serialized;
2061
- });
2062
- return this.serialized;
2063
- }
2064
-
2065
- // #region modules
2066
-
2067
- /**
2068
- * A module at the newest chain (or at `chain`, from {@link sync}), or
2069
- * `null` when there is no such module.
2070
- */
2071
- async module(path, chain) {
2072
- const synced = await this.at(chain);
2073
- if ("error" in synced) return synced;
2074
- return {
2075
- ok: await this.moduleIn(synced.ok, path)
2076
- };
2077
- }
2078
- async moduleIn(chain, path) {
2079
- const asked = versionIn(chain, path);
2080
- if (asked === undefined) return null;
2081
- const records = chain.byModule.get(path) ?? [];
2082
- const key = internal.moduleKey(path, asked);
2083
- const found = await this.store.get(key);
2084
- if (found !== null) {
2085
- const facts = this.factsOf(found);
2086
- return {
2087
- module: found,
2088
- asked,
2089
- failed: facts.failed,
2090
- applied: facts.applied,
2091
- records
2092
- };
2093
- }
2094
- const made = await this.make(path, asked, records);
2095
- this.memory.put(key, made, made.bytes);
2096
- const facts = this.factsOf(made);
2097
- return {
2098
- module: made,
2099
- asked,
2100
- failed: facts.failed,
2101
- applied: facts.applied,
2102
- records
2103
- };
2104
- }
2105
-
2106
- /**
2107
- * A module at `asked`, from the newest version held of the same base when
2108
- * its chain is a start of this one (a keystroke: the new patch alone), and
2109
- * from its base otherwise (a discard, a publish, an eviction).
2110
- */
2111
- async make(path, asked, records) {
2112
- var _await$this$ops$baseM;
2113
- counted.materialized++;
2114
- const schema = (await this.serializedSchemas())[path];
2115
- const isRecord = (schema === null || schema === void 0 ? void 0 : schema.type) === "record" && schema.jsonValues === true;
2116
- let start = null;
2117
- const latest = this.memory.latest(path);
2118
- 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) => {
2119
- var _records$i;
2120
- return ((_records$i = records[i]) === null || _records$i === void 0 ? void 0 : _records$i.patchId) === id;
2121
- })) {
2122
- start = latest;
2123
- counted.extended++;
2124
- }
2125
- if (start === null) {
2126
- start = await this.store.get(internal.moduleKey(path, {
2127
- ...asked,
2128
- chain: internal.EMPTY_CHAIN
2129
- }));
2130
- }
2131
- if (start === null) {
2132
- // No base for this version: the module as the build serves it.
2133
- const base = await this.ops.baseModule(path);
2134
- start = {
2135
- path,
2136
- version: {
2137
- ...asked,
2138
- chain: internal.EMPTY_CHAIN
2139
- },
2140
- content: internal.baseModuleContent((base === null || base === void 0 ? void 0 : base.source) ?? null),
2141
- patches: [],
2142
- bytes: 0
2143
- };
2144
- }
2145
- const startFacts = this.factsOf(start);
2146
- let content = start.content;
2147
- const ids = [...start.patches];
2148
- let failed = null;
2149
- let entryChains = startFacts.entryChains;
2150
- let wholeChain = startFacts.wholeChain;
2151
- for (const record of records.slice(start.patches.length)) {
2152
- const res = internal.applyPatchRecord(content, record, schema);
2153
- if (res.status === "failed") {
2154
- failed = {
2155
- patchId: res.patchId,
2156
- message: res.message
2157
- };
2158
- break;
2159
- }
2160
- if (isRecord) {
2161
- const touched = touchedEntries(content, res.module);
2162
- if (touched === "all") {
2163
- wholeChain = internal.extendChain(wholeChain, record.patchId);
2164
- entryChains = new Map();
2165
- } else if (touched.length > 0) {
2166
- const next = new Map(entryChains);
2167
- for (const key of touched) {
2168
- next.set(key, internal.extendChain(entryChains.get(key) ?? wholeChain, record.patchId));
2169
- }
2170
- entryChains = next;
2171
- }
2172
- }
2173
- content = res.module;
2174
- ids.push(record.patchId);
2175
- }
2176
- 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;
2177
- const bytes = heldBeyond(base, content.source) + entriesBytes(content);
2178
- const version = failed === null ? asked : {
2179
- ...asked,
2180
- chain: this.ops.chainAt(path, ids.length)
2181
- };
2182
- const made = {
2183
- path,
2184
- version,
2185
- content,
2186
- patches: ids,
2187
- bytes
2188
- };
2189
- this.facts.set(made, {
2190
- failed,
2191
- applied: ids.length,
2192
- entryChains,
2193
- wholeChain,
2194
- resolved: new Map(),
2195
- draft: null
2196
- });
2197
- return made;
2198
- }
2199
- factsOf(module) {
2200
- let facts = this.facts.get(module);
2201
- if (facts === undefined) {
2202
- facts = {
2203
- failed: null,
2204
- applied: module.patches.length,
2205
- entryChains: new Map(),
2206
- wholeChain: internal.EMPTY_CHAIN,
2207
- resolved: new Map(),
2208
- draft: null
2209
- };
2210
- this.facts.set(module, facts);
2211
- }
2212
- return facts;
2213
- }
2214
-
2215
- // #region entries
2216
-
2217
- /**
2218
- * `.jsonValues()` entries at the newest chain (or at `chain`, from
2219
- * {@link sync}), by key: what the module's chain made of each, and for an
2220
- * entry it holds edits for but nobody has loaded, those edits on the base
2221
- * entry. Made once per entry and version.
2222
- */
2223
- async entries(path, keys, chain) {
2224
- const synced = await this.at(chain);
2225
- if ("error" in synced) {
2226
- return {
2227
- status: "error",
2228
- message: synced.error.message
2229
- };
2230
- }
2231
- return this.entriesIn(synced.ok, path, keys);
2232
- }
2233
- async entriesIn(chain, path, keys) {
2234
- if (chain.fetched.errors && chain.fetched.errors.length > 0) {
2235
- return {
2236
- status: "error",
2237
- message: `Could not fetch patches: ${JSON.stringify(chain.fetched.errors)}`
2238
- };
2239
- }
2240
- const base = await this.ops.baseModule(path);
2241
- if (base === null || base.source === null || typeof base.source !== "object" || Array.isArray(base.source)) {
2242
- return {
2243
- status: "not-found",
2244
- message: base === null || base.source === null ? `Module not found: ${path}` : `Module is not a record: ${path}`
2245
- };
2246
- }
2247
- const held = await this.moduleIn(chain, path);
2248
- if (held === null) {
2249
- return {
2250
- status: "not-found",
2251
- message: `Module not found: ${path}`
2252
- };
2253
- }
2254
- const record = base.source;
2255
- const facts = this.factsOf(held.module);
2256
- const value = {
2257
- entries: [],
2258
- missing: [],
2259
- errors: [],
2260
- total: recordKeysOf(record).length,
2261
- version: held.module.version,
2262
- entryVersions: {}
2263
- };
2264
- const reads = new Map();
2265
- await Promise.all(keys.map(async key => {
2266
- reads.set(key, await this.resolved(path, record, held.module, key));
2267
- }));
2268
- for (const key of keys) {
2269
- const marker = record[key];
2270
- if (marker !== undefined && !core.Internal.isJson(marker)) {
2271
- // Not a jsonValues entry: the value inlined in the module, as is.
2272
- value.entries.push({
2273
- key,
2274
- content: marker
2275
- });
2276
- continue;
2277
- }
2278
- const read = reads.get(key);
2279
- if (read === undefined || read.kind === "missing") {
2280
- value.missing.push(key);
2281
- } else if (read.kind === "error") {
2282
- value.errors.push({
2283
- key,
2284
- message: read.message
2285
- });
2286
- } else {
2287
- value.entries.push({
2288
- key,
2289
- content: read.content
2290
- });
2291
- value.entryVersions[key] = {
2292
- ...held.module.version,
2293
- key,
2294
- chain: facts.entryChains.get(key) ?? facts.wholeChain
2295
- };
2296
- }
2297
- }
2298
- return {
2299
- status: "success",
2300
- value
2301
- };
2302
- }
2303
-
2304
- /**
2305
- * An entry on `module`, resolved once and kept on it -- unless it could
2306
- * not be read (`transient`): that is tried again on the next read rather
2307
- * than kept for the version's life.
2308
- */
2309
- async resolved(path, baseRecord, module, key) {
2310
- const facts = this.factsOf(module);
2311
- const kept = facts.resolved.get(key);
2312
- if (kept !== undefined) return kept;
2313
- const read = await this.resolve(path, baseRecord, module, key);
2314
- if (!(read.kind === "error" && read.transient === true)) {
2315
- facts.resolved.set(key, read);
2316
- }
2317
- return read;
2318
- }
2319
- async resolve(path, baseRecord, module, key) {
2320
- counted.entriesResolved++;
2321
- const state = internal.entryState(module.content, key);
2322
- let from = {
2323
- content: undefined
2324
- };
2325
- if ((state === null || state === void 0 ? void 0 : state.kind) === "waiting") {
2326
- from = await this.ops.baseJsonEntry(path, baseRecord, state.from);
2327
- if ("message" in from) {
2328
- return {
2329
- kind: "error",
2330
- message: from.message,
2331
- transient: true
2332
- };
2333
- }
2334
- }
2335
- const copiedBefore = internal.engineWork().cloneBytes;
2336
- const read = internal.resolveEntry(key, state, () => "content" in from ? from.content : undefined);
2337
- if (read.kind === "content" && (state === null || state === void 0 ? void 0 : state.kind) === "waiting" && state.ops) {
2338
- // Held edits made a new entry: the head holds it now.
2339
- this.memory.charge(internal.moduleKey(path, module.version), internal.engineWork().cloneBytes - copiedBefore);
2340
- }
2341
- return read;
2342
- }
2343
-
2344
- // #region drafts
2345
-
2346
- /**
2347
- * A module as a draft reader is given it ({@link Draft}): `bundle` when the
2348
- * newest version is the bundle's own -- the reader's bundle answers, and
2349
- * nothing is read -- and otherwise the head's, made once per version.
2350
- */
2351
- async draft(path, chain) {
2352
- const synced = await this.at(chain);
2353
- if ("error" in synced) return synced;
2354
- const asked = versionIn(synced.ok, path);
2355
- if (asked === undefined) return {
2356
- ok: null
2357
- };
2358
- const bundle = await this.ops.bundleModule(path);
2359
- if (bundle !== null && asked.chain === internal.EMPTY_CHAIN && bundle.version.schema === asked.schema && bundle.version.base === asked.base) {
2360
- return {
2361
- ok: {
2362
- kind: "bundle",
2363
- version: asked
2364
- }
2365
- };
2366
- }
2367
- const held = await this.moduleIn(synced.ok, path);
2368
- if (held === null) return {
2369
- ok: null
2370
- };
2371
- const facts = this.factsOf(held.module);
2372
- if (facts.draft !== null) return {
2373
- ok: facts.draft
2374
- };
2375
- const made = await this.makeDraft(synced.ok, path, held);
2376
- // Kept for the version, unless its entries could not be read: the next
2377
- // read tries them again rather than serving markers for the version's
2378
- // life.
2379
- if (made.kind !== "draft" || !made.entriesFailed) facts.draft = made;
2380
- return {
2381
- ok: made
2382
- };
2383
- }
2384
-
2385
- /**
2386
- * The draft of `held`, its entries read at `chain` -- the chain `held` was
2387
- * made at, so the entries are the same version's even when the chain has
2388
- * moved since.
2389
- */
2390
- async makeDraft(chain, path, held) {
2391
- const source = held.module.content.source;
2392
- const version = held.module.version;
2393
- if (!isRecordOfMarkers(source)) {
2394
- return {
2395
- kind: "draft",
2396
- version,
2397
- source,
2398
- changed: held.records.length > 0,
2399
- entriesFailed: false
2400
- };
2401
- }
2402
- // The entries a draft changes: the ones the chain touched, and the ones
2403
- // a publish wrote that the bundle has not got (a marker with a
2404
- // `patch_id`). Every other one is the bundle's, behind its marker.
2405
- const wire = {};
2406
- const fill = [];
2407
- const touched = held.module.content.entries;
2408
- let fromServer = false;
2409
- for (const [key, value] of Object.entries(source)) {
2410
- if (core.Internal.isJson(value)) {
2411
- wire[key] = transportMarker(value);
2412
- const published = core.Internal.isJsonFromServer(value);
2413
- fromServer ||= published;
2414
- if (published || touched.has(key)) fill.push(key);
2415
- } else {
2416
- wire[key] = value;
2417
- }
2418
- }
2419
- let entriesFailed = false;
2420
- if (fill.length > 0) {
2421
- const read = await this.entriesIn(chain, path, fill);
2422
- if (read.status !== "success" || read.value.errors.length > 0 || read.value.missing.length > 0) {
2423
- entriesFailed = true;
2424
- } else {
2425
- for (const {
2426
- key,
2427
- content
2428
- } of read.value.entries) {
2429
- wire[key] = content;
2430
- }
2431
- }
2432
- }
2433
- return {
2434
- kind: "draft",
2435
- version,
2436
- source: entriesFailed ? stripped(source) : wire,
2437
- changed: held.records.length > 0 || fromServer,
2438
- entriesFailed
2439
- };
2440
- }
2441
-
2442
- /**
2443
- * The modules a draft changes: a patch in their chain, or an entry a
2444
- * publish wrote that the bundle has not got. What `fetchValDraft` sends.
2445
- */
2446
- async changed(at) {
2447
- var _made;
2448
- const synced = await this.at(at);
2449
- if ("error" in synced) return synced;
2450
- const chain = synced.ok;
2451
- let made = this.changedIn;
2452
- if (((_made = made) === null || _made === void 0 ? void 0 : _made.chain) !== chain) {
2453
- made = {
2454
- chain,
2455
- paths: this.changedOf(chain)
2456
- };
2457
- this.changedIn = made;
2458
- }
2459
- return {
2460
- ok: [...(await made.paths)]
2461
- };
2462
- }
2463
-
2464
- /** {@link changed}, made once per chain: it looks at every record's markers. */
2465
- changedIn = null;
2466
- async changedOf(chain) {
2467
- const changed = new Set(chain.byModule.keys());
2468
- for (const path of Object.keys(chain.versions)) {
2469
- if (changed.has(path)) continue;
2470
- const base = await this.ops.baseModule(path);
2471
- if (base !== null && hasMarkersFromServer(base.source)) changed.add(path);
2472
- }
2473
- return [...changed];
2474
- }
2475
-
2476
- // #region the whole tree
2477
-
2478
- /**
2479
- * Every module at the newest chain: the patched ones made (once per
2480
- * version), the rest the base's own objects. What `PUT /sources/~` and
2481
- * MCP read; made once per chain.
2482
- */
2483
- async tree() {
2484
- var _this$wholeTree;
2485
- const synced = await this.sync();
2486
- if ("error" in synced) return synced;
2487
- const chain = synced.ok;
2488
- if (((_this$wholeTree = this.wholeTree) === null || _this$wholeTree === void 0 ? void 0 : _this$wholeTree.chain) !== chain) {
2489
- this.wholeTree = {
2490
- chain,
2491
- promise: this.makeTree(chain)
2492
- };
2493
- }
2494
- return this.wholeTree.promise;
2495
- }
2496
- async makeTree(chain) {
2497
- const base = await this.ops.getBaseSources();
2498
- const sources = {
2499
- ...base
2500
- };
2501
- const errors = {};
2502
- const stopped = {};
2503
- const versions = {
2504
- ...chain.versions
2505
- };
2506
- for (const patch of chain.overlay) {
2507
- if (base[patch.path] === undefined && errors[patch.path] === undefined) {
2508
- errors[patch.path] = [];
2509
- }
2510
- }
2511
- for (const [path, records] of chain.byModule) {
2512
- if (base[path] === undefined) {
2513
- core.Internal.log.error("Module not found", path);
2514
- errors[path] = records.map(record => ({
2515
- patchId: record.patchId,
2516
- skipped: true,
2517
- error: {
2518
- message: "Module not found"
2519
- }
2520
- }));
2521
- continue;
2522
- }
2523
- const held = await this.moduleIn(chain, path);
2524
- if (held === null) continue;
2525
- sources[path] = held.module.content.source;
2526
- versions[path] = held.module.version;
2527
- if (held.failed !== null) {
2528
- core.Internal.log.error("Could not apply patch", {
2529
- path,
2530
- patchId: held.failed.patchId,
2531
- error: held.failed.message
2532
- });
2533
- stopped[path] = held.applied;
2534
- errors[path] = [{
2535
- patchId: held.failed.patchId,
2536
- skipped: false,
2537
- error: {
2538
- message: held.failed.message
2539
- }
2540
- }, ...records.slice(held.applied + 1).map(record => ({
2541
- patchId: record.patchId,
2542
- skipped: true,
2543
- error: {
2544
- message: "Cannot apply patch: previous errors exists"
2545
- }
2546
- }))];
2547
- }
2548
- }
2549
- for (const [path, list] of Object.entries(errors)) {
2550
- if (list.length === 0) delete errors[path];
2551
- }
2552
- return {
2553
- ok: {
2554
- chain,
2555
- sources,
2556
- errors,
2557
- stopped,
2558
- versions
2559
- }
2560
- };
2561
- }
2562
-
2563
- // #region the module endpoint
2564
-
2565
- /**
2566
- * `GET /modules`: one module at a version. `v` the version wanted (by
2567
- * default the newest); `have` the version the caller holds, from which the
2568
- * answer is a delta -- the patches from it -- when the caller's chain is a
2569
- * start of this one under the same schema and base.
2570
- */
2571
- async answer(path, opts) {
2572
- const synced = await this.sync();
2573
- if ("error" in synced) return synced;
2574
- const chain = synced.ok;
2575
- const current = await this.moduleIn(chain, path);
2576
- if (current === null) return {
2577
- ok: null
2578
- };
2579
- let target = current.module;
2580
- let isCurrent = true;
2581
- if (opts.v !== undefined) {
2582
- const wanted = internal.parseModuleKey(opts.v);
2583
- if (wanted === null || wanted.path !== path) {
2584
- return {
2585
- ok: {
2586
- kind: "not-held",
2587
- current: current.module.version
2588
- }
2589
- };
2590
- }
2591
- const currentKeys = [internal.moduleKey(path, current.module.version), internal.moduleKey(path, current.asked)];
2592
- if (!currentKeys.includes(opts.v)) {
2593
- const held = await this.store.get(opts.v);
2594
- if (held === null) {
2595
- return {
2596
- ok: {
2597
- kind: "not-held",
2598
- current: current.module.version
2599
- }
2600
- };
2601
- }
2602
- target = held;
2603
- isCurrent = false;
2604
- }
2605
- }
2606
- const have = opts.have !== undefined ? internal.parseModuleKey(opts.have) : null;
2607
- if (isCurrent && have !== null && have.path === path && have.version.schema === target.version.schema && have.version.base === target.version.base) {
2608
- const facts = this.factsOf(target);
2609
- for (let n = facts.applied; n >= 0; n--) {
2610
- if (this.ops.chainAt(path, n) === have.version.chain) {
2611
- return {
2612
- ok: {
2613
- kind: "delta",
2614
- from: have.version,
2615
- to: target.version,
2616
- patches: current.records.slice(n, facts.applied).map(({
2617
- patchId,
2618
- patch
2619
- }) => ({
2620
- patchId,
2621
- patch
2622
- }))
2623
- }
2624
- };
2625
- }
2626
- }
2627
- }
2628
- const facts = this.factsOf(target);
2629
- const source = target.content.source;
2630
- const entries = {};
2631
- if (isRecordOfMarkers(source)) {
2632
- const baseModule = await this.ops.baseModule(path);
2633
- const baseRecord = baseModule !== null && typeof baseModule.source === "object" && baseModule.source !== null && !Array.isArray(baseModule.source) ? baseModule.source : {};
2634
- for (const key of target.content.entries.keys()) {
2635
- const read = await this.resolved(path, baseRecord, target, key);
2636
- const version = {
2637
- ...target.version,
2638
- key,
2639
- chain: facts.entryChains.get(key) ?? facts.wholeChain
2640
- };
2641
- entries[key] = read.kind === "content" ? {
2642
- content: read.content,
2643
- version
2644
- } : read.kind === "missing" ? {
2645
- deleted: true,
2646
- version
2647
- } : {
2648
- error: read.message,
2649
- ...(read.patchId !== undefined ? {
2650
- patchId: read.patchId
2651
- } : {}),
2652
- version
2653
- };
2654
- }
2655
- }
2656
- return {
2657
- ok: {
2658
- kind: "module",
2659
- version: target.version,
2660
- source: isRecordOfMarkers(source) ? stripped(source) : source,
2661
- entries,
2662
- patches: [...target.patches],
2663
- ...(facts.failed !== null ? {
2664
- failed: facts.failed
2665
- } : {})
2666
- }
2667
- };
2668
- }
2669
- }
2670
-
2671
- /** What {@link ValHead.entries} answers. */
2672
-
2673
- /**
2674
- * A module's version at `chain`. `versions` is keyed by module path, and a
2675
- * path comes from a request: `~constructor` is not a module.
2676
- */
2677
- function versionIn(chain, path) {
2678
- return Object.hasOwn(chain.versions, path) ? chain.versions[path] : undefined;
2679
- }
2680
-
2681
- /**
2682
- * Whether an answer of {@link ValHead.answer} is the same for good, so an
2683
- * answer for an asked version may be cached as immutable: not when an
2684
- * entry's content could not be READ (it carries no `patchId`; its base's
2685
- * `import()` failed, and the next read may succeed). An entry a patch could
2686
- * not be applied to names that patch, and is the version's for good.
2687
- */
2688
- function isLastingAnswer(answer) {
2689
- if (answer.kind !== "module") return true;
2690
- return Object.values(answer.entries).every(entry => !("error" in entry) || entry.patchId !== undefined);
2691
- }
2692
-
2693
- /** What {@link ValHead.tree} answers. */
2694
-
2695
- /** What `GET /modules` answers: see `ModuleAnswer` in the plan. */
2696
-
2697
- /**
2698
- * The entries a patch touched: the ones whose state it replaced, or `all`
2699
- * when it replaced the record (every entry went, or the map was reset).
2700
- */
2701
- function touchedEntries(before, after) {
2702
- if (after.entries === before.entries) return [];
2703
- if (after.entries.size < before.entries.size) return "all";
2704
- const touched = [];
2705
- for (const [key, state] of after.entries) {
2706
- if (before.entries.get(key) !== state) touched.push(key);
2707
- }
2708
- return touched;
2709
- }
2710
-
2711
- /**
2712
- * What `next` holds that `base` does not: every container copy-on-write made
2713
- * (8 bytes a slot, as the engine counts them) and every string a patch
2714
- * brought, walking only where the two differ -- a subtree the patches did not
2715
- * touch is the base's own object, which the build holds anyway. A child that
2716
- * is one of the base container's own children (moved, or shifted by an
2717
- * insert) costs nothing. What the head's byte budget is measured in.
2718
- */
2719
- function heldBeyond(base, next) {
2720
- if (base === next) return 0;
2721
- if (typeof next === "string") return next.length;
2722
- if (typeof next !== "object" || next === null) return 8;
2723
- const shared = new Set(typeof base === "object" && base !== null ? Object.values(base) : []);
2724
- let bytes = 0;
2725
- if (Array.isArray(next)) {
2726
- bytes += 8 * next.length;
2727
- for (const [index, child] of next.entries()) {
2728
- if (shared.has(child)) continue;
2729
- bytes += heldBeyond(Array.isArray(base) ? base[index] : undefined, child);
2730
- }
2731
- return bytes;
2732
- }
2733
- const record = base;
2734
- for (const [key, child] of Object.entries(next)) {
2735
- bytes += 8;
2736
- if (shared.has(child)) continue;
2737
- bytes += heldBeyond(typeof record === "object" && record !== null && !Array.isArray(record) ? record[key] : undefined, child);
2738
- }
2739
- return bytes;
2740
- }
2741
-
2742
- /** What the entries a chain wrote hold: their content, which patches brought. */
2743
- function entriesBytes(content) {
2744
- let bytes = 8 * content.entries.size;
2745
- for (const state of content.entries.values()) {
2746
- if (state.kind === "content") bytes += heldBeyond(undefined, state.content);
2747
- }
2748
- return bytes;
2749
- }
2750
- function isRecordOfMarkers(source) {
2751
- return typeof source === "object" && source !== null && !Array.isArray(source) && Object.values(source).some(value => core.Internal.isJson(value));
2752
- }
2753
- function hasMarkersFromServer(source) {
2754
- return isRecordOfMarkers(source) && Object.values(source).some(value => core.Internal.isJsonFromServer(value));
2755
- }
2756
-
2757
- /** A marker as it travels: without the `import()` only this process can run. */
2758
- function transportMarker(marker) {
2759
- if (typeof marker !== "object" || marker === null || Array.isArray(marker)) {
2760
- return marker;
2761
- }
2762
- const copy = {};
2763
- for (const [key, value] of Object.entries(marker)) {
2764
- if (typeof value !== "function") copy[key] = value;
2765
- }
2766
- return copy;
2767
- }
2768
-
2769
- /** A record of markers, as it travels. */
2770
- function stripped(source) {
2771
- const wire = {};
2772
- for (const [key, value] of Object.entries(source)) {
2773
- wire[key] = core.Internal.isJson(value) ? transportMarker(value) : value;
2774
- }
2775
- return wire;
1482
+ // The hash covers only these of what was recorded (`getValidationBasis`):
1483
+ // `alt` and `hotspot` are the editor's, and change no byte.
1484
+ const metadata = {
1485
+ width: value.width,
1486
+ height: value.height,
1487
+ mimeType: value.mimeType
1488
+ };
1489
+ const expected = core.Internal.remote.getValidationHash(parsed.version, schema, getFileExt(parsed.filePath), metadata, parsed.fileHash, textEncoder);
1490
+ return expected !== parsed.validationHash;
2776
1491
  }
2777
1492
 
2778
1493
  /* eslint-disable @typescript-eslint/no-unused-vars */
@@ -2808,7 +1523,7 @@ function findNestedJsonValuesModuleErrors(schemas) {
2808
1523
  // Serialization errors are reported elsewhere (e.g. by extractValModules).
2809
1524
  continue;
2810
1525
  }
2811
- for (const nestedPath of findNestedJsonValuesRecords(serialized)) {
1526
+ for (const nestedPath of jsonValuesPatch.findNestedJsonValuesRecords(serialized)) {
2812
1527
  errors.push({
2813
1528
  path: moduleFilePath,
2814
1529
  message: `Nested .jsonValues() records are not supported: '${nestedPath.join(".")}' in ${moduleFilePath}. Use .jsonValues() only on a module's root record/router.`
@@ -2930,7 +1645,7 @@ class ValOps {
2930
1645
  * version, which every reader in the process reads through. See
2931
1646
  * `head.ts`.
2932
1647
  */
2933
- head = new ValHead(this);
1648
+ head = new ValPatchStore.ValHead(this);
2934
1649
 
2935
1650
  /**
2936
1651
  * Take a formatter for saves, when this instance was built without one.
@@ -3758,7 +2473,7 @@ class ValOps {
3758
2473
  }
3759
2474
  const record = moduleSource;
3760
2475
  // Walked once per record, not per request: see `recordKeysOf`.
3761
- const allKeys = recordKeysOf(record);
2476
+ const allKeys = ValPatchStore.recordKeysOf(record);
3762
2477
  const requestedKeys = isWindow ? allKeys.slice(selector.offset, selector.offset + selector.limit) : selector.keys;
3763
2478
  /** The record module's version: its base, with no chain applied. */
3764
2479
  const version = await this.moduleVersion(moduleFilePath, [], false);
@@ -4601,7 +3316,7 @@ class ValOps {
4601
3316
  filePath: path
4602
3317
  });
4603
3318
  }
4604
- return fp.result.ok(resolveExistingJsonPath(path, entry.importPath));
3319
+ return fp.result.ok(jsonValuesPatch.resolveExistingJsonPath(path, entry.importPath));
4605
3320
  };
4606
3321
  const loadEntryContent = async jsonPath => {
4607
3322
  const current = jsonEntryContents.get(jsonPath);
@@ -4837,7 +3552,7 @@ class ValOps {
4837
3552
  if (cls.subPath.length === 0) {
4838
3553
  // Structural / whole-entry op.
4839
3554
  if (op.op === "add") {
4840
- const newPathsRes = getNewJsonEntryPaths(path, cls.entryKey);
3555
+ const newPathsRes = jsonValuesPatch.getNewJsonEntryPaths(path, cls.entryKey);
4841
3556
  if (fp.result.isErr(newPathsRes)) {
4842
3557
  errors.push(newPathsRes.error);
4843
3558
  patchHadError = true;
@@ -4924,7 +3639,7 @@ class ValOps {
4924
3639
  }
4925
3640
  // LOCKED convention: the destination always uses the generated
4926
3641
  // path, so renaming a hand-placed file relocates it.
4927
- const newPathsRes = getNewJsonEntryPaths(path, cls.entryKey);
3642
+ const newPathsRes = jsonValuesPatch.getNewJsonEntryPaths(path, cls.entryKey);
4928
3643
  if (fp.result.isErr(newPathsRes)) {
4929
3644
  errors.push(newPathsRes.error);
4930
3645
  patchHadError = true;
@@ -6409,7 +5124,7 @@ var packageJson = {
6409
5124
  ],
6410
5125
  exports: true
6411
5126
  },
6412
- version: "0.154.1",
5127
+ version: "0.154.3",
6413
5128
  scripts: {
6414
5129
  typecheck: "tsc --noEmit",
6415
5130
  test: "jest",
@@ -8228,7 +6943,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
8228
6943
  }
8229
6944
  patchOps = {
8230
6945
  ...patchOps,
8231
- patches: draftOverlay(patchOps.patches, patchOps.commits)
6946
+ patches: ValPatchStore.draftOverlay(patchOps.patches, patchOps.commits)
8232
6947
  };
8233
6948
  const analysis = serverOps.analyzePatches(patchOps.patches);
8234
6949
  const {
@@ -9912,7 +8627,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
9912
8627
  // version is the same for ever. The newest is a question, and
9913
8628
  // so is an answer with an entry that could not be read this
9914
8629
  // time (`isLastingAnswer`).
9915
- "Cache-Control": req.query.v !== undefined && isLastingAnswer(answer.ok) ? "private, max-age=31536000, immutable" : "no-cache"
8630
+ "Cache-Control": req.query.v !== undefined && ValPatchStore.isLastingAnswer(answer.ok) ? "private, max-age=31536000, immutable" : "no-cache"
9916
8631
  },
9917
8632
  json: answer.ok
9918
8633
  };
@@ -12114,34 +10829,6 @@ function createMemorySketchpadStore(now = () => new Date()) {
12114
10829
  };
12115
10830
  }
12116
10831
 
12117
- /**
12118
- * One stored patch. Everything the ordered chain needs and nothing else.
12119
- */
12120
-
12121
- /**
12122
- * One pending binary file: an upload that has not been published yet.
12123
- *
12124
- * Keyed by the patch that carries it, exactly as `fs` mode keys the directory
12125
- * it writes to. The patch's own `file` op holds a hash, not the bytes, so these
12126
- * arrive on their own request and are joined up by `(patchId, filePath)`.
12127
- */
12128
-
12129
- /**
12130
- * Where pending patches live.
12131
- *
12132
- * The point of the interface: `ValOpsMemory` is not tied to memory. The default
12133
- * implementation below is explicitly NOT durable -- it dies with the process,
12134
- * or in a Worker with the isolate -- and a durable one (a Durable Object, whose
12135
- * single-threaded execution is the lock Val's fs store builds out of a file)
12136
- * is a swap rather than a rewrite.
12137
- *
12138
- * ORDER IS THE CONTRACT. `list()` returns patch ids in the order they were
12139
- * written, and that order is the chain: entry i's parent is entry i-1. This is
12140
- * the same decision `ValOpsFS` makes with `patches.log` -- the server decides
12141
- * where a patch goes, and it goes last -- and it exists for the same reason: an
12142
- * order held in the patches themselves lets a client working from a stale view
12143
- * strand every patch behind a parent that never landed.
12144
- */
12145
10832
  /**
12146
10833
  * Memory mode's `seq` (`ProjectVersion` in `@valbuild/shared/internal`), per
12147
10834
  * patch store: bumped beside `announceChange` by every write and delete, and
@@ -12168,69 +10855,6 @@ function seqOf(store) {
12168
10855
  }
12169
10856
  return counter;
12170
10857
  }
12171
- /** The default store. Not durable, deliberately and visibly. */
12172
- class InMemoryPatchStore {
12173
- order = [];
12174
- byId = new Map();
12175
- async list() {
12176
- return [...this.order];
12177
- }
12178
- async get(patchId) {
12179
- return this.byId.get(patchId) ?? null;
12180
- }
12181
- async append(patch) {
12182
- if (!this.byId.has(patch.patchId)) {
12183
- this.order.push(patch.patchId);
12184
- }
12185
- this.byId.set(patch.patchId, patch);
12186
- }
12187
- async delete(patchIds) {
12188
- for (const patchId of patchIds) {
12189
- const at = this.order.indexOf(patchId);
12190
- if (at !== -1) {
12191
- this.order.splice(at, 1);
12192
- }
12193
- this.byId.delete(patchId);
12194
- // The bytes go with the patch. They are only reachable through it, so
12195
- // keeping them would be a leak with no reader -- and these are images.
12196
- for (const key of this.files.keys()) {
12197
- if (key.startsWith(`${patchId}\u0000`)) {
12198
- this.files.delete(key);
12199
- }
12200
- }
12201
- }
12202
- }
12203
-
12204
- /*
12205
- * `\u0000` cannot occur in a patch id or a path, so the two halves of the key
12206
- * can never run together into a different pair.
12207
- *
12208
- * The PATH is normalised for the same reason `sourceFiles` is, and it is not
12209
- * cosmetic: an upload arrives as `/public/val/x.png`, and the publish step
12210
- * looks the same file up as `public/val/x.png` because that is what
12211
- * `splitRemoteRef` yields from a remote ref. `ValOpsFS` never noticed --
12212
- * `path.join` collapses the difference -- so this is another thing a
12213
- * filesystem was doing for free. Without it a remote image uploads fine,
12214
- * patches fine, and fails at publish with "No bytes held", naming a ref whose
12215
- * bytes are sitting right there under the other spelling.
12216
- */
12217
- static fileKey(patchId, filePath) {
12218
- return `${patchId}\u0000${filePath.replace(/^\//, "")}`;
12219
- }
12220
- files = new Map();
12221
- async putFile(file) {
12222
- this.files.set(InMemoryPatchStore.fileKey(file.patchId, file.filePath), file);
12223
- }
12224
- async getFile(patchId, filePath) {
12225
- return this.files.get(InMemoryPatchStore.fileKey(patchId, filePath)) ?? null;
12226
- }
12227
- async deleteFile(patchId, filePath) {
12228
- this.files.delete(InMemoryPatchStore.fileKey(patchId, filePath));
12229
- }
12230
- async filesOf(patchId) {
12231
- return [...this.files.values()].filter(file => file.patchId === patchId);
12232
- }
12233
- }
12234
10858
  /**
12235
10859
  * A `ValOps` for a host that is neither a developer's machine nor
12236
10860
  * content.val.build.
@@ -12304,7 +10928,7 @@ class ValOpsMemory extends ValOps {
12304
10928
  contentUrl;
12305
10929
  constructor(valModules, options) {
12306
10930
  super(valModules, options);
12307
- this.store = options.patchStore ?? new InMemoryPatchStore();
10931
+ this.store = options.patchStore ?? new ValPatchStore.InMemoryPatchStore();
12308
10932
  newestOnStore.set(this.store, this);
12309
10933
  this.contentUrl = options.contentUrl;
12310
10934
  this.requiresAuth = !options.unsafelyAllowUnauthenticated;
@@ -12395,7 +11019,7 @@ class ValOpsMemory extends ValOps {
12395
11019
  * one's count never saw: `null`, so the head reads the chain each time.
12396
11020
  */
12397
11021
  async chainSeq() {
12398
- if (!(this.store instanceof InMemoryPatchStore)) return null;
11022
+ if (!(this.store instanceof ValPatchStore.InMemoryPatchStore)) return null;
12399
11023
  return super.chainSeq();
12400
11024
  }
12401
11025
 
@@ -12852,615 +11476,9 @@ class ValOpsMemory extends ValOps {
12852
11476
 
12853
11477
  /** Kept exported so a host can name the error shape it may get back. */
12854
11478
 
12855
- /**
12856
- * What `redirect_to` may be on Val's routes (`/enable`, `/disable`,
12857
- * `/authorize`, `/draft/enable`, ...): a path on the site that was asked,
12858
- * which is made absolute against the request's own origin, or an absolute
12859
- * URL on that same site.
12860
- *
12861
- * A path used to go through as it was, and two things downstream need an
12862
- * absolute URL: `/authorize` reads the origin off it to build the callback,
12863
- * and Next's `NextResponse.redirect` refuses anything else. Both threw, so
12864
- * `/api/val/enable?redirect_to=/` answered 500 in a Next app.
12865
- *
12866
- * `//host/path` is a URL on another host, not a path on this one, and
12867
- * anything that is neither is refused with what is accepted instead. An
12868
- * empty value is not resolved at all: the router leaves it to the route, as
12869
- * it always was (`/logout` reads it as absent).
12870
- */
12871
-
12872
- 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).";
12873
-
12874
- /**
12875
- * `siteHosts` are the other names the request knows this site by (`Host`,
12876
- * `X-Forwarded-Host`), for a server behind a proxy whose own URL is internal.
12877
- */
12878
- function resolveRedirectTo(value, requestOrigin, siteHosts = []) {
12879
- if (value.startsWith("/") && !value.startsWith("//")) {
12880
- // A path stays on this origin. `/\host/x` also starts with one slash,
12881
- // and a URL parser reads the backslash as a second one: another host,
12882
- // not a path here.
12883
- const resolved = parsed(value, requestOrigin);
12884
- return resolved !== null && resolved.origin === new URL(requestOrigin).origin ? {
12885
- ok: true,
12886
- href: resolved.href
12887
- } : {
12888
- ok: false,
12889
- message: REDIRECT_TO_ACCEPTS
12890
- };
12891
- }
12892
- // An absolute URL, on this site only. Any URL used to pass, which made
12893
- // `/logout` and `/enable` redirect wherever a link said, and `/authorize`
12894
- // send the sign-in's code to that host: it reads the callback's origin off
12895
- // this. http(s) only: `javascript:` parses as a URL too.
12896
- const url = parsed(value);
12897
- if (url === null || url.protocol !== "https:" && url.protocol !== "http:") {
12898
- return {
12899
- ok: false,
12900
- message: REDIRECT_TO_ACCEPTS
12901
- };
12902
- }
12903
- const hosts = [new URL(requestOrigin).host, ...siteHosts].filter(host => typeof host === "string" && host !== "").map(host => host.toLowerCase());
12904
- return hosts.includes(url.host.toLowerCase()) ? {
12905
- ok: true,
12906
- href: value
12907
- } : {
12908
- ok: false,
12909
- message: REDIRECT_TO_ACCEPTS
12910
- };
12911
- }
12912
-
12913
- /**
12914
- * `value` as a URL, or null. Not `URL.canParse`: this runs in the browser
12915
- * too (demo mode), where it is missing before Safari 17 and Chrome 120.
12916
- */
12917
- function parsed(value, base) {
12918
- try {
12919
- return new URL(value, base);
12920
- } catch {
12921
- return null;
12922
- }
12923
- }
12924
-
12925
- /**
12926
- * Which requests Val's API answers in fs mode, where there is no session.
12927
- *
12928
- * fs mode reads and writes a working tree and asks nobody who they are: it is
12929
- * a developer's own machine. That holds only while the request really comes
12930
- * from that developer's Studio, and three kinds do not:
12931
- *
12932
- * - **A deployed site.** fs is the mode an app falls into when it has no
12933
- * `VAL_API_KEY` and `VAL_SECRET`, so a site deployed without them served
12934
- * this API, unauthenticated, to the internet.
12935
- * - **Another site's page**, in the developer's browser. A `text/plain` POST
12936
- * needs no preflight, and the router reads its body as JSON, so any page
12937
- * open in another tab could write to the working tree.
12938
- * - **A name that resolves to 127.0.0.1** (DNS rebinding), which makes such a
12939
- * page same-origin with the dev server as far as the browser can tell.
12940
- *
12941
- * The MCP endpoint has refused all three since it was written
12942
- * (`refuseUnsafeRequest` in `@valbuild/mcp`); this is the same rule for the
12943
- * API the Studio uses. Nothing here needs Node: `ValRouterCore` runs in a
12944
- * browser tab too, where no server is registered and nothing is refused.
12945
- */
12946
-
12947
- const guards = new WeakMap();
12948
-
12949
- /** Say how `server`'s requests are to be checked. Without it, none are. */
12950
- function setRequestGuard(server, guard) {
12951
- guards.set(server, guard);
12952
- }
12953
-
12954
- /** `VAL_ALLOWED_HOSTS`: comma separated host names, without a port. */
12955
- function parseAllowedHosts(value) {
12956
- return (value ?? "").split(",").map(host => host.trim().toLowerCase()).filter(host => host !== "");
12957
- }
12958
-
12959
- /** The refusal, or `null` when the request may go on to its route. */
12960
- function refuseUnsafeRequest(server, req, apiPath) {
12961
- var _req$method;
12962
- const guard = guards.get(server);
12963
- if (guard === undefined || guard.mode !== "fs") {
12964
- return null;
12965
- }
12966
- // Beacons are not refused: in fs mode one is checked and dropped, nothing
12967
- // is written or forwarded, and a deployed site with analytics on would fill
12968
- // every visitor's console with errors.
12969
- if (apiPath === "/analytics") {
12970
- return null;
12971
- }
12972
- if (guard.production) {
12973
- 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.");
12974
- }
12975
- const host = hostOf(req);
12976
- const forwardedHost = firstOf(req.headers.get("x-forwarded-host"));
12977
- const origin = req.headers.get("origin");
12978
- if (origin !== null) {
12979
- // `null` is the opaque origin (a sandboxed frame, a `file:` page). It
12980
- // cannot be compared with anything, so it is refused.
12981
- const originHost = origin === "null" ? null : hostOfUrl(origin);
12982
- if (originHost === null || originHost !== host && originHost !== forwardedHost) {
12983
- return refusal(`Val refused a request from another site (${origin}). In local filesystem mode the API only answers the Studio on its own address.`);
12984
- }
12985
- }
12986
- // A request with no `Origin` can still come from another site: an `<img>`,
12987
- // a script. Following a link here is not refused: sign-in comes back as
12988
- // one. A link is a GET; a form posted from another site navigates too.
12989
- const followedLink = ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === "GET" && req.headers.get("sec-fetch-mode") === "navigate";
12990
- if (req.headers.get("sec-fetch-site") === "cross-site" && !followedLink) {
12991
- return refusal("Val refused a request from another site. In local filesystem mode the API only answers the Studio on its own address.");
12992
- }
12993
- const hostname = host === null ? null : hostnameOf(host);
12994
- if (hostname === null || !isLocalName(hostname, guard.allowedHosts)) {
12995
- 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.`);
12996
- }
12997
- return null;
12998
- }
12999
- function refusal(message) {
13000
- return {
13001
- status: 403,
13002
- json: {
13003
- message
13004
- }
13005
- };
13006
- }
13007
- function firstOf(header) {
13008
- var _header$split$;
13009
- const first = header === null || header === void 0 || (_header$split$ = header.split(",")[0]) === null || _header$split$ === void 0 ? void 0 : _header$split$.trim().toLowerCase();
13010
- return first ? first : null;
13011
- }
13012
- function hostOf(req) {
13013
- const header = firstOf(req.headers.get("host"));
13014
- if (header !== null) {
13015
- return header;
13016
- }
13017
- // No Host header: the URL the framework built the request from.
13018
- return hostOfUrl(req.url);
13019
- }
13020
- function hostOfUrl(url) {
13021
- try {
13022
- return new URL(url).host.toLowerCase();
13023
- } catch {
13024
- return null;
13025
- }
13026
- }
13027
-
13028
- /** A host without its port. An IPv6 literal keeps its brackets. */
13029
- function hostnameOf(host) {
13030
- if (host.startsWith("[")) {
13031
- const end = host.indexOf("]");
13032
- return end === -1 ? host : host.slice(0, end + 1);
13033
- }
13034
- const colon = host.indexOf(":");
13035
- return colon === -1 ? host : host.slice(0, colon);
13036
- }
13037
-
13038
- /**
13039
- * localhost, an IP address, or a name the developer listed.
13040
- *
13041
- * An IP address is allowed because it cannot be rebound: a page that reaches
13042
- * this server by address is on another origin, and the `Origin` check above
13043
- * has already refused it. A phone on the same network uses one.
13044
- */
13045
- function isLocalName(hostname, allowedHosts) {
13046
- return hostname === "localhost" || hostname.endsWith(".localhost") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[") && hostname.endsWith("]") || allowedHosts.includes(hostname);
13047
- }
13048
-
13049
- /**
13050
- * Val's API as a web-standard handler: a `Request` in, a converted result out.
13051
- *
13052
- * The request handling itself -- matching a route, parsing it against `Api`,
13053
- * calling the server, checking the answer -- and nothing that needs Node, so it
13054
- * runs in a browser tab as well as on a server. That is what the demo does
13055
- * (`@valbuild/server/browser`): the Studio's own client sends its requests
13056
- * here, in the same tab, instead of over the network.
13057
- *
13058
- * `serveStatic` answers `/static/...`, the Studio's own scripts and styles.
13059
- * `createValApiRouter` passes the embedded bundle; the demo passes nothing,
13060
- * because its page loaded those from the app already.
13061
- */
13062
- function createValRequestHandler(route, valServerPromise, convert, serveStatic) {
13063
- // valServerPromise is created at module-eval time, but only awaited per request.
13064
- // Without this no-op catch, a config error (e.g. proxy mode without a project)
13065
- // rejects with no handler attached, which becomes an unhandledRejection and kills
13066
- // the dev server. The error is still reported per request by the try/catch below.
13067
- valServerPromise.catch(() => {
13068
- // handled below
13069
- });
13070
- return async req => {
13071
- let valServer;
13072
- try {
13073
- valServer = await valServerPromise;
13074
- } catch (err) {
13075
- const error = {
13076
- message: "Val: could not start the Val server",
13077
- details: err instanceof Error ? err.message : String(err)
13078
- };
13079
- core.Internal.log.error(error.message + ": " + error.details);
13080
- return convert({
13081
- status: 500,
13082
- json: error
13083
- });
13084
- }
13085
- const url = new URL(req.url);
13086
- if (!url.pathname.startsWith(route)) {
13087
- const error = {
13088
- message: "Val: routes are not configured correctly",
13089
- details: `Check you api routes. Expected pathname to start with "${route}", but it was: "${url.pathname}"`
13090
- };
13091
- core.Internal.log.error(error);
13092
- return convert({
13093
- status: 500,
13094
- json: error
13095
- });
13096
- }
13097
- const path = url.pathname.slice(route.length);
13098
- if (path === internal.QUICK_PREVIEW_SERVICE_WORKER_PATH) {
13099
- /*
13100
- * The quick preview worker (`quickPreview.ts` in
13101
- * `@valbuild/shared`). `Service-Worker-Allowed: /` lets a script at
13102
- * this path control the whole origin, which it needs: it serves the
13103
- * page's `/_app/` files. It serves them only to a page opened as a
13104
- * quick preview, and the bridge stores them only for the site.
13105
- */
13106
- return convert({
13107
- status: 200,
13108
- headers: {
13109
- "Content-Type": "text/javascript; charset=utf-8",
13110
- "Service-Worker-Allowed": "/",
13111
- "Cache-Control": "no-cache"
13112
- },
13113
- body: internal.QUICK_PREVIEW_SERVICE_WORKER_SOURCE
13114
- });
13115
- }
13116
- const groupQueryParams = arr => {
13117
- const map = {};
13118
- for (const [key, value] of arr) {
13119
- const list = map[key] || [];
13120
- list.push(value);
13121
- map[key] = list;
13122
- }
13123
- return map;
13124
- };
13125
- async function getValServerResponse(reqApiRoutePath, req) {
13126
- var _req$method, _anyApi$route, _anyValServer$route;
13127
- const anyApi =
13128
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
13129
- internal.Api;
13130
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
13131
- const anyValServer = valServer;
13132
- const refused = refuseUnsafeRequest(valServer, req, reqApiRoutePath);
13133
- if (refused !== null) {
13134
- return refused;
13135
- }
13136
- const method = (_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase();
13137
- let route = null;
13138
- let path = undefined;
13139
- // An exact match wins over every prefix match, wherever it sits in
13140
- // `Api`: checked per key, in order, `/validate` took `/validate/fix`
13141
- // because it was declared first.
13142
- const exactRouteDef = Object.keys(internal.Api).find(routeDef => routeDef === reqApiRoutePath);
13143
- for (const routeDef of exactRouteDef ? [exactRouteDef] : Object.keys(internal.Api)) {
13144
- if (routeDef === reqApiRoutePath) {
13145
- route = routeDef;
13146
- break;
13147
- }
13148
- if (reqApiRoutePath.startsWith(routeDef)) {
13149
- var _anyApi$routeDef;
13150
- 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;
13151
- if (reqDefinition) {
13152
- route = routeDef;
13153
- if (reqDefinition.path) {
13154
- const subPath = reqApiRoutePath.slice(routeDef.length);
13155
- const pathRes = reqDefinition.path.safeParse(subPath);
13156
- if (!pathRes.success) {
13157
- return zodErrorResult(pathRes.error, `invalid path: '${subPath}' endpoint: '${routeDef}'`);
13158
- } else {
13159
- path = pathRes.data;
13160
- }
13161
- }
13162
- break;
13163
- }
13164
- }
13165
- }
13166
- if (!route) {
13167
- return {
13168
- status: 404,
13169
- json: {
13170
- message: "Route not found. Valid routes are: " + Object.keys(internal.Api),
13171
- details: {
13172
- route,
13173
- method
13174
- }
13175
- }
13176
- };
13177
- }
13178
- const apiEndpoint = anyApi === null || anyApi === void 0 || (_anyApi$route = anyApi[route]) === null || _anyApi$route === void 0 ? void 0 : _anyApi$route[method];
13179
- const reqDefinition = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.req;
13180
- if (!reqDefinition) {
13181
- return {
13182
- status: 404,
13183
- json: {
13184
- message: `Requested method ${method} on route ${route} is not valid. Valid methods are: ${Object.keys(anyApi[route]).join(", ")}`,
13185
- details: {
13186
- route,
13187
- method
13188
- }
13189
- }
13190
- };
13191
- }
13192
- const endpointImpl = anyValServer === null || anyValServer === void 0 || (_anyValServer$route = anyValServer[route]) === null || _anyValServer$route === void 0 ? void 0 : _anyValServer$route[method];
13193
- if (!endpointImpl) {
13194
- return {
13195
- status: 500,
13196
- json: {
13197
- message: "Missing server implementation of route with method. This might be caused by a mismatch between Val package versions.",
13198
- details: {
13199
- valid: {
13200
- route: {
13201
- server: Object.keys(anyValServer || {}),
13202
- api: Object.keys(anyApi || {})
13203
- },
13204
- method: {
13205
- server: Object.keys((anyValServer === null || anyValServer === void 0 ? void 0 : anyValServer[route]) || {}),
13206
- api: Object.keys((anyApi === null || anyApi === void 0 ? void 0 : anyApi[route]) || {})
13207
- }
13208
- },
13209
- route,
13210
- method
13211
- }
13212
- }
13213
- };
13214
- }
13215
- let bodyRes;
13216
- try {
13217
- bodyRes = reqDefinition.body ? reqDefinition.body.safeParse(await readJsonBody(req)) : {
13218
- success: true,
13219
- data: {}
13220
- };
13221
- if (!bodyRes.success) {
13222
- return zodErrorResult(bodyRes.error, "invalid body data");
13223
- }
13224
- } catch (e) {
13225
- return {
13226
- status: 400,
13227
- json: {
13228
- message: "Could not parse request body",
13229
- details: {
13230
- error: JSON.stringify(e)
13231
- }
13232
- }
13233
- };
13234
- }
13235
- const cookiesRes = reqDefinition.cookies ? getCookies(req, reqDefinition.cookies) : {
13236
- success: true,
13237
- data: {}
13238
- };
13239
- if (!cookiesRes.success) {
13240
- return zodErrorResult(cookiesRes.error, "invalid cookies");
13241
- }
13242
- const headersRes = reqDefinition.headers ? getHeaders(req, reqDefinition.headers) : {
13243
- success: true,
13244
- data: {}
13245
- };
13246
- if (!headersRes.success) {
13247
- return zodErrorResult(headersRes.error, "invalid headers");
13248
- }
13249
- const actualQueryParams = groupQueryParams(Array.from(url.searchParams.entries()));
13250
- let query = {};
13251
- if (reqDefinition.query) {
13252
- const queryRules = reqDefinition.query;
13253
- const queryRes = z.z.object(queryRules).safeParse(actualQueryParams);
13254
- if (!queryRes.success) {
13255
- return zodErrorResult(queryRes.error, `invalid query params: (${JSON.stringify(actualQueryParams)})`);
13256
- }
13257
- query = queryRes.data;
13258
- }
13259
- // `redirect_to` is a URL or a path on this site: see `resolveRedirectTo`.
13260
- if ("redirect_to" in query && typeof query.redirect_to === "string" && query.redirect_to !== "") {
13261
- var _req$headers$get;
13262
- // Behind a proxy `url` can be an internal address: the site's own
13263
- // name is then in `Host` or `X-Forwarded-Host`.
13264
- 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()]);
13265
- if (!resolved.ok) {
13266
- return {
13267
- status: 400,
13268
- json: {
13269
- message: resolved.message
13270
- }
13271
- };
13272
- }
13273
- query = {
13274
- ...query,
13275
- redirect_to: resolved.href
13276
- };
13277
- }
13278
-
13279
- /*
13280
- * A throw from an endpoint is Val's to report, not the framework's.
13281
- *
13282
- * Nothing here used to catch, so an endpoint that threw left the router
13283
- * entirely and became whatever the host does with an unhandled error --
13284
- * and on TanStack Start that is h3, which replaces the message with the
13285
- * literal string "HTTPError" and drops the stack. Its `debug` and
13286
- * `silent` options are not reachable from out here: `requestHandler`
13287
- * calls `toResponse(value, event)` with no config, and the default is
13288
- * `{}`. So the body a caller got was
13289
- * `{"status":500,"unhandled":true,"message":"HTTPError"}` -- the same
13290
- * five words for a missing project, a bad cookie secret and a module
13291
- * that failed to link -- with the real cause only on the server's
13292
- * console.
13293
- *
13294
- * That is survivable where the console is readable. It is not in a
13295
- * Cloudflare Dynamic Worker, whose `console` reaches no tail stream: a
13296
- * link error in a lazily imported chunk (`does not provide an export
13297
- * named 'getSerovalPlugins'`) showed up as an unreadable 500 on
13298
- * `/authorize` and nowhere else at all.
13299
- *
13300
- * So every endpoint's throw becomes Val's own 500 envelope, which the
13301
- * Studio already renders and `curl` already prints. The route and method
13302
- * are named because a message rarely says which endpoint it came from.
13303
- *
13304
- * The MESSAGE travels and the STACK does not. The message is the whole
13305
- * diagnostic value -- the line above names the package, the chunk and
13306
- * the export -- while a stack is a walk through somebody's bundle, and
13307
- * `/authorize` and `/enable` are reachable without a session. So the
13308
- * stack goes to the console, where a host that can read one will find
13309
- * it, and the body carries what a caller can act on.
13310
- */
13311
- let res;
13312
- try {
13313
- res = await endpointImpl({
13314
- body: bodyRes.data,
13315
- cookies: cookiesRes.data,
13316
- headers: headersRes.data,
13317
- rawQuery: reqDefinition.rawQuery ? url.search : undefined,
13318
- query,
13319
- path
13320
- });
13321
- } catch (err) {
13322
- const error = err instanceof Error ? err : new Error(String(err));
13323
- core.Internal.log.error(`${method} ${route} threw: ${error.message}`, error.stack);
13324
- return {
13325
- status: 500,
13326
- json: {
13327
- message: `Val: ${method} ${route} failed: ${error.message}`,
13328
- details: {
13329
- route,
13330
- method,
13331
- error: error.message
13332
- }
13333
- }
13334
- };
13335
- }
13336
- const resDef = apiEndpoint.res;
13337
- if (res.status === 500) {
13338
- var _res$json;
13339
- /*
13340
- * A failure the route declares goes out as declared, as a success
13341
- * does below. DELETE /patches says which change was not discarded and
13342
- * which publish holds it, and collapsed to its message the Studio
13343
- * could only say "Failed to delete patches" -- not why, nor offer to
13344
- * cancel that publish. Anything undeclared is still reduced to its
13345
- * message.
13346
- */
13347
- if (resDef !== null && resDef !== void 0 && resDef.safeParse(res).success) return res;
13348
- return {
13349
- status: 500,
13350
- json: {
13351
- message: ((_res$json = res.json) === null || _res$json === void 0 ? void 0 : _res$json.message) || "Internal Server Error"
13352
- }
13353
- };
13354
- }
13355
- if (resDef) {
13356
- const responseResult = resDef.safeParse(res);
13357
- if (!responseResult.success) {
13358
- return {
13359
- status: 500,
13360
- json: {
13361
- message: "Could not validate response. This is likely a bug in Val server.",
13362
- details: {
13363
- response: res,
13364
- errors: formatZodErrorString(responseResult.error)
13365
- }
13366
- }
13367
- };
13368
- }
13369
- }
13370
- return res;
13371
- }
13372
- if (path.startsWith("/static")) {
13373
- if (!serveStatic) {
13374
- return convert({
13375
- status: 404,
13376
- json: {
13377
- message: "Val: this server does not serve the Studio's own files"
13378
- }
13379
- });
13380
- }
13381
- return convert(await serveStatic(path.slice("/static".length), url.href));
13382
- } else {
13383
- return convert(await getValServerResponse(path, req));
13384
- }
13385
- };
13386
- }
13387
- function formatZodErrorString(error) {
13388
- const errors = zodValidationError.fromError(error).toString();
13389
- return errors.length > 640 ? `${errors.slice(0, 640)}...` : errors;
13390
- }
13391
-
13392
- /**
13393
- * The request's JSON body, or `undefined` when it has none.
13394
- *
13395
- * `req.json()` THROWS on an empty body, and the router used to call it
13396
- * unconditionally for any route that declares a body — so the moment
13397
- * `DELETE /patches` gained an optional body, every caller that sent none got
13398
- * `400 Could not parse request body`. Declaring the schema `.optional()` did
13399
- * not help: the throw happens before zod is ever consulted. Six e2e tests went
13400
- * red on a helper doing exactly what the route still permits.
13401
- *
13402
- * Told apart by the request rather than by catching, so a body that IS sent and
13403
- * is malformed still fails: absent means no content type and nothing to read,
13404
- * and anything else is parsed and allowed to throw. A route whose schema
13405
- * requires a body is unaffected — it gets `undefined` and zod refuses it, with
13406
- * the same 400 as before, now naming the field.
13407
- */
13408
- async function readJsonBody(req) {
13409
- if (req.headers.get("content-length") === "0") {
13410
- return undefined;
13411
- }
13412
- const text = await req.text();
13413
- if (text.length === 0) {
13414
- return undefined;
13415
- }
13416
- return JSON.parse(text);
13417
- }
13418
- function zodErrorResult(error, message) {
13419
- return {
13420
- status: 400,
13421
- json: {
13422
- message: "Bad Request: " + message,
13423
- details: {
13424
- errors: formatZodErrorString(error)
13425
- }
13426
- }
13427
- };
13428
- }
13429
-
13430
- // TODO: is this naive implementation is too naive?
13431
- /** The declared headers, by name; `Headers.get` is case-insensitive. */
13432
- function getHeaders(req, headersDef) {
13433
- const input = {};
13434
- for (const name of Object.keys(headersDef)) {
13435
- var _req$headers;
13436
- const value = (_req$headers = req.headers) === null || _req$headers === void 0 ? void 0 : _req$headers.get(name);
13437
- if (value !== null && value !== undefined) {
13438
- input[name] = value;
13439
- }
13440
- }
13441
- return z.z.object(headersDef).safeParse(input);
13442
- }
13443
- function getCookies(req, cookiesDef) {
13444
- var _req$headers2;
13445
- const input = {};
13446
- 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("; ");
13447
- for (const name of Object.keys(cookiesDef)) {
13448
- const cookie = cookieParts === null || cookieParts === void 0 ? void 0 : cookieParts.find(cookie => cookie.startsWith(`${name}=`));
13449
- const value = cookie ? decodeURIComponent(cookie === null || cookie === void 0 ? void 0 : cookie.split("=")[1]) : undefined;
13450
- if (value) {
13451
- input[name.trim()] = value;
13452
- }
13453
- }
13454
- return z.z.object(cookiesDef).safeParse(input);
13455
- }
13456
-
13457
11479
  exports.DEFAULT_ANALYTICS_INGEST_URL = DEFAULT_ANALYTICS_INGEST_URL;
13458
- exports.HEAD_BUDGET_BYTES = HEAD_BUDGET_BYTES;
13459
- exports.HEAD_VERSIONS_PER_MODULE = HEAD_VERSIONS_PER_MODULE;
13460
- exports.InMemoryPatchStore = InMemoryPatchStore;
13461
11480
  exports.MEDIA_FILE_PATH_ACCEPTS = MEDIA_FILE_PATH_ACCEPTS;
13462
11481
  exports.VAL_CLIENT_HEADERS = VAL_CLIENT_HEADERS;
13463
- exports.ValHead = ValHead;
13464
11482
  exports.ValOps = ValOps;
13465
11483
  exports.ValOpsMemory = ValOpsMemory;
13466
11484
  exports.ValServer = ValServer;
@@ -13472,17 +11490,13 @@ exports.bytesToBase64 = bytesToBase64;
13472
11490
  exports.bytesToUtf8 = bytesToUtf8;
13473
11491
  exports.checkRemoteFiles = checkRemoteFiles;
13474
11492
  exports.createMetadataFromBuffer = createMetadataFromBuffer;
13475
- exports.createValRequestHandler = createValRequestHandler;
13476
11493
  exports.fallbackRefOf = fallbackRefOf;
13477
11494
  exports.fallbackRemoteHost = fallbackRemoteHost;
13478
- exports.findNestedJsonValuesRecords = findNestedJsonValuesRecords;
13479
11495
  exports.formatPatchSourceError = formatPatchSourceError;
13480
11496
  exports.getFieldsForType = getFieldsForType;
13481
11497
  exports.getFileExt = getFileExt;
13482
- exports.getNewJsonEntryPaths = getNewJsonEntryPaths;
13483
11498
  exports.getSettings = getSettings;
13484
11499
  exports.guessMimeTypeFromPath = guessMimeTypeFromPath;
13485
- exports.headWork = headWork;
13486
11500
  exports.isHlsMasterPlaylist = isHlsMasterPlaylist;
13487
11501
  exports.isHttpOps = isHttpOps;
13488
11502
  exports.isMediaFilePath = isMediaFilePath;
@@ -13495,13 +11509,9 @@ exports.matchesFilter = matchesFilter;
13495
11509
  exports.movedRemoteHost = movedRemoteHost;
13496
11510
  exports.needsHostCheck = needsHostCheck;
13497
11511
  exports.newSketchpad = newSketchpad;
13498
- exports.parseAllowedHosts = parseAllowedHosts;
13499
11512
  exports.parseHlsMasterVariants = parseHlsMasterVariants;
13500
- exports.posixPath = posixPath;
13501
- exports.resolveExistingJsonPath = resolveExistingJsonPath;
13502
11513
  exports.rewriteRefHost = rewriteRefHost;
13503
11514
  exports.sessionAuth = sessionAuth;
13504
- exports.setRequestGuard = setRequestGuard;
13505
11515
  exports.sumHlsSegmentDurations = sumHlsSegmentDurations;
13506
11516
  exports.summaryOf = summaryOf;
13507
11517
  exports.uploadRemoteFile = uploadRemoteFile;