@valbuild/server 0.155.0 → 0.156.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 (49) hide show
  1. package/CHANGELOG.md +30 -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/{ValOpsMemory-f000531b.cjs.prod.js → ValOpsMemory-6155aa9b.cjs.prod.js} +36 -4
  6. package/dist/{ValOpsMemory-1a0bc2dc.esm.js → ValOpsMemory-a00c3187.esm.js} +36 -4
  7. package/dist/{ValOpsMemory-6e829758.cjs.dev.js → ValOpsMemory-c1453e6a.cjs.dev.js} +36 -4
  8. package/dist/{createPrettierFormatter-5d830bdf.cjs.dev.js → createPrettierFormatter-8e60f596.cjs.prod.js} +1 -1
  9. package/dist/{createPrettierFormatter-b31bfbe5.cjs.prod.js → createPrettierFormatter-a9109288.cjs.dev.js} +1 -1
  10. package/dist/{createPrettierFormatter-ce478de1.esm.js → createPrettierFormatter-fb68e363.esm.js} +1 -1
  11. package/dist/{createValRuntime-f55300a0.esm.js → createValRuntime-4371c69b.esm.js} +6 -4
  12. package/dist/{createValRuntime-a519939b.cjs.prod.js → createValRuntime-5eb0336d.cjs.prod.js} +6 -4
  13. package/dist/{createValRuntime-1c7d891e.cjs.dev.js → createValRuntime-82f38747.cjs.dev.js} +6 -4
  14. package/dist/declarations/src/internal/index.d.ts +14 -0
  15. package/dist/declarations/src/proposalMerge/foldContent.d.ts +45 -0
  16. package/dist/declarations/src/proposalMerge/project.d.ts +124 -0
  17. package/dist/declarations/src/proposalMerge/threeWay.d.ts +51 -0
  18. package/dist/declarations/src/proposalMerge/validate.d.ts +16 -0
  19. package/dist/foldContent-2c218a30.cjs.dev.js +216 -0
  20. package/dist/foldContent-54f2c87c.cjs.prod.js +216 -0
  21. package/dist/foldContent-f065c19f.esm.js +214 -0
  22. package/dist/{inTabFetch-dae5dd87.esm.js → inTabFetch-22fc6815.esm.js} +1 -1
  23. package/dist/{inTabFetch-3d8ceb84.cjs.prod.js → inTabFetch-4efbd411.cjs.prod.js} +1 -1
  24. package/dist/{inTabFetch-75753a09.cjs.dev.js → inTabFetch-f5eedbd0.cjs.dev.js} +1 -1
  25. package/dist/{proposalJsonEntries-2cd6f6fe.esm.js → jsonValuesModule-12fc4bb0.esm.js} +2 -128
  26. package/dist/{proposalJsonEntries-d21900d4.cjs.dev.js → jsonValuesModule-6cf73937.cjs.prod.js} +2 -130
  27. package/dist/{proposalJsonEntries-d4623810.cjs.prod.js → jsonValuesModule-ed68a9de.cjs.dev.js} +2 -130
  28. package/dist/merge-5a8fc685.cjs.prod.js +1596 -0
  29. package/dist/merge-a21a9c78.cjs.dev.js +1596 -0
  30. package/dist/merge-eca8ec38.esm.js +1566 -0
  31. package/dist/proposalJsonEntries-4fcfab08.cjs.prod.js +135 -0
  32. package/dist/proposalJsonEntries-878ad5b6.cjs.dev.js +135 -0
  33. package/dist/proposalJsonEntries-e1b07915.esm.js +128 -0
  34. package/dist/{publishKit-395b92e5.cjs.prod.js → publishKit-0ec427f3.cjs.prod.js} +19 -22
  35. package/dist/{publishKit-04b6d255.esm.js → publishKit-a40062cd.esm.js} +11 -14
  36. package/dist/{publishKit-de4baed6.cjs.dev.js → publishKit-ffcaf2af.cjs.dev.js} +19 -22
  37. package/dist/{valRuntime-e922e372.cjs.prod.js → valRuntime-175e2032.cjs.prod.js} +21 -995
  38. package/dist/{valRuntime-7fd12e16.esm.js → valRuntime-18d4c693.esm.js} +11 -982
  39. package/dist/{valRuntime-d3cc6e0d.cjs.dev.js → valRuntime-c4b2e906.cjs.dev.js} +21 -995
  40. package/dist/valbuild-server.cjs.dev.js +45 -462
  41. package/dist/valbuild-server.cjs.prod.js +45 -462
  42. package/dist/valbuild-server.esm.js +15 -431
  43. package/internal/browser/dist/valbuild-server-internal-browser.cjs.dev.js +2 -2
  44. package/internal/browser/dist/valbuild-server-internal-browser.cjs.prod.js +2 -2
  45. package/internal/browser/dist/valbuild-server-internal-browser.esm.js +2 -2
  46. package/internal/dist/valbuild-server-internal.cjs.dev.js +20 -2
  47. package/internal/dist/valbuild-server-internal.cjs.prod.js +20 -2
  48. package/internal/dist/valbuild-server-internal.esm.js +20 -3
  49. package/package.json +3 -3
@@ -1,23 +1,22 @@
1
1
  'use strict';
2
2
 
3
3
  var core = require('@valbuild/core');
4
- var ValOpsMemory = require('./ValOpsMemory-6e829758.cjs.dev.js');
4
+ var ValOpsMemory = require('./ValOpsMemory-c1453e6a.cjs.dev.js');
5
5
  var path = require('path');
6
6
  var ts = require('typescript');
7
7
  var z = require('zod');
8
8
  var fs = require('fs');
9
9
  var zodValidationError = require('zod-validation-error');
10
10
  var fp = require('@valbuild/core/fp');
11
- var proposalJsonEntries = require('./proposalJsonEntries-d21900d4.cjs.dev.js');
11
+ var jsonValuesModule = require('./jsonValuesModule-ed68a9de.cjs.dev.js');
12
12
  var jsonValuesPatch = require('./jsonValuesPatch-88bc661d.cjs.dev.js');
13
13
  var internal = require('@valbuild/shared/internal');
14
14
  var os = require('os');
15
15
  var crypto$1 = require('crypto');
16
16
  var buffer = require('buffer');
17
- var createPrettierFormatter = require('./createPrettierFormatter-5d830bdf.cjs.dev.js');
18
- var patch = require('@valbuild/core/patch');
19
- require('node:vm');
20
- require('node:module');
17
+ var proposalJsonEntries = require('./proposalJsonEntries-878ad5b6.cjs.dev.js');
18
+ var createPrettierFormatter = require('./createPrettierFormatter-a9109288.cjs.dev.js');
19
+ var merge = require('./merge-a21a9c78.cjs.dev.js');
21
20
 
22
21
  function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
23
22
 
@@ -45,353 +44,6 @@ var fs__default = /*#__PURE__*/_interopDefault(fs);
45
44
  var os__default = /*#__PURE__*/_interopDefault(os);
46
45
  var crypto__default = /*#__PURE__*/_interopDefault(crypto$1);
47
46
 
48
- function isValidIdentifier(text) {
49
- if (text.length === 0) {
50
- return false;
51
- }
52
- if (!ts__default["default"].isIdentifierStart(text.charCodeAt(0), ts__default["default"].ScriptTarget.ES2020)) {
53
- return false;
54
- }
55
- for (let i = 1; i < text.length; ++i) {
56
- if (!ts__default["default"].isIdentifierPart(text.charCodeAt(i), ts__default["default"].ScriptTarget.ES2020)) {
57
- return false;
58
- }
59
- }
60
- return true;
61
- }
62
- function createPropertyAssignment(key, value) {
63
- return ts__default["default"].factory.createPropertyAssignment(isValidIdentifier(key) ? ts__default["default"].factory.createIdentifier(key) : ts__default["default"].factory.createStringLiteral(key), toExpression(value));
64
- }
65
-
66
- /**
67
- * Builds the expression `c.json(() => import("<importPath>"))` used to reference
68
- * a lazily-loaded `*.val.json` entry of a `.jsonValues()` record.
69
- */
70
- function createValJsonReference(importPath) {
71
- // () => import("<importPath>")
72
- // NOTE: an `import` identifier prints as the dynamic-import keyword call,
73
- // which avoids casting the ImportKeyword token (not typed as an Expression).
74
- const importCall = ts__default["default"].factory.createCallExpression(ts__default["default"].factory.createIdentifier("import"), undefined, [ts__default["default"].factory.createStringLiteral(importPath)]);
75
- const thunk = ts__default["default"].factory.createArrowFunction(undefined, undefined, [], undefined, ts__default["default"].factory.createToken(ts__default["default"].SyntaxKind.EqualsGreaterThanToken), importCall);
76
- // c.json(<thunk>)
77
- return ts__default["default"].factory.createCallExpression(ts__default["default"].factory.createPropertyAccessExpression(ts__default["default"].factory.createIdentifier("c"), ts__default["default"].factory.createIdentifier("json")), undefined, [thunk]);
78
- }
79
-
80
- /**
81
- * Inserts a new `.jsonValues()` entry `"<key>": c.json(() => import("<importPath>"))`
82
- * into the record's object literal in a `.val.ts` module. `recordPath` is the
83
- * path from the module source to the record (empty for a root record/router).
84
- * Fails if the entry key already exists.
85
- */
86
- function insertValJsonEntry(document, recordPath, key, importPath) {
87
- return fp.pipe(proposalJsonEntries.analyzeValModule(document), fp.result.flatMap(({
88
- source
89
- }) => getAtPath(source, recordPath)), fp.result.flatMap(recordNode => {
90
- if (!ts__default["default"].isObjectLiteralExpression(recordNode)) {
91
- return fp.result.err(new patch.PatchError("Cannot add jsonValues entry: record source is not an object literal"));
92
- }
93
- return fp.pipe(proposalJsonEntries.findObjectPropertyAssignment(recordNode, key), fp.result.flatMap(assignment => {
94
- if (assignment) {
95
- return fp.result.err(new patch.PatchError(`Cannot add jsonValues entry '${key}': it already exists`));
96
- }
97
- const property = ts__default["default"].factory.createPropertyAssignment(isValidIdentifier(key) ? ts__default["default"].factory.createIdentifier(key) : ts__default["default"].factory.createStringLiteral(key), createValJsonReference(importPath));
98
- return fp.result.ok(insertAt(document, recordNode.properties, recordNode.properties.length, property));
99
- }));
100
- }));
101
- }
102
-
103
- /**
104
- * Removes the `.jsonValues()` entry `"<key>"` from the record's object literal
105
- * in a `.val.ts` module. `recordPath` is the path from the module source to the
106
- * record (empty for a root record/router). Fails if the entry key is missing.
107
- */
108
- function removeValJsonEntry(document, recordPath, key) {
109
- return fp.pipe(proposalJsonEntries.analyzeValModule(document), fp.result.flatMap(({
110
- source
111
- }) => getAtPath(source, recordPath)), fp.result.flatMap(recordNode => {
112
- if (!ts__default["default"].isObjectLiteralExpression(recordNode)) {
113
- return fp.result.err(new patch.PatchError("Cannot remove jsonValues entry: record source is not an object literal"));
114
- }
115
- return fp.pipe(proposalJsonEntries.findObjectPropertyAssignmentToRemove(recordNode, key), fp.result.flatMap(assignment => {
116
- if (!assignment) {
117
- return fp.result.err(new patch.PatchError(`Cannot remove jsonValues entry '${key}': it does not exist`));
118
- }
119
- const [doc] = removeAt(document, recordNode.properties, recordNode.properties.indexOf(assignment));
120
- return fp.result.ok(doc);
121
- }));
122
- }));
123
- }
124
- function toExpression(value) {
125
- if (typeof value === "string") {
126
- // TODO: Use configuration/heuristics to determine use of single quote or double quote
127
- return ts__default["default"].factory.createStringLiteral(value);
128
- } else if (typeof value === "number") {
129
- // TODO: do we want to do something like this for very large numbers?
130
- // if (value > Number.MAX_SAFE_INTEGER) {
131
- // return ts.factory.createBigIntLiteral(`${value}n`);
132
- // }
133
- // if (value < Number.MIN_SAFE_INTEGER) {
134
- // return ts.factory.createPrefixUnaryExpression(
135
- // ts.SyntaxKind.MinusToken,
136
- // ts.factory.createBigIntLiteral(`${value}n`),
137
- // );
138
- // }
139
- if (value < 0) {
140
- return ts__default["default"].factory.createPrefixUnaryExpression(ts__default["default"].SyntaxKind.MinusToken, ts__default["default"].factory.createNumericLiteral(Math.abs(value)));
141
- }
142
- return ts__default["default"].factory.createNumericLiteral(value);
143
- } else if (typeof value === "boolean") {
144
- return value ? ts__default["default"].factory.createTrue() : ts__default["default"].factory.createFalse();
145
- } else if (value === null) {
146
- return ts__default["default"].factory.createNull();
147
- } else if (Array.isArray(value)) {
148
- return ts__default["default"].factory.createArrayLiteralExpression(value.map(toExpression));
149
- } else if (typeof value === "object") {
150
- return ts__default["default"].factory.createObjectLiteralExpression(Object.entries(value)
151
- // `patch_id` is injected server-side onto a media source whose bytes are
152
- // not committed yet. It describes the draft, not the content, and a
153
- // whole-object write built from the client's optimistic view would
154
- // otherwise print it into the user's file.
155
- .filter(([key]) => key !== "patch_id").map(([key, value]) => createPropertyAssignment(key, value)));
156
- } else {
157
- return ts__default["default"].factory.createStringLiteral(value);
158
- }
159
- }
160
-
161
- // TODO: Choose newline based on project settings/heuristics/system default?
162
- const newLine = ts__default["default"].NewLineKind.LineFeed;
163
- // TODO: Handle indentation of printed code
164
- const printer = ts__default["default"].createPrinter({
165
- newLine: newLine
166
- // neverAsciiEscape: true,
167
- });
168
- function replaceNodeValue(document, node, value) {
169
- const replacementText = printer.printNode(ts__default["default"].EmitHint.Unspecified, toExpression(value), document);
170
- const span = ts__default["default"].createTextSpanFromBounds(node.getStart(document, false), node.end);
171
- const newText = `${document.text.substring(0, span.start)}${replacementText}${document.text.substring(ts__default["default"].textSpanEnd(span))}`;
172
- return [document.update(newText, ts__default["default"].createTextChangeRange(span, replacementText.length)), node];
173
- }
174
- function isIndentation(s) {
175
- for (let i = 0; i < s.length; ++i) {
176
- const c = s.charAt(i);
177
- if (c !== " " && c !== "\t") {
178
- return false;
179
- }
180
- }
181
- return true;
182
- }
183
- function newLineStr(kind) {
184
- if (kind === ts__default["default"].NewLineKind.CarriageReturnLineFeed) {
185
- return "\r\n";
186
- } else {
187
- return "\n";
188
- }
189
- }
190
- function getSeparator(document, neighbor) {
191
- const startPos = neighbor.getStart(document, true);
192
- const basis = document.getLineAndCharacterOfPosition(startPos);
193
- const lineStartPos = document.getPositionOfLineAndCharacter(basis.line, 0);
194
- const maybeIndentation = document.getText().substring(lineStartPos, startPos);
195
- if (isIndentation(maybeIndentation)) {
196
- return `,${newLineStr(newLine)}${maybeIndentation}`;
197
- } else {
198
- return `, `;
199
- }
200
- }
201
- function insertAt(document, nodes, index, node) {
202
- let span;
203
- let replacementText;
204
- if (nodes.length === 0) {
205
- // Replace entire range of nodes
206
- replacementText = printer.printNode(ts__default["default"].EmitHint.Unspecified, node, document);
207
- span = ts__default["default"].createTextSpanFromBounds(nodes.pos, nodes.end);
208
- } else if (index === nodes.length) {
209
- // Insert after last node
210
- const neighbor = nodes[nodes.length - 1];
211
- replacementText = `${getSeparator(document, neighbor)}${printer.printNode(ts__default["default"].EmitHint.Unspecified, node, document)}`;
212
- span = ts__default["default"].createTextSpan(neighbor.end, 0);
213
- } else {
214
- // Insert before node
215
- const neighbor = nodes[index];
216
- replacementText = `${printer.printNode(ts__default["default"].EmitHint.Unspecified, node, document)}${getSeparator(document, neighbor)}`;
217
- span = ts__default["default"].createTextSpan(neighbor.getStart(document, true), 0);
218
- }
219
- const newText = `${document.text.substring(0, span.start)}${replacementText}${document.text.substring(ts__default["default"].textSpanEnd(span))}`;
220
- return document.update(newText, ts__default["default"].createTextChangeRange(span, replacementText.length));
221
- }
222
- function removeAt(document, nodes, index) {
223
- const node = nodes[index];
224
- let span;
225
- if (nodes.length === 1) {
226
- span = ts__default["default"].createTextSpanFromBounds(nodes.pos, nodes.end);
227
- } else if (index === nodes.length - 1) {
228
- // Remove until previous node
229
- const neighbor = nodes[index - 1];
230
- span = ts__default["default"].createTextSpanFromBounds(neighbor.end, node.end);
231
- } else {
232
- // Remove before next node
233
- const neighbor = nodes[index + 1];
234
- span = ts__default["default"].createTextSpanFromBounds(node.getStart(document, true), neighbor.getStart(document, true));
235
- }
236
- const newText = `${document.text.substring(0, span.start)}${document.text.substring(ts__default["default"].textSpanEnd(span))}`;
237
- return [document.update(newText, ts__default["default"].createTextChangeRange(span, 0)), node];
238
- }
239
- function parseAndValidateArrayInsertIndex(key, nodes) {
240
- if (key === "-") {
241
- // For insertion, all nodes up until the insertion index must be valid
242
- // initializers
243
- const err = proposalJsonEntries.validateInitializers(nodes);
244
- if (err) {
245
- return fp.result.err(err);
246
- }
247
- return fp.result.ok(nodes.length);
248
- }
249
- return fp.pipe(patch.parseAndValidateArrayIndex(key), fp.result.flatMap(index => {
250
- // For insertion, all nodes up until the insertion index must be valid
251
- // initializers
252
- const err = proposalJsonEntries.validateInitializers(nodes.slice(0, index));
253
- if (err) {
254
- return fp.result.err(err);
255
- }
256
- if (index > nodes.length) {
257
- return fp.result.err(new patch.PatchError("Array index out of bounds"));
258
- } else {
259
- return fp.result.ok(index);
260
- }
261
- }));
262
- }
263
- function parseAndValidateArrayInboundsIndex(key, nodes) {
264
- return fp.pipe(patch.parseAndValidateArrayIndex(key), fp.result.flatMap(index => {
265
- // For in-bounds operations, all nodes up until and including the index
266
- // must be valid initializers
267
- const err = proposalJsonEntries.validateInitializers(nodes.slice(0, index + 1));
268
- if (err) {
269
- return fp.result.err(err);
270
- }
271
- if (index >= nodes.length) {
272
- return fp.result.err(new patch.PatchError("Array index out of bounds"));
273
- } else {
274
- return fp.result.ok(index);
275
- }
276
- }));
277
- }
278
- function replaceInNode(document, node, key, value) {
279
- if (ts__default["default"].isArrayLiteralExpression(node)) {
280
- return fp.pipe(parseAndValidateArrayInboundsIndex(key, node.elements), fp.result.map(index => replaceNodeValue(document, node.elements[index], value)));
281
- } else if (ts__default["default"].isObjectLiteralExpression(node)) {
282
- return fp.pipe(proposalJsonEntries.findObjectPropertyAssignment(node, key), fp.result.flatMap(assignment => {
283
- if (!assignment) {
284
- return fp.result.err(new patch.PatchError("Cannot replace object element which does not exist"));
285
- }
286
- return fp.result.ok(assignment);
287
- }), fp.result.map(assignment => replaceNodeValue(document, assignment.initializer, value)));
288
- } else {
289
- return fp.result.err(proposalJsonEntries.shallowValidateExpression(node) ?? new patch.PatchError("Cannot replace in non-object/array"));
290
- }
291
- }
292
- function replaceAtPath(document, rootNode, path, value) {
293
- if (patch.isNotRoot(path)) {
294
- return fp.pipe(getPointerFromPath(rootNode, path), fp.result.flatMap(([node, key]) => replaceInNode(document, node, key, value)));
295
- } else {
296
- return fp.result.ok(replaceNodeValue(document, rootNode, value));
297
- }
298
- }
299
- function getFromNode(node, key) {
300
- if (ts__default["default"].isArrayLiteralExpression(node)) {
301
- return fp.pipe(parseAndValidateArrayInboundsIndex(key, node.elements), fp.result.map(index => node.elements[index]));
302
- } else if (ts__default["default"].isObjectLiteralExpression(node)) {
303
- return fp.pipe(proposalJsonEntries.findObjectPropertyAssignment(node, key), fp.result.map(assignment => assignment === null || assignment === void 0 ? void 0 : assignment.initializer));
304
- } else {
305
- return fp.result.err(proposalJsonEntries.shallowValidateExpression(node) ?? new patch.PatchError("Cannot access non-object/array"));
306
- }
307
- }
308
- function getPointerFromPath(node, path) {
309
- let targetNode = node;
310
- let key = path[0];
311
- for (let i = 0; i < path.length - 1; ++i, key = path[i]) {
312
- const childNode = getFromNode(targetNode, key);
313
- if (fp.result.isErr(childNode)) {
314
- return childNode;
315
- }
316
- if (childNode.value === undefined) {
317
- return fp.result.err(new patch.PatchError(`Path refers to non-existing object/array: ${path.join("/")}`));
318
- }
319
- targetNode = childNode.value;
320
- }
321
- return fp.result.ok([targetNode, key]);
322
- }
323
- function getAtPath(rootNode, path) {
324
- return fp.pipe(path, fp.result.flatMapReduce((node, key) => fp.pipe(getFromNode(node, key), fp.result.filterOrElse(childNode => childNode !== undefined, () => new patch.PatchError("Path refers to non-existing object/array"))), rootNode));
325
- }
326
- function removeFromNode(document, node, key) {
327
- if (ts__default["default"].isArrayLiteralExpression(node)) {
328
- return fp.pipe(parseAndValidateArrayInboundsIndex(key, node.elements), fp.result.map(index => removeAt(document, node.elements, index)));
329
- } else if (ts__default["default"].isObjectLiteralExpression(node)) {
330
- return fp.pipe(proposalJsonEntries.findObjectPropertyAssignmentToRemove(node, key), fp.result.flatMap(assignment => {
331
- if (!assignment) {
332
- return fp.result.err(new patch.PatchError("Cannot remove object element which does not exist"));
333
- }
334
- return fp.result.ok(assignment);
335
- }), fp.result.map(assignment => [removeAt(document, node.properties, node.properties.indexOf(assignment))[0], assignment.initializer]));
336
- } else {
337
- return fp.result.err(proposalJsonEntries.shallowValidateExpression(node) ?? new patch.PatchError("Cannot remove from non-object/array"));
338
- }
339
- }
340
- function removeAtPath(document, rootNode, path) {
341
- return fp.pipe(getPointerFromPath(rootNode, path), fp.result.flatMap(([node, key]) => removeFromNode(document, node, key)));
342
- }
343
- function addToNode(document, node, key, value) {
344
- if (ts__default["default"].isArrayLiteralExpression(node)) {
345
- return fp.pipe(parseAndValidateArrayInsertIndex(key, node.elements), fp.result.map(index => [insertAt(document, node.elements, index, toExpression(value))]));
346
- } else if (ts__default["default"].isObjectLiteralExpression(node)) {
347
- return fp.pipe(proposalJsonEntries.findObjectPropertyAssignment(node, key), fp.result.map(assignment => {
348
- if (!assignment) {
349
- return [insertAt(document, node.properties, node.properties.length, createPropertyAssignment(key, value))];
350
- } else {
351
- return replaceNodeValue(document, assignment.initializer, value);
352
- }
353
- }));
354
- } else {
355
- return fp.result.err(proposalJsonEntries.shallowValidateExpression(node) ?? new patch.PatchError("Cannot add to non-object/array"));
356
- }
357
- }
358
- function addAtPath(document, rootNode, path, value) {
359
- if (patch.isNotRoot(path)) {
360
- return fp.pipe(getPointerFromPath(rootNode, path), fp.result.flatMap(([node, key]) => addToNode(document, node, key, value)));
361
- } else {
362
- return fp.result.ok(replaceNodeValue(document, rootNode, value));
363
- }
364
- }
365
- function pickDocument([document]) {
366
- return document;
367
- }
368
- class TSOps {
369
- constructor(findRoot) {
370
- this.findRoot = findRoot;
371
- }
372
- get(document, path) {
373
- return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => getAtPath(rootNode, path)), fp.result.flatMap(proposalJsonEntries.evaluateExpression));
374
- }
375
- add(document, path, value) {
376
- return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => addAtPath(document, rootNode, path, value)), fp.result.map(pickDocument));
377
- }
378
- remove(document, path) {
379
- return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => removeAtPath(document, rootNode, path)), fp.result.map(pickDocument));
380
- }
381
- replace(document, path, value) {
382
- return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => replaceAtPath(document, rootNode, path, value)), fp.result.map(pickDocument));
383
- }
384
- move(document, from, path) {
385
- return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => removeAtPath(document, rootNode, from)), fp.result.flatMap(([document, removedNode]) => fp.pipe(proposalJsonEntries.evaluateExpression(removedNode), fp.result.map(removedValue => [document, removedValue]))), fp.result.flatMap(([document, removedValue]) => fp.pipe(document, this.findRoot, fp.result.flatMap(root => addAtPath(document, root, path, removedValue)))), fp.result.map(pickDocument));
386
- }
387
- copy(document, from, path) {
388
- return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => fp.pipe(getAtPath(rootNode, from), fp.result.flatMap(proposalJsonEntries.evaluateExpression), fp.result.flatMap(value => addAtPath(document, rootNode, path, value)))), fp.result.map(pickDocument));
389
- }
390
- test(document, path, value) {
391
- return fp.pipe(document, this.findRoot, fp.result.flatMap(rootNode => getAtPath(rootNode, path)), fp.result.flatMap(proposalJsonEntries.evaluateExpression), fp.result.map(documentValue => patch.deepEqual(value, documentValue)));
392
- }
393
- }
394
-
395
47
  /**
396
48
  * The `*.val.json` files backing a `.jsonValues()` module's entries, as paths
397
49
  * relative to the project root.
@@ -403,7 +55,7 @@ class TSOps {
403
55
  function findJsonEntryFilePathsInSource(moduleFilePath, valTsSourceFile) {
404
56
  let analysis;
405
57
  try {
406
- analysis = proposalJsonEntries.analyzeValModule(valTsSourceFile);
58
+ analysis = jsonValuesModule.analyzeValModule(valTsSourceFile);
407
59
  } catch {
408
60
  return [];
409
61
  }
@@ -411,7 +63,7 @@ function findJsonEntryFilePathsInSource(moduleFilePath, valTsSourceFile) {
411
63
  return [];
412
64
  }
413
65
  const paths = [];
414
- proposalJsonEntries.analyzeJsonValuesEntries(analysis.value.source).forEach(entry => {
66
+ jsonValuesModule.analyzeJsonValuesEntries(analysis.value.source).forEach(entry => {
415
67
  paths.push(jsonValuesPatch.resolveExistingJsonPath(moduleFilePath, entry.importPath));
416
68
  });
417
69
  return paths;
@@ -1889,7 +1541,7 @@ function createFsSketchpadStore(rootDir, now = () => new Date()) {
1889
1541
  * as a bundler does.
1890
1542
  */
1891
1543
  function loadTypeScriptKit() {
1892
- return Promise.resolve().then(function () { return require('./publishKit-de4baed6.cjs.dev.js'); });
1544
+ return Promise.resolve().then(function () { return require('./publishKit-ffcaf2af.cjs.dev.js'); });
1893
1545
  }
1894
1546
 
1895
1547
  /** Serializes a schema, or gives up quietly — serialization errors are reported elsewhere. */
@@ -3308,629 +2960,6 @@ class FSOpsHost {
3308
2960
  }
3309
2961
  }
3310
2962
 
3311
- /** What a schema reports about this content: see `schemaErrorsOf`. */
3312
- const validateWith = (schema, moduleFilePath, source) => internal.schemaErrorsOf(schema, moduleFilePath, source);
3313
-
3314
- /**
3315
- * A module's errors for this content: its own `validate` where the schema was
3316
- * evaluated, custom rules and all; otherwise what its serialized schema says,
3317
- * which is every rule but a custom `.validate(...)` (a closure does not
3318
- * serialize).
3319
- */
3320
- function validateModule(moduleFilePath, module, source) {
3321
- if (module.validate) return module.validate(source);
3322
- return validateWith(core.deserializeSchema(module.schema), moduleFilePath, source);
3323
- }
3324
-
3325
- /** The errors of a module's own Source: as evaluated where they were, else found here. */
3326
- function errorsOfSource(moduleFilePath, module) {
3327
- return module.errors ?? validateModule(moduleFilePath, module, module.source);
3328
- }
3329
-
3330
- /**
3331
- * A `.jsonValues()` record's entry files, by key, read out of its `.val.ts`
3332
- * (the loaded marker does not carry the path). `null` when it has none.
3333
- */
3334
- function entryFilesOf(moduleFilePath, text) {
3335
- const analysis = valModuleOf(moduleFilePath, text);
3336
- if (analysis === null) return null;
3337
- const entries = proposalJsonEntries.analyzeJsonValuesEntries(analysis.source);
3338
- if (entries.size === 0) return null;
3339
- const dir = path__default["default"].posix.dirname(moduleFilePath.slice(1));
3340
- return Object.fromEntries([...entries].map(([key, {
3341
- importPath
3342
- }]) => [key, path__default["default"].posix.join(dir, importPath)]));
3343
- }
3344
-
3345
- // --- code and content ------------------------------------------------------------
3346
-
3347
- /**
3348
- * A file's code: for a `.val.ts`, everything but `c.define`'s content
3349
- * argument, which Val reads at request time (step 2) and so is no part of a
3350
- * build; a `.val.json` entry is no code at all. Every other file is code
3351
- * whole.
3352
- */
3353
- function codeOf(file, text) {
3354
- // A `.jsonValues()` entry is content, read at request time like the rest.
3355
- if (file.endsWith(".val.json")) return "";
3356
- if (!file.endsWith(".val.ts")) return text;
3357
- const analysis = valModuleOf(file, text);
3358
- if (analysis === null) return text;
3359
- const {
3360
- source
3361
- } = analysis;
3362
- return text.slice(0, source.getStart()) + "/* content */" + text.slice(source.end);
3363
- }
3364
-
3365
- /**
3366
- * A `.val.ts`'s `c.define(...)`, or `null` when it has none: a file of schemas
3367
- * that pages share (`export const heroSchema = s.object(...)`) is named like a
3368
- * module and is code. `analyzeValModule` throws for one; this does not.
3369
- */
3370
- function valModuleOf(file, text) {
3371
- const sourceFile = ts__default["default"].createSourceFile(file, text, ts__default["default"].ScriptTarget.ES2015, true);
3372
- if (!sourceFile.statements.some(node => ts__default["default"].isExportAssignment(node))) {
3373
- return null;
3374
- }
3375
- const analysis = proposalJsonEntries.analyzeValModule(sourceFile);
3376
- return fp.result.isErr(analysis) ? null : analysis.value;
3377
- }
3378
-
3379
- /**
3380
- * The three-way merge of a module's content: where both sides started
3381
- * (`base`), and each side's version. Pure JSON -- the schema decides nothing
3382
- * here, and is checked afterwards (the schema check in `merge.ts`).
3383
- *
3384
- * The rules (valbuild/home `docs/hosted-publishing.md` step 8.2):
3385
- *
3386
- * - Changed on one side: that side's.
3387
- * - Changed on both: a conflict -- even to the same value, which is an easy
3388
- * conflict to resolve but still one somebody decides.
3389
- * - An object (a page, a record) merges key by key, so two keys changed on
3390
- * two sides combine.
3391
- * - A list merges item by item only when neither side changed its shape: no
3392
- * item added, removed or moved. Otherwise positions mean different items on
3393
- * the two sides, and the whole list is the conflict.
3394
- */
3395
-
3396
- function isObject(value) {
3397
- return typeof value === "object" && value !== null && !Array.isArray(value);
3398
- }
3399
- function same(a, b) {
3400
- if (a === undefined || b === undefined) return a === b;
3401
- return patch.deepEqual(a, b);
3402
- }
3403
-
3404
- /**
3405
- * Did this side add, remove or move an item? Lengths differ, or an item now
3406
- * sits where it was not, while it is still what used to be somewhere else.
3407
- */
3408
- function reshaped(base, side) {
3409
- if (base.length !== side.length) return true;
3410
- return side.some((item, at) => !same(item, base[at]) && base.some((was, from) => from !== at && same(item, was)));
3411
- }
3412
-
3413
- /**
3414
- * Where a value is one value, though it is an object: a media value (its path
3415
- * and what describes that file) or rich text. The schema says; see `merge.ts`.
3416
- */
3417
-
3418
- function mergeValues(base, site, proposal, atomic = () => false, path = []) {
3419
- if (same(site, base)) return {
3420
- value: proposal,
3421
- conflicts: []
3422
- };
3423
- if (same(proposal, base)) return {
3424
- value: site,
3425
- conflicts: []
3426
- };
3427
- if (atomic(path)) {
3428
- return {
3429
- value: site,
3430
- conflicts: [{
3431
- path,
3432
- base,
3433
- site,
3434
- proposal
3435
- }]
3436
- };
3437
- }
3438
- if (isObject(base) && isObject(site) && isObject(proposal)) {
3439
- const keys = [...new Set([...Object.keys(site), ...Object.keys(proposal), ...Object.keys(base)])];
3440
- const value = {};
3441
- const conflicts = [];
3442
- for (const key of keys) {
3443
- const merged = mergeValues(base[key], site[key], proposal[key], atomic, [...path, key]);
3444
- if (merged.value !== undefined) value[key] = merged.value;
3445
- conflicts.push(...merged.conflicts);
3446
- }
3447
- return {
3448
- value,
3449
- conflicts
3450
- };
3451
- }
3452
- if (Array.isArray(base) && Array.isArray(site) && Array.isArray(proposal) && !reshaped(base, site) && !reshaped(base, proposal)) {
3453
- const value = [];
3454
- const conflicts = [];
3455
- base.forEach((item, at) => {
3456
- const merged = mergeValues(item, site[at], proposal[at], atomic, [...path, String(at)]);
3457
- // Neither side removed an item, so every position holds one.
3458
- value.push(merged.value ?? null);
3459
- conflicts.push(...merged.conflicts);
3460
- });
3461
- return {
3462
- value,
3463
- conflicts
3464
- };
3465
- }
3466
- return {
3467
- value: site,
3468
- conflicts: [{
3469
- path,
3470
- base,
3471
- site,
3472
- proposal
3473
- }]
3474
- };
3475
- }
3476
-
3477
- /** `doc` with `value` at `path`; `undefined` removes it. `doc` is not changed. */
3478
- function setAt(doc, path, value) {
3479
- if (path.length === 0) return value;
3480
- const [head, ...rest] = path;
3481
- if (Array.isArray(doc)) {
3482
- const copy = [...doc];
3483
- const at = Number(head);
3484
- const next = setAt(copy[at], rest, value);
3485
- if (next === undefined) copy.splice(at, 1);else copy[at] = next;
3486
- return copy;
3487
- }
3488
- const copy = isObject(doc) ? {
3489
- ...doc
3490
- } : {};
3491
- const next = setAt(copy[head], rest, value);
3492
- if (next === undefined) delete copy[head];else copy[head] = next;
3493
- return copy;
3494
- }
3495
- function valueAt(doc, path) {
3496
- let current = doc;
3497
- for (const key of path) {
3498
- if (Array.isArray(current)) current = current[Number(key)];else if (isObject(current)) current = current[key];else return undefined;
3499
- }
3500
- return current;
3501
- }
3502
-
3503
- /**
3504
- * The Val patch that turns `from` into `to`, as small as it can be: what
3505
- * writes a merge into a `.val.ts` without rewriting what did not change.
3506
- */
3507
- function diffOps(from, to, path = []) {
3508
- if (same(from, to)) return [];
3509
- if (isObject(from) && isObject(to)) {
3510
- const ops = [];
3511
- for (const key of Object.keys(from)) {
3512
- if (!(key in to)) ops.push({
3513
- op: "remove",
3514
- path: below(path, key)
3515
- });
3516
- }
3517
- for (const [key, value] of Object.entries(to)) {
3518
- ops.push(...(key in from ? diffOps(from[key], value, [...path, key]) : [add([...path, key], value)]));
3519
- }
3520
- return ops;
3521
- }
3522
- if (Array.isArray(from) && Array.isArray(to) && from.length === to.length) {
3523
- return from.flatMap((item, at) => diffOps(item, to[at], [...path, String(at)]));
3524
- }
3525
- return [{
3526
- op: "replace",
3527
- path,
3528
- value: to ?? null
3529
- }];
3530
- }
3531
- function add(path, value) {
3532
- return {
3533
- op: "add",
3534
- path,
3535
- value
3536
- };
3537
- }
3538
- function below(path, key) {
3539
- return path.length === 0 ? [key] : [path[0], ...path.slice(1), key];
3540
- }
3541
-
3542
- /**
3543
- * Publishing a proposal as a pull request is merged: valbuild/home
3544
- * `docs/hosted-publishing.md`, step 8.2.
3545
- *
3546
- * Val's half: the two answers that need a schema. Content gets them as files
3547
- * and change ids and carries them out, never looking at a field, a list or a
3548
- * patch set.
3549
- *
3550
- * - {@link mergeFromSite} -- Update from the site: the merge commit `M`.
3551
- * - {@link changesToMove} -- which of the site's pending changes leave the
3552
- * site when a proposal is merged.
3553
- *
3554
- * `mergeScenarios.test.ts` is their specification.
3555
- */
3556
-
3557
- /** A field both sides changed since the proposal started. */
3558
-
3559
- /**
3560
- * Code both sides changed: a component, `val.modules.ts`, or the schema of a
3561
- * `.val.ts` (its code -- everything but `c.define`'s content argument, whose
3562
- * fields merge on their own).
3563
- */
3564
-
3565
- /**
3566
- * The schema check: content that merged cleanly and is not valid under the
3567
- * schema the merge ends with -- an entry the site added, say, under a field
3568
- * whose type the proposal changed.
3569
- */
3570
-
3571
- /** How a conflict is resolved: keep one side, or write it -- as AI or a developer does. */
3572
-
3573
- /**
3574
- * Update from the site: a three-way merge of where the proposal started
3575
- * (`base`), the site's head and the proposal's last save, written whole.
3576
- * Every conflict needs a resolution, or nothing is merged.
3577
- *
3578
- * File by file. A file that is not a `.val.ts` is code, and merges as a
3579
- * file: changed on one side, that side's; on both, a conflict. A `.val.ts`
3580
- * is code (everything but `c.define`'s content argument) and content, and the
3581
- * two merge apart: the code as a file, the content field by field
3582
- * (`mergeValues`). So a schema the proposal changed and a field the site
3583
- * published in the same file do not conflict. A code conflict in a `.val.ts`
3584
- * is resolved by keeping a side's code -- the content still merges -- or by
3585
- * writing the whole file.
3586
- *
3587
- * Not here: the schema check ({@link schemaCheck}). It needs the merged
3588
- * files' schemas, so whoever can evaluate them -- Val's loader, the builder
3589
- * tab -- runs it on `files` before the merge is committed.
3590
- */
3591
- function mergeFromSite(input) {
3592
- const {
3593
- base,
3594
- site,
3595
- proposal,
3596
- resolutions
3597
- } = input;
3598
- const files = {};
3599
- const modules = {};
3600
- const conflicts = [];
3601
- const paths = [...new Set([...Object.keys(base.files), ...Object.keys(site.files), ...Object.keys(proposal.files)])].sort();
3602
- // A `.jsonValues()` entry is written with its module, never on its own.
3603
- const entryFiles = new Set([base, site, proposal].flatMap(side => Object.values(side.modules).flatMap(module => Object.values(module.entries ?? {}))));
3604
- for (const file of paths) {
3605
- var _moduleOf3, _moduleOf4, _moduleOf5, _moduleOf6;
3606
- if (entryFiles.has(file)) continue;
3607
- const b = base.files[file] ?? null;
3608
- const s = site.files[file] ?? null;
3609
- const p = proposal.files[file] ?? null;
3610
- const resolution = fileResolution(resolutions, file);
3611
- const codeConflict = () => ({
3612
- kind: "code",
3613
- file,
3614
- base: b,
3615
- site: s,
3616
- proposal: p
3617
- });
3618
-
3619
- // A file named like a module that no side defines as one -- schemas the
3620
- // pages share -- is code.
3621
- const moduleFilePath = `/${file}`;
3622
- const isModule = [base, site, proposal].some(side => side.modules[moduleFilePath] !== undefined);
3623
- if (!file.endsWith(".val.ts") || !isModule) {
3624
- if (s === b) files[file] = p;else if (p === b) files[file] = s;else if (resolution) files[file] = resolvedText(resolution, s, p);else {
3625
- conflicts.push(codeConflict());
3626
- files[file] = s;
3627
- }
3628
- continue;
3629
- }
3630
-
3631
- // A .val.ts: whose code, then the content under it.
3632
- const code = text => text === null ? null : codeOf(file, text);
3633
- let side;
3634
- if (code(s) === code(b)) side = "proposal";else if (code(p) === code(b)) side = "site";else if (resolution && "text" in resolution) {
3635
- files[file] = resolution.text;
3636
- continue;
3637
- } else if (resolution) side = resolution.keep;else {
3638
- conflicts.push(codeConflict());
3639
- files[file] = s;
3640
- continue;
3641
- }
3642
- const moduleOf = project => project.modules[moduleFilePath];
3643
- const sourceOf = project => {
3644
- var _moduleOf;
3645
- return (_moduleOf = moduleOf(project)) === null || _moduleOf === void 0 ? void 0 : _moduleOf.source;
3646
- };
3647
- const chosen = side === "site" ? site : proposal;
3648
- const text = side === "site" ? s : p;
3649
- if (text === null) {
3650
- // That side deleted the file. Content the other side changed would go
3651
- // with it: that is for a person to decide -- unless they have.
3652
- const other = side === "site" ? p : s;
3653
- if (!resolution && other !== b) {
3654
- conflicts.push(codeConflict());
3655
- }
3656
- files[file] = null;
3657
- for (const project of [base, site, proposal]) {
3658
- for (const entry of Object.values(((_moduleOf2 = moduleOf(project)) === null || _moduleOf2 === void 0 ? void 0 : _moduleOf2.entries) ?? {})) {
3659
- var _moduleOf2;
3660
- files[entry] = null;
3661
- }
3662
- }
3663
- continue;
3664
- }
3665
- // What the chosen text holds, which the merge is written over.
3666
- const from = ((_moduleOf3 = moduleOf(chosen)) === null || _moduleOf3 === void 0 ? void 0 : _moduleOf3.written) ?? ((_moduleOf4 = moduleOf(chosen)) === null || _moduleOf4 === void 0 ? void 0 : _moduleOf4.source);
3667
- const merged = mergeValues(sourceOf(base), sourceOf(site), sourceOf(proposal), atomicFor((_moduleOf5 = moduleOf(chosen)) === null || _moduleOf5 === void 0 ? void 0 : _moduleOf5.schema));
3668
- const resolved = resolveContent(moduleFilePath, merged, resolutions);
3669
- conflicts.push(...resolved.unresolved);
3670
- const content = resolved.content;
3671
- modules[moduleFilePath] = content;
3672
- const entries = (_moduleOf6 = moduleOf(chosen)) === null || _moduleOf6 === void 0 ? void 0 : _moduleOf6.entries;
3673
- if (entries) {
3674
- var _moduleOf7, _moduleOf8;
3675
- Object.assign(files, writeEntries(file, text, chosen.files, entries, from, content, [(_moduleOf7 = moduleOf(site)) === null || _moduleOf7 === void 0 ? void 0 : _moduleOf7.entries, (_moduleOf8 = moduleOf(proposal)) === null || _moduleOf8 === void 0 ? void 0 : _moduleOf8.entries]));
3676
- } else {
3677
- files[file] = writeContent(file, text, from, content);
3678
- }
3679
- }
3680
- if (conflicts.length > 0) return {
3681
- status: "conflicts",
3682
- conflicts
3683
- };
3684
- return {
3685
- status: "merged",
3686
- files,
3687
- modules,
3688
- code: Object.keys(files).filter(file => {
3689
- const text = files[file];
3690
- const before = site.files[file] ?? null;
3691
- if (text === null || before === null) return text !== before;
3692
- return codeOf(file, text) !== codeOf(file, before);
3693
- })
3694
- };
3695
- }
3696
-
3697
- /** A change pending on the site, in chain order. */
3698
-
3699
- /**
3700
- * The site's pending changes that conflict with going from `site` to
3701
- * `merged`, as whole patch sets: each inner list moves together, into a
3702
- * proposal of its own. Everything else stays pending.
3703
- *
3704
- * Patch sets are the Studio's own (`PatchSets`), from the schema the changes
3705
- * were written against; sets that share a change are one, because a change
3706
- * cannot be split. A set moves when, taken as the site's side of a three-way
3707
- * merge with the merged commit as the other, it conflicts (`mergeValues`, so
3708
- * the same value on both sides moves too); or when it no longer applies to
3709
- * the merged commit, or leaves it invalid under the merged schema.
3710
- */
3711
- function changesToMove(input) {
3712
- const {
3713
- site,
3714
- merged,
3715
- pending
3716
- } = input;
3717
- const sets = new internal.PatchSets();
3718
- for (const change of pending) {
3719
- var _site$modules$change$;
3720
- sets.insert(change.moduleFilePath, (_site$modules$change$ = site.modules[change.moduleFilePath]) === null || _site$modules$change$ === void 0 ? void 0 : _site$modules$change$.schema, change.patch, change.patchId, "", null);
3721
- }
3722
- const groups = internal.joinSharedChanges(sets.serialize().map(set => set.patches.map(p => p.patchId)));
3723
- const moves = [];
3724
- for (const group of groups) {
3725
- const changes = pending.filter(change => group.has(change.patchId));
3726
- if (conflictsWithMerge(changes, site, merged)) {
3727
- moves.push(changes.map(change => change.patchId));
3728
- }
3729
- }
3730
- // In chain order, so the moved proposals are opened in the order the
3731
- // changes were written.
3732
- const order = ids => pending.findIndex(change => change.patchId === ids[0]);
3733
- return moves.sort((a, b) => order(a) - order(b));
3734
- }
3735
-
3736
- // --- the pieces --------------------------------------------------------------
3737
-
3738
- /**
3739
- * A module's merged content with the resolutions written in: each field
3740
- * conflict that has one, and any value written for the schema check (or
3741
- * anywhere else) as given. What is left is what still needs a person.
3742
- */
3743
- function resolveContent(moduleFilePath, merged, resolutions) {
3744
- let content = merged.value;
3745
- const unresolved = [];
3746
- for (const conflict of merged.conflicts) {
3747
- const resolved = fieldResolution(resolutions, moduleFilePath, conflict);
3748
- if (resolved === null) {
3749
- unresolved.push({
3750
- kind: "field",
3751
- moduleFilePath,
3752
- ...conflict
3753
- });
3754
- } else {
3755
- content = setAt(content, conflict.path, resolved.value);
3756
- }
3757
- }
3758
- for (const resolution of resolutions) {
3759
- if ("moduleFilePath" in resolution && resolution.moduleFilePath === moduleFilePath && "value" in resolution && !merged.conflicts.some(c => samePath(c.path, resolution.path))) {
3760
- content = setAt(content, resolution.path, resolution.value);
3761
- }
3762
- }
3763
- return {
3764
- content,
3765
- unresolved
3766
- };
3767
- }
3768
- function conflictsWithMerge(changes, site, merged) {
3769
- const modules = [...new Set(changes.map(change => change.moduleFilePath))];
3770
- for (const moduleFilePath of modules) {
3771
- var _site$modules$moduleF;
3772
- const ops = changes.filter(change => change.moduleFilePath === moduleFilePath).flatMap(change => change.patch).filter(op => op.op !== "file");
3773
- const before = (_site$modules$moduleF = site.modules[moduleFilePath]) === null || _site$modules$moduleF === void 0 ? void 0 : _site$modules$moduleF.source;
3774
- const after = merged.modules[moduleFilePath];
3775
- if (before === undefined || after === undefined) return true;
3776
- const written = apply(before, ops);
3777
- if (written === undefined) return true;
3778
- const mergedSource = after.source;
3779
- const atomic = atomicFor(after.schema);
3780
- if (mergeValues(before, written, mergedSource, atomic).conflicts.length) {
3781
- return true;
3782
- }
3783
- // Over the merged commit: it applies, and is as valid as it was.
3784
- const over = apply(mergedSource, ops);
3785
- if (over === undefined) return true;
3786
- const known = new Set(errorPaths(moduleFilePath, after, mergedSource));
3787
- if (errorPaths(moduleFilePath, after, over).some(path => !known.has(path))) {
3788
- return true;
3789
- }
3790
- }
3791
- return false;
3792
- }
3793
- function apply(source, ops) {
3794
- if (source === undefined) return undefined;
3795
- const applied = patch.applyPatch(patch.deepClone(source), new patch.JSONOps(), ops);
3796
- return fp.result.isOk(applied) ? applied.value : undefined;
3797
- }
3798
- function errorPaths(moduleFilePath, module, source) {
3799
- return validateModule(moduleFilePath, module, source).map(error => error.path.join("/"));
3800
- }
3801
-
3802
- /**
3803
- * The schema check of a merge: content in `merged` -- the project
3804
- * {@link mergeFromSite} wrote, with its schemas evaluated -- that is invalid
3805
- * under the schema it ends with, leaving out what was already invalid on a
3806
- * side. A conflict, each; a resolution with a value for one is written into
3807
- * the content by the merge, and so is checked here.
3808
- */
3809
- function schemaCheck(merged, sides) {
3810
- const conflicts = [];
3811
- for (const [path, module] of Object.entries(merged.modules)) {
3812
- const moduleFilePath = path;
3813
- const known = new Set(sides.flatMap(side => {
3814
- const there = side.modules[moduleFilePath];
3815
- return there ? errorsOfSource(moduleFilePath, there).map(e => e.path.join("/")) : [];
3816
- }));
3817
- for (const error of errorsOfSource(moduleFilePath, module)) {
3818
- if (known.has(error.path.join("/"))) continue;
3819
- conflicts.push({
3820
- kind: "invalid",
3821
- moduleFilePath,
3822
- path: error.path,
3823
- value: valueAt(module.source, error.path),
3824
- message: error.message
3825
- });
3826
- }
3827
- }
3828
- return conflicts;
3829
- }
3830
-
3831
- /**
3832
- * The values that merge whole, though they are objects: media (an image's
3833
- * alt text describes that image, not another) and rich text.
3834
- */
3835
- const ATOMIC = new Set(["image", "file", "video", "font", "richtext"]);
3836
-
3837
- /** See {@link ATOMIC}: where this schema holds a value that merges whole. */
3838
- function atomicFor(schema) {
3839
- if (!schema) return () => false;
3840
- return path => {
3841
- const types = internal.schemaTypesOfPath(schema, path);
3842
- return [...types].some(type => ATOMIC.has(type));
3843
- };
3844
- }
3845
- const tsOps = new TSOps(document => fp.pipe(proposalJsonEntries.analyzeValModule(document), fp.result.map(({
3846
- source
3847
- }) => source)));
3848
-
3849
- /**
3850
- * `content` written into the `.val.ts` `text`, whose content is `from`: as
3851
- * the smallest patch, through the same AST operations a save uses, so what
3852
- * did not change is left exactly as it was.
3853
- */
3854
- function writeContent(file, text, from, content) {
3855
- const ops = diffOps(from, content);
3856
- if (ops.length === 0) return text;
3857
- const sourceFile = ts__default["default"].createSourceFile(file, text, ts__default["default"].ScriptTarget.ES2015, true);
3858
- return printed(unwrap(file, patch.applyPatch(sourceFile, tsOps, ops)));
3859
- }
3860
-
3861
- /**
3862
- * A `.jsonValues()` module, written as its files: the `.val.ts` names the
3863
- * entries -- one added gets a `c.json(...)` line, as a save writes it, one
3864
- * removed loses its line -- and each entry is its own `.val.json`. An entry
3865
- * whose content did not change keeps its file's text exactly.
3866
- */
3867
- function writeEntries(file, text, chosenFiles, entries, from, content, others) {
3868
- const written = {};
3869
- const before = isRecord(from) ? from : {};
3870
- const after = isRecord(content) ? content : {};
3871
- const moduleDir = path__default["default"].posix.dirname(file);
3872
- let sourceFile = ts__default["default"].createSourceFile(file, text, ts__default["default"].ScriptTarget.ES2015, true);
3873
- for (const key of Object.keys(before)) {
3874
- if (key in after) continue;
3875
- sourceFile = unwrap(file, removeValJsonEntry(sourceFile, [], key));
3876
- written[entries[key]] = null;
3877
- }
3878
- for (const [key, value] of Object.entries(after)) {
3879
- const entryFile = entries[key] ?? others.map(other => other === null || other === void 0 ? void 0 : other[key]).find(f => f !== undefined) ?? path__default["default"].posix.join(moduleDir, path__default["default"].posix.basename(file, ".val.ts"), `${key}.val.json`);
3880
- if (!(key in before)) {
3881
- const importPath = `./${path__default["default"].posix.relative(moduleDir, entryFile)}`;
3882
- sourceFile = unwrap(file, insertValJsonEntry(sourceFile, [], key, importPath));
3883
- }
3884
- const kept = chosenFiles[entryFile];
3885
- written[entryFile] = key in before && diffOps(before[key], value).length === 0 && kept ? kept : JSON.stringify(value, null, 2);
3886
- }
3887
- written[file] = printed(sourceFile);
3888
- return written;
3889
- }
3890
- function isRecord(value) {
3891
- return typeof value === "object" && value !== null && !Array.isArray(value);
3892
- }
3893
- function unwrap(file, written) {
3894
- if (fp.result.isErr(written)) {
3895
- throw new Error(`could not write the merge into ${file}: ${String(written.error)}`);
3896
- }
3897
- return written.value;
3898
- }
3899
-
3900
- /** As `prepare` prints: TypeScript escapes non-ASCII as \\u sequences. */
3901
- function printed(sourceFile) {
3902
- return unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u"));
3903
- }
3904
- function fileResolution(resolutions, file) {
3905
- for (const resolution of resolutions) {
3906
- if ("file" in resolution && resolution.file === file) return resolution;
3907
- }
3908
- return null;
3909
- }
3910
- function resolvedText(resolution, site, proposal) {
3911
- if ("text" in resolution) return resolution.text;
3912
- return resolution.keep === "site" ? site : proposal;
3913
- }
3914
-
3915
- /** A field conflict's resolution, as the value it leaves; `null` when it has none. */
3916
- function fieldResolution(resolutions, moduleFilePath, conflict) {
3917
- for (const resolution of resolutions) {
3918
- if (!("moduleFilePath" in resolution) || resolution.moduleFilePath !== moduleFilePath || !samePath(resolution.path, conflict.path)) {
3919
- continue;
3920
- }
3921
- if ("value" in resolution) return {
3922
- value: resolution.value
3923
- };
3924
- return {
3925
- value: resolution.keep === "site" ? conflict.site : conflict.proposal
3926
- };
3927
- }
3928
- return null;
3929
- }
3930
- function samePath(a, b) {
3931
- return a.length === b.length && a.every((key, at) => key === b[at]);
3932
- }
3933
-
3934
2963
  /**
3935
2964
  * Update from the site when only content changed (valbuild/home
3936
2965
  * `docs/hosted-publishing.md` step 8.2, slice 1a): the proposal staged no code
@@ -3976,12 +3005,12 @@ function mergeContent(input) {
3976
3005
  }
3977
3006
  const serialized = schema["executeSerialize"]();
3978
3007
  const orUndefined = value => value ?? undefined;
3979
- const merged = mergeValues(orUndefined(base), orUndefined(site), orUndefined(proposal), atomicFor(serialized));
3980
- if (serialized.type === "record" && serialized.jsonValues && (merged.conflicts.length > 0 || diffOps(orUndefined(proposal), merged.value).length > 0)) {
3008
+ const merged = merge.mergeValues(orUndefined(base), orUndefined(site), orUndefined(proposal), merge.atomicFor(serialized));
3009
+ if (serialized.type === "record" && serialized.jsonValues && (merged.conflicts.length > 0 || merge.diffOps(orUndefined(proposal), merged.value).length > 0)) {
3981
3010
  needsFullMerge.push(moduleFilePath);
3982
3011
  continue;
3983
3012
  }
3984
- const resolved = resolveContent(moduleFilePath, merged, input.resolutions);
3013
+ const resolved = merge.resolveContent(moduleFilePath, merged, input.resolutions);
3985
3014
  conflicts.push(...resolved.unresolved);
3986
3015
  if (resolved.unresolved.length > 0) continue;
3987
3016
 
@@ -3989,20 +3018,20 @@ function mergeContent(input) {
3989
3018
  // invalid on a side is not the merge's doing. A value written as a
3990
3019
  // resolution is already in `content`, and checked like the rest -- as
3991
3020
  // `schemaCheck` does for the full merge.
3992
- const known = new Set([site, proposal].flatMap(side => validateWith(schema, moduleFilePath, orUndefined(side)).map(e => e.path.join("/"))));
3021
+ const known = new Set([site, proposal].flatMap(side => merge.validateWith(schema, moduleFilePath, orUndefined(side)).map(e => e.path.join("/"))));
3993
3022
  const content = resolved.content;
3994
- for (const error of validateWith(schema, moduleFilePath, content)) {
3023
+ for (const error of merge.validateWith(schema, moduleFilePath, content)) {
3995
3024
  if (known.has(error.path.join("/"))) continue;
3996
3025
  conflicts.push({
3997
3026
  kind: "invalid",
3998
3027
  moduleFilePath,
3999
3028
  path: error.path,
4000
- value: valueAt(content, error.path),
3029
+ value: merge.valueAt(content, error.path),
4001
3030
  message: error.message
4002
3031
  });
4003
3032
  }
4004
3033
  const file = moduleFilePath.slice(1);
4005
- files[file] = writeContent(file, text, orUndefined(proposal), content);
3034
+ files[file] = merge.writeContent(file, text, orUndefined(proposal), content);
4006
3035
  modules[moduleFilePath] = {
4007
3036
  source: content ?? null,
4008
3037
  schema: serialized
@@ -4062,7 +3091,7 @@ function updateWithCode(input) {
4062
3091
  const base = projectOf("base");
4063
3092
  const site = projectOf("site");
4064
3093
  const proposal = projectOf("proposal");
4065
- const result = mergeFromSite({
3094
+ const result = merge.mergeFromSite({
4066
3095
  base,
4067
3096
  site,
4068
3097
  proposal,
@@ -4097,7 +3126,7 @@ function updateWithCode(input) {
4097
3126
  files: mergedFiles,
4098
3127
  modules: modulesOf(Object.fromEntries(Object.entries(mergedFiles).filter(entry => entry[1] !== null)), input.merged.evaluated, path => result.modules[path] ?? null)
4099
3128
  };
4100
- const invalid = schemaCheck(mergedProject, [site, proposal]);
3129
+ const invalid = merge.schemaCheck(mergedProject, [site, proposal]);
4101
3130
  if (invalid.length > 0) return {
4102
3131
  status: "conflicts",
4103
3132
  conflicts: invalid
@@ -4142,7 +3171,7 @@ function modulesOf(files, evaluated, sourceOf) {
4142
3171
  source: sourceOf(moduleFilePath) ?? module.written,
4143
3172
  written: module.written,
4144
3173
  schema: module.schema,
4145
- entries: text === undefined ? null : entryFilesOf(moduleFilePath, text),
3174
+ entries: text === undefined ? null : merge.entryFilesOf(moduleFilePath, text),
4146
3175
  errors: module.errors
4147
3176
  };
4148
3177
  }
@@ -4192,7 +3221,7 @@ async function stagedModuleSources(files) {
4192
3221
  parseValFile,
4193
3222
  analyzeValModule,
4194
3223
  evaluateModuleSource
4195
- } = await Promise.resolve().then(function () { return require('./publishKit-de4baed6.cjs.dev.js'); });
3224
+ } = await Promise.resolve().then(function () { return require('./publishKit-ffcaf2af.cjs.dev.js'); });
4196
3225
  const sources = {};
4197
3226
  for (const {
4198
3227
  path,
@@ -4275,7 +3304,7 @@ function movesAtMerge(inputs, schemas) {
4275
3304
  const schema = schemas[moduleFilePath];
4276
3305
  if (schema === undefined) continue;
4277
3306
  const serialized = schema["executeSerialize"]();
4278
- const validate = source => validateWith(schema, moduleFilePath, source);
3307
+ const validate = source => merge.validateWith(schema, moduleFilePath, source);
4279
3308
  if (before !== null) {
4280
3309
  site.modules[moduleFilePath] = {
4281
3310
  source: before,
@@ -4293,7 +3322,7 @@ function movesAtMerge(inputs, schemas) {
4293
3322
  };
4294
3323
  }
4295
3324
  }
4296
- const groups = changesToMove({
3325
+ const groups = merge.changesToMove({
4297
3326
  site,
4298
3327
  merged,
4299
3328
  pending: inputs.pending.map(change => ({
@@ -8713,7 +7742,6 @@ function sameValue(a, b) {
8713
7742
  }
8714
7743
 
8715
7744
  exports.APP_MODE_REQUIRES_REMOTE_FILES = APP_MODE_REQUIRES_REMOTE_FILES;
8716
- exports.TSOps = TSOps;
8717
7745
  exports.ValOpsFS = ValOpsFS;
8718
7746
  exports.ValOpsHttp = ValOpsHttp;
8719
7747
  exports.createValOps = createValOps;
@@ -8723,12 +7751,10 @@ exports.encodeJwt = encodeJwt;
8723
7751
  exports.getExpire = getExpire;
8724
7752
  exports.getPersonalAccessTokenPath = getPersonalAccessTokenPath;
8725
7753
  exports.initHandlerOptions = initHandlerOptions;
8726
- exports.insertValJsonEntry = insertValJsonEntry;
8727
7754
  exports.loadTypeScriptKit = loadTypeScriptKit;
8728
7755
  exports.parsePersonalAccessTokenFile = parsePersonalAccessTokenFile;
8729
7756
  exports.readPatchStore = readPatchStore;
8730
7757
  exports.readValLoginToken = readValLoginToken;
8731
- exports.removeValJsonEntry = removeValJsonEntry;
8732
7758
  exports.resolveRemoteFileAuth = resolveRemoteFileAuth;
8733
7759
  exports.valRuntime = valRuntime;
8734
7760
  exports.verifyJwt = verifyJwt;