@valbuild/server 0.150.3 → 0.150.8

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.
@@ -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-2e82ae18.cjs.prod.js');
15
+ var ValRouterCore = require('./ValRouterCore-97c47cec.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');
@@ -4978,6 +4978,46 @@ function sameJson(a, b) {
4978
4978
  return JSON.stringify(a) === JSON.stringify(b);
4979
4979
  }
4980
4980
 
4981
+ /**
4982
+ * A module's file with a patch written into it: what a save does to a
4983
+ * `.val.ts`, for one file and one patch, with nothing pending around it.
4984
+ *
4985
+ * The design tab's `create_patch` (valbuild/home `docs/design-tab.md`): there
4986
+ * the assistant changes a proposal's code, and content it writes goes into the
4987
+ * module's file and is staged with the code -- so a field it just added can
4988
+ * be filled in the same change, and is built and rendered with it.
4989
+ *
4990
+ * Only the module's own file. A `.jsonValues()` entry lives in a `*.val.json`
4991
+ * of its own, which a save routes to op by op (`ValOps.prepare`); a patch that
4992
+ * reaches into one fails here, and the message says to write that file.
4993
+ */
4994
+ async function patchModuleText(text, patch$1) {
4995
+ // The TypeScript compiler, loaded when a patch asks for it, as a save loads
4996
+ // it: see `publishKit.ts`.
4997
+ const {
4998
+ tsOps,
4999
+ parseValFile
5000
+ } = await Promise.resolve().then(function () { return require('./publishKit-580f558a.cjs.prod.js'); });
5001
+ const applied = patch.applyPatch(parseValFile(text), tsOps, patch$1);
5002
+ if (fp.result.isErr(applied)) {
5003
+ const reason = messagesOf(applied.error).join(" ");
5004
+ return fp.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);
5005
+ }
5006
+ const sourceFile = applied.value;
5007
+ // As a save writes it: https://github.com/microsoft/TypeScript/issues/36174
5008
+ return fp.result.ok(unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u")));
5009
+ }
5010
+
5011
+ /**
5012
+ * A patch error, or a tree of syntax errors, as sentences. Walked here rather
5013
+ * than with `syntax.ts`'s `flattenErrors`, which would bring the compiler in
5014
+ * with this module.
5015
+ */
5016
+
5017
+ function messagesOf(error) {
5018
+ return Array.isArray(error) ? error.flatMap(messagesOf) : [error.message];
5019
+ }
5020
+
4981
5021
  /**
4982
5022
  * Which of the site's pending changes a merge of a proposal moves into
4983
5023
  * proposals of their own (valbuild/home `docs/hosted-publishing.md`, step 8.2,
@@ -5083,6 +5123,18 @@ const textEncoder$2 = new TextEncoder();
5083
5123
  const PlanRefusedBody = z.z.object({
5084
5124
  error: internal.PlanRefusalError
5085
5125
  });
5126
+
5127
+ /** `POST /proposals-api/<name>/patch-file`: see `patchFileInProposal`. */
5128
+ const PatchFileBody = z.z.object({
5129
+ moduleFilePath: z.z.string().regex(/^\/.+\.val\.(ts|js)$/),
5130
+ patch: internal.Patch,
5131
+ message: z.z.string().max(500).optional()
5132
+ });
5133
+
5134
+ /** What `patchFileInProposal` reads of content's answer for a proposal's files. */
5135
+ const ProposalFilesRead = z.z.object({
5136
+ files: z.z.record(z.z.string(), z.z.string().nullable())
5137
+ });
5086
5138
  const PatchId = z.z.string().refine(s => !!s); // TODO: validate
5087
5139
  const CommitSha = z.z.string().refine(s => !!s); // TODO: validate
5088
5140
  z.z.string().refine(s => !!s); // TODO: validate
@@ -5842,16 +5894,49 @@ class ValOpsHttp extends ValRouterCore.ValOps {
5842
5894
  * (valbuild/home `docs/adept.md`, step 6), reporting the typecheck of
5843
5895
  * them (step 7, decision 20), serving a build of it
5844
5896
  * (valbuild/home `docs/hosted-publishing.md`, step 7), or moving it onto the
5845
- * site's code (step 8, "Update from the site") -- is made by the
5846
- * proposal's own server and nobody else's: the file tools act on the
5847
- * proposal the Studio is open in (P11), and the site's files change only
5848
- * when a proposal is merged. The proposal it names, or `null` when this
5849
- * path is not such a write.
5897
+ * site's code (step 8, "Update from the site"). The proposal it names and
5898
+ * what it does, or `null` when this path is not such a write.
5899
+ *
5900
+ * Who may make one is {@link ValOpsHttp.mayWriteFiles}.
5850
5901
  */
5851
5902
  static proposalFilesWrite(method, path) {
5852
- var _exec;
5853
5903
  if (method !== "POST") return null;
5854
- return ((_exec = /^\/([0-9a-f]{20})\/(files|lockfile|typecheck|build|update-from-site|restore-code)$/.exec(path)) === null || _exec === void 0 ? void 0 : _exec[1]) ?? null;
5904
+ const match = /^\/([0-9a-f]{20})\/(files|lockfile|typecheck|build|update-from-site|restore-code)$/.exec(path);
5905
+ return match === null ? null : {
5906
+ name: match[1],
5907
+ write: match[2]
5908
+ };
5909
+ }
5910
+
5911
+ /**
5912
+ * The writes the SITE's server may make to a proposal's files: what the
5913
+ * design tab does (valbuild/home `docs/design-tab.md`, step 2) -- stage
5914
+ * code, build it, and report its typecheck. The tab is served by the site's
5915
+ * build so that a build the assistant breaks in the proposal cannot take
5916
+ * down the tools it would fix it with; at the proposal's address those
5917
+ * tools run on the proposal's own code.
5918
+ *
5919
+ * The typecheck too, though it blocks the proposal's Publish (adept.md,
5920
+ * decision 20): it is the proposal's staged files checked against the
5921
+ * site's, the same program from either address, and the content service
5922
+ * keeps it only for the inputs it was made from. Without it the tab's
5923
+ * Types check, and the assistant's `typecheck`, had nothing to show.
5924
+ *
5925
+ * The rest stay the proposal's own: Update from the site and the lockfile
5926
+ * are answered from the proposal's build and schemas, and bringing back a
5927
+ * point's code is the Studio at its address finishing a restore.
5928
+ */
5929
+ static SITE_MAY_WRITE = new Set(["files", "build", "typecheck"]);
5930
+
5931
+ /**
5932
+ * Whether this server may make a write to a proposal's files: the
5933
+ * proposal's own server, any of them; the site's, the design tab's; and a
5934
+ * proposal's address, none to another proposal. Either way the site's own
5935
+ * files change only when a proposal is merged.
5936
+ */
5937
+ mayWriteFiles(write) {
5938
+ if (this.proposal !== null) return write.name === this.proposal.name;
5939
+ return ValOpsHttp.SITE_MAY_WRITE.has(write.write);
5855
5940
  }
5856
5941
 
5857
5942
  /**
@@ -5878,12 +5963,16 @@ class ValOpsHttp extends ValRouterCore.ValOps {
5878
5963
  return /^\/publish-jobs\/[A-Za-z0-9_-]{1,100}\/(merge-prepare|steps|renew|cancel)$/.test(path);
5879
5964
  }
5880
5965
  async proposalsApi(path, init, profileId) {
5881
- var _exec2, _exec3, _exec4, _exec5, _this$proposal;
5966
+ var _exec, _exec2, _exec3, _exec4, _exec5;
5882
5967
  const json = "application/json";
5883
- const updating = (_exec2 = /^\/([0-9a-f]{20})\/update-content$/.exec(path)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
5968
+ const updating = (_exec = /^\/([0-9a-f]{20})\/update-content$/.exec(path)) === null || _exec === void 0 ? void 0 : _exec[1];
5884
5969
  if (updating !== undefined && init.method === "POST") {
5885
5970
  return this.updateContentFromSite(updating, init.body, profileId);
5886
5971
  }
5972
+ const patching = (_exec2 = /^\/([0-9a-f]{20})\/patch-file$/.exec(path)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
5973
+ if (patching !== undefined && init.method === "POST") {
5974
+ return this.patchFileInProposal(patching, init.body, profileId);
5975
+ }
5887
5976
  const withCode = (_exec3 = /^\/([0-9a-f]{20})\/update-code$/.exec(path)) === null || _exec3 === void 0 ? void 0 : _exec3[1];
5888
5977
  if (withCode !== undefined && init.method === "POST") {
5889
5978
  return this.updateCodeFromSite(withCode, init.body, profileId);
@@ -5912,12 +6001,12 @@ class ValOpsHttp extends ValRouterCore.ValOps {
5912
6001
  };
5913
6002
  }
5914
6003
  const writes = ValOpsHttp.proposalFilesWrite(init.method, path);
5915
- if (writes !== null && writes !== ((_this$proposal = this.proposal) === null || _this$proposal === void 0 ? void 0 : _this$proposal.name)) {
6004
+ if (writes !== null && !this.mayWriteFiles(writes)) {
5916
6005
  return {
5917
6006
  status: 403,
5918
6007
  contentType: json,
5919
6008
  body: JSON.stringify({
5920
- message: this.proposal === null ? "The site's files are changed in a proposal: open one, and change them there." : "Files are changed in the proposal this Studio is open in, not in another."
6009
+ message: this.proposal === null ? "Only the proposal's own Studio does this: open the proposal, and do it there." : "Files are changed in the proposal this Studio is open in, not in another."
5921
6010
  })
5922
6011
  };
5923
6012
  }
@@ -5948,6 +6037,121 @@ class ValOpsHttp extends ValRouterCore.ValOps {
5948
6037
  };
5949
6038
  }
5950
6039
 
6040
+ /**
6041
+ * A patch written into a module's FILE in a proposal, and staged there as
6042
+ * code: the design tab's `create_patch` (valbuild/home `docs/design-tab.md`).
6043
+ * The assistant there changes the proposal's code, so content it writes goes
6044
+ * with that code -- a field it just added is filled in the same change, and
6045
+ * built and rendered with it -- rather than into the proposal's saves, which
6046
+ * the site's server does not write.
6047
+ *
6048
+ * Answered here, at `POST /<name>/patch-file`: the file is the proposal's
6049
+ * copy if it has one, otherwise the one this build was made from, and the
6050
+ * patch is written into it as a save writes one (`patchModuleText`). Who may
6051
+ * is who may stage files: {@link ValOpsHttp.mayWriteFiles}.
6052
+ */
6053
+ async patchFileInProposal(name, body, profileId) {
6054
+ var _this$projectSource, _this$options;
6055
+ const json = "application/json";
6056
+ const answer = (status, value) => ({
6057
+ status,
6058
+ contentType: json,
6059
+ body: JSON.stringify(value)
6060
+ });
6061
+ if (!this.mayWriteFiles({
6062
+ name,
6063
+ write: "files"
6064
+ })) {
6065
+ return answer(403, {
6066
+ message: "Files are changed in the proposal this Studio is open in, not in another."
6067
+ });
6068
+ }
6069
+ let parsedBody;
6070
+ try {
6071
+ parsedBody = body === undefined || body === "" ? {} : JSON.parse(body);
6072
+ } catch {
6073
+ return answer(400, {
6074
+ message: "The patch's body is not JSON."
6075
+ });
6076
+ }
6077
+ const request = PatchFileBody.safeParse(parsedBody);
6078
+ if (!request.success) {
6079
+ return answer(400, {
6080
+ message: `Invalid patch: ${zodValidationError.fromError(request.error).toString()}`
6081
+ });
6082
+ }
6083
+ const {
6084
+ moduleFilePath,
6085
+ patch,
6086
+ message
6087
+ } = request.data;
6088
+ const content = this.proposalContent(name, profileId);
6089
+ const read = await content("/files");
6090
+ if (!read.ok) {
6091
+ return {
6092
+ status: read.status,
6093
+ contentType: json,
6094
+ body: await read.text()
6095
+ };
6096
+ }
6097
+ const files = ProposalFilesRead.safeParse(await read.json());
6098
+ if (!files.success) {
6099
+ return answer(502, {
6100
+ message: `Content answered the proposal's files in a shape this Val does not read: ${zodValidationError.fromError(files.error).toString()}`
6101
+ });
6102
+ }
6103
+ const filePath = moduleFilePath.replace(/^\/+/, "");
6104
+ const own = files.data.files[filePath];
6105
+ if (own === null) {
6106
+ return answer(409, {
6107
+ message: `${moduleFilePath} is deleted in this proposal.`
6108
+ });
6109
+ }
6110
+ if (own === undefined && this.projectSource === null) {
6111
+ return answer(409, {
6112
+ 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.`
6113
+ });
6114
+ }
6115
+ const text = own ?? ((_this$projectSource = this.projectSource) === null || _this$projectSource === void 0 ? void 0 : _this$projectSource[filePath]);
6116
+ if (text === undefined) {
6117
+ return answer(404, {
6118
+ message: `There is no module file ${moduleFilePath} in this proposal or on the site.`
6119
+ });
6120
+ }
6121
+ const patched = await patchModuleText(text, patch);
6122
+ if (fp.result.isErr(patched)) {
6123
+ return answer(422, {
6124
+ message: `The patch does not apply to ${moduleFilePath}: ${patched.error}`
6125
+ });
6126
+ }
6127
+ let formatted = patched.value;
6128
+ if ((_this$options = this.options) !== null && _this$options !== void 0 && _this$options.formatter) {
6129
+ try {
6130
+ formatted = await this.options.formatter(patched.value, moduleFilePath);
6131
+ } catch (error) {
6132
+ return answer(422, {
6133
+ message: `The patched ${moduleFilePath} could not be formatted: ${error instanceof Error ? error.message : String(error)}`
6134
+ });
6135
+ }
6136
+ }
6137
+ const staged = await content("/files", {
6138
+ method: "POST",
6139
+ body: JSON.stringify({
6140
+ files: {
6141
+ [filePath]: formatted
6142
+ },
6143
+ ...(message !== undefined ? {
6144
+ message
6145
+ } : {})
6146
+ })
6147
+ });
6148
+ return {
6149
+ status: staged.status,
6150
+ contentType: staged.headers.get("Content-Type") ?? json,
6151
+ body: await staged.text()
6152
+ };
6153
+ }
6154
+
5951
6155
  /**
5952
6156
  * Update from the site, for a proposal that changes only content
5953
6157
  * (valbuild/home `docs/hosted-publishing.md`, step 8.2, slice 1a): content
@@ -5962,14 +6166,14 @@ class ValOpsHttp extends ValRouterCore.ValOps {
5962
6166
  * with their `resolutions` merges.
5963
6167
  */
5964
6168
  async updateContentFromSite(name, body, profileId) {
5965
- var _this$proposal2;
6169
+ var _this$proposal;
5966
6170
  const json = "application/json";
5967
6171
  const answer = (status, value) => ({
5968
6172
  status,
5969
6173
  contentType: json,
5970
6174
  body: JSON.stringify(value)
5971
6175
  });
5972
- if (((_this$proposal2 = this.proposal) === null || _this$proposal2 === void 0 ? void 0 : _this$proposal2.name) !== name) {
6176
+ if (((_this$proposal = this.proposal) === null || _this$proposal === void 0 ? void 0 : _this$proposal.name) !== name) {
5973
6177
  return answer(403, {
5974
6178
  message: "A proposal is updated from the site at its own address, where its build is."
5975
6179
  });
@@ -6239,14 +6443,14 @@ class ValOpsHttp extends ValRouterCore.ValOps {
6239
6443
  * Only at the proposal's own address, as every write to its files is.
6240
6444
  */
6241
6445
  async updateCodeFromSite(name, body, profileId) {
6242
- var _this$proposal3;
6446
+ var _this$proposal2;
6243
6447
  const json = "application/json";
6244
6448
  const answer = (status, value) => ({
6245
6449
  status,
6246
6450
  contentType: json,
6247
6451
  body: JSON.stringify(value)
6248
6452
  });
6249
- if (((_this$proposal3 = this.proposal) === null || _this$proposal3 === void 0 ? void 0 : _this$proposal3.name) !== name) {
6453
+ if (((_this$proposal2 = this.proposal) === null || _this$proposal2 === void 0 ? void 0 : _this$proposal2.name) !== name) {
6250
6454
  return answer(403, {
6251
6455
  message: "A proposal is updated from the site at its own address, where its files are written."
6252
6456
  });
@@ -6692,8 +6896,8 @@ class ValOpsHttp extends ValRouterCore.ValOps {
6692
6896
 
6693
6897
  /** The branch this server's patches are on, where it knows it. */
6694
6898
  ownBranch() {
6695
- var _this$proposal4, _this$git;
6696
- return ((_this$proposal4 = this.proposal) === null || _this$proposal4 === void 0 ? void 0 : _this$proposal4.branch) ?? ((_this$git = this.git) === null || _this$git === void 0 ? void 0 : _this$git.branch);
6899
+ var _this$proposal3, _this$git;
6900
+ return ((_this$proposal3 = this.proposal) === null || _this$proposal3 === void 0 ? void 0 : _this$proposal3.branch) ?? ((_this$git = this.git) === null || _this$git === void 0 ? void 0 : _this$git.branch);
6697
6901
  }
6698
6902
  async getWebSocketNonce(profileId) {
6699
6903
  return fetch(`${this.contentUrl}/v1/${this.project}/websocket/nonces`, {
@@ -7458,13 +7662,13 @@ class ValOpsHttp extends ValRouterCore.ValOps {
7458
7662
  */
7459
7663
  intoProposal) {
7460
7664
  try {
7461
- var _this$proposal5, _res$headers$get3;
7665
+ var _this$proposal4, _res$headers$get3;
7462
7666
  /*
7463
7667
  * A save in a proposal is a commit on the proposal's branch, at its own
7464
7668
  * route: the site's `/commit` refuses a proposal's patches, which is
7465
7669
  * the line that keeps them off the site until a merge.
7466
7670
  */
7467
- const proposalName = intoProposal ?? ((_this$proposal5 = this.proposal) === null || _this$proposal5 === void 0 ? void 0 : _this$proposal5.name);
7671
+ const proposalName = intoProposal ?? ((_this$proposal4 = this.proposal) === null || _this$proposal4 === void 0 ? void 0 : _this$proposal4.name);
7468
7672
  const commitUrl = proposalName !== undefined ? `${this.contentUrl}/v1/${this.project}/proposals/${proposalName}/save` : `${this.contentUrl}/v1/${this.project}/commit`;
7469
7673
  const res = await fetch(commitUrl, {
7470
7674
  method: "POST",