@valbuild/server 0.150.20 → 0.150.22

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 (23) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +1 -1
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +1 -1
  4. package/browser/dist/valbuild-server-browser.esm.js +1 -1
  5. package/dist/{ValRouterCore-94671fe0.cjs.dev.js → ValRouterCore-3431ce5f.cjs.dev.js} +3 -3
  6. package/dist/{ValRouterCore-69585ccd.esm.js → ValRouterCore-c5f6885a.esm.js} +3 -3
  7. package/dist/{ValRouterCore-e59bbc75.cjs.prod.js → ValRouterCore-df3f99c6.cjs.prod.js} +3 -3
  8. package/dist/{getJsonEntryAtCommit-cd0b317b.cjs.dev.js → getJsonEntryAtCommit-21a4bbfa.cjs.dev.js} +2 -2
  9. package/dist/{getJsonEntryAtCommit-47003e4a.esm.js → getJsonEntryAtCommit-93f9aba9.esm.js} +2 -2
  10. package/dist/{getJsonEntryAtCommit-bc6d4f82.cjs.prod.js → getJsonEntryAtCommit-b52171b1.cjs.prod.js} +2 -2
  11. package/dist/{jsonValuesModule-8ae503a8.cjs.dev.js → jsonValuesModule-235bd751.cjs.dev.js} +38 -0
  12. package/dist/{jsonValuesModule-427d68c8.esm.js → jsonValuesModule-23eb6f53.esm.js} +38 -1
  13. package/dist/{jsonValuesModule-d1bb8d8f.cjs.prod.js → jsonValuesModule-625ebae8.cjs.prod.js} +38 -0
  14. package/dist/{ops-b15239ac.cjs.prod.js → ops-0e54b388.cjs.prod.js} +1 -1
  15. package/dist/{ops-f37d18c6.cjs.dev.js → ops-9ca2ef2a.cjs.dev.js} +1 -1
  16. package/dist/{ops-0d05feaf.esm.js → ops-b904007e.esm.js} +1 -1
  17. package/dist/{publishKit-5865095c.cjs.dev.js → publishKit-34f71e50.cjs.dev.js} +3 -2
  18. package/dist/{publishKit-580f558a.cjs.prod.js → publishKit-65e9e564.cjs.prod.js} +3 -2
  19. package/dist/{publishKit-bc8df53d.esm.js → publishKit-7441c0fd.esm.js} +4 -4
  20. package/dist/valbuild-server.cjs.dev.js +223 -15
  21. package/dist/valbuild-server.cjs.prod.js +223 -15
  22. package/dist/valbuild-server.esm.js +225 -17
  23. package/package.json +3 -3
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var jsonValuesModule = require('./jsonValuesModule-8ae503a8.cjs.dev.js');
5
+ var jsonValuesModule = require('./jsonValuesModule-235bd751.cjs.dev.js');
6
6
  var patch = require('@valbuild/core/patch');
7
- var ops$1 = require('./ops-f37d18c6.cjs.dev.js');
7
+ var ops$1 = require('./ops-9ca2ef2a.cjs.dev.js');
8
8
  var fp = require('@valbuild/core/fp');
9
9
  var core = require('@valbuild/core');
10
10
  var ts = require('typescript');
@@ -12,7 +12,7 @@ var path = require('path');
12
12
  var fs = require('fs');
13
13
  var vm = require('node:vm');
14
14
  var node_module = require('node:module');
15
- var ValRouterCore = require('./ValRouterCore-94671fe0.cjs.dev.js');
15
+ var ValRouterCore = require('./ValRouterCore-3431ce5f.cjs.dev.js');
16
16
  var server = require('@valbuild/ui/server');
17
17
  var z = require('zod');
18
18
  var zodValidationError = require('zod-validation-error');
@@ -5083,7 +5083,7 @@ async function patchModuleText(text, patch$1) {
5083
5083
  const {
5084
5084
  tsOps,
5085
5085
  parseValFile
5086
- } = await Promise.resolve().then(function () { return require('./publishKit-5865095c.cjs.dev.js'); });
5086
+ } = await Promise.resolve().then(function () { return require('./publishKit-34f71e50.cjs.dev.js'); });
5087
5087
  const applied = patch.applyPatch(parseValFile(text), tsOps, patch$1);
5088
5088
  if (fp.result.isErr(applied)) {
5089
5089
  const reason = messagesOf(applied.error).join(" ");
@@ -5094,6 +5094,106 @@ async function patchModuleText(text, patch$1) {
5094
5094
  return fp.result.ok(unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u")));
5095
5095
  }
5096
5096
 
5097
+ /**
5098
+ * A patch written into a module's files: {@link patchModuleText}, and an op
5099
+ * that reaches INTO a `.jsonValues()` entry written into that entry's own
5100
+ * `*.val.json`, as a save routes it (`ValOps.prepare`).
5101
+ *
5102
+ * The design tab's `create_patch` used to refuse those, and the assistant
5103
+ * rewrote the whole entry file to change one field -- over whatever had been
5104
+ * saved into it since it read it.
5105
+ *
5106
+ * Only into an entry that is already there. Adding, replacing or removing a
5107
+ * whole entry is a key in the `.val.ts` and a file beside it, which a save
5108
+ * writes from the record's schema; here that is still `write_files`, and the
5109
+ * error says so.
5110
+ *
5111
+ * `readFile` answers a file by its path without a leading slash: the
5112
+ * proposal's copy, else the build's, `null` for one the proposal deleted.
5113
+ * `moduleText` is `null` when no op is the module file's own; `entries` is
5114
+ * each entry file written, by the same kind of path.
5115
+ */
5116
+ async function patchModuleFiles(moduleFilePath, text, readFile, patch$1) {
5117
+ const entryFiles = await jsonEntryFilesOf(moduleFilePath, text);
5118
+ const textOps = [];
5119
+ const entryOps = new Map();
5120
+ for (const op of patch$1) {
5121
+ const key = op.path[0];
5122
+ // The record itself, or one of its entries as a whole -- a new one too,
5123
+ // which would otherwise be written into the record's text inline.
5124
+ if (entryFiles.size > 0 && op.path.length <= 1) {
5125
+ return fp.result.err(`${key !== undefined ? `"${key}" is a whole entry` : "This is the whole record"} of a .jsonValues() record: add, replace or remove an entry by writing ${moduleFilePath} and the entry's .val.json with write_files.`);
5126
+ }
5127
+ const entryFile = key !== undefined ? entryFiles.get(key) : undefined;
5128
+ if (key === undefined || entryFile === undefined) {
5129
+ textOps.push(op);
5130
+ continue;
5131
+ }
5132
+ if (op.op === "file") {
5133
+ return fp.result.err(`A file in a .jsonValues() entry is uploaded by the Studio, not written here.`);
5134
+ }
5135
+ if ((op.op === "move" || op.op === "copy") && op.from[0] !== key) {
5136
+ return fp.result.err(`An op from one .jsonValues() entry into another is not written here: write the entries' .val.json files with write_files.`);
5137
+ }
5138
+ const rebased = ValRouterCore.rebaseContentOp(op, 1);
5139
+ if (fp.result.isErr(rebased)) return fp.result.err(rebased.error.message);
5140
+ entryOps.set(entryFile, [...(entryOps.get(entryFile) ?? []), rebased.value]);
5141
+ }
5142
+ let moduleText = null;
5143
+ if (textOps.length > 0) {
5144
+ const patched = await patchModuleText(text, textOps);
5145
+ if (fp.result.isErr(patched)) return patched;
5146
+ moduleText = patched.value;
5147
+ }
5148
+ const entries = {};
5149
+ for (const [entryFile, ops] of entryOps) {
5150
+ const raw = readFile(entryFile);
5151
+ if (raw === null || raw === undefined) {
5152
+ return fp.result.err(`${entryFile} is ${raw === null ? "deleted in this proposal" : "not in this proposal or on the site"}.`);
5153
+ }
5154
+ let content;
5155
+ try {
5156
+ content = JSON.parse(raw);
5157
+ } catch {
5158
+ return fp.result.err(`${entryFile} is not JSON.`);
5159
+ }
5160
+ const applied = patch.applyPatch(patch.deepClone(content), new patch.JSONOps(), ops);
5161
+ if (fp.result.isErr(applied)) {
5162
+ return fp.result.err(`${entryFile}: ${messagesOf(applied.error).join(" ")}`);
5163
+ }
5164
+ entries[entryFile] = applied.value;
5165
+ }
5166
+ return fp.result.ok({
5167
+ moduleText,
5168
+ entries
5169
+ });
5170
+ }
5171
+
5172
+ /**
5173
+ * Each `.jsonValues()` entry's file, by key, without a leading slash: from the
5174
+ * `c.json(() => import("..."))` thunks in the module's text. Empty for a
5175
+ * module that has none, or whose text cannot be read that way.
5176
+ */
5177
+ async function jsonEntryFilesOf(moduleFilePath, text) {
5178
+ const files = new Map();
5179
+ if (!text.includes(".jsonValues(")) return files;
5180
+ const {
5181
+ parseValFile,
5182
+ analyzeValModule,
5183
+ analyzeJsonValuesEntries
5184
+ } = await Promise.resolve().then(function () { return require('./publishKit-34f71e50.cjs.dev.js'); });
5185
+ try {
5186
+ const analysis = analyzeValModule(parseValFile(text));
5187
+ if (fp.result.isErr(analysis)) return files;
5188
+ for (const [key, entry] of analyzeJsonValuesEntries(analysis.value.source)) {
5189
+ files.set(key, ValRouterCore.resolveExistingJsonPath(moduleFilePath, entry.importPath).replace(/^\/+/, ""));
5190
+ }
5191
+ } catch {
5192
+ // No `c.define` (`analyzeValModule` throws): no entries.
5193
+ }
5194
+ return files;
5195
+ }
5196
+
5097
5197
  /**
5098
5198
  * A patch error, or a tree of syntax errors, as sentences. Walked here rather
5099
5199
  * than with `syntax.ts`'s `flattenErrors`, which would bring the compiler in
@@ -5104,6 +5204,57 @@ function messagesOf(error) {
5104
5204
  return Array.isArray(error) ? error.flatMap(messagesOf) : [error.message];
5105
5205
  }
5106
5206
 
5207
+ /**
5208
+ * The Source each staged module file declares, read from its text: what a
5209
+ * staging sends content beside the files (`POST /proposals/:name/files`,
5210
+ * `modules`), so the proposal's Source moves with its code.
5211
+ *
5212
+ * A proposal's address serves a module's Source from what the proposal has
5213
+ * SAVED, over the site's, over the build -- never from the text. A save writes
5214
+ * both, so they agree. A staging wrote only the text, so after the design
5215
+ * tab's `create_patch` added a button to a module, its text and its build had
5216
+ * the button and the Source the server served and saved did not. The Studio,
5217
+ * lined up with that Source, could not apply an edit into the new button: the
5218
+ * canvas showed it, and then it was gone.
5219
+ *
5220
+ * Only what can be read without running anything: a `c.define(...)` whose
5221
+ * Source is a literal, a `.jsonValues()` record's entries as the markers its
5222
+ * stored Source holds (`evaluateModuleSource`) -- so an entry the design tab
5223
+ * adds is one the proposal has. Anything else -- a Source built by code, a
5224
+ * file of shared schemas -- is left out, and content keeps the Source it has
5225
+ * for it, as before this existed.
5226
+ */
5227
+ async function stagedModuleSources(files) {
5228
+ const modules = Object.entries(files).flatMap(([path, text]) => text !== null && /\.val\.(ts|js)$/.test(path) ? [{
5229
+ path,
5230
+ text
5231
+ }] : []);
5232
+ if (modules.length === 0) return {};
5233
+ // The compiler, loaded when a staging asks for it, as a save loads it.
5234
+ const {
5235
+ parseValFile,
5236
+ analyzeValModule,
5237
+ evaluateModuleSource
5238
+ } = await Promise.resolve().then(function () { return require('./publishKit-34f71e50.cjs.dev.js'); });
5239
+ const sources = {};
5240
+ for (const {
5241
+ path,
5242
+ text
5243
+ } of modules) {
5244
+ try {
5245
+ const analysis = analyzeValModule(parseValFile(text));
5246
+ if (fp.result.isErr(analysis)) continue;
5247
+ const source = evaluateModuleSource(analysis.value.source);
5248
+ if (fp.result.isErr(source)) continue;
5249
+ sources[`/${path.replace(/^\/+/, "")}`] = source.value;
5250
+ } catch {
5251
+ // No `c.define` at all (`analyzeValModule` throws): code, not a module.
5252
+ continue;
5253
+ }
5254
+ }
5255
+ return sources;
5256
+ }
5257
+
5107
5258
  /**
5108
5259
  * Which of the site's pending changes a merge of a proposal moves into
5109
5260
  * proposals of their own (valbuild/home `docs/hosted-publishing.md`, step 8.2,
@@ -5335,6 +5486,35 @@ const PatchFileBody = z.z.object({
5335
5486
  message: z.z.string().max(500).optional()
5336
5487
  });
5337
5488
 
5489
+ /** A staging's body, as `write_files` sends it. */
5490
+ const StageFilesBody = z.z.object({
5491
+ files: z.z.record(z.z.string(), z.z.string().nullable())
5492
+ });
5493
+
5494
+ /**
5495
+ * A staging's body with the Source its module files declare added
5496
+ * (`stagedModuleSources`). A body this does not read goes as it came: content
5497
+ * answers it.
5498
+ */
5499
+ async function withStagedModuleSources(body) {
5500
+ let parsed;
5501
+ try {
5502
+ parsed = JSON.parse(body);
5503
+ } catch {
5504
+ return body;
5505
+ }
5506
+ const request = StageFilesBody.safeParse(parsed);
5507
+ if (!request.success || typeof parsed !== "object" || parsed === null) {
5508
+ return body;
5509
+ }
5510
+ const modules = await stagedModuleSources(request.data.files);
5511
+ if (Object.keys(modules).length === 0) return body;
5512
+ return JSON.stringify({
5513
+ ...parsed,
5514
+ modules
5515
+ });
5516
+ }
5517
+
5338
5518
  /** What `patchFileInProposal` reads of content's answer for a proposal's files. */
5339
5519
  const ProposalFilesRead = z.z.object({
5340
5520
  files: z.z.record(z.z.string(), z.z.string().nullable())
@@ -6223,6 +6403,8 @@ class ValOpsHttp extends ValRouterCore.ValOps {
6223
6403
  })
6224
6404
  };
6225
6405
  }
6406
+ // Staged module files go with the Source they declare.
6407
+ const body = (writes === null || writes === void 0 ? void 0 : writes.write) === "files" && init.body !== undefined ? await withStagedModuleSources(init.body) : init.body;
6226
6408
  const res = await fetch(`${this.contentUrl}/v1/${this.project}/proposals${path}`, {
6227
6409
  method: init.method,
6228
6410
  headers: {
@@ -6235,12 +6417,12 @@ class ValOpsHttp extends ValRouterCore.ValOps {
6235
6417
  ...(profileId !== null ? {
6236
6418
  "x-val-profile-id": profileId
6237
6419
  } : {}),
6238
- ...(init.body === undefined ? {} : {
6420
+ ...(body === undefined ? {} : {
6239
6421
  "Content-Type": json
6240
6422
  })
6241
6423
  },
6242
- ...(init.body === undefined ? {} : {
6243
- body: init.body
6424
+ ...(body === undefined ? {} : {
6425
+ body
6244
6426
  })
6245
6427
  });
6246
6428
  return {
@@ -6331,28 +6513,54 @@ class ValOpsHttp extends ValRouterCore.ValOps {
6331
6513
  message: `There is no module file ${moduleFilePath} in this proposal or on the site.`
6332
6514
  });
6333
6515
  }
6334
- const patched = await patchModuleText(text, patch);
6516
+ const patched = await patchModuleFiles(moduleFilePath, text, path => {
6517
+ var _this$projectSource2;
6518
+ const proposalCopy = files.data.files[path];
6519
+ return proposalCopy !== undefined ? proposalCopy : (_this$projectSource2 = this.projectSource) === null || _this$projectSource2 === void 0 ? void 0 : _this$projectSource2[path];
6520
+ }, patch);
6335
6521
  if (fp.result.isErr(patched)) {
6336
6522
  return answer(422, {
6337
6523
  message: `The patch does not apply to ${moduleFilePath}: ${patched.error}`
6338
6524
  });
6339
6525
  }
6340
- let formatted = patched.value;
6341
- if ((_this$options = this.options) !== null && _this$options !== void 0 && _this$options.formatter) {
6526
+ const formatter = (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.formatter;
6527
+ const format = async (written, path) => {
6528
+ if (!formatter) return fp.result.ok(written);
6342
6529
  try {
6343
- formatted = await this.options.formatter(patched.value, moduleFilePath);
6530
+ return fp.result.ok(await formatter(written, path));
6344
6531
  } catch (error) {
6532
+ return fp.result.err(`The patched ${path} could not be formatted: ${error instanceof Error ? error.message : String(error)}`);
6533
+ }
6534
+ };
6535
+ const staging = {};
6536
+ if (patched.value.moduleText !== null) {
6537
+ const formatted = await format(patched.value.moduleText, moduleFilePath);
6538
+ if (fp.result.isErr(formatted)) {
6345
6539
  return answer(422, {
6346
- message: `The patched ${moduleFilePath} could not be formatted: ${error instanceof Error ? error.message : String(error)}`
6540
+ message: formatted.error
6347
6541
  });
6348
6542
  }
6543
+ staging[filePath] = formatted.value;
6349
6544
  }
6545
+ // An entry's file as a save writes it: see `ValOps.prepare`.
6546
+ for (const [entryFile, content] of Object.entries(patched.value.entries)) {
6547
+ const formatted = await format(JSON.stringify(content, null, 2), `/${entryFile}`);
6548
+ if (fp.result.isErr(formatted)) {
6549
+ return answer(422, {
6550
+ message: formatted.error
6551
+ });
6552
+ }
6553
+ staging[entryFile] = formatted.value;
6554
+ }
6555
+ const modules = await stagedModuleSources(staging);
6350
6556
  const staged = await content("/files", {
6351
6557
  method: "POST",
6352
6558
  body: JSON.stringify({
6353
- files: {
6354
- [filePath]: formatted
6355
- },
6559
+ files: staging,
6560
+ // The Source the patched text declares: see `stagedModuleSources`.
6561
+ ...(Object.keys(modules).length > 0 ? {
6562
+ modules
6563
+ } : {}),
6356
6564
  ...(message !== undefined ? {
6357
6565
  message
6358
6566
  } : {})
@@ -2,9 +2,9 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var jsonValuesModule = require('./jsonValuesModule-d1bb8d8f.cjs.prod.js');
5
+ var jsonValuesModule = require('./jsonValuesModule-625ebae8.cjs.prod.js');
6
6
  var patch = require('@valbuild/core/patch');
7
- var ops$1 = require('./ops-b15239ac.cjs.prod.js');
7
+ var ops$1 = require('./ops-0e54b388.cjs.prod.js');
8
8
  var fp = require('@valbuild/core/fp');
9
9
  var core = require('@valbuild/core');
10
10
  var ts = require('typescript');
@@ -12,7 +12,7 @@ var path = require('path');
12
12
  var fs = require('fs');
13
13
  var vm = require('node:vm');
14
14
  var node_module = require('node:module');
15
- var ValRouterCore = require('./ValRouterCore-e59bbc75.cjs.prod.js');
15
+ var ValRouterCore = require('./ValRouterCore-df3f99c6.cjs.prod.js');
16
16
  var server = require('@valbuild/ui/server');
17
17
  var z = require('zod');
18
18
  var zodValidationError = require('zod-validation-error');
@@ -5083,7 +5083,7 @@ async function patchModuleText(text, patch$1) {
5083
5083
  const {
5084
5084
  tsOps,
5085
5085
  parseValFile
5086
- } = await Promise.resolve().then(function () { return require('./publishKit-580f558a.cjs.prod.js'); });
5086
+ } = await Promise.resolve().then(function () { return require('./publishKit-65e9e564.cjs.prod.js'); });
5087
5087
  const applied = patch.applyPatch(parseValFile(text), tsOps, patch$1);
5088
5088
  if (fp.result.isErr(applied)) {
5089
5089
  const reason = messagesOf(applied.error).join(" ");
@@ -5094,6 +5094,106 @@ async function patchModuleText(text, patch$1) {
5094
5094
  return fp.result.ok(unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u")));
5095
5095
  }
5096
5096
 
5097
+ /**
5098
+ * A patch written into a module's files: {@link patchModuleText}, and an op
5099
+ * that reaches INTO a `.jsonValues()` entry written into that entry's own
5100
+ * `*.val.json`, as a save routes it (`ValOps.prepare`).
5101
+ *
5102
+ * The design tab's `create_patch` used to refuse those, and the assistant
5103
+ * rewrote the whole entry file to change one field -- over whatever had been
5104
+ * saved into it since it read it.
5105
+ *
5106
+ * Only into an entry that is already there. Adding, replacing or removing a
5107
+ * whole entry is a key in the `.val.ts` and a file beside it, which a save
5108
+ * writes from the record's schema; here that is still `write_files`, and the
5109
+ * error says so.
5110
+ *
5111
+ * `readFile` answers a file by its path without a leading slash: the
5112
+ * proposal's copy, else the build's, `null` for one the proposal deleted.
5113
+ * `moduleText` is `null` when no op is the module file's own; `entries` is
5114
+ * each entry file written, by the same kind of path.
5115
+ */
5116
+ async function patchModuleFiles(moduleFilePath, text, readFile, patch$1) {
5117
+ const entryFiles = await jsonEntryFilesOf(moduleFilePath, text);
5118
+ const textOps = [];
5119
+ const entryOps = new Map();
5120
+ for (const op of patch$1) {
5121
+ const key = op.path[0];
5122
+ // The record itself, or one of its entries as a whole -- a new one too,
5123
+ // which would otherwise be written into the record's text inline.
5124
+ if (entryFiles.size > 0 && op.path.length <= 1) {
5125
+ return fp.result.err(`${key !== undefined ? `"${key}" is a whole entry` : "This is the whole record"} of a .jsonValues() record: add, replace or remove an entry by writing ${moduleFilePath} and the entry's .val.json with write_files.`);
5126
+ }
5127
+ const entryFile = key !== undefined ? entryFiles.get(key) : undefined;
5128
+ if (key === undefined || entryFile === undefined) {
5129
+ textOps.push(op);
5130
+ continue;
5131
+ }
5132
+ if (op.op === "file") {
5133
+ return fp.result.err(`A file in a .jsonValues() entry is uploaded by the Studio, not written here.`);
5134
+ }
5135
+ if ((op.op === "move" || op.op === "copy") && op.from[0] !== key) {
5136
+ return fp.result.err(`An op from one .jsonValues() entry into another is not written here: write the entries' .val.json files with write_files.`);
5137
+ }
5138
+ const rebased = ValRouterCore.rebaseContentOp(op, 1);
5139
+ if (fp.result.isErr(rebased)) return fp.result.err(rebased.error.message);
5140
+ entryOps.set(entryFile, [...(entryOps.get(entryFile) ?? []), rebased.value]);
5141
+ }
5142
+ let moduleText = null;
5143
+ if (textOps.length > 0) {
5144
+ const patched = await patchModuleText(text, textOps);
5145
+ if (fp.result.isErr(patched)) return patched;
5146
+ moduleText = patched.value;
5147
+ }
5148
+ const entries = {};
5149
+ for (const [entryFile, ops] of entryOps) {
5150
+ const raw = readFile(entryFile);
5151
+ if (raw === null || raw === undefined) {
5152
+ return fp.result.err(`${entryFile} is ${raw === null ? "deleted in this proposal" : "not in this proposal or on the site"}.`);
5153
+ }
5154
+ let content;
5155
+ try {
5156
+ content = JSON.parse(raw);
5157
+ } catch {
5158
+ return fp.result.err(`${entryFile} is not JSON.`);
5159
+ }
5160
+ const applied = patch.applyPatch(patch.deepClone(content), new patch.JSONOps(), ops);
5161
+ if (fp.result.isErr(applied)) {
5162
+ return fp.result.err(`${entryFile}: ${messagesOf(applied.error).join(" ")}`);
5163
+ }
5164
+ entries[entryFile] = applied.value;
5165
+ }
5166
+ return fp.result.ok({
5167
+ moduleText,
5168
+ entries
5169
+ });
5170
+ }
5171
+
5172
+ /**
5173
+ * Each `.jsonValues()` entry's file, by key, without a leading slash: from the
5174
+ * `c.json(() => import("..."))` thunks in the module's text. Empty for a
5175
+ * module that has none, or whose text cannot be read that way.
5176
+ */
5177
+ async function jsonEntryFilesOf(moduleFilePath, text) {
5178
+ const files = new Map();
5179
+ if (!text.includes(".jsonValues(")) return files;
5180
+ const {
5181
+ parseValFile,
5182
+ analyzeValModule,
5183
+ analyzeJsonValuesEntries
5184
+ } = await Promise.resolve().then(function () { return require('./publishKit-65e9e564.cjs.prod.js'); });
5185
+ try {
5186
+ const analysis = analyzeValModule(parseValFile(text));
5187
+ if (fp.result.isErr(analysis)) return files;
5188
+ for (const [key, entry] of analyzeJsonValuesEntries(analysis.value.source)) {
5189
+ files.set(key, ValRouterCore.resolveExistingJsonPath(moduleFilePath, entry.importPath).replace(/^\/+/, ""));
5190
+ }
5191
+ } catch {
5192
+ // No `c.define` (`analyzeValModule` throws): no entries.
5193
+ }
5194
+ return files;
5195
+ }
5196
+
5097
5197
  /**
5098
5198
  * A patch error, or a tree of syntax errors, as sentences. Walked here rather
5099
5199
  * than with `syntax.ts`'s `flattenErrors`, which would bring the compiler in
@@ -5104,6 +5204,57 @@ function messagesOf(error) {
5104
5204
  return Array.isArray(error) ? error.flatMap(messagesOf) : [error.message];
5105
5205
  }
5106
5206
 
5207
+ /**
5208
+ * The Source each staged module file declares, read from its text: what a
5209
+ * staging sends content beside the files (`POST /proposals/:name/files`,
5210
+ * `modules`), so the proposal's Source moves with its code.
5211
+ *
5212
+ * A proposal's address serves a module's Source from what the proposal has
5213
+ * SAVED, over the site's, over the build -- never from the text. A save writes
5214
+ * both, so they agree. A staging wrote only the text, so after the design
5215
+ * tab's `create_patch` added a button to a module, its text and its build had
5216
+ * the button and the Source the server served and saved did not. The Studio,
5217
+ * lined up with that Source, could not apply an edit into the new button: the
5218
+ * canvas showed it, and then it was gone.
5219
+ *
5220
+ * Only what can be read without running anything: a `c.define(...)` whose
5221
+ * Source is a literal, a `.jsonValues()` record's entries as the markers its
5222
+ * stored Source holds (`evaluateModuleSource`) -- so an entry the design tab
5223
+ * adds is one the proposal has. Anything else -- a Source built by code, a
5224
+ * file of shared schemas -- is left out, and content keeps the Source it has
5225
+ * for it, as before this existed.
5226
+ */
5227
+ async function stagedModuleSources(files) {
5228
+ const modules = Object.entries(files).flatMap(([path, text]) => text !== null && /\.val\.(ts|js)$/.test(path) ? [{
5229
+ path,
5230
+ text
5231
+ }] : []);
5232
+ if (modules.length === 0) return {};
5233
+ // The compiler, loaded when a staging asks for it, as a save loads it.
5234
+ const {
5235
+ parseValFile,
5236
+ analyzeValModule,
5237
+ evaluateModuleSource
5238
+ } = await Promise.resolve().then(function () { return require('./publishKit-65e9e564.cjs.prod.js'); });
5239
+ const sources = {};
5240
+ for (const {
5241
+ path,
5242
+ text
5243
+ } of modules) {
5244
+ try {
5245
+ const analysis = analyzeValModule(parseValFile(text));
5246
+ if (fp.result.isErr(analysis)) continue;
5247
+ const source = evaluateModuleSource(analysis.value.source);
5248
+ if (fp.result.isErr(source)) continue;
5249
+ sources[`/${path.replace(/^\/+/, "")}`] = source.value;
5250
+ } catch {
5251
+ // No `c.define` at all (`analyzeValModule` throws): code, not a module.
5252
+ continue;
5253
+ }
5254
+ }
5255
+ return sources;
5256
+ }
5257
+
5107
5258
  /**
5108
5259
  * Which of the site's pending changes a merge of a proposal moves into
5109
5260
  * proposals of their own (valbuild/home `docs/hosted-publishing.md`, step 8.2,
@@ -5335,6 +5486,35 @@ const PatchFileBody = z.z.object({
5335
5486
  message: z.z.string().max(500).optional()
5336
5487
  });
5337
5488
 
5489
+ /** A staging's body, as `write_files` sends it. */
5490
+ const StageFilesBody = z.z.object({
5491
+ files: z.z.record(z.z.string(), z.z.string().nullable())
5492
+ });
5493
+
5494
+ /**
5495
+ * A staging's body with the Source its module files declare added
5496
+ * (`stagedModuleSources`). A body this does not read goes as it came: content
5497
+ * answers it.
5498
+ */
5499
+ async function withStagedModuleSources(body) {
5500
+ let parsed;
5501
+ try {
5502
+ parsed = JSON.parse(body);
5503
+ } catch {
5504
+ return body;
5505
+ }
5506
+ const request = StageFilesBody.safeParse(parsed);
5507
+ if (!request.success || typeof parsed !== "object" || parsed === null) {
5508
+ return body;
5509
+ }
5510
+ const modules = await stagedModuleSources(request.data.files);
5511
+ if (Object.keys(modules).length === 0) return body;
5512
+ return JSON.stringify({
5513
+ ...parsed,
5514
+ modules
5515
+ });
5516
+ }
5517
+
5338
5518
  /** What `patchFileInProposal` reads of content's answer for a proposal's files. */
5339
5519
  const ProposalFilesRead = z.z.object({
5340
5520
  files: z.z.record(z.z.string(), z.z.string().nullable())
@@ -6223,6 +6403,8 @@ class ValOpsHttp extends ValRouterCore.ValOps {
6223
6403
  })
6224
6404
  };
6225
6405
  }
6406
+ // Staged module files go with the Source they declare.
6407
+ const body = (writes === null || writes === void 0 ? void 0 : writes.write) === "files" && init.body !== undefined ? await withStagedModuleSources(init.body) : init.body;
6226
6408
  const res = await fetch(`${this.contentUrl}/v1/${this.project}/proposals${path}`, {
6227
6409
  method: init.method,
6228
6410
  headers: {
@@ -6235,12 +6417,12 @@ class ValOpsHttp extends ValRouterCore.ValOps {
6235
6417
  ...(profileId !== null ? {
6236
6418
  "x-val-profile-id": profileId
6237
6419
  } : {}),
6238
- ...(init.body === undefined ? {} : {
6420
+ ...(body === undefined ? {} : {
6239
6421
  "Content-Type": json
6240
6422
  })
6241
6423
  },
6242
- ...(init.body === undefined ? {} : {
6243
- body: init.body
6424
+ ...(body === undefined ? {} : {
6425
+ body
6244
6426
  })
6245
6427
  });
6246
6428
  return {
@@ -6331,28 +6513,54 @@ class ValOpsHttp extends ValRouterCore.ValOps {
6331
6513
  message: `There is no module file ${moduleFilePath} in this proposal or on the site.`
6332
6514
  });
6333
6515
  }
6334
- const patched = await patchModuleText(text, patch);
6516
+ const patched = await patchModuleFiles(moduleFilePath, text, path => {
6517
+ var _this$projectSource2;
6518
+ const proposalCopy = files.data.files[path];
6519
+ return proposalCopy !== undefined ? proposalCopy : (_this$projectSource2 = this.projectSource) === null || _this$projectSource2 === void 0 ? void 0 : _this$projectSource2[path];
6520
+ }, patch);
6335
6521
  if (fp.result.isErr(patched)) {
6336
6522
  return answer(422, {
6337
6523
  message: `The patch does not apply to ${moduleFilePath}: ${patched.error}`
6338
6524
  });
6339
6525
  }
6340
- let formatted = patched.value;
6341
- if ((_this$options = this.options) !== null && _this$options !== void 0 && _this$options.formatter) {
6526
+ const formatter = (_this$options = this.options) === null || _this$options === void 0 ? void 0 : _this$options.formatter;
6527
+ const format = async (written, path) => {
6528
+ if (!formatter) return fp.result.ok(written);
6342
6529
  try {
6343
- formatted = await this.options.formatter(patched.value, moduleFilePath);
6530
+ return fp.result.ok(await formatter(written, path));
6344
6531
  } catch (error) {
6532
+ return fp.result.err(`The patched ${path} could not be formatted: ${error instanceof Error ? error.message : String(error)}`);
6533
+ }
6534
+ };
6535
+ const staging = {};
6536
+ if (patched.value.moduleText !== null) {
6537
+ const formatted = await format(patched.value.moduleText, moduleFilePath);
6538
+ if (fp.result.isErr(formatted)) {
6345
6539
  return answer(422, {
6346
- message: `The patched ${moduleFilePath} could not be formatted: ${error instanceof Error ? error.message : String(error)}`
6540
+ message: formatted.error
6347
6541
  });
6348
6542
  }
6543
+ staging[filePath] = formatted.value;
6349
6544
  }
6545
+ // An entry's file as a save writes it: see `ValOps.prepare`.
6546
+ for (const [entryFile, content] of Object.entries(patched.value.entries)) {
6547
+ const formatted = await format(JSON.stringify(content, null, 2), `/${entryFile}`);
6548
+ if (fp.result.isErr(formatted)) {
6549
+ return answer(422, {
6550
+ message: formatted.error
6551
+ });
6552
+ }
6553
+ staging[entryFile] = formatted.value;
6554
+ }
6555
+ const modules = await stagedModuleSources(staging);
6350
6556
  const staged = await content("/files", {
6351
6557
  method: "POST",
6352
6558
  body: JSON.stringify({
6353
- files: {
6354
- [filePath]: formatted
6355
- },
6559
+ files: staging,
6560
+ // The Source the patched text declares: see `stagedModuleSources`.
6561
+ ...(Object.keys(modules).length > 0 ? {
6562
+ modules
6563
+ } : {}),
6356
6564
  ...(message !== undefined ? {
6357
6565
  message
6358
6566
  } : {})