@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.
@@ -10,8 +10,8 @@ import path from 'path';
10
10
  import fs from 'fs';
11
11
  import vm from 'node:vm';
12
12
  import { Module } from 'node:module';
13
- import { r as resolveExistingJsonPath, f as findNestedJsonValuesRecords, v as validateJsonValuesEntries, i as isJsonValuesRootOp, a as rebaseContentOp, c as classifyJsonValuesOp, V as ValOps, b as bufferFromDataUrl, g as getFieldsForType, u as uploadRemoteFile, d as getFileExt, e as guessMimeTypeFromPath, h as createMetadataFromBuffer, j as ValOpsMemory, k as isHlsMasterPlaylist, s as sumHlsSegmentDurations, p as parseHlsMasterVariants, l as largestHlsVariant, m as fallbackRefOf, n as mapHlsUris, o as movedRemoteHost, q as needsHostCheck, t as rewriteRefHost, w as fallbackRemoteHost, x as checkRemoteFiles, y as ValServer, z as createValRequestHandler, A as getNewJsonEntryPaths, B as formatPatchSourceError } from './ValRouterCore-b3c6a562.esm.js';
14
- export { I as InMemoryPatchStore, j as ValOpsMemory, C as askOncePerHost, c as classifyJsonValuesOp, B as formatPatchSourceError, d as getFileExt, D as getSettings, a as rebaseContentOp, u as uploadRemoteFile } from './ValRouterCore-b3c6a562.esm.js';
13
+ import { r as resolveExistingJsonPath, f as findNestedJsonValuesRecords, v as validateJsonValuesEntries, i as isJsonValuesRootOp, a as rebaseContentOp, c as classifyJsonValuesOp, V as ValOps, b as bufferFromDataUrl, g as getFieldsForType, u as uploadRemoteFile, d as getFileExt, e as guessMimeTypeFromPath, h as createMetadataFromBuffer, j as ValOpsMemory, k as isHlsMasterPlaylist, s as sumHlsSegmentDurations, p as parseHlsMasterVariants, l as largestHlsVariant, m as fallbackRefOf, n as mapHlsUris, o as movedRemoteHost, q as needsHostCheck, t as rewriteRefHost, w as fallbackRemoteHost, x as checkRemoteFiles, y as ValServer, z as createValRequestHandler, A as getNewJsonEntryPaths, B as formatPatchSourceError } from './ValRouterCore-2f7ad9b9.esm.js';
14
+ export { I as InMemoryPatchStore, j as ValOpsMemory, C as askOncePerHost, c as classifyJsonValuesOp, B as formatPatchSourceError, d as getFileExt, D as getSettings, a as rebaseContentOp, u as uploadRemoteFile } from './ValRouterCore-2f7ad9b9.esm.js';
15
15
  import { createUIRequestHandler } from '@valbuild/ui/server';
16
16
  import z$1, { z } from 'zod';
17
17
  import { fromError } from 'zod-validation-error';
@@ -4942,6 +4942,46 @@ function sameJson(a, b) {
4942
4942
  return JSON.stringify(a) === JSON.stringify(b);
4943
4943
  }
4944
4944
 
4945
+ /**
4946
+ * A module's file with a patch written into it: what a save does to a
4947
+ * `.val.ts`, for one file and one patch, with nothing pending around it.
4948
+ *
4949
+ * The design tab's `create_patch` (valbuild/home `docs/design-tab.md`): there
4950
+ * the assistant changes a proposal's code, and content it writes goes into the
4951
+ * module's file and is staged with the code -- so a field it just added can
4952
+ * be filled in the same change, and is built and rendered with it.
4953
+ *
4954
+ * Only the module's own file. A `.jsonValues()` entry lives in a `*.val.json`
4955
+ * of its own, which a save routes to op by op (`ValOps.prepare`); a patch that
4956
+ * reaches into one fails here, and the message says to write that file.
4957
+ */
4958
+ async function patchModuleText(text, patch) {
4959
+ // The TypeScript compiler, loaded when a patch asks for it, as a save loads
4960
+ // it: see `publishKit.ts`.
4961
+ const {
4962
+ tsOps,
4963
+ parseValFile
4964
+ } = await import('./publishKit-bc8df53d.esm.js');
4965
+ const applied = applyPatch(parseValFile(text), tsOps, patch);
4966
+ if (result.isErr(applied)) {
4967
+ const reason = messagesOf(applied.error).join(" ");
4968
+ 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);
4969
+ }
4970
+ const sourceFile = applied.value;
4971
+ // As a save writes it: https://github.com/microsoft/TypeScript/issues/36174
4972
+ return result.ok(unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u")));
4973
+ }
4974
+
4975
+ /**
4976
+ * A patch error, or a tree of syntax errors, as sentences. Walked here rather
4977
+ * than with `syntax.ts`'s `flattenErrors`, which would bring the compiler in
4978
+ * with this module.
4979
+ */
4980
+
4981
+ function messagesOf(error) {
4982
+ return Array.isArray(error) ? error.flatMap(messagesOf) : [error.message];
4983
+ }
4984
+
4945
4985
  /**
4946
4986
  * Which of the site's pending changes a merge of a proposal moves into
4947
4987
  * proposals of their own (valbuild/home `docs/hosted-publishing.md`, step 8.2,
@@ -5047,6 +5087,18 @@ const textEncoder$2 = new TextEncoder();
5047
5087
  const PlanRefusedBody = z.object({
5048
5088
  error: PlanRefusalError
5049
5089
  });
5090
+
5091
+ /** `POST /proposals-api/<name>/patch-file`: see `patchFileInProposal`. */
5092
+ const PatchFileBody = z.object({
5093
+ moduleFilePath: z.string().regex(/^\/.+\.val\.(ts|js)$/),
5094
+ patch: Patch,
5095
+ message: z.string().max(500).optional()
5096
+ });
5097
+
5098
+ /** What `patchFileInProposal` reads of content's answer for a proposal's files. */
5099
+ const ProposalFilesRead = z.object({
5100
+ files: z.record(z.string(), z.string().nullable())
5101
+ });
5050
5102
  const PatchId = z.string().refine(s => !!s); // TODO: validate
5051
5103
  const CommitSha = z.string().refine(s => !!s); // TODO: validate
5052
5104
  z.string().refine(s => !!s); // TODO: validate
@@ -5806,16 +5858,49 @@ class ValOpsHttp extends ValOps {
5806
5858
  * (valbuild/home `docs/adept.md`, step 6), reporting the typecheck of
5807
5859
  * them (step 7, decision 20), serving a build of it
5808
5860
  * (valbuild/home `docs/hosted-publishing.md`, step 7), or moving it onto the
5809
- * site's code (step 8, "Update from the site") -- is made by the
5810
- * proposal's own server and nobody else's: the file tools act on the
5811
- * proposal the Studio is open in (P11), and the site's files change only
5812
- * when a proposal is merged. The proposal it names, or `null` when this
5813
- * path is not such a write.
5861
+ * site's code (step 8, "Update from the site"). The proposal it names and
5862
+ * what it does, or `null` when this path is not such a write.
5863
+ *
5864
+ * Who may make one is {@link ValOpsHttp.mayWriteFiles}.
5814
5865
  */
5815
5866
  static proposalFilesWrite(method, path) {
5816
- var _exec;
5817
5867
  if (method !== "POST") return null;
5818
- 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;
5868
+ const match = /^\/([0-9a-f]{20})\/(files|lockfile|typecheck|build|update-from-site|restore-code)$/.exec(path);
5869
+ return match === null ? null : {
5870
+ name: match[1],
5871
+ write: match[2]
5872
+ };
5873
+ }
5874
+
5875
+ /**
5876
+ * The writes the SITE's server may make to a proposal's files: what the
5877
+ * design tab does (valbuild/home `docs/design-tab.md`, step 2) -- stage
5878
+ * code, build it, and report its typecheck. The tab is served by the site's
5879
+ * build so that a build the assistant breaks in the proposal cannot take
5880
+ * down the tools it would fix it with; at the proposal's address those
5881
+ * tools run on the proposal's own code.
5882
+ *
5883
+ * The typecheck too, though it blocks the proposal's Publish (adept.md,
5884
+ * decision 20): it is the proposal's staged files checked against the
5885
+ * site's, the same program from either address, and the content service
5886
+ * keeps it only for the inputs it was made from. Without it the tab's
5887
+ * Types check, and the assistant's `typecheck`, had nothing to show.
5888
+ *
5889
+ * The rest stay the proposal's own: Update from the site and the lockfile
5890
+ * are answered from the proposal's build and schemas, and bringing back a
5891
+ * point's code is the Studio at its address finishing a restore.
5892
+ */
5893
+ static SITE_MAY_WRITE = new Set(["files", "build", "typecheck"]);
5894
+
5895
+ /**
5896
+ * Whether this server may make a write to a proposal's files: the
5897
+ * proposal's own server, any of them; the site's, the design tab's; and a
5898
+ * proposal's address, none to another proposal. Either way the site's own
5899
+ * files change only when a proposal is merged.
5900
+ */
5901
+ mayWriteFiles(write) {
5902
+ if (this.proposal !== null) return write.name === this.proposal.name;
5903
+ return ValOpsHttp.SITE_MAY_WRITE.has(write.write);
5819
5904
  }
5820
5905
 
5821
5906
  /**
@@ -5842,12 +5927,16 @@ class ValOpsHttp extends ValOps {
5842
5927
  return /^\/publish-jobs\/[A-Za-z0-9_-]{1,100}\/(merge-prepare|steps|renew|cancel)$/.test(path);
5843
5928
  }
5844
5929
  async proposalsApi(path, init, profileId) {
5845
- var _exec2, _exec3, _exec4, _exec5, _this$proposal;
5930
+ var _exec, _exec2, _exec3, _exec4, _exec5;
5846
5931
  const json = "application/json";
5847
- const updating = (_exec2 = /^\/([0-9a-f]{20})\/update-content$/.exec(path)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
5932
+ const updating = (_exec = /^\/([0-9a-f]{20})\/update-content$/.exec(path)) === null || _exec === void 0 ? void 0 : _exec[1];
5848
5933
  if (updating !== undefined && init.method === "POST") {
5849
5934
  return this.updateContentFromSite(updating, init.body, profileId);
5850
5935
  }
5936
+ const patching = (_exec2 = /^\/([0-9a-f]{20})\/patch-file$/.exec(path)) === null || _exec2 === void 0 ? void 0 : _exec2[1];
5937
+ if (patching !== undefined && init.method === "POST") {
5938
+ return this.patchFileInProposal(patching, init.body, profileId);
5939
+ }
5851
5940
  const withCode = (_exec3 = /^\/([0-9a-f]{20})\/update-code$/.exec(path)) === null || _exec3 === void 0 ? void 0 : _exec3[1];
5852
5941
  if (withCode !== undefined && init.method === "POST") {
5853
5942
  return this.updateCodeFromSite(withCode, init.body, profileId);
@@ -5876,12 +5965,12 @@ class ValOpsHttp extends ValOps {
5876
5965
  };
5877
5966
  }
5878
5967
  const writes = ValOpsHttp.proposalFilesWrite(init.method, path);
5879
- if (writes !== null && writes !== ((_this$proposal = this.proposal) === null || _this$proposal === void 0 ? void 0 : _this$proposal.name)) {
5968
+ if (writes !== null && !this.mayWriteFiles(writes)) {
5880
5969
  return {
5881
5970
  status: 403,
5882
5971
  contentType: json,
5883
5972
  body: JSON.stringify({
5884
- 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."
5973
+ 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."
5885
5974
  })
5886
5975
  };
5887
5976
  }
@@ -5912,6 +6001,121 @@ class ValOpsHttp extends ValOps {
5912
6001
  };
5913
6002
  }
5914
6003
 
6004
+ /**
6005
+ * A patch written into a module's FILE in a proposal, and staged there as
6006
+ * code: the design tab's `create_patch` (valbuild/home `docs/design-tab.md`).
6007
+ * The assistant there changes the proposal's code, so content it writes goes
6008
+ * with that code -- a field it just added is filled in the same change, and
6009
+ * built and rendered with it -- rather than into the proposal's saves, which
6010
+ * the site's server does not write.
6011
+ *
6012
+ * Answered here, at `POST /<name>/patch-file`: the file is the proposal's
6013
+ * copy if it has one, otherwise the one this build was made from, and the
6014
+ * patch is written into it as a save writes one (`patchModuleText`). Who may
6015
+ * is who may stage files: {@link ValOpsHttp.mayWriteFiles}.
6016
+ */
6017
+ async patchFileInProposal(name, body, profileId) {
6018
+ var _this$projectSource, _this$options;
6019
+ const json = "application/json";
6020
+ const answer = (status, value) => ({
6021
+ status,
6022
+ contentType: json,
6023
+ body: JSON.stringify(value)
6024
+ });
6025
+ if (!this.mayWriteFiles({
6026
+ name,
6027
+ write: "files"
6028
+ })) {
6029
+ return answer(403, {
6030
+ message: "Files are changed in the proposal this Studio is open in, not in another."
6031
+ });
6032
+ }
6033
+ let parsedBody;
6034
+ try {
6035
+ parsedBody = body === undefined || body === "" ? {} : JSON.parse(body);
6036
+ } catch {
6037
+ return answer(400, {
6038
+ message: "The patch's body is not JSON."
6039
+ });
6040
+ }
6041
+ const request = PatchFileBody.safeParse(parsedBody);
6042
+ if (!request.success) {
6043
+ return answer(400, {
6044
+ message: `Invalid patch: ${fromError(request.error).toString()}`
6045
+ });
6046
+ }
6047
+ const {
6048
+ moduleFilePath,
6049
+ patch,
6050
+ message
6051
+ } = request.data;
6052
+ const content = this.proposalContent(name, profileId);
6053
+ const read = await content("/files");
6054
+ if (!read.ok) {
6055
+ return {
6056
+ status: read.status,
6057
+ contentType: json,
6058
+ body: await read.text()
6059
+ };
6060
+ }
6061
+ const files = ProposalFilesRead.safeParse(await read.json());
6062
+ if (!files.success) {
6063
+ return answer(502, {
6064
+ message: `Content answered the proposal's files in a shape this Val does not read: ${fromError(files.error).toString()}`
6065
+ });
6066
+ }
6067
+ const filePath = moduleFilePath.replace(/^\/+/, "");
6068
+ const own = files.data.files[filePath];
6069
+ if (own === null) {
6070
+ return answer(409, {
6071
+ message: `${moduleFilePath} is deleted in this proposal.`
6072
+ });
6073
+ }
6074
+ if (own === undefined && this.projectSource === null) {
6075
+ return answer(409, {
6076
+ 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.`
6077
+ });
6078
+ }
6079
+ const text = own ?? ((_this$projectSource = this.projectSource) === null || _this$projectSource === void 0 ? void 0 : _this$projectSource[filePath]);
6080
+ if (text === undefined) {
6081
+ return answer(404, {
6082
+ message: `There is no module file ${moduleFilePath} in this proposal or on the site.`
6083
+ });
6084
+ }
6085
+ const patched = await patchModuleText(text, patch);
6086
+ if (result.isErr(patched)) {
6087
+ return answer(422, {
6088
+ message: `The patch does not apply to ${moduleFilePath}: ${patched.error}`
6089
+ });
6090
+ }
6091
+ let formatted = patched.value;
6092
+ if ((_this$options = this.options) !== null && _this$options !== void 0 && _this$options.formatter) {
6093
+ try {
6094
+ formatted = await this.options.formatter(patched.value, moduleFilePath);
6095
+ } catch (error) {
6096
+ return answer(422, {
6097
+ message: `The patched ${moduleFilePath} could not be formatted: ${error instanceof Error ? error.message : String(error)}`
6098
+ });
6099
+ }
6100
+ }
6101
+ const staged = await content("/files", {
6102
+ method: "POST",
6103
+ body: JSON.stringify({
6104
+ files: {
6105
+ [filePath]: formatted
6106
+ },
6107
+ ...(message !== undefined ? {
6108
+ message
6109
+ } : {})
6110
+ })
6111
+ });
6112
+ return {
6113
+ status: staged.status,
6114
+ contentType: staged.headers.get("Content-Type") ?? json,
6115
+ body: await staged.text()
6116
+ };
6117
+ }
6118
+
5915
6119
  /**
5916
6120
  * Update from the site, for a proposal that changes only content
5917
6121
  * (valbuild/home `docs/hosted-publishing.md`, step 8.2, slice 1a): content
@@ -5926,14 +6130,14 @@ class ValOpsHttp extends ValOps {
5926
6130
  * with their `resolutions` merges.
5927
6131
  */
5928
6132
  async updateContentFromSite(name, body, profileId) {
5929
- var _this$proposal2;
6133
+ var _this$proposal;
5930
6134
  const json = "application/json";
5931
6135
  const answer = (status, value) => ({
5932
6136
  status,
5933
6137
  contentType: json,
5934
6138
  body: JSON.stringify(value)
5935
6139
  });
5936
- if (((_this$proposal2 = this.proposal) === null || _this$proposal2 === void 0 ? void 0 : _this$proposal2.name) !== name) {
6140
+ if (((_this$proposal = this.proposal) === null || _this$proposal === void 0 ? void 0 : _this$proposal.name) !== name) {
5937
6141
  return answer(403, {
5938
6142
  message: "A proposal is updated from the site at its own address, where its build is."
5939
6143
  });
@@ -6203,14 +6407,14 @@ class ValOpsHttp extends ValOps {
6203
6407
  * Only at the proposal's own address, as every write to its files is.
6204
6408
  */
6205
6409
  async updateCodeFromSite(name, body, profileId) {
6206
- var _this$proposal3;
6410
+ var _this$proposal2;
6207
6411
  const json = "application/json";
6208
6412
  const answer = (status, value) => ({
6209
6413
  status,
6210
6414
  contentType: json,
6211
6415
  body: JSON.stringify(value)
6212
6416
  });
6213
- if (((_this$proposal3 = this.proposal) === null || _this$proposal3 === void 0 ? void 0 : _this$proposal3.name) !== name) {
6417
+ if (((_this$proposal2 = this.proposal) === null || _this$proposal2 === void 0 ? void 0 : _this$proposal2.name) !== name) {
6214
6418
  return answer(403, {
6215
6419
  message: "A proposal is updated from the site at its own address, where its files are written."
6216
6420
  });
@@ -6656,8 +6860,8 @@ class ValOpsHttp extends ValOps {
6656
6860
 
6657
6861
  /** The branch this server's patches are on, where it knows it. */
6658
6862
  ownBranch() {
6659
- var _this$proposal4, _this$git;
6660
- 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);
6863
+ var _this$proposal3, _this$git;
6864
+ 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);
6661
6865
  }
6662
6866
  async getWebSocketNonce(profileId) {
6663
6867
  return fetch(`${this.contentUrl}/v1/${this.project}/websocket/nonces`, {
@@ -7422,13 +7626,13 @@ class ValOpsHttp extends ValOps {
7422
7626
  */
7423
7627
  intoProposal) {
7424
7628
  try {
7425
- var _this$proposal5, _res$headers$get3;
7629
+ var _this$proposal4, _res$headers$get3;
7426
7630
  /*
7427
7631
  * A save in a proposal is a commit on the proposal's branch, at its own
7428
7632
  * route: the site's `/commit` refuses a proposal's patches, which is
7429
7633
  * the line that keeps them off the site until a merge.
7430
7634
  */
7431
- const proposalName = intoProposal ?? ((_this$proposal5 = this.proposal) === null || _this$proposal5 === void 0 ? void 0 : _this$proposal5.name);
7635
+ const proposalName = intoProposal ?? ((_this$proposal4 = this.proposal) === null || _this$proposal4 === void 0 ? void 0 : _this$proposal4.name);
7432
7636
  const commitUrl = proposalName !== undefined ? `${this.contentUrl}/v1/${this.project}/proposals/${proposalName}/save` : `${this.contentUrl}/v1/${this.project}/commit`;
7433
7637
  const res = await fetch(commitUrl, {
7434
7638
  method: "POST",
package/package.json CHANGED
@@ -27,7 +27,7 @@
27
27
  ],
28
28
  "exports": true
29
29
  },
30
- "version": "0.150.3",
30
+ "version": "0.150.8",
31
31
  "devDependencies": {
32
32
  "@prettier/sync": "^0.6.1",
33
33
  "@types/jest": "^30.0.0",
@@ -42,8 +42,8 @@
42
42
  "zod": "^4.4.3",
43
43
  "zod-validation-error": "^5.0.0",
44
44
  "@valbuild/core": "0.150.3",
45
- "@valbuild/ui": "0.150.3",
46
- "@valbuild/shared": "0.150.3"
45
+ "@valbuild/shared": "0.150.8",
46
+ "@valbuild/ui": "0.150.8"
47
47
  },
48
48
  "engines": {
49
49
  "node": "^20.19.0 || >=22"