@valbuild/server 0.154.1 → 0.154.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +6 -3
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +6 -3
  4. package/browser/dist/valbuild-server-browser.esm.js +6 -3
  5. package/dist/{ValRouterCore-cfb35067.cjs.prod.js → ValOpsMemory-18337353.cjs.prod.js} +23 -2013
  6. package/dist/{ValRouterCore-361673dc.cjs.dev.js → ValOpsMemory-45ba05ad.cjs.dev.js} +23 -2013
  7. package/dist/{ValRouterCore-be314bc7.esm.js → ValOpsMemory-972616ae.esm.js} +14 -1992
  8. package/dist/ValPatchStore-2f92eced.cjs.prod.js +1128 -0
  9. package/dist/ValPatchStore-df8cdbe7.cjs.dev.js +1128 -0
  10. package/dist/ValPatchStore-e23070df.esm.js +1119 -0
  11. package/dist/ValRouterCore-5b747abb.cjs.prod.js +612 -0
  12. package/dist/ValRouterCore-73eb843d.esm.js +608 -0
  13. package/dist/ValRouterCore-86757d56.cjs.dev.js +612 -0
  14. package/dist/createPrettierFormatter-05ad7480.cjs.prod.js +692 -0
  15. package/dist/createPrettierFormatter-1edca494.esm.js +673 -0
  16. package/dist/createPrettierFormatter-851fcf99.cjs.dev.js +692 -0
  17. package/dist/createValRuntime-472df6e8.cjs.prod.js +47 -0
  18. package/dist/createValRuntime-5cebf459.cjs.dev.js +47 -0
  19. package/dist/createValRuntime-c77ee010.esm.js +45 -0
  20. package/dist/declarations/src/ValOpsMemory.d.ts +3 -73
  21. package/dist/declarations/src/ValPatchStore.d.ts +92 -0
  22. package/dist/declarations/src/ValRouter.d.ts +1 -11
  23. package/dist/declarations/src/createPrettierFormatter.d.ts +18 -3
  24. package/dist/declarations/src/createValRuntime.d.ts +12 -0
  25. package/dist/declarations/src/draftReads.d.ts +11 -3
  26. package/dist/declarations/src/index.d.ts +4 -2
  27. package/dist/declarations/src/internal/index.d.ts +28 -6
  28. package/dist/declarations/src/proposal.d.ts +13 -25
  29. package/dist/declarations/src/proposalJsonEntries.d.ts +30 -0
  30. package/dist/declarations/src/serverMode.d.ts +31 -0
  31. package/dist/{draftReads-0dcddf72.cjs.prod.js → draftReads-3f7dcda5.cjs.prod.js} +10 -2
  32. package/dist/{draftReads-df44e629.cjs.dev.js → draftReads-a300a02f.cjs.dev.js} +10 -2
  33. package/dist/{draftReads-1f29aedd.esm.js → draftReads-bca0d49c.esm.js} +10 -2
  34. package/dist/{inTabFetch-7c8a5628.esm.js → inTabFetch-0c997998.esm.js} +2 -1
  35. package/dist/{inTabFetch-56226d62.cjs.prod.js → inTabFetch-c2efa1bd.cjs.prod.js} +5 -4
  36. package/dist/{inTabFetch-5d0314a3.cjs.dev.js → inTabFetch-db6d6425.cjs.dev.js} +5 -4
  37. package/dist/jsonValuesPatch-13acc674.esm.js +276 -0
  38. package/dist/jsonValuesPatch-88bc661d.cjs.dev.js +281 -0
  39. package/dist/jsonValuesPatch-92798812.cjs.prod.js +281 -0
  40. package/dist/proposalJsonEntries-0669f027.esm.js +480 -0
  41. package/dist/proposalJsonEntries-26f397bd.cjs.dev.js +500 -0
  42. package/dist/proposalJsonEntries-9e537244.cjs.prod.js +500 -0
  43. package/dist/{publishKit-707230bc.cjs.prod.js → publishKit-38d46a51.cjs.dev.js} +20 -22
  44. package/dist/{publishKit-5a8c9a0d.cjs.dev.js → publishKit-7aca03bb.cjs.prod.js} +20 -22
  45. package/dist/{publishKit-b850045b.esm.js → publishKit-ac0af189.esm.js} +8 -9
  46. package/dist/{ValRouter-9505c550.cjs.dev.js → valRuntime-2a3cc887.cjs.prod.js} +158 -6038
  47. package/dist/{ValRouter-31f89baf.cjs.prod.js → valRuntime-70ee2dc2.cjs.dev.js} +158 -6038
  48. package/dist/{ValRouter-b7dc784d.esm.js → valRuntime-e4d26702.esm.js} +107 -5937
  49. package/dist/valbuild-server.cjs.dev.js +5146 -352
  50. package/dist/valbuild-server.cjs.prod.js +5146 -352
  51. package/dist/valbuild-server.esm.js +4902 -132
  52. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +7 -4
  53. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +7 -4
  54. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +7 -4
  55. package/internal/dist/valbuild-server-internal.cjs.dev.js +47 -31
  56. package/internal/dist/valbuild-server-internal.cjs.prod.js +47 -31
  57. package/internal/dist/valbuild-server-internal.esm.js +38 -22
  58. package/package.json +4 -4
@@ -0,0 +1,692 @@
1
+ 'use strict';
2
+
3
+ var core = require('@valbuild/core');
4
+ var internal = require('@valbuild/shared/internal');
5
+ var path = require('path');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
8
+
9
+ var path__default = /*#__PURE__*/_interopDefault(path);
10
+
11
+ /**
12
+ * The modules whose staged code the build serving the address was NOT made
13
+ * of, each with its schema version (`staged:<inputs>`): every module the
14
+ * overlay names as staged, except those whose version names the very inputs
15
+ * the build was made of. Those the build evaluated: they are served as any
16
+ * other module.
17
+ *
18
+ * A module staged after the build has a schema this server does not have.
19
+ * Its Source is read from its staged text ({@link ValProposal.files}), its
20
+ * version is the staging's, so no reader takes it for the build's, and a save
21
+ * applies to that text (`docs/plans/one-content-model.md`, "Phase 9 without
22
+ * phases 6 and 7"; valbuild/home `docs/proposals.md`, "Staged schemas").
23
+ *
24
+ * Whole-staging inputs, not one per module, and that is what makes this
25
+ * sound: a module's schema can move with a file it imports, so "its own file
26
+ * is unchanged" never says its code is in the build.
27
+ */
28
+ function stagedAfterBuild(proposal, build) {
29
+ const inBuild = proposal.buildInputs === null || proposal.buildInputs === undefined ? null : `${internal.STAGED_SCHEMA_PREFIX}${proposal.buildInputs}`;
30
+ const after = {};
31
+ for (const [path, version] of Object.entries(proposal.staged ?? {})) {
32
+ if (version === inBuild) continue;
33
+ after[path] = version;
34
+ }
35
+ if (build === undefined || proposal.files === undefined) return after;
36
+ /*
37
+ * Through what a module imports. The overlay names only staged MODULE
38
+ * files, and a module's schema moves with any file it imports, so a module
39
+ * whose own file is not staged can still be of code the build was not made
40
+ * of. What changed since the build is read from text: a file the proposal
41
+ * holds that is code (not a module file, not an entry's `*.val.json` --
42
+ * saves write those, stagings write code) and whose text is not what the
43
+ * build was made of; and every module file staged after the build. A
44
+ * module that depends on one of those, as the build resolved its imports,
45
+ * is staged after the build as well.
46
+ */
47
+ const changed = new Set(Object.keys(after).map(path => path.replace(/^\/+/, "")));
48
+ const changedCode = [];
49
+ for (const [path, text] of Object.entries(proposal.files)) {
50
+ if (isModuleOrEntryFile(path)) continue;
51
+ if (build.source[path] === text) continue;
52
+ changed.add(path);
53
+ changedCode.push([path, text]);
54
+ }
55
+ if (changed.size === 0) return after;
56
+ /*
57
+ * Named after the staging where the overlay names it (every staged
58
+ * module's version is the same `staged:<inputs>`); where it names none --
59
+ * only code that is not a module was staged -- after the code that
60
+ * changed, which is as distinct per staging and is never a build's.
61
+ */
62
+ const named = Object.values(proposal.staged ?? {})[0] ?? `${internal.STAGED_SCHEMA_PREFIX}${hashOfFiles(changedCode)}`;
63
+ for (const [modulePath, dependencies] of Object.entries(build.moduleDependencies)) {
64
+ const moduleFilePath = `/${modulePath.replace(/^\/+/, "")}`;
65
+ if (after[moduleFilePath] !== undefined) continue;
66
+ if (dependencies.some(dependency => changed.has(dependency))) {
67
+ after[moduleFilePath] = named;
68
+ }
69
+ }
70
+ return after;
71
+ }
72
+
73
+ /**
74
+ * What the build serving the address was made of, as the platform builds it
75
+ * and embeds it: its own source (`platform:project-source`) and, for each
76
+ * module file, every project file it depends on as the build resolved its
77
+ * imports (`moduleDependencies`, by path with no leading slash, transitive).
78
+ * For {@link stagedAfterBuild}.
79
+ */
80
+
81
+ /** The {@link ServingBuild} a host handed over, or `undefined` when not both. */
82
+ function servingBuildOf(http) {
83
+ return http.projectSource !== undefined && http.moduleDependencies !== undefined ? {
84
+ source: http.projectSource,
85
+ moduleDependencies: http.moduleDependencies
86
+ } : undefined;
87
+ }
88
+ function isModuleOrEntryFile(path) {
89
+ return /\.val\.(ts|js|json)$/.test(path);
90
+ }
91
+
92
+ /** A 64-hex name for code that changed: its paths and text, in order. */
93
+ function hashOfFiles(files) {
94
+ const sorted = [...files].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
95
+ return core.Internal.getSHA256Hash(new TextEncoder().encode(JSON.stringify(sorted)));
96
+ }
97
+
98
+ /**
99
+ * The proposal a platform describes in its runtime env, or `undefined` when
100
+ * this is not a proposal's address.
101
+ *
102
+ * `VAL_PROPOSAL` and `VAL_BRANCH` name it; `VAL_OVERLAY` is the snapshot as
103
+ * JSON (`{ commit, modules, files, staged }`); `VAL_BUILD_INPUTS` says which
104
+ * staging the build was made of. Throws on a snapshot that does not parse
105
+ * rather than serving the base build as though it were the proposal: a
106
+ * reviewer would be looking at the wrong content and nothing would say so.
107
+ */
108
+ function proposalFromEnv(env) {
109
+ const name = env.VAL_PROPOSAL;
110
+ const branch = env.VAL_BRANCH;
111
+ if (!name || !branch) {
112
+ return undefined;
113
+ }
114
+ let parsed = {};
115
+ if (env.VAL_OVERLAY) {
116
+ try {
117
+ parsed = JSON.parse(env.VAL_OVERLAY);
118
+ } catch (err) {
119
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY is not JSON (${err instanceof Error ? err.message : String(err)})`, {
120
+ cause: err
121
+ });
122
+ }
123
+ }
124
+ if (!isObject(parsed)) {
125
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY is not an object`);
126
+ }
127
+ const modulesIn = parsed["modules"] ?? {};
128
+ const filesIn = parsed["files"] ?? {};
129
+ const commit = parsed["commit"] ?? null;
130
+ if (!isObject(modulesIn) || !isObject(filesIn)) {
131
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY's modules and files must be objects`);
132
+ }
133
+ if (commit !== null && typeof commit !== "string") {
134
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY's commit must be a string or null`);
135
+ }
136
+ const files = {};
137
+ for (const [path, text] of Object.entries(filesIn)) {
138
+ if (typeof text === "string") {
139
+ files[path] = text;
140
+ }
141
+ }
142
+ return {
143
+ name,
144
+ branch,
145
+ commit,
146
+ modules: modulesIn,
147
+ files,
148
+ staged: stagedOf(name, parsed["staged"]),
149
+ buildInputs: buildInputsOf(name, env.VAL_BUILD_INPUTS)
150
+ };
151
+ }
152
+
153
+ /**
154
+ * The overlay's `staged`, checked: `{}` when it does not say (an overlay
155
+ * written before it). One that says something else than module paths with
156
+ * `staged:` versions is thrown: read as "none staged", a save would apply to
157
+ * a staged module as a build that never evaluated it.
158
+ */
159
+ function stagedOf(name, staged) {
160
+ if (staged === undefined || staged === null) return {};
161
+ if (!isObject(staged)) {
162
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY's staged must be an object`);
163
+ }
164
+ const out = {};
165
+ for (const [path, version] of Object.entries(staged)) {
166
+ if (!path.startsWith("/") || typeof version !== "string" || !version.startsWith(internal.STAGED_SCHEMA_PREFIX)) {
167
+ throw new Error(`Val: proposal ${name}: VAL_OVERLAY's staged must name module files with staged:<inputs> versions (${JSON.stringify(path)})`);
168
+ }
169
+ out[path] = version;
170
+ }
171
+ return out;
172
+ }
173
+
174
+ /**
175
+ * `VAL_BUILD_INPUTS`: 64 hex, or nothing. Anything else is thrown, for the
176
+ * same reason as {@link stagedOf}, in the other direction: read as "the
177
+ * build has it", a save would apply to staged code as though it were built.
178
+ */
179
+ function buildInputsOf(name, inputs) {
180
+ if (inputs === undefined || inputs === "") return null;
181
+ if (!/^[0-9a-f]{64}$/.test(inputs)) {
182
+ throw new Error(`Val: proposal ${name}: VAL_BUILD_INPUTS is not a build's staged inputs (64 hex)`);
183
+ }
184
+ return inputs;
185
+ }
186
+
187
+ /**
188
+ * A content version: the site's content, served by a build that bundles an
189
+ * older one. valbuild/home `docs/hosted-publishing.md`, step 2.
190
+ *
191
+ * The platform hands over only what differs from the bundle -- the modules
192
+ * whose Source changed and the Val files whose text did -- the way it hands a
193
+ * proposal's address its saved content, and it is read the same way: the
194
+ * snapshot source provider, over the bundle. What differs is the position: a
195
+ * version names the publish that made it (`job`, or its `commit`), and that is
196
+ * where this server says it sits, never at the build it runs in.
197
+ */
198
+
199
+ /**
200
+ * The content version a platform hands over in its runtime env
201
+ * (`VAL_CONTENT`), or `undefined` when it hands over none.
202
+ *
203
+ * Throws on one it cannot read rather than serving the bundle as though it
204
+ * were the version: the site would show content older than what was
205
+ * published, and nothing would say so.
206
+ *
207
+ * A version too large for one variable names others under `refs`: a module's
208
+ * Source (JSON) or a file's text, each in a variable of its own --
209
+ * `{ "refs": { "modules": { "/a.val.ts": "env://VAL_CONTENT_1" } } }`. Flat:
210
+ * a referenced variable holds the value itself and is never read for further
211
+ * references. Only `refs` is resolved, never a string inside Source, and only
212
+ * `VAL_CONTENT_<n>` is ever read: Source is text editors write, and a
213
+ * reference resolved in there would read any variable the isolate holds,
214
+ * `VAL_SECRET` included, into a page. The scheme leaves room for another
215
+ * place to read from; one this does not know is refused, not skipped.
216
+ */
217
+ function contentFromEnv(env) {
218
+ if (!env.VAL_CONTENT) {
219
+ return undefined;
220
+ }
221
+ let parsed;
222
+ try {
223
+ parsed = JSON.parse(env.VAL_CONTENT);
224
+ } catch (err) {
225
+ throw new Error(`Val: VAL_CONTENT is not JSON (${err instanceof Error ? err.message : String(err)})`, {
226
+ cause: err
227
+ });
228
+ }
229
+ if (!isObject(parsed) || Array.isArray(parsed)) {
230
+ throw new Error("Val: VAL_CONTENT is not an object");
231
+ }
232
+ const id = parsed["id"];
233
+ if (typeof id !== "string" || id === "") {
234
+ throw new Error("Val: VAL_CONTENT has no id");
235
+ }
236
+ const job = parsed["job"] ?? null;
237
+ const commit = parsed["commit"] ?? null;
238
+ if (job !== null && typeof job !== "string") {
239
+ throw new Error(`Val: content version ${id}: job must be a string or null`);
240
+ }
241
+ if (commit !== null && typeof commit !== "string") {
242
+ throw new Error(`Val: content version ${id}: commit must be a string or null`);
243
+ }
244
+ const modulesIn = parsed["modules"] ?? {};
245
+ const filesIn = parsed["files"] ?? {};
246
+ if (!isObject(modulesIn) || Array.isArray(modulesIn) || !isObject(filesIn) || Array.isArray(filesIn)) {
247
+ throw new Error(`Val: content version ${id}: modules and files must be objects`);
248
+ }
249
+ const files = {};
250
+ for (const [path, text] of Object.entries(filesIn)) {
251
+ if (typeof text === "string") {
252
+ files[path] = text;
253
+ }
254
+ }
255
+ const modules = {
256
+ ...modulesIn
257
+ };
258
+ const refs = parsed["refs"] ?? {};
259
+ if (!isObject(refs) || Array.isArray(refs)) {
260
+ throw new Error(`Val: content version ${id}: refs must be an object`);
261
+ }
262
+ const read = (kind, path, ref) => {
263
+ const where = `Val: content version ${id}: refs.${kind}["${path}"]`;
264
+ if (typeof ref !== "string") {
265
+ throw new Error(`${where} must be a string`);
266
+ }
267
+ if (!ref.startsWith(ENV_REF)) {
268
+ throw new Error(`${where} is ${ref}: only ${ENV_REF}VAL_CONTENT_<n> is read`);
269
+ }
270
+ const name = ref.slice(ENV_REF.length);
271
+ if (!CONTENT_VARIABLE.test(name)) {
272
+ throw new Error(`${where} names ${name}: only VAL_CONTENT_<n> is read`);
273
+ }
274
+ const value = env[name];
275
+ if (value === undefined) {
276
+ throw new Error(`${where} names ${name}, which is not set`);
277
+ }
278
+ return {
279
+ where,
280
+ name,
281
+ value
282
+ };
283
+ };
284
+ const refModules = refs["modules"] ?? {};
285
+ const refFiles = refs["files"] ?? {};
286
+ if (!isObject(refModules) || Array.isArray(refModules) || !isObject(refFiles) || Array.isArray(refFiles)) {
287
+ throw new Error(`Val: content version ${id}: refs.modules and refs.files must be objects`);
288
+ }
289
+ for (const [path, ref] of Object.entries(refModules)) {
290
+ const {
291
+ where,
292
+ name,
293
+ value
294
+ } = read("modules", path, ref);
295
+ if (Object.prototype.hasOwnProperty.call(modules, path)) {
296
+ throw new Error(`${where}: ${path} is also in modules`);
297
+ }
298
+ try {
299
+ modules[path] = JSON.parse(value);
300
+ } catch (err) {
301
+ throw new Error(`${where}: ${name} is not JSON (${err instanceof Error ? err.message : String(err)})`, {
302
+ cause: err
303
+ });
304
+ }
305
+ }
306
+ for (const [path, ref] of Object.entries(refFiles)) {
307
+ const {
308
+ where,
309
+ value
310
+ } = read("files", path, ref);
311
+ // The handed object, not `files`: an inline value that is not text was
312
+ // dropped from `files`, and is still a second naming of the path.
313
+ if (Object.prototype.hasOwnProperty.call(filesIn, path)) {
314
+ throw new Error(`${where}: ${path} is also in files`);
315
+ }
316
+ files[path] = value;
317
+ }
318
+ if (job === null && commit === null) {
319
+ // Placed nowhere, Val would place it at the build it runs in -- the one
320
+ // position a version must never take: its own changes would be replayed
321
+ // over a snapshot that already holds them.
322
+ throw new Error(`Val: content version ${id} must name a job or a commit, or it would be placed at the build it runs in`);
323
+ }
324
+ return {
325
+ id,
326
+ job,
327
+ commit,
328
+ modules,
329
+ files
330
+ };
331
+ }
332
+
333
+ /** The one scheme a content version's `refs` may use, for now. */
334
+ const ENV_REF = "env://";
335
+ /** The only variables a reference may name. */
336
+ const CONTENT_VARIABLE = /^VAL_CONTENT_[0-9]+$/;
337
+
338
+ /**
339
+ * What a server or reader renders over the bundle: a proposal's saves over the
340
+ * content version the site serves, either alone, or nothing.
341
+ *
342
+ * Layered rather than chosen. At a proposal's address the platform hands both
343
+ * when the base the proposal was opened from serves content its build does not
344
+ * bundle (a content-only publish), and the proposal saves only the modules it
345
+ * changed: choosing the proposal alone would show every other module as the
346
+ * build bundles it -- older than the site it was opened from.
347
+ */
348
+ function layeredSnapshot(proposal, contentVersion) {
349
+ if (proposal === undefined) return contentVersion;
350
+ if (contentVersion === undefined) return proposal;
351
+ return {
352
+ modules: {
353
+ ...contentVersion.modules,
354
+ ...proposal.modules
355
+ },
356
+ files: {
357
+ ...contentVersion.files,
358
+ ...proposal.files
359
+ }
360
+ };
361
+ }
362
+
363
+ /**
364
+ * The proposal as a reader whose code is the serving build reads it: without
365
+ * the Source of a module staged after that build ({@link stagedAfterBuild}),
366
+ * which was made for code the reader has not got. Left out, such a module
367
+ * reads as the site or the build has it -- content of the code that reads it
368
+ * -- until a build of the staging serves the address. The same rule as
369
+ * `layered`'s, for the one source that carries no version.
370
+ */
371
+ function proposalAsBuilt(proposal, build) {
372
+ const after = stagedAfterBuild(proposal, build);
373
+ if (Object.keys(after).length === 0) return proposal;
374
+ const modules = {};
375
+ for (const [path, source] of Object.entries(proposal.modules)) {
376
+ if (after[path] === undefined) modules[path] = source;
377
+ }
378
+ return {
379
+ ...proposal,
380
+ modules
381
+ };
382
+ }
383
+
384
+ /**
385
+ * The proposal's saved Source, as Source: every module whose value is JSON.
386
+ * One place, so the server and the readers that render without it agree on
387
+ * what the snapshot holds.
388
+ */
389
+ function proposalSnapshot(proposal) {
390
+ const snapshot = {};
391
+ for (const [path, source] of Object.entries(proposal.modules)) {
392
+ if (isJsonValue(source)) {
393
+ snapshot[path] = source;
394
+ }
395
+ }
396
+ return snapshot;
397
+ }
398
+
399
+ /**
400
+ * `proposalSnapshotForReaders`, loading the compiler only when the snapshot
401
+ * needs it: what the server-side readers render over the bundle.
402
+ *
403
+ * A saved `.jsonValues()` entry is found through its module's `.val.ts`, which
404
+ * takes TypeScript to read (`./proposalJsonEntries`). Without one -- every
405
+ * site serving published content, and a proposal or content version that saved
406
+ * no entry -- the snapshot is {@link proposalSnapshot} and nothing is loaded:
407
+ * the readers are on every page's path, and a cold isolate pays for every
408
+ * module it evaluates.
409
+ */
410
+ async function readerSnapshot(proposal, projectSource) {
411
+ // The same test `proposalJsonEntries` starts with: no saved entry file, no
412
+ // entry to put in place of a marker.
413
+ if (!Object.keys(proposal.files).some(path => path.endsWith(".val.json"))) {
414
+ return proposalSnapshot(proposal);
415
+ }
416
+ const {
417
+ proposalSnapshotForReaders
418
+ } = await Promise.resolve().then(function () { return require('./proposalJsonEntries-9e537244.cjs.prod.js'); }).then(function (n) { return n.proposalJsonEntries$1; });
419
+ return proposalSnapshotForReaders(proposal, projectSource);
420
+ }
421
+
422
+ /** A plain object: not `null`, not an array. */
423
+ function isObject(value) {
424
+ return typeof value === "object" && value !== null && !Array.isArray(value);
425
+ }
426
+
427
+ /** What `JSON.parse` can produce, checked rather than assumed. */
428
+ function isJsonValue(value) {
429
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
430
+ return true;
431
+ }
432
+ if (Array.isArray(value)) {
433
+ return value.every(isJsonValue);
434
+ }
435
+ return isObject(value) && Object.values(value).every(isJsonValue);
436
+ }
437
+
438
+ /*
439
+ * Which mode a server's options and environment select, apart from
440
+ * `initHandlerOptions` (in `./valServerConfig`), which builds the rest of the
441
+ * config and imports the data layer to do it. A framework binding asks this
442
+ * BEFORE it loads the server: in `fs` and `memory` mode the newest server
443
+ * built in a process is the build the patches are relative to
444
+ * (`ValOps.chainBaseSha`), so it is built when the app starts; in `http`
445
+ * mode the content service says which build is live, so the server can wait for
446
+ * the first request -- which keeps it off a cold isolate's first page.
447
+ *
448
+ * Nothing here may import more than types: it is on every page's path.
449
+ */
450
+
451
+ /**
452
+ * The value of `VAL_ENV` that means "this is the Val app".
453
+ *
454
+ * The Val app builds a project in a browser and runs it in a Worker isolate.
455
+ * There is no disk there and there never will be, so `fs` mode is never the
456
+ * right fall-through -- and the content is Val's own, reached over HTTP at a
457
+ * commit, exactly as it is for any other deployed app. So this names `http`.
458
+ *
459
+ * What makes the app unusual is not where its content comes from but what
460
+ * publishing means: the browser rebuilds the site and the new build is served
461
+ * immediately, instead of a host noticing a commit and redeploying. That is a
462
+ * difference in what happens AFTER the commit, and `publishOverride` is where
463
+ * a host says so -- not a difference in where patches, files or sources live.
464
+ *
465
+ * A host says WHERE it runs, which is a fact it knows. Which Val mode that
466
+ * implies is Val's to derive, and that is the whole reason this exists next to
467
+ * `VAL_MODE` rather than the platform naming a mode itself: one is a
468
+ * description of an environment, the other an assertion about Val's internals,
469
+ * and only the first stays true when the internals move. They have already
470
+ * moved once -- this meant `memory` while the app kept its own patch store --
471
+ * and no platform had to be changed to follow.
472
+ */
473
+ const VAL_APP_ENV = "app";
474
+
475
+ /** Which mode the environment SAYS this is, and which variable said so. */
476
+
477
+ /**
478
+ * `null` is "the environment did not say", which is the normal case.
479
+ *
480
+ * The two variables differ in what can be DONE with an answer, and the
481
+ * difference is whether the environment holds everything the mode needs.
482
+ * `http` does -- an api key, a secret, a project, a commit and a branch are all
483
+ * env vars -- so `VAL_ENV=app` SELECTS it, and the checks in
484
+ * {@link initHandlerOptions} name whichever one is missing. `memory` does not:
485
+ * it needs the host's own source files, which nothing in an environment can
486
+ * supply, so `VAL_MODE=memory` can only ever turn a fall-through into an error.
487
+ */
488
+ function namedMode() {
489
+ const declared = process.env.VAL_MODE;
490
+ /*
491
+ * An empty value counts as unset, which is what `VAL_MODE=` in a shell or a
492
+ * CI settings page means. An explicit `VAL_MODE` otherwise wins over
493
+ * `VAL_ENV`: naming a mode outright says something more specific than naming
494
+ * an environment does, including when what it names is wrong and has to be
495
+ * refused.
496
+ */
497
+ if (declared !== undefined && declared !== "") {
498
+ return {
499
+ mode: declared,
500
+ from: "VAL_MODE"
501
+ };
502
+ }
503
+ if (process.env.VAL_ENV === VAL_APP_ENV) {
504
+ return {
505
+ mode: "http",
506
+ from: "VAL_ENV"
507
+ };
508
+ }
509
+ return null;
510
+ }
511
+
512
+ /**
513
+ * Whether these options select `http` mode, as `initHandlerOptions` decides
514
+ * it: a mode of "proxy", the Val app's environment, or a credential with no
515
+ * mode given. `sourceFiles` (memory mode) is decided before this is asked,
516
+ * and the environment's refusals are `initHandlerOptions`'s to throw.
517
+ */
518
+ function selectsHttpMode(opts, declared = namedMode()) {
519
+ const maybeApiKey = opts.apiKey || process.env.VAL_API_KEY;
520
+ const maybeValSecret = opts.valSecret || process.env.VAL_SECRET;
521
+ return opts.mode === "proxy" || (declared === null || declared === void 0 ? void 0 : declared.from) === "VAL_ENV" || opts.mode === undefined && !!(maybeApiKey || maybeValSecret);
522
+ }
523
+
524
+ /**
525
+ * Whether a server with these options can be built at its first request
526
+ * rather than when the app starts: only in `http` mode, for the reason at
527
+ * the top of this file. Memory mode is selected by `sourceFiles` alone.
528
+ */
529
+ function serverCanStartLazily(opts) {
530
+ return opts.sourceFiles === undefined && selectsHttpMode(opts);
531
+ }
532
+
533
+ /**
534
+ * What Val calls to format a file it has just written.
535
+ *
536
+ * The same shape `initValServer`, `initValMcp` and `ValOps` take as their
537
+ * `formatter` option. The path is the file's path INSIDE the project — a
538
+ * `ModuleFilePath` such as `/content/page.val.ts`, or a `*.val.json` entry
539
+ * beside it — never an absolute path on disk, because the writers that call it
540
+ * (`ValOps.prepare`, the CLI's `--fix`) only ever know a module by that path.
541
+ */
542
+
543
+ /**
544
+ * Prettier's options, as far as this file is concerned.
545
+ *
546
+ * Deliberately opaque: this file never reads an option, it only carries the
547
+ * bag from `resolveConfig` to `format`. Naming the real `Options` here would
548
+ * make it a compile error to build `@valbuild/server` in a project that has no
549
+ * prettier installed, which is most of them — prettier is a dependency the app
550
+ * opts into, so it is passed IN rather than imported.
551
+ */
552
+
553
+ /**
554
+ * `prettier`, as this file wants it.
555
+ *
556
+ * Structural for the same reason `SharpLike` in `@valbuild/mcp` is: a type-only
557
+ * import of a package that is not installed is still a compile error, and this
558
+ * package has to typecheck without prettier. `createPrettierFormatter.test.ts`
559
+ * asserts the real library against this type so the structural description
560
+ * cannot drift away from it unnoticed.
561
+ *
562
+ * Every result is `T | Promise<T>` so that `@prettier/sync` — the same API with
563
+ * the awaits taken out — satisfies it too. Everything here is awaited either
564
+ * way, and a formatter is allowed to be synchronous: `ValFormatter` says so.
565
+ */
566
+
567
+ /**
568
+ * `prettier`, loaded when the first file is formatted: `() => import("prettier")`.
569
+ *
570
+ * What an app's `val.server.ts` should pass. That module is imported by every
571
+ * page (it holds the readers too), so a static `import prettier from
572
+ * "prettier"` there makes every cold start of the site evaluate prettier --
573
+ * for a formatter that only runs when an editor saves. The loader is called at
574
+ * most once.
575
+ */
576
+
577
+ /**
578
+ * Resolve a path Val handed us against the project.
579
+ *
580
+ * Val's writers pass a project-relative path (`/content/page.val.ts`), and
581
+ * prettier needs a real one — both to find the `.prettierrc` that governs the
582
+ * file and to match it against `.prettierignore`. An absolute path that is
583
+ * already inside the project is taken as it comes, so a caller that happens to
584
+ * hold a real path is not mangled into `<root>/<root>/...`.
585
+ */
586
+ function resolveAgainstProject(projectRoot, filePath) {
587
+ if (path__default["default"].isAbsolute(filePath)) {
588
+ const relative = path__default["default"].relative(projectRoot, filePath);
589
+ if (relative && !relative.startsWith("..") && !path__default["default"].isAbsolute(relative)) {
590
+ return filePath;
591
+ }
592
+ }
593
+ return path__default["default"].join(projectRoot, filePath);
594
+ }
595
+
596
+ /**
597
+ * A {@link ValFormatter} that formats the way the project itself does.
598
+ *
599
+ * ONE implementation, for every writer of source files Val has: the Studio and
600
+ * the dev server (`initValServer`), an agent (`initValMcp`) and
601
+ * `val validate --fix`. They used to disagree — the CLI called
602
+ * `prettier.format(code, { filepath })` on its own behalf, and `format` does
603
+ * not read `.prettierrc`; only `resolveConfig`, `getFileInfo` and the prettier
604
+ * CLI do. `filepath` there selects the PARSER and nothing else, so the output
605
+ * was valid TypeScript in prettier's default style rather than the project's:
606
+ * a two-line content fix arriving as a whole-file rewrite, and a red `format`
607
+ * job in any repo that checks formatting in CI.
608
+ *
609
+ * ```ts
610
+ * import { createPrettierFormatter } from "@valbuild/next/server";
611
+ *
612
+ * initValServer(valModules, config, {
613
+ * draftMode,
614
+ * formatter: createPrettierFormatter(() => import("prettier"), {
615
+ * projectRoot: process.cwd(),
616
+ * }),
617
+ * });
618
+ * ```
619
+ *
620
+ * `prettier` itself is accepted too (`createPrettierFormatter(prettier, …)`),
621
+ * for a caller that has it loaded anyway, like the CLI; a server should pass
622
+ * the loader ({@link PrettierLoader}).
623
+ *
624
+ * `projectRoot` is what a project-relative path is resolved against, and is
625
+ * therefore also where `.prettierignore` is looked for. Prettier's own config
626
+ * search walks UP from the resolved file, so a monorepo package with its own
627
+ * `.prettierrc` is found without being named here.
628
+ *
629
+ * Two decisions worth knowing:
630
+ *
631
+ * - **`.prettierignore` is honoured; `.gitignore` is not.** The prettier CLI
632
+ * consults both, but only one of them is a statement about formatting — a
633
+ * file is gitignored for reasons that have nothing to do with style, and the
634
+ * only files reaching this function are ones Val itself just wrote.
635
+ * - **No config found is not an error.** `resolveConfig` returns `null` and
636
+ * the file is formatted with prettier's defaults, which is what a project
637
+ * without a config has asked for.
638
+ */
639
+ function createPrettierFormatter(prettierOrLoader, options) {
640
+ let loaded = null;
641
+ const loadPrettier = () => {
642
+ if (typeof prettierOrLoader !== "function") {
643
+ return Promise.resolve(prettierOrLoader);
644
+ }
645
+ // Forgotten when it fails, so the next save tries again rather than
646
+ // failing on the same rejected promise for the life of the process.
647
+ loaded ??= prettierOrLoader().catch(err => {
648
+ loaded = null;
649
+ throw err;
650
+ });
651
+ return loaded;
652
+ };
653
+ const projectRoot = path__default["default"].resolve(options.projectRoot);
654
+ // One array, built once: prettier reads and caches the ignore file itself, so
655
+ // this is only here to avoid rebuilding the path per file.
656
+ const ignorePath = [path__default["default"].join(projectRoot, ".prettierignore")];
657
+ return async (code, filePath) => {
658
+ const absoluteFilePath = resolveAgainstProject(projectRoot, filePath);
659
+ const prettier = await loadPrettier();
660
+ const {
661
+ ignored
662
+ } = await prettier.getFileInfo(absoluteFilePath, {
663
+ ignorePath
664
+ });
665
+ if (ignored) {
666
+ return code;
667
+ }
668
+ // `resolveConfig` applies the `overrides` that match this file and caches
669
+ // per directory, so calling it per file is cheap even on a project-wide
670
+ // `--fix`. `filepath` is still required: it is what picks the parser.
671
+ const config = await prettier.resolveConfig(absoluteFilePath);
672
+ return prettier.format(code, {
673
+ ...config,
674
+ filepath: absoluteFilePath
675
+ });
676
+ };
677
+ }
678
+
679
+ exports.contentFromEnv = contentFromEnv;
680
+ exports.createPrettierFormatter = createPrettierFormatter;
681
+ exports.isJsonValue = isJsonValue;
682
+ exports.isObject = isObject;
683
+ exports.layeredSnapshot = layeredSnapshot;
684
+ exports.namedMode = namedMode;
685
+ exports.proposalAsBuilt = proposalAsBuilt;
686
+ exports.proposalFromEnv = proposalFromEnv;
687
+ exports.proposalSnapshot = proposalSnapshot;
688
+ exports.readerSnapshot = readerSnapshot;
689
+ exports.selectsHttpMode = selectsHttpMode;
690
+ exports.serverCanStartLazily = serverCanStartLazily;
691
+ exports.servingBuildOf = servingBuildOf;
692
+ exports.stagedAfterBuild = stagedAfterBuild;