@valbuild/server 0.152.0 → 0.152.1

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 (28) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/browser/dist/valbuild-server-browser.cjs.dev.js +2 -2
  3. package/browser/dist/valbuild-server-browser.cjs.prod.js +2 -2
  4. package/browser/dist/valbuild-server-browser.esm.js +2 -2
  5. package/dist/{ValRouter-afcba447.cjs.dev.js → ValRouter-541c76f5.cjs.dev.js} +16 -336
  6. package/dist/{ValRouter-05fcb0da.esm.js → ValRouter-b4125d35.esm.js} +17 -337
  7. package/dist/{ValRouter-b4e5b412.cjs.prod.js → ValRouter-e1e0101b.cjs.prod.js} +16 -336
  8. package/dist/{ValRouterCore-d16c3327.cjs.dev.js → ValRouterCore-0c0359fe.cjs.prod.js} +2 -2
  9. package/dist/{ValRouterCore-a0ea46bf.cjs.prod.js → ValRouterCore-bd3e9b6c.cjs.dev.js} +2 -2
  10. package/dist/{ValRouterCore-b5d70504.esm.js → ValRouterCore-eea19e82.esm.js} +2 -2
  11. package/dist/declarations/src/ValOpsHttp.d.ts +4 -39
  12. package/dist/declarations/src/patch/ts/jsonValuesModule.d.ts +1 -1
  13. package/dist/{inTabFetch-095bb2be.cjs.prod.js → inTabFetch-5caf8250.cjs.prod.js} +1 -1
  14. package/dist/{inTabFetch-2cbbfaa4.cjs.dev.js → inTabFetch-6d54acd8.cjs.dev.js} +1 -1
  15. package/dist/{inTabFetch-91c3e85e.esm.js → inTabFetch-de7cf596.esm.js} +1 -1
  16. package/dist/{publishKit-4e2b0014.cjs.dev.js → publishKit-42f08a69.cjs.dev.js} +2 -2
  17. package/dist/{publishKit-6e52ffa6.cjs.prod.js → publishKit-9600ecef.cjs.prod.js} +2 -2
  18. package/dist/{publishKit-af14cd7a.esm.js → publishKit-c13ba76f.esm.js} +3 -3
  19. package/dist/valbuild-server.cjs.dev.js +2 -2
  20. package/dist/valbuild-server.cjs.prod.js +2 -2
  21. package/dist/valbuild-server.esm.js +4 -4
  22. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +2 -2
  23. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +2 -2
  24. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +2 -2
  25. package/internal/dist/valbuild-server-internal.cjs.dev.js +2 -2
  26. package/internal/dist/valbuild-server-internal.cjs.prod.js +2 -2
  27. package/internal/dist/valbuild-server-internal.esm.js +2 -2
  28. package/package.json +3 -3
@@ -1,13 +1,13 @@
1
1
  import { Internal, deserializeSchema, DEFAULT_CONTENT_HOST, DEFAULT_VAL_REMOTE_HOST } from '@valbuild/core';
2
2
  import { createUIRequestHandler } from '@valbuild/ui/server';
3
- import { r as resolveExistingJsonPath, s as summaryOf, m as matchesFilter, h as byUpdatedAt, n as newSketchpad, i as isSketchpadId, j as applySketchpadChange, k as ValOps, V as VAL_CLIENT_HEADERS, l as bufferFromDataUrl, o as getFieldsForType, u as uploadRemoteFile, d as getFileExt, p as guessMimeTypeFromPath, q as createMetadataFromBuffer, D as DEFAULT_ANALYTICS_INGEST_URL, e as ValOpsMemory, t as sessionAuth, w as isHttpOps, x as isHlsMasterPlaylist, y as sumHlsSegmentDurations, z as parseHlsMasterVariants, A as largestHlsVariant, B as fallbackRefOf, C as mapHlsUris, E as movedRemoteHost, F as needsHostCheck, G as rewriteRefHost, H as fallbackRemoteHost, J as checkRemoteFiles, K as ValServer, L as createValRequestHandler } from './ValRouterCore-b5d70504.esm.js';
3
+ import { r as resolveExistingJsonPath, s as summaryOf, m as matchesFilter, h as byUpdatedAt, n as newSketchpad, i as isSketchpadId, j as applySketchpadChange, k as ValOps, V as VAL_CLIENT_HEADERS, l as bufferFromDataUrl, o as getFieldsForType, u as uploadRemoteFile, d as getFileExt, p as guessMimeTypeFromPath, q as createMetadataFromBuffer, D as DEFAULT_ANALYTICS_INGEST_URL, e as ValOpsMemory, t as sessionAuth, w as isHttpOps, x as isHlsMasterPlaylist, y as sumHlsSegmentDurations, z as parseHlsMasterVariants, A as largestHlsVariant, B as fallbackRefOf, C as mapHlsUris, E as movedRemoteHost, F as needsHostCheck, G as rewriteRefHost, H as fallbackRemoteHost, J as checkRemoteFiles, K as ValServer, L as createValRequestHandler } from './ValRouterCore-eea19e82.esm.js';
4
4
  import path from 'path';
5
5
  import ts from 'typescript';
6
6
  import { z } from 'zod';
7
7
  import fs from 'fs';
8
8
  import { fromError } from 'zod-validation-error';
9
9
  import { result, pipe } from '@valbuild/core/fp';
10
- import { Patch, Sketchpad, STAGED_SCHEMA_PREFIX, schemaErrorsOf, PatchSets, joinSharedChanges, schemaTypesOfPath, sideFiles, sideSource, rebaseContentOp, JSONValue, SketchpadSummary, getErrorMessageFromUnknownJson, PlanRefusalError, PatchId as PatchId$1, SerializedSchema, valModulesEntryPath, newestCommitSha, LOCAL_FILE_IN_REMOTE_PROJECT_WARNING, LOCAL_FILE_IN_REMOTE_PROJECT_HINT, traverseSchemaSource, richTextImageSchema, forEachRichTextImage, isStudioFix } from '@valbuild/shared/internal';
10
+ import { Patch, Sketchpad, STAGED_SCHEMA_PREFIX, schemaErrorsOf, PatchSets, joinSharedChanges, schemaTypesOfPath, sideFiles, sideSource, JSONValue, SketchpadSummary, getErrorMessageFromUnknownJson, PlanRefusalError, PatchId as PatchId$1, SerializedSchema, valModulesEntryPath, newestCommitSha, LOCAL_FILE_IN_REMOTE_PROJECT_WARNING, LOCAL_FILE_IN_REMOTE_PROJECT_HINT, traverseSchemaSource, richTextImageSchema, forEachRichTextImage, isStudioFix } from '@valbuild/shared/internal';
11
11
  import os from 'os';
12
12
  import crypto$1, { randomBytes, createHash } from 'crypto';
13
13
  import { Buffer as Buffer$1 } from 'buffer';
@@ -585,7 +585,7 @@ function jsonValuesRecordKeys(source) {
585
585
  * as written. An error for anything that is not a literal.
586
586
  *
587
587
  * What a staging records for a module (`stagedModuleSources`): without the
588
- * markers, an entry the design tab added to a record was in the module's code
588
+ * markers, an entry the assistant added to a record was in the module's code
589
589
  * and not in its Source, and an edit into it was undone.
590
590
  */
591
591
  function evaluateModuleSource(source) {
@@ -2171,7 +2171,7 @@ function createFsSketchpadStore(rootDir, now = () => new Date()) {
2171
2171
  * as a bundler does.
2172
2172
  */
2173
2173
  function loadTypeScriptKit() {
2174
- return import('./publishKit-af14cd7a.esm.js');
2174
+ return import('./publishKit-c13ba76f.esm.js');
2175
2175
  }
2176
2176
 
2177
2177
  /** Serializes a schema, or gives up quietly — serialization errors are reported elsewhere. */
@@ -4861,146 +4861,6 @@ function sameJson(a, b) {
4861
4861
  return JSON.stringify(a) === JSON.stringify(b);
4862
4862
  }
4863
4863
 
4864
- /**
4865
- * A module's file with a patch written into it: what a save does to a
4866
- * `.val.ts`, for one file and one patch, with nothing pending around it.
4867
- *
4868
- * The design tab's `create_patch` (valbuild/home `docs/design-tab.md`): there
4869
- * the assistant changes a proposal's code, and content it writes goes into the
4870
- * module's file and is staged with the code -- so a field it just added can
4871
- * be filled in the same change, and is built and rendered with it.
4872
- *
4873
- * Only the module's own file. A `.jsonValues()` entry lives in a `*.val.json`
4874
- * of its own, which a save routes to op by op (`ValOps.prepare`); a patch that
4875
- * reaches into one fails here, and the message says to write that file.
4876
- */
4877
- async function patchModuleText(text, patch) {
4878
- // The TypeScript compiler, loaded when a patch asks for it, as a save loads
4879
- // it: see `publishKit.ts`.
4880
- const {
4881
- tsOps,
4882
- parseValFile
4883
- } = await import('./publishKit-af14cd7a.esm.js');
4884
- const applied = applyPatch(parseValFile(text), tsOps, patch);
4885
- if (result.isErr(applied)) {
4886
- const reason = messagesOf(applied.error).join(" ");
4887
- return result.err(text.includes(".jsonValues(") ? `${reason} This module keeps entries in .val.json files of their own: change an entry by writing its file with write_files.` : reason);
4888
- }
4889
- const sourceFile = applied.value;
4890
- // As a save writes it: https://github.com/microsoft/TypeScript/issues/36174
4891
- return result.ok(unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u")));
4892
- }
4893
-
4894
- /**
4895
- * A patch written into a module's files: {@link patchModuleText}, and an op
4896
- * that reaches INTO a `.jsonValues()` entry written into that entry's own
4897
- * `*.val.json`, as a save routes it (`ValOps.prepare`).
4898
- *
4899
- * The design tab's `create_patch` used to refuse those, and the assistant
4900
- * rewrote the whole entry file to change one field -- over whatever had been
4901
- * saved into it since it read it.
4902
- *
4903
- * Only into an entry that is already there. Adding, replacing or removing a
4904
- * whole entry is a key in the `.val.ts` and a file beside it, which a save
4905
- * writes from the record's schema; here that is still `write_files`, and the
4906
- * error says so.
4907
- *
4908
- * `readFile` answers a file by its path without a leading slash: the
4909
- * proposal's copy, else the build's, `null` for one the proposal deleted.
4910
- * `moduleText` is `null` when no op is the module file's own; `entries` is
4911
- * each entry file written, by the same kind of path.
4912
- */
4913
- async function patchModuleFiles(moduleFilePath, text, readFile, patch) {
4914
- const entryFiles = await jsonEntryFilesOf(moduleFilePath, text);
4915
- const textOps = [];
4916
- const entryOps = new Map();
4917
- for (const op of patch) {
4918
- const key = op.path[0];
4919
- // The record itself, or one of its entries as a whole -- a new one too,
4920
- // which would otherwise be written into the record's text inline.
4921
- if (entryFiles.size > 0 && op.path.length <= 1) {
4922
- return 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.`);
4923
- }
4924
- const entryFile = key !== undefined ? entryFiles.get(key) : undefined;
4925
- if (key === undefined || entryFile === undefined) {
4926
- textOps.push(op);
4927
- continue;
4928
- }
4929
- if (op.op === "file") {
4930
- return result.err(`A file in a .jsonValues() entry is uploaded by the Studio, not written here.`);
4931
- }
4932
- if ((op.op === "move" || op.op === "copy") && op.from[0] !== key) {
4933
- return result.err(`An op from one .jsonValues() entry into another is not written here: write the entries' .val.json files with write_files.`);
4934
- }
4935
- const rebased = rebaseContentOp(op, 1);
4936
- if (result.isErr(rebased)) return result.err(rebased.error.message);
4937
- entryOps.set(entryFile, [...(entryOps.get(entryFile) ?? []), rebased.value]);
4938
- }
4939
- let moduleText = null;
4940
- if (textOps.length > 0) {
4941
- const patched = await patchModuleText(text, textOps);
4942
- if (result.isErr(patched)) return patched;
4943
- moduleText = patched.value;
4944
- }
4945
- const entries = {};
4946
- for (const [entryFile, ops] of entryOps) {
4947
- const raw = readFile(entryFile);
4948
- if (raw === null || raw === undefined) {
4949
- return result.err(`${entryFile} is ${raw === null ? "deleted in this proposal" : "not in this proposal or on the site"}.`);
4950
- }
4951
- let content;
4952
- try {
4953
- content = JSON.parse(raw);
4954
- } catch {
4955
- return result.err(`${entryFile} is not JSON.`);
4956
- }
4957
- const applied = applyPatch(deepClone(content), new JSONOps(), ops);
4958
- if (result.isErr(applied)) {
4959
- return result.err(`${entryFile}: ${messagesOf(applied.error).join(" ")}`);
4960
- }
4961
- entries[entryFile] = applied.value;
4962
- }
4963
- return result.ok({
4964
- moduleText,
4965
- entries
4966
- });
4967
- }
4968
-
4969
- /**
4970
- * Each `.jsonValues()` entry's file, by key, without a leading slash: from the
4971
- * `c.json(() => import("..."))` thunks in the module's text. Empty for a
4972
- * module that has none, or whose text cannot be read that way.
4973
- */
4974
- async function jsonEntryFilesOf(moduleFilePath, text) {
4975
- const files = new Map();
4976
- if (!text.includes(".jsonValues(")) return files;
4977
- const {
4978
- parseValFile,
4979
- analyzeValModule,
4980
- analyzeJsonValuesEntries
4981
- } = await import('./publishKit-af14cd7a.esm.js');
4982
- try {
4983
- const analysis = analyzeValModule(parseValFile(text));
4984
- if (result.isErr(analysis)) return files;
4985
- for (const [key, entry] of analyzeJsonValuesEntries(analysis.value.source)) {
4986
- files.set(key, resolveExistingJsonPath(moduleFilePath, entry.importPath).replace(/^\/+/, ""));
4987
- }
4988
- } catch {
4989
- // No `c.define` (`analyzeValModule` throws): no entries.
4990
- }
4991
- return files;
4992
- }
4993
-
4994
- /**
4995
- * A patch error, or a tree of syntax errors, as sentences. Walked here rather
4996
- * than with `syntax.ts`'s `flattenErrors`, which would bring the compiler in
4997
- * with this module.
4998
- */
4999
-
5000
- function messagesOf(error) {
5001
- return Array.isArray(error) ? error.flatMap(messagesOf) : [error.message];
5002
- }
5003
-
5004
4864
  /**
5005
4865
  * The Source each staged module file declares, read from its text: what a
5006
4866
  * staging sends content beside the files (`POST /proposals/:name/files`,
@@ -5008,15 +4868,15 @@ function messagesOf(error) {
5008
4868
  *
5009
4869
  * A proposal's address serves a module's Source from what the proposal has
5010
4870
  * SAVED, over the site's, over the build -- never from the text. A save writes
5011
- * both, so they agree. A staging wrote only the text, so after the design
5012
- * tab's `create_patch` added a button to a module, its text and its build had
4871
+ * both, so they agree. A staging wrote only the text, so after the assistant
4872
+ * added a button to a module, its text and its build had
5013
4873
  * the button and the Source the server served and saved did not. The Studio,
5014
4874
  * lined up with that Source, could not apply an edit into the new button: the
5015
4875
  * canvas showed it, and then it was gone.
5016
4876
  *
5017
4877
  * Only what can be read without running anything: a `c.define(...)` whose
5018
4878
  * Source is a literal, a `.jsonValues()` record's entries as the markers its
5019
- * stored Source holds (`evaluateModuleSource`) -- so an entry the design tab
4879
+ * stored Source holds (`evaluateModuleSource`) -- so an entry the assistant
5020
4880
  * adds is one the proposal has. Anything else -- a Source built by code, a
5021
4881
  * file of shared schemas -- is left out, and content keeps the Source it has
5022
4882
  * for it, as before this existed.
@@ -5032,7 +4892,7 @@ async function stagedModuleSources(files) {
5032
4892
  parseValFile,
5033
4893
  analyzeValModule,
5034
4894
  evaluateModuleSource
5035
- } = await import('./publishKit-af14cd7a.esm.js');
4895
+ } = await import('./publishKit-c13ba76f.esm.js');
5036
4896
  const sources = {};
5037
4897
  for (const {
5038
4898
  path,
@@ -5396,13 +5256,6 @@ const PlanRefusedBody = z.object({
5396
5256
  error: PlanRefusalError
5397
5257
  });
5398
5258
 
5399
- /** `POST /proposals-api/<name>/patch-file`: see `patchFileInProposal`. */
5400
- const PatchFileBody = z.object({
5401
- moduleFilePath: z.string().regex(/^\/.+\.val\.(ts|js)$/),
5402
- patch: Patch,
5403
- message: z.string().max(500).optional()
5404
- });
5405
-
5406
5259
  /** A staging's body, as `write_files` sends it. */
5407
5260
  const StageFilesBody = z.object({
5408
5261
  files: z.record(z.string(), z.string().nullable())
@@ -5431,11 +5284,6 @@ async function withStagedModuleSources(body) {
5431
5284
  modules
5432
5285
  });
5433
5286
  }
5434
-
5435
- /** What `patchFileInProposal` reads of content's answer for a proposal's files. */
5436
- const ProposalFilesRead = z.object({
5437
- files: z.record(z.string(), z.string().nullable())
5438
- });
5439
5287
  const PatchId = z.string().refine(s => !!s); // TODO: validate
5440
5288
  const CommitSha = z.string().refine(s => !!s); // TODO: validate
5441
5289
  z.string().refine(s => !!s); // TODO: validate
@@ -6361,38 +6209,15 @@ class ValOpsHttp extends ValOps {
6361
6209
  };
6362
6210
  }
6363
6211
 
6364
- /**
6365
- * The writes the SITE's server may make to a proposal's files: what the
6366
- * design tab does (valbuild/home `docs/design-tab.md`, step 2) -- stage
6367
- * code, build it, and report its typecheck. The tab is served by the site's
6368
- * build so that a build the assistant breaks in the proposal cannot take
6369
- * down the tools it would fix it with; at the proposal's address those
6370
- * tools run on the proposal's own code.
6371
- *
6372
- * The typecheck too, though it blocks the proposal's Publish (adept.md,
6373
- * decision 20): it is the proposal's staged files checked against the
6374
- * site's, the same program from either address, and the content service
6375
- * keeps it only for the inputs it was made from. Without it the tab's
6376
- * Types check, and the assistant's `typecheck`, had nothing to show.
6377
- *
6378
- * And a quick preview: the browser half of a build of the staged files,
6379
- * which Val Build makes and nothing serves.
6380
- *
6381
- * The rest stay the proposal's own: Update from the site and the lockfile
6382
- * are answered from the proposal's build and schemas, and bringing back a
6383
- * point's code is the Studio at its address finishing a restore.
6384
- */
6385
- static SITE_MAY_WRITE = new Set(["files", "build", "quick-preview", "typecheck"]);
6386
-
6387
6212
  /**
6388
6213
  * Whether this server may make a write to a proposal's files: the
6389
- * proposal's own server, any of them; the site's, the design tab's; and a
6390
- * proposal's address, none to another proposal. Either way the site's own
6391
- * files change only when a proposal is merged.
6214
+ * proposal's own server, to its own files, and no other. The site's server
6215
+ * makes none -- code is changed in the proposal's own Studio, in code mode
6216
+ * -- and a proposal's address none to another proposal. Either way the
6217
+ * site's own files change only when a proposal is merged.
6392
6218
  */
6393
6219
  mayWriteFiles(write) {
6394
- if (this.proposal !== null) return write.name === this.proposal.name;
6395
- return ValOpsHttp.SITE_MAY_WRITE.has(write.write);
6220
+ return this.proposal !== null && write.name === this.proposal.name;
6396
6221
  }
6397
6222
 
6398
6223
  /**
@@ -6419,17 +6244,13 @@ class ValOpsHttp extends ValOps {
6419
6244
  return /^\/publish-jobs\/[A-Za-z0-9_-]{1,100}\/(merge-prepare|steps|renew|cancel)$/.test(path);
6420
6245
  }
6421
6246
  async proposalsApi(path, init, profileId) {
6422
- var _exec, _exec2, _exec3, _exec4, _exec5;
6247
+ var _exec, _exec2, _exec3, _exec4;
6423
6248
  const json = "application/json";
6424
6249
  const updating = (_exec = /^\/([0-9a-f]{20})\/update-content$/.exec(path)) === null || _exec === void 0 ? void 0 : _exec[1];
6425
6250
  if (updating !== undefined && init.method === "POST") {
6426
6251
  return this.updateContentFromSite(updating, init.body, profileId);
6427
6252
  }
6428
- const patching = (_exec2 = /^\/([0-9a-f]{20})\/patch-file$/.exec(path)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
6429
- if (patching !== undefined && init.method === "POST") {
6430
- return this.patchFileInProposal(patching, init.body, profileId);
6431
- }
6432
- const withCode = (_exec3 = /^\/([0-9a-f]{20})\/update-code$/.exec(path)) === null || _exec3 === void 0 ? void 0 : _exec3[1];
6253
+ const withCode = (_exec2 = /^\/([0-9a-f]{20})\/update-code$/.exec(path)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
6433
6254
  if (withCode !== undefined && init.method === "POST") {
6434
6255
  return this.updateCodeFromSite(withCode, init.body, profileId);
6435
6256
  }
@@ -6439,11 +6260,11 @@ class ValOpsHttp extends ValOps {
6439
6260
  * build's schemas (step 8.2). Anywhere else they go to content as they
6440
6261
  * are, and the site's pending changes block as they always did.
6441
6262
  */
6442
- const checking = (_exec4 = /^\/([0-9a-f]{20})\/merge-checks$/.exec(path)) === null || _exec4 === void 0 ? void 0 : _exec4[1];
6263
+ const checking = (_exec3 = /^\/([0-9a-f]{20})\/merge-checks$/.exec(path)) === null || _exec3 === void 0 ? void 0 : _exec3[1];
6443
6264
  if (checking !== undefined && init.method === "GET" && (await this.answersMovesFor(checking, profileId))) {
6444
6265
  return this.mergeChecksWithMoves(checking, profileId);
6445
6266
  }
6446
- const pressing = (_exec5 = /^\/([0-9a-f]{20})\/merge$/.exec(path)) === null || _exec5 === void 0 ? void 0 : _exec5[1];
6267
+ const pressing = (_exec4 = /^\/([0-9a-f]{20})\/merge$/.exec(path)) === null || _exec4 === void 0 ? void 0 : _exec4[1];
6447
6268
  if (pressing !== undefined && init.method === "POST" && (await this.answersMovesFor(pressing, profileId))) {
6448
6269
  return this.pressMergeWithMoves(pressing, init.body, profileId);
6449
6270
  }
@@ -6495,147 +6316,6 @@ class ValOpsHttp extends ValOps {
6495
6316
  };
6496
6317
  }
6497
6318
 
6498
- /**
6499
- * A patch written into a module's FILE in a proposal, and staged there as
6500
- * code: the design tab's `create_patch` (valbuild/home `docs/design-tab.md`).
6501
- * The assistant there changes the proposal's code, so content it writes goes
6502
- * with that code -- a field it just added is filled in the same change, and
6503
- * built and rendered with it -- rather than into the proposal's saves, which
6504
- * the site's server does not write.
6505
- *
6506
- * Answered here, at `POST /<name>/patch-file`: the file is the proposal's
6507
- * copy if it has one, otherwise the one this build was made from, and the
6508
- * patch is written into it as a save writes one (`patchModuleText`). Who may
6509
- * is who may stage files: {@link ValOpsHttp.mayWriteFiles}.
6510
- */
6511
- async patchFileInProposal(name, body, profileId) {
6512
- var _this$projectSource, _this$options2;
6513
- const json = "application/json";
6514
- const answer = (status, value) => ({
6515
- status,
6516
- contentType: json,
6517
- body: JSON.stringify(value)
6518
- });
6519
- if (!this.mayWriteFiles({
6520
- name,
6521
- write: "files"
6522
- })) {
6523
- return answer(403, {
6524
- message: "Files are changed in the proposal this Studio is open in, not in another."
6525
- });
6526
- }
6527
- let parsedBody;
6528
- try {
6529
- parsedBody = body === undefined || body === "" ? {} : JSON.parse(body);
6530
- } catch {
6531
- return answer(400, {
6532
- message: "The patch's body is not JSON."
6533
- });
6534
- }
6535
- const request = PatchFileBody.safeParse(parsedBody);
6536
- if (!request.success) {
6537
- return answer(400, {
6538
- message: `Invalid patch: ${fromError(request.error).toString()}`
6539
- });
6540
- }
6541
- const {
6542
- moduleFilePath,
6543
- patch,
6544
- message
6545
- } = request.data;
6546
- const content = this.proposalContent(name, profileId);
6547
- const read = await content("/files");
6548
- if (!read.ok) {
6549
- return {
6550
- status: read.status,
6551
- contentType: json,
6552
- body: await read.text()
6553
- };
6554
- }
6555
- const files = ProposalFilesRead.safeParse(await read.json());
6556
- if (!files.success) {
6557
- return answer(502, {
6558
- message: `Content answered the proposal's files in a shape this Val does not read: ${fromError(files.error).toString()}`
6559
- });
6560
- }
6561
- const filePath = moduleFilePath.replace(/^\/+/, "");
6562
- const own = files.data.files[filePath];
6563
- if (own === null) {
6564
- return answer(409, {
6565
- message: `${moduleFilePath} is deleted in this proposal.`
6566
- });
6567
- }
6568
- if (own === undefined && this.projectSource === null) {
6569
- return answer(409, {
6570
- message: `This build does not carry its source, so ${moduleFilePath} can only be patched once the proposal has its own copy: write it with write_files.`
6571
- });
6572
- }
6573
- const text = own ?? ((_this$projectSource = this.projectSource) === null || _this$projectSource === void 0 ? void 0 : _this$projectSource[filePath]);
6574
- if (text === undefined) {
6575
- return answer(404, {
6576
- message: `There is no module file ${moduleFilePath} in this proposal or on the site.`
6577
- });
6578
- }
6579
- const patched = await patchModuleFiles(moduleFilePath, text, path => {
6580
- var _this$projectSource2;
6581
- const proposalCopy = files.data.files[path];
6582
- return proposalCopy !== undefined ? proposalCopy : (_this$projectSource2 = this.projectSource) === null || _this$projectSource2 === void 0 ? void 0 : _this$projectSource2[path];
6583
- }, patch);
6584
- if (result.isErr(patched)) {
6585
- return answer(422, {
6586
- message: `The patch does not apply to ${moduleFilePath}: ${patched.error}`
6587
- });
6588
- }
6589
- const formatter = (_this$options2 = this.options) === null || _this$options2 === void 0 ? void 0 : _this$options2.formatter;
6590
- const format = async (written, path) => {
6591
- if (!formatter) return result.ok(written);
6592
- try {
6593
- return result.ok(await formatter(written, path));
6594
- } catch (error) {
6595
- return result.err(`The patched ${path} could not be formatted: ${error instanceof Error ? error.message : String(error)}`);
6596
- }
6597
- };
6598
- const staging = {};
6599
- if (patched.value.moduleText !== null) {
6600
- const formatted = await format(patched.value.moduleText, moduleFilePath);
6601
- if (result.isErr(formatted)) {
6602
- return answer(422, {
6603
- message: formatted.error
6604
- });
6605
- }
6606
- staging[filePath] = formatted.value;
6607
- }
6608
- // An entry's file as a save writes it: see `ValOps.prepare`.
6609
- for (const [entryFile, content] of Object.entries(patched.value.entries)) {
6610
- const formatted = await format(JSON.stringify(content, null, 2), `/${entryFile}`);
6611
- if (result.isErr(formatted)) {
6612
- return answer(422, {
6613
- message: formatted.error
6614
- });
6615
- }
6616
- staging[entryFile] = formatted.value;
6617
- }
6618
- const modules = await stagedModuleSources(staging);
6619
- const staged = await content("/files", {
6620
- method: "POST",
6621
- body: JSON.stringify({
6622
- files: staging,
6623
- // The Source the patched text declares: see `stagedModuleSources`.
6624
- ...(Object.keys(modules).length > 0 ? {
6625
- modules
6626
- } : {}),
6627
- ...(message !== undefined ? {
6628
- message
6629
- } : {})
6630
- })
6631
- });
6632
- return {
6633
- status: staged.status,
6634
- contentType: staged.headers.get("Content-Type") ?? json,
6635
- body: await staged.text()
6636
- };
6637
- }
6638
-
6639
6319
  /**
6640
6320
  * Update from the site, for a proposal that changes only content
6641
6321
  * (valbuild/home `docs/hosted-publishing.md`, step 8.2, slice 1a): content