@valbuild/server 0.154.0 → 0.154.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +49 -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-fe985e4c.esm.js → ValOpsMemory-611f33d2.esm.js} +44 -1988
  6. package/dist/{ValRouterCore-4be8eaf1.cjs.prod.js → ValOpsMemory-6ebbb3ba.cjs.prod.js} +53 -2009
  7. package/dist/{ValRouterCore-0c088c9e.cjs.dev.js → ValOpsMemory-d8bf9f5d.cjs.dev.js} +53 -2009
  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-2dc83070.cjs.prod.js +47 -0
  18. package/dist/createValRuntime-62836dbe.esm.js +45 -0
  19. package/dist/createValRuntime-fd9b673d.cjs.dev.js +47 -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-f6694ad2.cjs.prod.js → inTabFetch-0124da2e.cjs.prod.js} +5 -4
  35. package/dist/{inTabFetch-c8966e73.cjs.dev.js → inTabFetch-d0c9c58a.cjs.dev.js} +5 -4
  36. package/dist/{inTabFetch-877e7d11.esm.js → inTabFetch-e48a801e.esm.js} +2 -1
  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-cfe1273d.cjs.dev.js → publishKit-96522d5a.cjs.prod.js} +20 -22
  44. package/dist/{publishKit-e7f7db7c.cjs.prod.js → publishKit-b06031dc.cjs.dev.js} +20 -22
  45. package/dist/{publishKit-0709423c.esm.js → publishKit-b8929fe8.esm.js} +8 -9
  46. package/dist/{ValRouter-1f427c38.cjs.dev.js → valRuntime-ba8ff718.cjs.prod.js} +158 -6038
  47. package/dist/{ValRouter-cd6e854a.cjs.prod.js → valRuntime-c8c82b24.cjs.dev.js} +158 -6038
  48. package/dist/{ValRouter-558dc66d.esm.js → valRuntime-ccbbbfad.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-92798812.cjs.prod.js');
6
7
  var zodValidationError = require('zod-validation-error');
7
8
  var fp = require('@valbuild/core/fp');
9
+ var ValPatchStore = require('./ValPatchStore-2f92eced.cjs.prod.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
 
@@ -1760,1021 +1490,6 @@ function isStale(parsed, schema, value) {
1760
1490
  return expected !== parsed.validationHash;
1761
1491
  }
1762
1492
 
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;
2776
- }
2777
-
2778
1493
  /* eslint-disable @typescript-eslint/no-unused-vars */
2779
1494
  const jsonOps = new patch.JSONOps();
2780
1495
  /**
@@ -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.0",
5127
+ version: "0.154.2",
6413
5128
  scripts: {
6414
5129
  typecheck: "tsc --noEmit",
6415
5130
  test: "jest",
@@ -7966,10 +6681,26 @@ const ValServer = (valModules, options, callbacks, platform) => {
7966
6681
  changedAt: codeMode.changedAt
7967
6682
  }
7968
6683
  }
7969
- };
6684
+ };
6685
+ }
6686
+ const saved = await saveBeforeCodeOutcome(cookies, "Saved before the code was changed");
6687
+ if ("saved" in saved) {
6688
+ const savedFirst = saved.saved;
6689
+ const staged = await proxyProposalsApi(path, "POST", profileId, JSON.stringify(body ?? {}));
6690
+ /*
6691
+ * `savedFirst` goes with content's answer: the tab that staged holds
6692
+ * the proposal's files (`projectSnapshot.ts` in `@valbuild/ui`), and a
6693
+ * save made here wrote `.val.ts` files it did not write itself.
6694
+ */
6695
+ return staged.status === 200 && isJsonObject(staged.json) ? {
6696
+ status: 200,
6697
+ json: {
6698
+ ...staged.json,
6699
+ savedFirst
6700
+ }
6701
+ } : staged;
7970
6702
  }
7971
- const saved = await saveBeforeCode(cookies, "Saved before the code was changed");
7972
- return saved === null ? null : {
6703
+ return {
7973
6704
  status: saved.status,
7974
6705
  json: {
7975
6706
  message: `The code was not changed, because the changes waiting to be saved could not be saved first: ${saved.message}`,
@@ -7985,6 +6716,17 @@ const ValServer = (valModules, options, callbacks, platform) => {
7985
6716
  * `null` when there was nothing to save or it was saved, otherwise why not.
7986
6717
  */
7987
6718
  const saveBeforeCode = async (cookies, message) => {
6719
+ const outcome = await saveBeforeCodeOutcome(cookies, message);
6720
+ return "saved" in outcome ? null : outcome;
6721
+ };
6722
+
6723
+ /**
6724
+ * {@link saveBeforeCode}, saying whether anything was saved: `saved: false`
6725
+ * when nothing was pending. What a staging's answer tells the tab
6726
+ * (`savedFirst`), which holds the proposal's files and has to know whether
6727
+ * a save changed a `.val.ts` under them.
6728
+ */
6729
+ const saveBeforeCodeOutcome = async (cookies, message) => {
7988
6730
  const chain = await serverOps.fetchPatches({
7989
6731
  excludePatchOps: true
7990
6732
  });
@@ -7995,12 +6737,16 @@ const ValServer = (valModules, options, callbacks, platform) => {
7995
6737
  };
7996
6738
  }
7997
6739
  const pending = chain.patches.filter(patch => patch.appliedAt === null).map(patch => patch.patchId);
7998
- if (pending.length === 0) return null;
6740
+ if (pending.length === 0) return {
6741
+ saved: false
6742
+ };
7999
6743
  const saved = await saveChanges(cookies, {
8000
6744
  patchIds: pending,
8001
6745
  message
8002
6746
  });
8003
- if (saved.status === 200) return null;
6747
+ if (saved.status === 200) return {
6748
+ saved: true
6749
+ };
8004
6750
  const said = "message" in saved.json && typeof saved.json.message === "string" ? saved.json.message : `the save answered ${saved.status}`;
8005
6751
  /*
8006
6752
  * Why, in the words of each module that could not be saved: "Failed to
@@ -8197,7 +6943,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
8197
6943
  }
8198
6944
  patchOps = {
8199
6945
  ...patchOps,
8200
- patches: draftOverlay(patchOps.patches, patchOps.commits)
6946
+ patches: ValPatchStore.draftOverlay(patchOps.patches, patchOps.commits)
8201
6947
  };
8202
6948
  const analysis = serverOps.analyzePatches(patchOps.patches);
8203
6949
  const {
@@ -9881,7 +8627,7 @@ const ValServer = (valModules, options, callbacks, platform) => {
9881
8627
  // version is the same for ever. The newest is a question, and
9882
8628
  // so is an answer with an entry that could not be read this
9883
8629
  // time (`isLastingAnswer`).
9884
- "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"
9885
8631
  },
9886
8632
  json: answer.ok
9887
8633
  };
@@ -11906,6 +10652,9 @@ function sourceFilePatchErrorsOf(json) {
11906
10652
  }
11907
10653
  return messages;
11908
10654
  }
10655
+ function isJsonObject(value) {
10656
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10657
+ }
11909
10658
 
11910
10659
  async function uploadRemoteFile(contentHost, project, bucket, fileHash, fileExt, fileBuffer, auth) {
11911
10660
  const authHeader = "apiKey" in auth ? {
@@ -12080,34 +10829,6 @@ function createMemorySketchpadStore(now = () => new Date()) {
12080
10829
  };
12081
10830
  }
12082
10831
 
12083
- /**
12084
- * One stored patch. Everything the ordered chain needs and nothing else.
12085
- */
12086
-
12087
- /**
12088
- * One pending binary file: an upload that has not been published yet.
12089
- *
12090
- * Keyed by the patch that carries it, exactly as `fs` mode keys the directory
12091
- * it writes to. The patch's own `file` op holds a hash, not the bytes, so these
12092
- * arrive on their own request and are joined up by `(patchId, filePath)`.
12093
- */
12094
-
12095
- /**
12096
- * Where pending patches live.
12097
- *
12098
- * The point of the interface: `ValOpsMemory` is not tied to memory. The default
12099
- * implementation below is explicitly NOT durable -- it dies with the process,
12100
- * or in a Worker with the isolate -- and a durable one (a Durable Object, whose
12101
- * single-threaded execution is the lock Val's fs store builds out of a file)
12102
- * is a swap rather than a rewrite.
12103
- *
12104
- * ORDER IS THE CONTRACT. `list()` returns patch ids in the order they were
12105
- * written, and that order is the chain: entry i's parent is entry i-1. This is
12106
- * the same decision `ValOpsFS` makes with `patches.log` -- the server decides
12107
- * where a patch goes, and it goes last -- and it exists for the same reason: an
12108
- * order held in the patches themselves lets a client working from a stale view
12109
- * strand every patch behind a parent that never landed.
12110
- */
12111
10832
  /**
12112
10833
  * Memory mode's `seq` (`ProjectVersion` in `@valbuild/shared/internal`), per
12113
10834
  * patch store: bumped beside `announceChange` by every write and delete, and
@@ -12134,69 +10855,6 @@ function seqOf(store) {
12134
10855
  }
12135
10856
  return counter;
12136
10857
  }
12137
- /** The default store. Not durable, deliberately and visibly. */
12138
- class InMemoryPatchStore {
12139
- order = [];
12140
- byId = new Map();
12141
- async list() {
12142
- return [...this.order];
12143
- }
12144
- async get(patchId) {
12145
- return this.byId.get(patchId) ?? null;
12146
- }
12147
- async append(patch) {
12148
- if (!this.byId.has(patch.patchId)) {
12149
- this.order.push(patch.patchId);
12150
- }
12151
- this.byId.set(patch.patchId, patch);
12152
- }
12153
- async delete(patchIds) {
12154
- for (const patchId of patchIds) {
12155
- const at = this.order.indexOf(patchId);
12156
- if (at !== -1) {
12157
- this.order.splice(at, 1);
12158
- }
12159
- this.byId.delete(patchId);
12160
- // The bytes go with the patch. They are only reachable through it, so
12161
- // keeping them would be a leak with no reader -- and these are images.
12162
- for (const key of this.files.keys()) {
12163
- if (key.startsWith(`${patchId}\u0000`)) {
12164
- this.files.delete(key);
12165
- }
12166
- }
12167
- }
12168
- }
12169
-
12170
- /*
12171
- * `\u0000` cannot occur in a patch id or a path, so the two halves of the key
12172
- * can never run together into a different pair.
12173
- *
12174
- * The PATH is normalised for the same reason `sourceFiles` is, and it is not
12175
- * cosmetic: an upload arrives as `/public/val/x.png`, and the publish step
12176
- * looks the same file up as `public/val/x.png` because that is what
12177
- * `splitRemoteRef` yields from a remote ref. `ValOpsFS` never noticed --
12178
- * `path.join` collapses the difference -- so this is another thing a
12179
- * filesystem was doing for free. Without it a remote image uploads fine,
12180
- * patches fine, and fails at publish with "No bytes held", naming a ref whose
12181
- * bytes are sitting right there under the other spelling.
12182
- */
12183
- static fileKey(patchId, filePath) {
12184
- return `${patchId}\u0000${filePath.replace(/^\//, "")}`;
12185
- }
12186
- files = new Map();
12187
- async putFile(file) {
12188
- this.files.set(InMemoryPatchStore.fileKey(file.patchId, file.filePath), file);
12189
- }
12190
- async getFile(patchId, filePath) {
12191
- return this.files.get(InMemoryPatchStore.fileKey(patchId, filePath)) ?? null;
12192
- }
12193
- async deleteFile(patchId, filePath) {
12194
- this.files.delete(InMemoryPatchStore.fileKey(patchId, filePath));
12195
- }
12196
- async filesOf(patchId) {
12197
- return [...this.files.values()].filter(file => file.patchId === patchId);
12198
- }
12199
- }
12200
10858
  /**
12201
10859
  * A `ValOps` for a host that is neither a developer's machine nor
12202
10860
  * content.val.build.
@@ -12270,7 +10928,7 @@ class ValOpsMemory extends ValOps {
12270
10928
  contentUrl;
12271
10929
  constructor(valModules, options) {
12272
10930
  super(valModules, options);
12273
- this.store = options.patchStore ?? new InMemoryPatchStore();
10931
+ this.store = options.patchStore ?? new ValPatchStore.InMemoryPatchStore();
12274
10932
  newestOnStore.set(this.store, this);
12275
10933
  this.contentUrl = options.contentUrl;
12276
10934
  this.requiresAuth = !options.unsafelyAllowUnauthenticated;
@@ -12361,7 +11019,7 @@ class ValOpsMemory extends ValOps {
12361
11019
  * one's count never saw: `null`, so the head reads the chain each time.
12362
11020
  */
12363
11021
  async chainSeq() {
12364
- if (!(this.store instanceof InMemoryPatchStore)) return null;
11022
+ if (!(this.store instanceof ValPatchStore.InMemoryPatchStore)) return null;
12365
11023
  return super.chainSeq();
12366
11024
  }
12367
11025
 
@@ -12818,615 +11476,9 @@ class ValOpsMemory extends ValOps {
12818
11476
 
12819
11477
  /** Kept exported so a host can name the error shape it may get back. */
12820
11478
 
12821
- /**
12822
- * What `redirect_to` may be on Val's routes (`/enable`, `/disable`,
12823
- * `/authorize`, `/draft/enable`, ...): a path on the site that was asked,
12824
- * which is made absolute against the request's own origin, or an absolute
12825
- * URL on that same site.
12826
- *
12827
- * A path used to go through as it was, and two things downstream need an
12828
- * absolute URL: `/authorize` reads the origin off it to build the callback,
12829
- * and Next's `NextResponse.redirect` refuses anything else. Both threw, so
12830
- * `/api/val/enable?redirect_to=/` answered 500 in a Next app.
12831
- *
12832
- * `//host/path` is a URL on another host, not a path on this one, and
12833
- * anything that is neither is refused with what is accepted instead. An
12834
- * empty value is not resolved at all: the router leaves it to the route, as
12835
- * it always was (`/logout` reads it as absent).
12836
- */
12837
-
12838
- 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).";
12839
-
12840
- /**
12841
- * `siteHosts` are the other names the request knows this site by (`Host`,
12842
- * `X-Forwarded-Host`), for a server behind a proxy whose own URL is internal.
12843
- */
12844
- function resolveRedirectTo(value, requestOrigin, siteHosts = []) {
12845
- if (value.startsWith("/") && !value.startsWith("//")) {
12846
- // A path stays on this origin. `/\host/x` also starts with one slash,
12847
- // and a URL parser reads the backslash as a second one: another host,
12848
- // not a path here.
12849
- const resolved = parsed(value, requestOrigin);
12850
- return resolved !== null && resolved.origin === new URL(requestOrigin).origin ? {
12851
- ok: true,
12852
- href: resolved.href
12853
- } : {
12854
- ok: false,
12855
- message: REDIRECT_TO_ACCEPTS
12856
- };
12857
- }
12858
- // An absolute URL, on this site only. Any URL used to pass, which made
12859
- // `/logout` and `/enable` redirect wherever a link said, and `/authorize`
12860
- // send the sign-in's code to that host: it reads the callback's origin off
12861
- // this. http(s) only: `javascript:` parses as a URL too.
12862
- const url = parsed(value);
12863
- if (url === null || url.protocol !== "https:" && url.protocol !== "http:") {
12864
- return {
12865
- ok: false,
12866
- message: REDIRECT_TO_ACCEPTS
12867
- };
12868
- }
12869
- const hosts = [new URL(requestOrigin).host, ...siteHosts].filter(host => typeof host === "string" && host !== "").map(host => host.toLowerCase());
12870
- return hosts.includes(url.host.toLowerCase()) ? {
12871
- ok: true,
12872
- href: value
12873
- } : {
12874
- ok: false,
12875
- message: REDIRECT_TO_ACCEPTS
12876
- };
12877
- }
12878
-
12879
- /**
12880
- * `value` as a URL, or null. Not `URL.canParse`: this runs in the browser
12881
- * too (demo mode), where it is missing before Safari 17 and Chrome 120.
12882
- */
12883
- function parsed(value, base) {
12884
- try {
12885
- return new URL(value, base);
12886
- } catch {
12887
- return null;
12888
- }
12889
- }
12890
-
12891
- /**
12892
- * Which requests Val's API answers in fs mode, where there is no session.
12893
- *
12894
- * fs mode reads and writes a working tree and asks nobody who they are: it is
12895
- * a developer's own machine. That holds only while the request really comes
12896
- * from that developer's Studio, and three kinds do not:
12897
- *
12898
- * - **A deployed site.** fs is the mode an app falls into when it has no
12899
- * `VAL_API_KEY` and `VAL_SECRET`, so a site deployed without them served
12900
- * this API, unauthenticated, to the internet.
12901
- * - **Another site's page**, in the developer's browser. A `text/plain` POST
12902
- * needs no preflight, and the router reads its body as JSON, so any page
12903
- * open in another tab could write to the working tree.
12904
- * - **A name that resolves to 127.0.0.1** (DNS rebinding), which makes such a
12905
- * page same-origin with the dev server as far as the browser can tell.
12906
- *
12907
- * The MCP endpoint has refused all three since it was written
12908
- * (`refuseUnsafeRequest` in `@valbuild/mcp`); this is the same rule for the
12909
- * API the Studio uses. Nothing here needs Node: `ValRouterCore` runs in a
12910
- * browser tab too, where no server is registered and nothing is refused.
12911
- */
12912
-
12913
- const guards = new WeakMap();
12914
-
12915
- /** Say how `server`'s requests are to be checked. Without it, none are. */
12916
- function setRequestGuard(server, guard) {
12917
- guards.set(server, guard);
12918
- }
12919
-
12920
- /** `VAL_ALLOWED_HOSTS`: comma separated host names, without a port. */
12921
- function parseAllowedHosts(value) {
12922
- return (value ?? "").split(",").map(host => host.trim().toLowerCase()).filter(host => host !== "");
12923
- }
12924
-
12925
- /** The refusal, or `null` when the request may go on to its route. */
12926
- function refuseUnsafeRequest(server, req, apiPath) {
12927
- var _req$method;
12928
- const guard = guards.get(server);
12929
- if (guard === undefined || guard.mode !== "fs") {
12930
- return null;
12931
- }
12932
- // Beacons are not refused: in fs mode one is checked and dropped, nothing
12933
- // is written or forwarded, and a deployed site with analytics on would fill
12934
- // every visitor's console with errors.
12935
- if (apiPath === "/analytics") {
12936
- return null;
12937
- }
12938
- if (guard.production) {
12939
- 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.");
12940
- }
12941
- const host = hostOf(req);
12942
- const forwardedHost = firstOf(req.headers.get("x-forwarded-host"));
12943
- const origin = req.headers.get("origin");
12944
- if (origin !== null) {
12945
- // `null` is the opaque origin (a sandboxed frame, a `file:` page). It
12946
- // cannot be compared with anything, so it is refused.
12947
- const originHost = origin === "null" ? null : hostOfUrl(origin);
12948
- if (originHost === null || originHost !== host && originHost !== forwardedHost) {
12949
- return refusal(`Val refused a request from another site (${origin}). In local filesystem mode the API only answers the Studio on its own address.`);
12950
- }
12951
- }
12952
- // A request with no `Origin` can still come from another site: an `<img>`,
12953
- // a script. Following a link here is not refused: sign-in comes back as
12954
- // one. A link is a GET; a form posted from another site navigates too.
12955
- const followedLink = ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === "GET" && req.headers.get("sec-fetch-mode") === "navigate";
12956
- if (req.headers.get("sec-fetch-site") === "cross-site" && !followedLink) {
12957
- return refusal("Val refused a request from another site. In local filesystem mode the API only answers the Studio on its own address.");
12958
- }
12959
- const hostname = host === null ? null : hostnameOf(host);
12960
- if (hostname === null || !isLocalName(hostname, guard.allowedHosts)) {
12961
- 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.`);
12962
- }
12963
- return null;
12964
- }
12965
- function refusal(message) {
12966
- return {
12967
- status: 403,
12968
- json: {
12969
- message
12970
- }
12971
- };
12972
- }
12973
- function firstOf(header) {
12974
- var _header$split$;
12975
- const first = header === null || header === void 0 || (_header$split$ = header.split(",")[0]) === null || _header$split$ === void 0 ? void 0 : _header$split$.trim().toLowerCase();
12976
- return first ? first : null;
12977
- }
12978
- function hostOf(req) {
12979
- const header = firstOf(req.headers.get("host"));
12980
- if (header !== null) {
12981
- return header;
12982
- }
12983
- // No Host header: the URL the framework built the request from.
12984
- return hostOfUrl(req.url);
12985
- }
12986
- function hostOfUrl(url) {
12987
- try {
12988
- return new URL(url).host.toLowerCase();
12989
- } catch {
12990
- return null;
12991
- }
12992
- }
12993
-
12994
- /** A host without its port. An IPv6 literal keeps its brackets. */
12995
- function hostnameOf(host) {
12996
- if (host.startsWith("[")) {
12997
- const end = host.indexOf("]");
12998
- return end === -1 ? host : host.slice(0, end + 1);
12999
- }
13000
- const colon = host.indexOf(":");
13001
- return colon === -1 ? host : host.slice(0, colon);
13002
- }
13003
-
13004
- /**
13005
- * localhost, an IP address, or a name the developer listed.
13006
- *
13007
- * An IP address is allowed because it cannot be rebound: a page that reaches
13008
- * this server by address is on another origin, and the `Origin` check above
13009
- * has already refused it. A phone on the same network uses one.
13010
- */
13011
- function isLocalName(hostname, allowedHosts) {
13012
- return hostname === "localhost" || hostname.endsWith(".localhost") || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname) || hostname.startsWith("[") && hostname.endsWith("]") || allowedHosts.includes(hostname);
13013
- }
13014
-
13015
- /**
13016
- * Val's API as a web-standard handler: a `Request` in, a converted result out.
13017
- *
13018
- * The request handling itself -- matching a route, parsing it against `Api`,
13019
- * calling the server, checking the answer -- and nothing that needs Node, so it
13020
- * runs in a browser tab as well as on a server. That is what the demo does
13021
- * (`@valbuild/server/browser`): the Studio's own client sends its requests
13022
- * here, in the same tab, instead of over the network.
13023
- *
13024
- * `serveStatic` answers `/static/...`, the Studio's own scripts and styles.
13025
- * `createValApiRouter` passes the embedded bundle; the demo passes nothing,
13026
- * because its page loaded those from the app already.
13027
- */
13028
- function createValRequestHandler(route, valServerPromise, convert, serveStatic) {
13029
- // valServerPromise is created at module-eval time, but only awaited per request.
13030
- // Without this no-op catch, a config error (e.g. proxy mode without a project)
13031
- // rejects with no handler attached, which becomes an unhandledRejection and kills
13032
- // the dev server. The error is still reported per request by the try/catch below.
13033
- valServerPromise.catch(() => {
13034
- // handled below
13035
- });
13036
- return async req => {
13037
- let valServer;
13038
- try {
13039
- valServer = await valServerPromise;
13040
- } catch (err) {
13041
- const error = {
13042
- message: "Val: could not start the Val server",
13043
- details: err instanceof Error ? err.message : String(err)
13044
- };
13045
- core.Internal.log.error(error.message + ": " + error.details);
13046
- return convert({
13047
- status: 500,
13048
- json: error
13049
- });
13050
- }
13051
- const url = new URL(req.url);
13052
- if (!url.pathname.startsWith(route)) {
13053
- const error = {
13054
- message: "Val: routes are not configured correctly",
13055
- details: `Check you api routes. Expected pathname to start with "${route}", but it was: "${url.pathname}"`
13056
- };
13057
- core.Internal.log.error(error);
13058
- return convert({
13059
- status: 500,
13060
- json: error
13061
- });
13062
- }
13063
- const path = url.pathname.slice(route.length);
13064
- if (path === internal.QUICK_PREVIEW_SERVICE_WORKER_PATH) {
13065
- /*
13066
- * The quick preview worker (`quickPreview.ts` in
13067
- * `@valbuild/shared`). `Service-Worker-Allowed: /` lets a script at
13068
- * this path control the whole origin, which it needs: it serves the
13069
- * page's `/_app/` files. It serves them only to a page opened as a
13070
- * quick preview, and the bridge stores them only for the site.
13071
- */
13072
- return convert({
13073
- status: 200,
13074
- headers: {
13075
- "Content-Type": "text/javascript; charset=utf-8",
13076
- "Service-Worker-Allowed": "/",
13077
- "Cache-Control": "no-cache"
13078
- },
13079
- body: internal.QUICK_PREVIEW_SERVICE_WORKER_SOURCE
13080
- });
13081
- }
13082
- const groupQueryParams = arr => {
13083
- const map = {};
13084
- for (const [key, value] of arr) {
13085
- const list = map[key] || [];
13086
- list.push(value);
13087
- map[key] = list;
13088
- }
13089
- return map;
13090
- };
13091
- async function getValServerResponse(reqApiRoutePath, req) {
13092
- var _req$method, _anyApi$route, _anyValServer$route;
13093
- const anyApi =
13094
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
13095
- internal.Api;
13096
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
13097
- const anyValServer = valServer;
13098
- const refused = refuseUnsafeRequest(valServer, req, reqApiRoutePath);
13099
- if (refused !== null) {
13100
- return refused;
13101
- }
13102
- const method = (_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase();
13103
- let route = null;
13104
- let path = undefined;
13105
- // An exact match wins over every prefix match, wherever it sits in
13106
- // `Api`: checked per key, in order, `/validate` took `/validate/fix`
13107
- // because it was declared first.
13108
- const exactRouteDef = Object.keys(internal.Api).find(routeDef => routeDef === reqApiRoutePath);
13109
- for (const routeDef of exactRouteDef ? [exactRouteDef] : Object.keys(internal.Api)) {
13110
- if (routeDef === reqApiRoutePath) {
13111
- route = routeDef;
13112
- break;
13113
- }
13114
- if (reqApiRoutePath.startsWith(routeDef)) {
13115
- var _anyApi$routeDef;
13116
- 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;
13117
- if (reqDefinition) {
13118
- route = routeDef;
13119
- if (reqDefinition.path) {
13120
- const subPath = reqApiRoutePath.slice(routeDef.length);
13121
- const pathRes = reqDefinition.path.safeParse(subPath);
13122
- if (!pathRes.success) {
13123
- return zodErrorResult(pathRes.error, `invalid path: '${subPath}' endpoint: '${routeDef}'`);
13124
- } else {
13125
- path = pathRes.data;
13126
- }
13127
- }
13128
- break;
13129
- }
13130
- }
13131
- }
13132
- if (!route) {
13133
- return {
13134
- status: 404,
13135
- json: {
13136
- message: "Route not found. Valid routes are: " + Object.keys(internal.Api),
13137
- details: {
13138
- route,
13139
- method
13140
- }
13141
- }
13142
- };
13143
- }
13144
- const apiEndpoint = anyApi === null || anyApi === void 0 || (_anyApi$route = anyApi[route]) === null || _anyApi$route === void 0 ? void 0 : _anyApi$route[method];
13145
- const reqDefinition = apiEndpoint === null || apiEndpoint === void 0 ? void 0 : apiEndpoint.req;
13146
- if (!reqDefinition) {
13147
- return {
13148
- status: 404,
13149
- json: {
13150
- message: `Requested method ${method} on route ${route} is not valid. Valid methods are: ${Object.keys(anyApi[route]).join(", ")}`,
13151
- details: {
13152
- route,
13153
- method
13154
- }
13155
- }
13156
- };
13157
- }
13158
- const endpointImpl = anyValServer === null || anyValServer === void 0 || (_anyValServer$route = anyValServer[route]) === null || _anyValServer$route === void 0 ? void 0 : _anyValServer$route[method];
13159
- if (!endpointImpl) {
13160
- return {
13161
- status: 500,
13162
- json: {
13163
- message: "Missing server implementation of route with method. This might be caused by a mismatch between Val package versions.",
13164
- details: {
13165
- valid: {
13166
- route: {
13167
- server: Object.keys(anyValServer || {}),
13168
- api: Object.keys(anyApi || {})
13169
- },
13170
- method: {
13171
- server: Object.keys((anyValServer === null || anyValServer === void 0 ? void 0 : anyValServer[route]) || {}),
13172
- api: Object.keys((anyApi === null || anyApi === void 0 ? void 0 : anyApi[route]) || {})
13173
- }
13174
- },
13175
- route,
13176
- method
13177
- }
13178
- }
13179
- };
13180
- }
13181
- let bodyRes;
13182
- try {
13183
- bodyRes = reqDefinition.body ? reqDefinition.body.safeParse(await readJsonBody(req)) : {
13184
- success: true,
13185
- data: {}
13186
- };
13187
- if (!bodyRes.success) {
13188
- return zodErrorResult(bodyRes.error, "invalid body data");
13189
- }
13190
- } catch (e) {
13191
- return {
13192
- status: 400,
13193
- json: {
13194
- message: "Could not parse request body",
13195
- details: {
13196
- error: JSON.stringify(e)
13197
- }
13198
- }
13199
- };
13200
- }
13201
- const cookiesRes = reqDefinition.cookies ? getCookies(req, reqDefinition.cookies) : {
13202
- success: true,
13203
- data: {}
13204
- };
13205
- if (!cookiesRes.success) {
13206
- return zodErrorResult(cookiesRes.error, "invalid cookies");
13207
- }
13208
- const headersRes = reqDefinition.headers ? getHeaders(req, reqDefinition.headers) : {
13209
- success: true,
13210
- data: {}
13211
- };
13212
- if (!headersRes.success) {
13213
- return zodErrorResult(headersRes.error, "invalid headers");
13214
- }
13215
- const actualQueryParams = groupQueryParams(Array.from(url.searchParams.entries()));
13216
- let query = {};
13217
- if (reqDefinition.query) {
13218
- const queryRules = reqDefinition.query;
13219
- const queryRes = z.z.object(queryRules).safeParse(actualQueryParams);
13220
- if (!queryRes.success) {
13221
- return zodErrorResult(queryRes.error, `invalid query params: (${JSON.stringify(actualQueryParams)})`);
13222
- }
13223
- query = queryRes.data;
13224
- }
13225
- // `redirect_to` is a URL or a path on this site: see `resolveRedirectTo`.
13226
- if ("redirect_to" in query && typeof query.redirect_to === "string" && query.redirect_to !== "") {
13227
- var _req$headers$get;
13228
- // Behind a proxy `url` can be an internal address: the site's own
13229
- // name is then in `Host` or `X-Forwarded-Host`.
13230
- 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()]);
13231
- if (!resolved.ok) {
13232
- return {
13233
- status: 400,
13234
- json: {
13235
- message: resolved.message
13236
- }
13237
- };
13238
- }
13239
- query = {
13240
- ...query,
13241
- redirect_to: resolved.href
13242
- };
13243
- }
13244
-
13245
- /*
13246
- * A throw from an endpoint is Val's to report, not the framework's.
13247
- *
13248
- * Nothing here used to catch, so an endpoint that threw left the router
13249
- * entirely and became whatever the host does with an unhandled error --
13250
- * and on TanStack Start that is h3, which replaces the message with the
13251
- * literal string "HTTPError" and drops the stack. Its `debug` and
13252
- * `silent` options are not reachable from out here: `requestHandler`
13253
- * calls `toResponse(value, event)` with no config, and the default is
13254
- * `{}`. So the body a caller got was
13255
- * `{"status":500,"unhandled":true,"message":"HTTPError"}` -- the same
13256
- * five words for a missing project, a bad cookie secret and a module
13257
- * that failed to link -- with the real cause only on the server's
13258
- * console.
13259
- *
13260
- * That is survivable where the console is readable. It is not in a
13261
- * Cloudflare Dynamic Worker, whose `console` reaches no tail stream: a
13262
- * link error in a lazily imported chunk (`does not provide an export
13263
- * named 'getSerovalPlugins'`) showed up as an unreadable 500 on
13264
- * `/authorize` and nowhere else at all.
13265
- *
13266
- * So every endpoint's throw becomes Val's own 500 envelope, which the
13267
- * Studio already renders and `curl` already prints. The route and method
13268
- * are named because a message rarely says which endpoint it came from.
13269
- *
13270
- * The MESSAGE travels and the STACK does not. The message is the whole
13271
- * diagnostic value -- the line above names the package, the chunk and
13272
- * the export -- while a stack is a walk through somebody's bundle, and
13273
- * `/authorize` and `/enable` are reachable without a session. So the
13274
- * stack goes to the console, where a host that can read one will find
13275
- * it, and the body carries what a caller can act on.
13276
- */
13277
- let res;
13278
- try {
13279
- res = await endpointImpl({
13280
- body: bodyRes.data,
13281
- cookies: cookiesRes.data,
13282
- headers: headersRes.data,
13283
- rawQuery: reqDefinition.rawQuery ? url.search : undefined,
13284
- query,
13285
- path
13286
- });
13287
- } catch (err) {
13288
- const error = err instanceof Error ? err : new Error(String(err));
13289
- core.Internal.log.error(`${method} ${route} threw: ${error.message}`, error.stack);
13290
- return {
13291
- status: 500,
13292
- json: {
13293
- message: `Val: ${method} ${route} failed: ${error.message}`,
13294
- details: {
13295
- route,
13296
- method,
13297
- error: error.message
13298
- }
13299
- }
13300
- };
13301
- }
13302
- const resDef = apiEndpoint.res;
13303
- if (res.status === 500) {
13304
- var _res$json;
13305
- /*
13306
- * A failure the route declares goes out as declared, as a success
13307
- * does below. DELETE /patches says which change was not discarded and
13308
- * which publish holds it, and collapsed to its message the Studio
13309
- * could only say "Failed to delete patches" -- not why, nor offer to
13310
- * cancel that publish. Anything undeclared is still reduced to its
13311
- * message.
13312
- */
13313
- if (resDef !== null && resDef !== void 0 && resDef.safeParse(res).success) return res;
13314
- return {
13315
- status: 500,
13316
- json: {
13317
- message: ((_res$json = res.json) === null || _res$json === void 0 ? void 0 : _res$json.message) || "Internal Server Error"
13318
- }
13319
- };
13320
- }
13321
- if (resDef) {
13322
- const responseResult = resDef.safeParse(res);
13323
- if (!responseResult.success) {
13324
- return {
13325
- status: 500,
13326
- json: {
13327
- message: "Could not validate response. This is likely a bug in Val server.",
13328
- details: {
13329
- response: res,
13330
- errors: formatZodErrorString(responseResult.error)
13331
- }
13332
- }
13333
- };
13334
- }
13335
- }
13336
- return res;
13337
- }
13338
- if (path.startsWith("/static")) {
13339
- if (!serveStatic) {
13340
- return convert({
13341
- status: 404,
13342
- json: {
13343
- message: "Val: this server does not serve the Studio's own files"
13344
- }
13345
- });
13346
- }
13347
- return convert(await serveStatic(path.slice("/static".length), url.href));
13348
- } else {
13349
- return convert(await getValServerResponse(path, req));
13350
- }
13351
- };
13352
- }
13353
- function formatZodErrorString(error) {
13354
- const errors = zodValidationError.fromError(error).toString();
13355
- return errors.length > 640 ? `${errors.slice(0, 640)}...` : errors;
13356
- }
13357
-
13358
- /**
13359
- * The request's JSON body, or `undefined` when it has none.
13360
- *
13361
- * `req.json()` THROWS on an empty body, and the router used to call it
13362
- * unconditionally for any route that declares a body — so the moment
13363
- * `DELETE /patches` gained an optional body, every caller that sent none got
13364
- * `400 Could not parse request body`. Declaring the schema `.optional()` did
13365
- * not help: the throw happens before zod is ever consulted. Six e2e tests went
13366
- * red on a helper doing exactly what the route still permits.
13367
- *
13368
- * Told apart by the request rather than by catching, so a body that IS sent and
13369
- * is malformed still fails: absent means no content type and nothing to read,
13370
- * and anything else is parsed and allowed to throw. A route whose schema
13371
- * requires a body is unaffected — it gets `undefined` and zod refuses it, with
13372
- * the same 400 as before, now naming the field.
13373
- */
13374
- async function readJsonBody(req) {
13375
- if (req.headers.get("content-length") === "0") {
13376
- return undefined;
13377
- }
13378
- const text = await req.text();
13379
- if (text.length === 0) {
13380
- return undefined;
13381
- }
13382
- return JSON.parse(text);
13383
- }
13384
- function zodErrorResult(error, message) {
13385
- return {
13386
- status: 400,
13387
- json: {
13388
- message: "Bad Request: " + message,
13389
- details: {
13390
- errors: formatZodErrorString(error)
13391
- }
13392
- }
13393
- };
13394
- }
13395
-
13396
- // TODO: is this naive implementation is too naive?
13397
- /** The declared headers, by name; `Headers.get` is case-insensitive. */
13398
- function getHeaders(req, headersDef) {
13399
- const input = {};
13400
- for (const name of Object.keys(headersDef)) {
13401
- var _req$headers;
13402
- const value = (_req$headers = req.headers) === null || _req$headers === void 0 ? void 0 : _req$headers.get(name);
13403
- if (value !== null && value !== undefined) {
13404
- input[name] = value;
13405
- }
13406
- }
13407
- return z.z.object(headersDef).safeParse(input);
13408
- }
13409
- function getCookies(req, cookiesDef) {
13410
- var _req$headers2;
13411
- const input = {};
13412
- 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("; ");
13413
- for (const name of Object.keys(cookiesDef)) {
13414
- const cookie = cookieParts === null || cookieParts === void 0 ? void 0 : cookieParts.find(cookie => cookie.startsWith(`${name}=`));
13415
- const value = cookie ? decodeURIComponent(cookie === null || cookie === void 0 ? void 0 : cookie.split("=")[1]) : undefined;
13416
- if (value) {
13417
- input[name.trim()] = value;
13418
- }
13419
- }
13420
- return z.z.object(cookiesDef).safeParse(input);
13421
- }
13422
-
13423
11479
  exports.DEFAULT_ANALYTICS_INGEST_URL = DEFAULT_ANALYTICS_INGEST_URL;
13424
- exports.HEAD_BUDGET_BYTES = HEAD_BUDGET_BYTES;
13425
- exports.HEAD_VERSIONS_PER_MODULE = HEAD_VERSIONS_PER_MODULE;
13426
- exports.InMemoryPatchStore = InMemoryPatchStore;
13427
11480
  exports.MEDIA_FILE_PATH_ACCEPTS = MEDIA_FILE_PATH_ACCEPTS;
13428
11481
  exports.VAL_CLIENT_HEADERS = VAL_CLIENT_HEADERS;
13429
- exports.ValHead = ValHead;
13430
11482
  exports.ValOps = ValOps;
13431
11483
  exports.ValOpsMemory = ValOpsMemory;
13432
11484
  exports.ValServer = ValServer;
@@ -13438,17 +11490,13 @@ exports.bytesToBase64 = bytesToBase64;
13438
11490
  exports.bytesToUtf8 = bytesToUtf8;
13439
11491
  exports.checkRemoteFiles = checkRemoteFiles;
13440
11492
  exports.createMetadataFromBuffer = createMetadataFromBuffer;
13441
- exports.createValRequestHandler = createValRequestHandler;
13442
11493
  exports.fallbackRefOf = fallbackRefOf;
13443
11494
  exports.fallbackRemoteHost = fallbackRemoteHost;
13444
- exports.findNestedJsonValuesRecords = findNestedJsonValuesRecords;
13445
11495
  exports.formatPatchSourceError = formatPatchSourceError;
13446
11496
  exports.getFieldsForType = getFieldsForType;
13447
11497
  exports.getFileExt = getFileExt;
13448
- exports.getNewJsonEntryPaths = getNewJsonEntryPaths;
13449
11498
  exports.getSettings = getSettings;
13450
11499
  exports.guessMimeTypeFromPath = guessMimeTypeFromPath;
13451
- exports.headWork = headWork;
13452
11500
  exports.isHlsMasterPlaylist = isHlsMasterPlaylist;
13453
11501
  exports.isHttpOps = isHttpOps;
13454
11502
  exports.isMediaFilePath = isMediaFilePath;
@@ -13461,13 +11509,9 @@ exports.matchesFilter = matchesFilter;
13461
11509
  exports.movedRemoteHost = movedRemoteHost;
13462
11510
  exports.needsHostCheck = needsHostCheck;
13463
11511
  exports.newSketchpad = newSketchpad;
13464
- exports.parseAllowedHosts = parseAllowedHosts;
13465
11512
  exports.parseHlsMasterVariants = parseHlsMasterVariants;
13466
- exports.posixPath = posixPath;
13467
- exports.resolveExistingJsonPath = resolveExistingJsonPath;
13468
11513
  exports.rewriteRefHost = rewriteRefHost;
13469
11514
  exports.sessionAuth = sessionAuth;
13470
- exports.setRequestGuard = setRequestGuard;
13471
11515
  exports.sumHlsSegmentDurations = sumHlsSegmentDurations;
13472
11516
  exports.summaryOf = summaryOf;
13473
11517
  exports.uploadRemoteFile = uploadRemoteFile;