@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
@@ -0,0 +1,1566 @@
1
+ import ts from 'typescript';
2
+ import { PatchError, deepEqual, isNotRoot, parseAndValidateArrayIndex, deepClone, applyPatch, JSONOps } from '@valbuild/core/patch';
3
+ import { pipe, result } from '@valbuild/core/fp';
4
+ import { schemaErrorsOf, PatchSets, joinSharedChanges, schemaTypesOfPath } from '@valbuild/shared/internal';
5
+ import path from 'path';
6
+ import { a as analyzeValModule, e as findObjectPropertyAssignment, g as findObjectPropertyAssignmentToRemove, h as evaluateExpression, s as shallowValidateExpression, v as validateInitializers, c as analyzeJsonValuesEntries, f as flatMapErrors, V as ValSyntaxError } from './jsonValuesModule-12fc4bb0.esm.js';
7
+ import { Internal, deserializeSchema } from '@valbuild/core';
8
+ import 'crypto';
9
+ import fs from 'fs';
10
+ import vm from 'node:vm';
11
+ import { Module } from 'node:module';
12
+
13
+ function isValidIdentifier(text) {
14
+ if (text.length === 0) {
15
+ return false;
16
+ }
17
+ if (!ts.isIdentifierStart(text.charCodeAt(0), ts.ScriptTarget.ES2020)) {
18
+ return false;
19
+ }
20
+ for (let i = 1; i < text.length; ++i) {
21
+ if (!ts.isIdentifierPart(text.charCodeAt(i), ts.ScriptTarget.ES2020)) {
22
+ return false;
23
+ }
24
+ }
25
+ return true;
26
+ }
27
+ function createPropertyAssignment(key, value) {
28
+ return ts.factory.createPropertyAssignment(isValidIdentifier(key) ? ts.factory.createIdentifier(key) : ts.factory.createStringLiteral(key), toExpression(value));
29
+ }
30
+
31
+ /**
32
+ * Builds the expression `c.json(() => import("<importPath>"))` used to reference
33
+ * a lazily-loaded `*.val.json` entry of a `.jsonValues()` record.
34
+ */
35
+ function createValJsonReference(importPath) {
36
+ // () => import("<importPath>")
37
+ // NOTE: an `import` identifier prints as the dynamic-import keyword call,
38
+ // which avoids casting the ImportKeyword token (not typed as an Expression).
39
+ const importCall = ts.factory.createCallExpression(ts.factory.createIdentifier("import"), undefined, [ts.factory.createStringLiteral(importPath)]);
40
+ const thunk = ts.factory.createArrowFunction(undefined, undefined, [], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), importCall);
41
+ // c.json(<thunk>)
42
+ return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("c"), ts.factory.createIdentifier("json")), undefined, [thunk]);
43
+ }
44
+
45
+ /**
46
+ * Inserts a new `.jsonValues()` entry `"<key>": c.json(() => import("<importPath>"))`
47
+ * into the record's object literal in a `.val.ts` module. `recordPath` is the
48
+ * path from the module source to the record (empty for a root record/router).
49
+ * Fails if the entry key already exists.
50
+ */
51
+ function insertValJsonEntry(document, recordPath, key, importPath) {
52
+ return pipe(analyzeValModule(document), result.flatMap(({
53
+ source
54
+ }) => getAtPath(source, recordPath)), result.flatMap(recordNode => {
55
+ if (!ts.isObjectLiteralExpression(recordNode)) {
56
+ return result.err(new PatchError("Cannot add jsonValues entry: record source is not an object literal"));
57
+ }
58
+ return pipe(findObjectPropertyAssignment(recordNode, key), result.flatMap(assignment => {
59
+ if (assignment) {
60
+ return result.err(new PatchError(`Cannot add jsonValues entry '${key}': it already exists`));
61
+ }
62
+ const property = ts.factory.createPropertyAssignment(isValidIdentifier(key) ? ts.factory.createIdentifier(key) : ts.factory.createStringLiteral(key), createValJsonReference(importPath));
63
+ return result.ok(insertAt(document, recordNode.properties, recordNode.properties.length, property));
64
+ }));
65
+ }));
66
+ }
67
+
68
+ /**
69
+ * Removes the `.jsonValues()` entry `"<key>"` from the record's object literal
70
+ * in a `.val.ts` module. `recordPath` is the path from the module source to the
71
+ * record (empty for a root record/router). Fails if the entry key is missing.
72
+ */
73
+ function removeValJsonEntry(document, recordPath, key) {
74
+ return pipe(analyzeValModule(document), result.flatMap(({
75
+ source
76
+ }) => getAtPath(source, recordPath)), result.flatMap(recordNode => {
77
+ if (!ts.isObjectLiteralExpression(recordNode)) {
78
+ return result.err(new PatchError("Cannot remove jsonValues entry: record source is not an object literal"));
79
+ }
80
+ return pipe(findObjectPropertyAssignmentToRemove(recordNode, key), result.flatMap(assignment => {
81
+ if (!assignment) {
82
+ return result.err(new PatchError(`Cannot remove jsonValues entry '${key}': it does not exist`));
83
+ }
84
+ const [doc] = removeAt(document, recordNode.properties, recordNode.properties.indexOf(assignment));
85
+ return result.ok(doc);
86
+ }));
87
+ }));
88
+ }
89
+ function toExpression(value) {
90
+ if (typeof value === "string") {
91
+ // TODO: Use configuration/heuristics to determine use of single quote or double quote
92
+ return ts.factory.createStringLiteral(value);
93
+ } else if (typeof value === "number") {
94
+ // TODO: do we want to do something like this for very large numbers?
95
+ // if (value > Number.MAX_SAFE_INTEGER) {
96
+ // return ts.factory.createBigIntLiteral(`${value}n`);
97
+ // }
98
+ // if (value < Number.MIN_SAFE_INTEGER) {
99
+ // return ts.factory.createPrefixUnaryExpression(
100
+ // ts.SyntaxKind.MinusToken,
101
+ // ts.factory.createBigIntLiteral(`${value}n`),
102
+ // );
103
+ // }
104
+ if (value < 0) {
105
+ return ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(Math.abs(value)));
106
+ }
107
+ return ts.factory.createNumericLiteral(value);
108
+ } else if (typeof value === "boolean") {
109
+ return value ? ts.factory.createTrue() : ts.factory.createFalse();
110
+ } else if (value === null) {
111
+ return ts.factory.createNull();
112
+ } else if (Array.isArray(value)) {
113
+ return ts.factory.createArrayLiteralExpression(value.map(toExpression));
114
+ } else if (typeof value === "object") {
115
+ return ts.factory.createObjectLiteralExpression(Object.entries(value)
116
+ // `patch_id` is injected server-side onto a media source whose bytes are
117
+ // not committed yet. It describes the draft, not the content, and a
118
+ // whole-object write built from the client's optimistic view would
119
+ // otherwise print it into the user's file.
120
+ .filter(([key]) => key !== "patch_id").map(([key, value]) => createPropertyAssignment(key, value)));
121
+ } else {
122
+ return ts.factory.createStringLiteral(value);
123
+ }
124
+ }
125
+
126
+ // TODO: Choose newline based on project settings/heuristics/system default?
127
+ const newLine = ts.NewLineKind.LineFeed;
128
+ // TODO: Handle indentation of printed code
129
+ const printer = ts.createPrinter({
130
+ newLine: newLine
131
+ // neverAsciiEscape: true,
132
+ });
133
+ function replaceNodeValue(document, node, value) {
134
+ const replacementText = printer.printNode(ts.EmitHint.Unspecified, toExpression(value), document);
135
+ const span = ts.createTextSpanFromBounds(node.getStart(document, false), node.end);
136
+ const newText = `${document.text.substring(0, span.start)}${replacementText}${document.text.substring(ts.textSpanEnd(span))}`;
137
+ return [document.update(newText, ts.createTextChangeRange(span, replacementText.length)), node];
138
+ }
139
+ function isIndentation(s) {
140
+ for (let i = 0; i < s.length; ++i) {
141
+ const c = s.charAt(i);
142
+ if (c !== " " && c !== "\t") {
143
+ return false;
144
+ }
145
+ }
146
+ return true;
147
+ }
148
+ function newLineStr(kind) {
149
+ if (kind === ts.NewLineKind.CarriageReturnLineFeed) {
150
+ return "\r\n";
151
+ } else {
152
+ return "\n";
153
+ }
154
+ }
155
+ function getSeparator(document, neighbor) {
156
+ const startPos = neighbor.getStart(document, true);
157
+ const basis = document.getLineAndCharacterOfPosition(startPos);
158
+ const lineStartPos = document.getPositionOfLineAndCharacter(basis.line, 0);
159
+ const maybeIndentation = document.getText().substring(lineStartPos, startPos);
160
+ if (isIndentation(maybeIndentation)) {
161
+ return `,${newLineStr(newLine)}${maybeIndentation}`;
162
+ } else {
163
+ return `, `;
164
+ }
165
+ }
166
+ function insertAt(document, nodes, index, node) {
167
+ let span;
168
+ let replacementText;
169
+ if (nodes.length === 0) {
170
+ // Replace entire range of nodes
171
+ replacementText = printer.printNode(ts.EmitHint.Unspecified, node, document);
172
+ span = ts.createTextSpanFromBounds(nodes.pos, nodes.end);
173
+ } else if (index === nodes.length) {
174
+ // Insert after last node
175
+ const neighbor = nodes[nodes.length - 1];
176
+ replacementText = `${getSeparator(document, neighbor)}${printer.printNode(ts.EmitHint.Unspecified, node, document)}`;
177
+ span = ts.createTextSpan(neighbor.end, 0);
178
+ } else {
179
+ // Insert before node
180
+ const neighbor = nodes[index];
181
+ replacementText = `${printer.printNode(ts.EmitHint.Unspecified, node, document)}${getSeparator(document, neighbor)}`;
182
+ span = ts.createTextSpan(neighbor.getStart(document, true), 0);
183
+ }
184
+ const newText = `${document.text.substring(0, span.start)}${replacementText}${document.text.substring(ts.textSpanEnd(span))}`;
185
+ return document.update(newText, ts.createTextChangeRange(span, replacementText.length));
186
+ }
187
+ function removeAt(document, nodes, index) {
188
+ const node = nodes[index];
189
+ let span;
190
+ if (nodes.length === 1) {
191
+ span = ts.createTextSpanFromBounds(nodes.pos, nodes.end);
192
+ } else if (index === nodes.length - 1) {
193
+ // Remove until previous node
194
+ const neighbor = nodes[index - 1];
195
+ span = ts.createTextSpanFromBounds(neighbor.end, node.end);
196
+ } else {
197
+ // Remove before next node
198
+ const neighbor = nodes[index + 1];
199
+ span = ts.createTextSpanFromBounds(node.getStart(document, true), neighbor.getStart(document, true));
200
+ }
201
+ const newText = `${document.text.substring(0, span.start)}${document.text.substring(ts.textSpanEnd(span))}`;
202
+ return [document.update(newText, ts.createTextChangeRange(span, 0)), node];
203
+ }
204
+ function parseAndValidateArrayInsertIndex(key, nodes) {
205
+ if (key === "-") {
206
+ // For insertion, all nodes up until the insertion index must be valid
207
+ // initializers
208
+ const err = validateInitializers(nodes);
209
+ if (err) {
210
+ return result.err(err);
211
+ }
212
+ return result.ok(nodes.length);
213
+ }
214
+ return pipe(parseAndValidateArrayIndex(key), result.flatMap(index => {
215
+ // For insertion, all nodes up until the insertion index must be valid
216
+ // initializers
217
+ const err = validateInitializers(nodes.slice(0, index));
218
+ if (err) {
219
+ return result.err(err);
220
+ }
221
+ if (index > nodes.length) {
222
+ return result.err(new PatchError("Array index out of bounds"));
223
+ } else {
224
+ return result.ok(index);
225
+ }
226
+ }));
227
+ }
228
+ function parseAndValidateArrayInboundsIndex(key, nodes) {
229
+ return pipe(parseAndValidateArrayIndex(key), result.flatMap(index => {
230
+ // For in-bounds operations, all nodes up until and including the index
231
+ // must be valid initializers
232
+ const err = validateInitializers(nodes.slice(0, index + 1));
233
+ if (err) {
234
+ return result.err(err);
235
+ }
236
+ if (index >= nodes.length) {
237
+ return result.err(new PatchError("Array index out of bounds"));
238
+ } else {
239
+ return result.ok(index);
240
+ }
241
+ }));
242
+ }
243
+ function replaceInNode(document, node, key, value) {
244
+ if (ts.isArrayLiteralExpression(node)) {
245
+ return pipe(parseAndValidateArrayInboundsIndex(key, node.elements), result.map(index => replaceNodeValue(document, node.elements[index], value)));
246
+ } else if (ts.isObjectLiteralExpression(node)) {
247
+ return pipe(findObjectPropertyAssignment(node, key), result.flatMap(assignment => {
248
+ if (!assignment) {
249
+ return result.err(new PatchError("Cannot replace object element which does not exist"));
250
+ }
251
+ return result.ok(assignment);
252
+ }), result.map(assignment => replaceNodeValue(document, assignment.initializer, value)));
253
+ } else {
254
+ return result.err(shallowValidateExpression(node) ?? new PatchError("Cannot replace in non-object/array"));
255
+ }
256
+ }
257
+ function replaceAtPath(document, rootNode, path, value) {
258
+ if (isNotRoot(path)) {
259
+ return pipe(getPointerFromPath(rootNode, path), result.flatMap(([node, key]) => replaceInNode(document, node, key, value)));
260
+ } else {
261
+ return result.ok(replaceNodeValue(document, rootNode, value));
262
+ }
263
+ }
264
+ function getFromNode(node, key) {
265
+ if (ts.isArrayLiteralExpression(node)) {
266
+ return pipe(parseAndValidateArrayInboundsIndex(key, node.elements), result.map(index => node.elements[index]));
267
+ } else if (ts.isObjectLiteralExpression(node)) {
268
+ return pipe(findObjectPropertyAssignment(node, key), result.map(assignment => assignment === null || assignment === void 0 ? void 0 : assignment.initializer));
269
+ } else {
270
+ return result.err(shallowValidateExpression(node) ?? new PatchError("Cannot access non-object/array"));
271
+ }
272
+ }
273
+ function getPointerFromPath(node, path) {
274
+ let targetNode = node;
275
+ let key = path[0];
276
+ for (let i = 0; i < path.length - 1; ++i, key = path[i]) {
277
+ const childNode = getFromNode(targetNode, key);
278
+ if (result.isErr(childNode)) {
279
+ return childNode;
280
+ }
281
+ if (childNode.value === undefined) {
282
+ return result.err(new PatchError(`Path refers to non-existing object/array: ${path.join("/")}`));
283
+ }
284
+ targetNode = childNode.value;
285
+ }
286
+ return result.ok([targetNode, key]);
287
+ }
288
+ function getAtPath(rootNode, path) {
289
+ return pipe(path, result.flatMapReduce((node, key) => pipe(getFromNode(node, key), result.filterOrElse(childNode => childNode !== undefined, () => new PatchError("Path refers to non-existing object/array"))), rootNode));
290
+ }
291
+ function removeFromNode(document, node, key) {
292
+ if (ts.isArrayLiteralExpression(node)) {
293
+ return pipe(parseAndValidateArrayInboundsIndex(key, node.elements), result.map(index => removeAt(document, node.elements, index)));
294
+ } else if (ts.isObjectLiteralExpression(node)) {
295
+ return pipe(findObjectPropertyAssignmentToRemove(node, key), result.flatMap(assignment => {
296
+ if (!assignment) {
297
+ return result.err(new PatchError("Cannot remove object element which does not exist"));
298
+ }
299
+ return result.ok(assignment);
300
+ }), result.map(assignment => [removeAt(document, node.properties, node.properties.indexOf(assignment))[0], assignment.initializer]));
301
+ } else {
302
+ return result.err(shallowValidateExpression(node) ?? new PatchError("Cannot remove from non-object/array"));
303
+ }
304
+ }
305
+ function removeAtPath(document, rootNode, path) {
306
+ return pipe(getPointerFromPath(rootNode, path), result.flatMap(([node, key]) => removeFromNode(document, node, key)));
307
+ }
308
+ function addToNode(document, node, key, value) {
309
+ if (ts.isArrayLiteralExpression(node)) {
310
+ return pipe(parseAndValidateArrayInsertIndex(key, node.elements), result.map(index => [insertAt(document, node.elements, index, toExpression(value))]));
311
+ } else if (ts.isObjectLiteralExpression(node)) {
312
+ return pipe(findObjectPropertyAssignment(node, key), result.map(assignment => {
313
+ if (!assignment) {
314
+ return [insertAt(document, node.properties, node.properties.length, createPropertyAssignment(key, value))];
315
+ } else {
316
+ return replaceNodeValue(document, assignment.initializer, value);
317
+ }
318
+ }));
319
+ } else {
320
+ return result.err(shallowValidateExpression(node) ?? new PatchError("Cannot add to non-object/array"));
321
+ }
322
+ }
323
+ function addAtPath(document, rootNode, path, value) {
324
+ if (isNotRoot(path)) {
325
+ return pipe(getPointerFromPath(rootNode, path), result.flatMap(([node, key]) => addToNode(document, node, key, value)));
326
+ } else {
327
+ return result.ok(replaceNodeValue(document, rootNode, value));
328
+ }
329
+ }
330
+ function pickDocument([document]) {
331
+ return document;
332
+ }
333
+ class TSOps {
334
+ constructor(findRoot) {
335
+ this.findRoot = findRoot;
336
+ }
337
+ get(document, path) {
338
+ return pipe(document, this.findRoot, result.flatMap(rootNode => getAtPath(rootNode, path)), result.flatMap(evaluateExpression));
339
+ }
340
+ add(document, path, value) {
341
+ return pipe(document, this.findRoot, result.flatMap(rootNode => addAtPath(document, rootNode, path, value)), result.map(pickDocument));
342
+ }
343
+ remove(document, path) {
344
+ return pipe(document, this.findRoot, result.flatMap(rootNode => removeAtPath(document, rootNode, path)), result.map(pickDocument));
345
+ }
346
+ replace(document, path, value) {
347
+ return pipe(document, this.findRoot, result.flatMap(rootNode => replaceAtPath(document, rootNode, path, value)), result.map(pickDocument));
348
+ }
349
+ move(document, from, path) {
350
+ return pipe(document, this.findRoot, result.flatMap(rootNode => removeAtPath(document, rootNode, from)), result.flatMap(([document, removedNode]) => pipe(evaluateExpression(removedNode), result.map(removedValue => [document, removedValue]))), result.flatMap(([document, removedValue]) => pipe(document, this.findRoot, result.flatMap(root => addAtPath(document, root, path, removedValue)))), result.map(pickDocument));
351
+ }
352
+ copy(document, from, path) {
353
+ return pipe(document, this.findRoot, result.flatMap(rootNode => pipe(getAtPath(rootNode, from), result.flatMap(evaluateExpression), result.flatMap(value => addAtPath(document, rootNode, path, value)))), result.map(pickDocument));
354
+ }
355
+ test(document, path, value) {
356
+ return pipe(document, this.findRoot, result.flatMap(rootNode => getAtPath(rootNode, path)), result.flatMap(evaluateExpression), result.map(documentValue => deepEqual(value, documentValue)));
357
+ }
358
+ }
359
+
360
+ const getCompilerOptions = (rootDir, parseConfigHost) => {
361
+ const tsConfigPath = path.resolve(rootDir, "tsconfig.json");
362
+ const jsConfigPath = path.resolve(rootDir, "jsconfig.json");
363
+ let configFilePath;
364
+ if (parseConfigHost.fileExists(jsConfigPath)) {
365
+ configFilePath = jsConfigPath;
366
+ } else if (parseConfigHost.fileExists(tsConfigPath)) {
367
+ configFilePath = tsConfigPath;
368
+ } else {
369
+ throw Error(`Could not read config from: "${tsConfigPath}" nor "${jsConfigPath}". Root dir: "${rootDir}"`);
370
+ }
371
+ const {
372
+ config,
373
+ error
374
+ } = ts.readConfigFile(configFilePath, parseConfigHost.readFile.bind(parseConfigHost));
375
+ if (error) {
376
+ if (typeof error.messageText === "string") {
377
+ throw Error(`Could not parse config file: ${configFilePath}. Error: ${error.messageText}`);
378
+ }
379
+ throw Error(`Could not parse config file: ${configFilePath}. Error: ${error.messageText.messageText}`);
380
+ }
381
+ const optionsOverrides = undefined;
382
+ const parsedConfigFile = ts.parseJsonConfigFileContent(config, parseConfigHost, rootDir, optionsOverrides, configFilePath);
383
+ if (parsedConfigFile.errors.length > 0) {
384
+ throw Error(`Could not parse config file: ${configFilePath}. Errors: ${parsedConfigFile.errors.map(e => e.messageText).join("\n")}`);
385
+ }
386
+ return parsedConfigFile.options;
387
+ };
388
+
389
+ /**
390
+ * Node's `require`, resolving as if from `filename`.
391
+ *
392
+ * Use this instead of importing `createRequire` from `node:module` directly.
393
+ * webpack special-cases a `createRequire` binding imported from `module` /
394
+ * `node:module`: it tries to resolve the call's argument at build time, and
395
+ * when the argument is not a literal it gives up with
396
+ *
397
+ * module.createRequire failed parsing argument.
398
+ *
399
+ * Our argument is never a literal — it is a path inside the user's project,
400
+ * known only at runtime — so there is nothing for that analysis to find, and
401
+ * nothing the warning can tell anyone. It is emitted on every build of every
402
+ * Next app that bundles `@valbuild/server` into its Val API route, which is
403
+ * all of them. Reaching `createRequire` through the `Module` class is the same
404
+ * function and is not what webpack tags, so the call is invisible to it.
405
+ *
406
+ * It has to stay a real `node:module` import: jest's module registry hands out
407
+ * its own `node:module`, and a `require` obtained around it (via
408
+ * `process.getBuiltinModule`, say) would resolve against the real filesystem
409
+ * rather than the registry the tests run in.
410
+ */
411
+ function createNodeRequire(filename) {
412
+ return Module.createRequire(filename);
413
+ }
414
+
415
+ /**
416
+ * The filesystem seam `loadValModules` reads through.
417
+ *
418
+ * Defaults to `ts.sys`, i.e. the real filesystem. An editor integration (see
419
+ * `@valbuild/language-server`) passes a host that overlays unsaved buffers, so
420
+ * that evaluation sees what the user is looking at rather than what was last
421
+ * saved.
422
+ */
423
+
424
+ /**
425
+ * Loads the project's root `val.modules.ts` (or `.js`) using Node's `vm`
426
+ * module and returns its default export (a `ValModules` registry).
427
+ *
428
+ * This is a recursive CommonJS loader: the root modules file and every
429
+ * relative `*.val.ts` / `val.config.ts` it (dynamically) imports are
430
+ * transpiled to CommonJS and evaluated in a `vm` sandbox. Bare specifiers
431
+ * (e.g. `@valbuild/core`) are resolved with the real Node `require` so the
432
+ * user modules share the exact same `@valbuild/core` instance that
433
+ * `extractValModules` uses.
434
+ *
435
+ * Mirrors the pattern already used by the CLI's `evalValConfigFile`.
436
+ *
437
+ * SECURITY: The `vm` context is NOT a security sandbox. It deliberately exposes
438
+ * `process` and a `require` that falls back to the real Node resolver (so user
439
+ * modules share the same `@valbuild/core` instance). This loader must therefore
440
+ * only ever be used to evaluate the project's own first-party, trusted files
441
+ * (`val.modules` and the local `*.val.ts`/`val.config.ts` it imports) — i.e. the
442
+ * same trust level as running the project's build. It must never be used to
443
+ * evaluate untrusted or third-party modules.
444
+ */
445
+ function loadValModules(projectRoot, host = ts.sys) {
446
+ const valModulesPath = findValModulesPath(projectRoot, host);
447
+ if (!valModulesPath) {
448
+ throw Error(`Could not find 'val.modules.ts' nor 'val.modules.js' in project root: '${projectRoot}'`);
449
+ }
450
+ const compilerOptions = getCompilerOptions(projectRoot, host);
451
+ const cache = {};
452
+ const loaded = loadModule(valModulesPath, cache, compilerOptions, host);
453
+ const valModules = loaded.exports.default;
454
+ if (!valModules) {
455
+ throw Error(`Val modules file at path: '${valModulesPath}' must have a default export. Got: ${valModules}`);
456
+ }
457
+ return valModules;
458
+ }
459
+ function findValModulesPath(projectRoot, host) {
460
+ for (const fileName of ["val.modules.ts", "val.modules.js"]) {
461
+ const candidate = path.join(projectRoot, fileName);
462
+ if (host.fileExists(candidate)) {
463
+ return candidate;
464
+ }
465
+ }
466
+ return null;
467
+ }
468
+ const RESOLVE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".cjs", ".mjs", ".json"];
469
+
470
+ // Specifiers that user val files must not actually use. We stub them so that
471
+ // importing is fine, but using a value throws a clear error. Real @valbuild
472
+ // packages are resolved via the real require, so when they (legitimately)
473
+ // import react/next internally those go through Node, not this stub.
474
+ function isStubbedSpecifier(spec) {
475
+ return spec === "react" || spec.startsWith("react/") || spec === "next" || spec.startsWith("next/") || spec === "@valbuild/ui" || spec === "@valbuild/react" || spec.startsWith("@valbuild/react/");
476
+ }
477
+ function makeStub(spec) {
478
+ const throwing = prop => () => {
479
+ throw Error(`Cannot use '${prop}' from '${spec}' in this type of file`);
480
+ };
481
+ const handler = {
482
+ get(_target, prop) {
483
+ if (prop === "__esModule") {
484
+ return true;
485
+ }
486
+ if (typeof prop === "symbol") {
487
+ return undefined;
488
+ }
489
+ // React.createContext is sometimes called at module top-level; return a
490
+ // proxy-returning function so evaluation does not crash on import.
491
+ if (prop === "createContext") {
492
+ return () => new Proxy({}, handler);
493
+ }
494
+ if (prop === "default") {
495
+ return stub;
496
+ }
497
+ return throwing(prop);
498
+ }
499
+ };
500
+ const stub = new Proxy({}, handler);
501
+ return stub;
502
+ }
503
+ function loadModule(absPath, cache, compilerOptions, host) {
504
+ const cached = cache[absPath];
505
+ if (cached) {
506
+ return cached;
507
+ }
508
+ // JSON modules (e.g. the `*.val.json` files backing `.jsonValues()` entries)
509
+ // are loaded by parsing, mirroring Node's `require("./x.json")` which returns
510
+ // the parsed object as `module.exports`. The importing `.val.ts` wraps this
511
+ // with `__importStar` so `import("./x.val.json")` yields `{ default, ... }`.
512
+ // These are only loaded when an entry thunk is invoked, never during
513
+ // `extractValModules`, so this stays lazy.
514
+ //
515
+ // Read through `host` like every other project file: an editor integration
516
+ // passes a host that overlays unsaved buffers, and an entry the user is
517
+ // editing has to resolve to what they are looking at.
518
+ if (absPath.endsWith(".json")) {
519
+ const json = host.readFile(absPath);
520
+ if (json === undefined) {
521
+ throw Error(`Could not read Val module file: '${absPath}'`);
522
+ }
523
+ const jsonModule = {
524
+ exports: JSON.parse(json)
525
+ };
526
+ cache[absPath] = jsonModule;
527
+ return jsonModule;
528
+ }
529
+ const code = host.readFile(absPath);
530
+ if (code === undefined) {
531
+ throw Error(`Could not read Val module file: '${absPath}'`);
532
+ }
533
+ const transpiled = ts.transpileModule(code, {
534
+ compilerOptions: {
535
+ target: ts.ScriptTarget.ES2020,
536
+ module: ts.ModuleKind.CommonJS,
537
+ esModuleInterop: true,
538
+ jsx: ts.JsxEmit.ReactJSX
539
+ },
540
+ fileName: absPath
541
+ });
542
+ const moduleObj = {
543
+ exports: {}
544
+ };
545
+ // Insert into the cache before evaluating so cyclic imports resolve.
546
+ cache[absPath] = moduleObj;
547
+ const dirName = path.dirname(absPath);
548
+ const realRequire = createNodeRequire(absPath);
549
+ const customRequire = spec => {
550
+ var _ts$resolveModuleName;
551
+ if (isStubbedSpecifier(spec)) {
552
+ return makeStub(spec);
553
+ }
554
+ if (spec.startsWith(".") || path.isAbsolute(spec)) {
555
+ const resolved = resolveRelative(dirName, spec, host);
556
+ if (!resolved) {
557
+ throw Error(`Could not resolve module '${spec}' from '${absPath}'`);
558
+ }
559
+ return loadModule(resolved, cache, compilerOptions, host).exports;
560
+ }
561
+ // Non-relative specifier: it might be a tsconfig path alias (e.g. "_/val.config")
562
+ // pointing at a local source file, or an actual node_modules package.
563
+ const tsResolved = (_ts$resolveModuleName = ts.resolveModuleName(spec, absPath, compilerOptions, host).resolvedModule) === null || _ts$resolveModuleName === void 0 ? void 0 : _ts$resolveModuleName.resolvedFileName;
564
+ if (tsResolved && !tsResolved.includes("/node_modules/") && !tsResolved.endsWith(".d.ts")) {
565
+ return loadModule(tsResolved, cache, compilerOptions, host).exports;
566
+ }
567
+ // Real node_modules package – use the real require so user modules share
568
+ // the same @valbuild/core instance as extractValModules.
569
+ return realRequire(spec);
570
+ };
571
+
572
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
573
+ const sandbox = {
574
+ exports: moduleObj.exports,
575
+ module: moduleObj,
576
+ require: customRequire,
577
+ __filename: absPath,
578
+ __dirname: dirName,
579
+ console,
580
+ process
581
+ };
582
+ sandbox.global = sandbox;
583
+ sandbox.globalThis = sandbox;
584
+ const context = vm.createContext(sandbox);
585
+ const script = new vm.Script(transpiled.outputText, {
586
+ filename: absPath
587
+ });
588
+ script.runInContext(context);
589
+ return moduleObj;
590
+ }
591
+ function resolveRelative(dirName, spec, host) {
592
+ var _host$directoryExists;
593
+ const base = path.resolve(dirName, spec);
594
+ // Exact file (with extension)
595
+ if (host.fileExists(base)) {
596
+ return base;
597
+ }
598
+ // Probe extensions (handles `./x.val` -> `./x.val.ts`)
599
+ for (const ext of RESOLVE_EXTENSIONS) {
600
+ const candidate = base + ext;
601
+ if (host.fileExists(candidate)) {
602
+ return candidate;
603
+ }
604
+ }
605
+ // Directory index
606
+ if (((_host$directoryExists = host.directoryExists) === null || _host$directoryExists === void 0 ? void 0 : _host$directoryExists.call(host, base)) ?? fs.existsSync(base)) {
607
+ for (const ext of RESOLVE_EXTENSIONS) {
608
+ const candidate = path.join(base, "index" + ext);
609
+ if (host.fileExists(candidate)) {
610
+ return candidate;
611
+ }
612
+ }
613
+ }
614
+ return null;
615
+ }
616
+
617
+ /**
618
+ * What a `*.val.ts` file that is NOT registered in `val.modules` turns out to
619
+ * be.
620
+ *
621
+ * A file matching `*.val.ts` is not necessarily a Val module: the same
622
+ * convention is used for shared schemas and other content-adjacent helpers, and
623
+ * those are not meant to be registered. Only a file that actually default
624
+ * exports a module is worth warning about; one that default exports something
625
+ * else is a mistake, because nothing will ever load it.
626
+ *
627
+ * See {@link createValModuleFileInspector}.
628
+ */
629
+
630
+ /**
631
+ * Inspects individual `*.val.{ts,js}` files, sharing one module cache and one
632
+ * parsed tsconfig across every call.
633
+ *
634
+ * The default export is checked SYNTACTICALLY first and only evaluated if it is
635
+ * there. That ordering is the point: a `.val.ts` with no default export is a
636
+ * helper file, and evaluating it to learn that would be both wasted work and a
637
+ * way to turn an unrelated top-level throw into a reported error.
638
+ *
639
+ * SECURITY: evaluation goes through the same `vm` loader as
640
+ * {@link loadValModules} — see the warning there. Only ever point this at the
641
+ * project's own first-party files.
642
+ */
643
+ function createValModuleFileInspector(projectRoot, host = ts.sys) {
644
+ const compilerOptions = getCompilerOptions(projectRoot, host);
645
+ const cache = {};
646
+ return absPath => {
647
+ const code = host.readFile(absPath);
648
+ if (code === undefined) {
649
+ return {
650
+ status: "invalid",
651
+ message: `Could not read file: '${absPath}'`
652
+ };
653
+ }
654
+ const sourceFile = ts.createSourceFile(absPath, code, ts.ScriptTarget.ES2020, true);
655
+ if (!hasDefaultExport(sourceFile)) {
656
+ return {
657
+ status: "no-default-export"
658
+ };
659
+ }
660
+ let exports;
661
+ // `loadModule` inserts a module into the cache BEFORE evaluating it, so
662
+ // that a cycle resolves. One that throws therefore leaves a half-built
663
+ // entry behind - and unlike `loadValModules`, which builds a cache per
664
+ // call and lets the throw escape, this cache outlives the failure. A later
665
+ // inspection of the same file (or of the helper that actually threw) would
666
+ // hit that entry, see empty exports, and report "default export is
667
+ // undefined" instead of the real error - or, worse, quietly downgrade it to
668
+ // a warning. So roll the cache back to what it was before this attempt.
669
+ const before = new Set(Object.keys(cache));
670
+ try {
671
+ exports = loadModule(absPath, cache, compilerOptions, host).exports;
672
+ } catch (e) {
673
+ for (const key of Object.keys(cache)) {
674
+ if (!before.has(key)) {
675
+ delete cache[key];
676
+ }
677
+ }
678
+ return {
679
+ status: "invalid",
680
+ message: `Could not be loaded. Error: ${errorMessage(e)}`
681
+ };
682
+ }
683
+ if (Internal.isValModule(exports.default)) {
684
+ return {
685
+ status: "val-module"
686
+ };
687
+ }
688
+ // NOTE: do NOT suggest wrapping this in `c.define`. A shared schema turned
689
+ // into a module is an UNREGISTERED module, i.e. straight back to a warning.
690
+ // The fix is to move it out of the default export slot, which is the one
691
+ // thing about a `.val.ts` that Val reserves for itself.
692
+ return {
693
+ status: "invalid",
694
+ message: `Default export is ${describeDefaultExport(exports.default)}, not a Val module. Only 'c.define(...)' may be the default export of a '*.val.ts' file: use a named export for a shared schema or helper`
695
+ };
696
+ };
697
+ }
698
+
699
+ /**
700
+ * The statement that exports a RUNTIME value as `default`, without evaluating
701
+ * it — or `undefined` when the file has no such export.
702
+ *
703
+ * This is the one rule that separates a Val module from a `*.val.ts` that
704
+ * merely wears the naming convention: a shared schema or helper is exported by
705
+ * name, a module is exported by default. Every caller that needs to tell those
706
+ * apart goes through this — `val validate` to decide whether an unregistered
707
+ * file is worth reporting, and the language server to decide the same thing and
708
+ * to put its diagnostic on the export rather than on line 1.
709
+ *
710
+ * Two things deliberately do not count, because neither exists once the file is
711
+ * transpiled — and treating either as a default export would send a pure helper
712
+ * off to be evaluated and reported:
713
+ *
714
+ * - `export * from "./x"`, since a star re-export never carries the default;
715
+ * - a type-only export, in any of its three spellings
716
+ * (`export type { T as default }`, `export { type T as default }` and
717
+ * `export default interface T {}` — the last one parses as a declaration
718
+ * carrying a `default` modifier, exactly like `export default class`, and is
719
+ * the one that looks like a runtime export and is not).
720
+ */
721
+ function findDefaultExport(sourceFile) {
722
+ return sourceFile.statements.find(statement => {
723
+ // `export default <expr>` — but not `export = x`, which shares this node.
724
+ if (ts.isExportAssignment(statement)) {
725
+ return !statement.isExportEquals;
726
+ }
727
+ // `export { x as default }` / `export { default } from "./x"`
728
+ if (ts.isExportDeclaration(statement) && !statement.isTypeOnly && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
729
+ return statement.exportClause.elements.some(element => !element.isTypeOnly && element.name.text === "default");
730
+ }
731
+ // `export default function f() {}` / `export default class C {}`, which are
732
+ // declarations carrying a `default` modifier rather than export assignments.
733
+ // `export default interface T {}` is spelled the same way and is a type, so
734
+ // it is excluded here rather than by the `isTypeOnly` checks above.
735
+ return !ts.isInterfaceDeclaration(statement) && ts.canHaveModifiers(statement) && (ts.getModifiers(statement) ?? []).some(modifier => modifier.kind === ts.SyntaxKind.DefaultKeyword);
736
+ });
737
+ }
738
+
739
+ /** Whether the file exports a runtime value as `default`. */
740
+ function hasDefaultExport(sourceFile) {
741
+ return findDefaultExport(sourceFile) !== undefined;
742
+ }
743
+
744
+ /** A short, human-readable "what you exported instead" for the error message. */
745
+ function describeDefaultExport(value) {
746
+ if (value === null) {
747
+ return "null";
748
+ }
749
+ if (Array.isArray(value)) {
750
+ return "an array";
751
+ }
752
+ if (typeof value === "object") {
753
+ // Duck-typed rather than `instanceof Schema`, for the same cross-realm
754
+ // reason `isValModule` avoids a constructor check.
755
+ if ("executeSerialize" in value && typeof value["executeSerialize"] === "function") {
756
+ return "a schema";
757
+ }
758
+ return "an object";
759
+ }
760
+ if (typeof value === "undefined") {
761
+ return "undefined";
762
+ }
763
+ return `a ${typeof value}`;
764
+ }
765
+ function errorMessage(e) {
766
+ // NOT `e instanceof Error`: an error thrown from inside the `vm` context is
767
+ // built from that realm's Error constructor. Duck-type the message instead.
768
+ if (typeof e === "object" && e !== null && "message" in e) {
769
+ const {
770
+ message
771
+ } = e;
772
+ if (typeof message === "string") {
773
+ return message;
774
+ }
775
+ }
776
+ return String(e);
777
+ }
778
+
779
+ /** What a schema reports about this content: see `schemaErrorsOf`. */
780
+ const validateWith = (schema, moduleFilePath, source) => schemaErrorsOf(schema, moduleFilePath, source);
781
+
782
+ /**
783
+ * A module's errors for this content: its own `validate` where the schema was
784
+ * evaluated, custom rules and all; otherwise what its serialized schema says,
785
+ * which is every rule but a custom `.validate(...)` (a closure does not
786
+ * serialize).
787
+ */
788
+ function validateModule(moduleFilePath, module, source) {
789
+ if (module.validate) return module.validate(source);
790
+ return validateWith(deserializeSchema(module.schema), moduleFilePath, source);
791
+ }
792
+
793
+ /** The errors of a module's own Source: as evaluated where they were, else found here. */
794
+ function errorsOfSource(moduleFilePath, module) {
795
+ return module.errors ?? validateModule(moduleFilePath, module, module.source);
796
+ }
797
+
798
+ /**
799
+ * A project as git holds it: every file's text, by path from the project
800
+ * root. A commit in the world is one of these -- `.val.ts` files, the
801
+ * components that render them, `val.modules.ts` -- and nothing else, the same
802
+ * way a commit on content's line is.
803
+ */
804
+
805
+ /**
806
+ * Where the files are said to be. Nothing is written there: the loader reads
807
+ * through {@link host}, which answers from the files for anything under it and
808
+ * from the disk for everything else, so `@valbuild/core` resolves to the one
809
+ * the tests run on.
810
+ */
811
+ function projectRoot() {
812
+ /*
813
+ * Asked when a project is loaded, never at import: `__dirname` exists only
814
+ * in CommonJS, and this module is imported by Val's server wherever it runs
815
+ * -- in the TanStack example's Vite SSR, which is ESM, a top-level read of
816
+ * it stopped the server from starting. There the app's own directory is
817
+ * where `@valbuild/core` resolves from, which is what a merge in a running
818
+ * app should load.
819
+ */
820
+ const base = typeof __dirname === "string" ? __dirname : process.cwd();
821
+ return path.join(base, "__project__");
822
+ }
823
+ function host(files) {
824
+ const ROOT = projectRoot();
825
+ const byAbs = new Map();
826
+ for (const [file, text] of Object.entries(files)) {
827
+ if (text !== null) byAbs.set(path.join(ROOT, file), text);
828
+ }
829
+ const dirs = new Set();
830
+ for (const file of byAbs.keys()) {
831
+ for (let dir = path.dirname(file); dir.startsWith(ROOT);) {
832
+ dirs.add(dir);
833
+ dir = path.dirname(dir);
834
+ }
835
+ }
836
+ const inProject = p => p === ROOT || p.startsWith(ROOT + path.sep);
837
+ return {
838
+ ...ts.sys,
839
+ fileExists: p => inProject(p) ? byAbs.has(p) : ts.sys.fileExists(p),
840
+ readFile: p => inProject(p) ? byAbs.get(p) : ts.sys.readFile(p),
841
+ directoryExists: p => {
842
+ var _ts$sys$directoryExis, _ts$sys;
843
+ return inProject(p) ? dirs.has(p) : ((_ts$sys$directoryExis = (_ts$sys = ts.sys).directoryExists) === null || _ts$sys$directoryExis === void 0 ? void 0 : _ts$sys$directoryExis.call(_ts$sys, p)) ?? false;
844
+ },
845
+ /*
846
+ * A real project's `tsconfig.json` names its inputs by glob (`include`),
847
+ * and parsing it asks for them: with no listing, every project but one
848
+ * whose config names its files outright failed to load ("No inputs were
849
+ * found"). The project's own files under `dir`, by extension, less what
850
+ * the config excludes by name (`node_modules`, `dist`, ...). Which files
851
+ * are inputs does not decide anything here: only the compiler options
852
+ * are read from the config.
853
+ */
854
+ readDirectory: (dir, extensions, excludes, includes, depth) => {
855
+ if (!inProject(dir)) {
856
+ return ts.sys.readDirectory(dir, extensions, excludes, includes, depth);
857
+ }
858
+ const excluded = new Set((excludes ?? []).map(pattern => pattern.replace(/^\.?\/|\/\*\*.*$/g, "")));
859
+ return [...byAbs.keys()].filter(file => {
860
+ if (file !== dir && !file.startsWith(dir + path.sep)) return false;
861
+ if (extensions !== undefined && !extensions.some(extension => file.endsWith(extension))) {
862
+ return false;
863
+ }
864
+ return !path.relative(dir, file).split(path.sep).some(part => excluded.has(part));
865
+ });
866
+ }
867
+ };
868
+ }
869
+
870
+ /**
871
+ * A module, as the merge needs it: data, so whoever evaluated the project's
872
+ * schemas can hand it over -- Val's loader here and in `val validate`, the
873
+ * builder tab with rolldown -- and the merge itself never runs project code.
874
+ */
875
+
876
+ /** A project at one commit: its files, and its modules as data. */
877
+
878
+ /** A loaded project, as the merge takes it. */
879
+ function projectOf(files, loaded) {
880
+ const modules = {};
881
+ for (const [path, {
882
+ module,
883
+ source,
884
+ entries
885
+ }] of Object.entries(loaded.modules)) {
886
+ const moduleFilePath = path;
887
+ const schema = Internal.getSchema(module);
888
+ if (!schema) continue;
889
+ modules[moduleFilePath] = {
890
+ source,
891
+ schema: schema["executeSerialize"](),
892
+ entries,
893
+ validate: content => validateWith(schema, moduleFilePath, content)
894
+ };
895
+ }
896
+ return {
897
+ files,
898
+ modules
899
+ };
900
+ }
901
+
902
+ /** A module as the project defines it, read by Val's own loader. */
903
+
904
+ /**
905
+ * Loads the project at a commit the way `val validate` does: `val.modules.ts`
906
+ * and every `.val.ts` it imports, transpiled and evaluated
907
+ * (`loadValModules`). So a schema a proposal changed is the schema it changed
908
+ * to, read from the text it wrote.
909
+ */
910
+ async function loadProject(files) {
911
+ const valModules = loadValModules(projectRoot(), host(files));
912
+ const modules = {};
913
+ for (const {
914
+ def
915
+ } of valModules.modules) {
916
+ const module = (await def()).default;
917
+ const id = Internal.getValPath(module);
918
+ if (id === undefined) continue;
919
+ const moduleFilePath = id;
920
+ const text = files[moduleFilePath.slice(1)] ?? null;
921
+ modules[moduleFilePath] = {
922
+ module,
923
+ // The one conversion, as `ValOps.getSources` makes it: a module's
924
+ // Source is JSON once its entries are read (media are plain objects).
925
+ source: deepClone(await Internal.resolveJsonValues(Internal.getSource(module))),
926
+ entries: text === null ? null : entryFilesOf(moduleFilePath, text)
927
+ };
928
+ }
929
+ const sourceFiles = {};
930
+ for (const [file, text] of Object.entries(files)) {
931
+ if (text !== null && (file.endsWith(".val.ts") || file.endsWith(".val.json"))) {
932
+ sourceFiles[file] = text;
933
+ }
934
+ }
935
+ return {
936
+ valModules,
937
+ modules,
938
+ sourceFiles
939
+ };
940
+ }
941
+
942
+ /**
943
+ * A `.jsonValues()` record's entry files, by key, read out of its `.val.ts`
944
+ * (the loaded marker does not carry the path). `null` when it has none.
945
+ */
946
+ function entryFilesOf(moduleFilePath, text) {
947
+ const analysis = valModuleOf(moduleFilePath, text);
948
+ if (analysis === null) return null;
949
+ const entries = analyzeJsonValuesEntries(analysis.source);
950
+ if (entries.size === 0) return null;
951
+ const dir = path.posix.dirname(moduleFilePath.slice(1));
952
+ return Object.fromEntries([...entries].map(([key, {
953
+ importPath
954
+ }]) => [key, path.posix.join(dir, importPath)]));
955
+ }
956
+
957
+ // --- code and content ------------------------------------------------------------
958
+
959
+ /**
960
+ * A file's code: for a `.val.ts`, everything but `c.define`'s content
961
+ * argument, which Val reads at request time (step 2) and so is no part of a
962
+ * build; a `.val.json` entry is no code at all. Every other file is code
963
+ * whole.
964
+ */
965
+ function codeOf(file, text) {
966
+ // A `.jsonValues()` entry is content, read at request time like the rest.
967
+ if (file.endsWith(".val.json")) return "";
968
+ if (!file.endsWith(".val.ts")) return text;
969
+ const analysis = valModuleOf(file, text);
970
+ if (analysis === null) return text;
971
+ const {
972
+ source
973
+ } = analysis;
974
+ return text.slice(0, source.getStart()) + "/* content */" + text.slice(source.end);
975
+ }
976
+
977
+ /**
978
+ * A `.val.ts`'s `c.define(...)`, or `null` when it has none: a file of schemas
979
+ * that pages share (`export const heroSchema = s.object(...)`) is named like a
980
+ * module and is code. `analyzeValModule` throws for one; this does not.
981
+ */
982
+ function valModuleOf(file, text) {
983
+ const sourceFile = ts.createSourceFile(file, text, ts.ScriptTarget.ES2015, true);
984
+ if (!sourceFile.statements.some(node => ts.isExportAssignment(node))) {
985
+ return null;
986
+ }
987
+ const analysis = analyzeValModule(sourceFile);
988
+ return result.isErr(analysis) ? null : analysis.value;
989
+ }
990
+
991
+ /**
992
+ * The three-way merge of a module's content: where both sides started
993
+ * (`base`), and each side's version. Pure JSON -- the schema decides nothing
994
+ * here, and is checked afterwards (the schema check in `merge.ts`).
995
+ *
996
+ * The rules (valbuild/home `docs/hosted-publishing.md` step 8.2):
997
+ *
998
+ * - Changed on one side: that side's.
999
+ * - Changed on both: a conflict -- even to the same value, which is an easy
1000
+ * conflict to resolve but still one somebody decides.
1001
+ * - An object (a page, a record) merges key by key, so two keys changed on
1002
+ * two sides combine.
1003
+ * - A list merges item by item only when neither side changed its shape: no
1004
+ * item added, removed or moved. Otherwise positions mean different items on
1005
+ * the two sides, and the whole list is the conflict.
1006
+ */
1007
+
1008
+ function isObject(value) {
1009
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1010
+ }
1011
+ function same(a, b) {
1012
+ if (a === undefined || b === undefined) return a === b;
1013
+ return deepEqual(a, b);
1014
+ }
1015
+
1016
+ /**
1017
+ * Did this side add, remove or move an item? Lengths differ, or an item now
1018
+ * sits where it was not, while it is still what used to be somewhere else.
1019
+ */
1020
+ function reshaped(base, side) {
1021
+ if (base.length !== side.length) return true;
1022
+ return side.some((item, at) => !same(item, base[at]) && base.some((was, from) => from !== at && same(item, was)));
1023
+ }
1024
+
1025
+ /**
1026
+ * Where a value is one value, though it is an object: a media value (its path
1027
+ * and what describes that file) or rich text. The schema says; see `merge.ts`.
1028
+ */
1029
+
1030
+ function mergeValues(base, site, proposal, atomic = () => false, path = []) {
1031
+ if (same(site, base)) return {
1032
+ value: proposal,
1033
+ conflicts: []
1034
+ };
1035
+ if (same(proposal, base)) return {
1036
+ value: site,
1037
+ conflicts: []
1038
+ };
1039
+ if (atomic(path)) {
1040
+ return {
1041
+ value: site,
1042
+ conflicts: [{
1043
+ path,
1044
+ base,
1045
+ site,
1046
+ proposal
1047
+ }]
1048
+ };
1049
+ }
1050
+ if (isObject(base) && isObject(site) && isObject(proposal)) {
1051
+ const keys = [...new Set([...Object.keys(site), ...Object.keys(proposal), ...Object.keys(base)])];
1052
+ const value = {};
1053
+ const conflicts = [];
1054
+ for (const key of keys) {
1055
+ const merged = mergeValues(base[key], site[key], proposal[key], atomic, [...path, key]);
1056
+ if (merged.value !== undefined) value[key] = merged.value;
1057
+ conflicts.push(...merged.conflicts);
1058
+ }
1059
+ return {
1060
+ value,
1061
+ conflicts
1062
+ };
1063
+ }
1064
+ if (Array.isArray(base) && Array.isArray(site) && Array.isArray(proposal) && !reshaped(base, site) && !reshaped(base, proposal)) {
1065
+ const value = [];
1066
+ const conflicts = [];
1067
+ base.forEach((item, at) => {
1068
+ const merged = mergeValues(item, site[at], proposal[at], atomic, [...path, String(at)]);
1069
+ // Neither side removed an item, so every position holds one.
1070
+ value.push(merged.value ?? null);
1071
+ conflicts.push(...merged.conflicts);
1072
+ });
1073
+ return {
1074
+ value,
1075
+ conflicts
1076
+ };
1077
+ }
1078
+ return {
1079
+ value: site,
1080
+ conflicts: [{
1081
+ path,
1082
+ base,
1083
+ site,
1084
+ proposal
1085
+ }]
1086
+ };
1087
+ }
1088
+
1089
+ /** `doc` with `value` at `path`; `undefined` removes it. `doc` is not changed. */
1090
+ function setAt(doc, path, value) {
1091
+ if (path.length === 0) return value;
1092
+ const [head, ...rest] = path;
1093
+ if (Array.isArray(doc)) {
1094
+ const copy = [...doc];
1095
+ const at = Number(head);
1096
+ const next = setAt(copy[at], rest, value);
1097
+ if (next === undefined) copy.splice(at, 1);else copy[at] = next;
1098
+ return copy;
1099
+ }
1100
+ const copy = isObject(doc) ? {
1101
+ ...doc
1102
+ } : {};
1103
+ const next = setAt(copy[head], rest, value);
1104
+ if (next === undefined) delete copy[head];else copy[head] = next;
1105
+ return copy;
1106
+ }
1107
+ function valueAt(doc, path) {
1108
+ let current = doc;
1109
+ for (const key of path) {
1110
+ if (Array.isArray(current)) current = current[Number(key)];else if (isObject(current)) current = current[key];else return undefined;
1111
+ }
1112
+ return current;
1113
+ }
1114
+
1115
+ /**
1116
+ * The Val patch that turns `from` into `to`, as small as it can be: what
1117
+ * writes a merge into a `.val.ts` without rewriting what did not change.
1118
+ */
1119
+ function diffOps(from, to, path = []) {
1120
+ if (same(from, to)) return [];
1121
+ if (isObject(from) && isObject(to)) {
1122
+ const ops = [];
1123
+ for (const key of Object.keys(from)) {
1124
+ if (!(key in to)) ops.push({
1125
+ op: "remove",
1126
+ path: below(path, key)
1127
+ });
1128
+ }
1129
+ for (const [key, value] of Object.entries(to)) {
1130
+ ops.push(...(key in from ? diffOps(from[key], value, [...path, key]) : [add([...path, key], value)]));
1131
+ }
1132
+ return ops;
1133
+ }
1134
+ if (Array.isArray(from) && Array.isArray(to) && from.length === to.length) {
1135
+ return from.flatMap((item, at) => diffOps(item, to[at], [...path, String(at)]));
1136
+ }
1137
+ return [{
1138
+ op: "replace",
1139
+ path,
1140
+ value: to ?? null
1141
+ }];
1142
+ }
1143
+ function add(path, value) {
1144
+ return {
1145
+ op: "add",
1146
+ path,
1147
+ value
1148
+ };
1149
+ }
1150
+ function below(path, key) {
1151
+ return path.length === 0 ? [key] : [path[0], ...path.slice(1), key];
1152
+ }
1153
+
1154
+ /**
1155
+ * Publishing a proposal as a pull request is merged: valbuild/home
1156
+ * `docs/hosted-publishing.md`, step 8.2.
1157
+ *
1158
+ * Val's half: the two answers that need a schema. Content gets them as files
1159
+ * and change ids and carries them out, never looking at a field, a list or a
1160
+ * patch set.
1161
+ *
1162
+ * - {@link mergeFromSite} -- Update from the site: the merge commit `M`.
1163
+ * - {@link changesToMove} -- which of the site's pending changes leave the
1164
+ * site when a proposal is merged.
1165
+ *
1166
+ * `mergeScenarios.test.ts` is their specification.
1167
+ */
1168
+
1169
+ /** A field both sides changed since the proposal started. */
1170
+
1171
+ /**
1172
+ * Code both sides changed: a component, `val.modules.ts`, or the schema of a
1173
+ * `.val.ts` (its code -- everything but `c.define`'s content argument, whose
1174
+ * fields merge on their own).
1175
+ */
1176
+
1177
+ /**
1178
+ * The schema check: content that merged cleanly and is not valid under the
1179
+ * schema the merge ends with -- an entry the site added, say, under a field
1180
+ * whose type the proposal changed.
1181
+ */
1182
+
1183
+ /** How a conflict is resolved: keep one side, or write it -- as AI or a developer does. */
1184
+
1185
+ /**
1186
+ * Update from the site: a three-way merge of where the proposal started
1187
+ * (`base`), the site's head and the proposal's last save, written whole.
1188
+ * Every conflict needs a resolution, or nothing is merged.
1189
+ *
1190
+ * File by file. A file that is not a `.val.ts` is code, and merges as a
1191
+ * file: changed on one side, that side's; on both, a conflict. A `.val.ts`
1192
+ * is code (everything but `c.define`'s content argument) and content, and the
1193
+ * two merge apart: the code as a file, the content field by field
1194
+ * (`mergeValues`). So a schema the proposal changed and a field the site
1195
+ * published in the same file do not conflict. A code conflict in a `.val.ts`
1196
+ * is resolved by keeping a side's code -- the content still merges -- or by
1197
+ * writing the whole file.
1198
+ *
1199
+ * Not here: the schema check ({@link schemaCheck}). It needs the merged
1200
+ * files' schemas, so whoever can evaluate them -- Val's loader, the builder
1201
+ * tab -- runs it on `files` before the merge is committed.
1202
+ */
1203
+ function mergeFromSite(input) {
1204
+ const {
1205
+ base,
1206
+ site,
1207
+ proposal,
1208
+ resolutions
1209
+ } = input;
1210
+ const files = {};
1211
+ const modules = {};
1212
+ const conflicts = [];
1213
+ const paths = [...new Set([...Object.keys(base.files), ...Object.keys(site.files), ...Object.keys(proposal.files)])].sort();
1214
+ // A `.jsonValues()` entry is written with its module, never on its own.
1215
+ const entryFiles = new Set([base, site, proposal].flatMap(side => Object.values(side.modules).flatMap(module => Object.values(module.entries ?? {}))));
1216
+ for (const file of paths) {
1217
+ var _moduleOf3, _moduleOf4, _moduleOf5, _moduleOf6;
1218
+ if (entryFiles.has(file)) continue;
1219
+ const b = base.files[file] ?? null;
1220
+ const s = site.files[file] ?? null;
1221
+ const p = proposal.files[file] ?? null;
1222
+ const resolution = fileResolution(resolutions, file);
1223
+ const codeConflict = () => ({
1224
+ kind: "code",
1225
+ file,
1226
+ base: b,
1227
+ site: s,
1228
+ proposal: p
1229
+ });
1230
+
1231
+ // A file named like a module that no side defines as one -- schemas the
1232
+ // pages share -- is code.
1233
+ const moduleFilePath = `/${file}`;
1234
+ const isModule = [base, site, proposal].some(side => side.modules[moduleFilePath] !== undefined);
1235
+ if (!file.endsWith(".val.ts") || !isModule) {
1236
+ if (s === b) files[file] = p;else if (p === b) files[file] = s;else if (resolution) files[file] = resolvedText(resolution, s, p);else {
1237
+ conflicts.push(codeConflict());
1238
+ files[file] = s;
1239
+ }
1240
+ continue;
1241
+ }
1242
+
1243
+ // A .val.ts: whose code, then the content under it.
1244
+ const code = text => text === null ? null : codeOf(file, text);
1245
+ let side;
1246
+ if (code(s) === code(b)) side = "proposal";else if (code(p) === code(b)) side = "site";else if (resolution && "text" in resolution) {
1247
+ files[file] = resolution.text;
1248
+ continue;
1249
+ } else if (resolution) side = resolution.keep;else {
1250
+ conflicts.push(codeConflict());
1251
+ files[file] = s;
1252
+ continue;
1253
+ }
1254
+ const moduleOf = project => project.modules[moduleFilePath];
1255
+ const sourceOf = project => {
1256
+ var _moduleOf;
1257
+ return (_moduleOf = moduleOf(project)) === null || _moduleOf === void 0 ? void 0 : _moduleOf.source;
1258
+ };
1259
+ const chosen = side === "site" ? site : proposal;
1260
+ const text = side === "site" ? s : p;
1261
+ if (text === null) {
1262
+ // That side deleted the file. Content the other side changed would go
1263
+ // with it: that is for a person to decide -- unless they have.
1264
+ const other = side === "site" ? p : s;
1265
+ if (!resolution && other !== b) {
1266
+ conflicts.push(codeConflict());
1267
+ }
1268
+ files[file] = null;
1269
+ for (const project of [base, site, proposal]) {
1270
+ for (const entry of Object.values(((_moduleOf2 = moduleOf(project)) === null || _moduleOf2 === void 0 ? void 0 : _moduleOf2.entries) ?? {})) {
1271
+ var _moduleOf2;
1272
+ files[entry] = null;
1273
+ }
1274
+ }
1275
+ continue;
1276
+ }
1277
+ // What the chosen text holds, which the merge is written over.
1278
+ const from = ((_moduleOf3 = moduleOf(chosen)) === null || _moduleOf3 === void 0 ? void 0 : _moduleOf3.written) ?? ((_moduleOf4 = moduleOf(chosen)) === null || _moduleOf4 === void 0 ? void 0 : _moduleOf4.source);
1279
+ const merged = mergeValues(sourceOf(base), sourceOf(site), sourceOf(proposal), atomicFor((_moduleOf5 = moduleOf(chosen)) === null || _moduleOf5 === void 0 ? void 0 : _moduleOf5.schema));
1280
+ const resolved = resolveContent(moduleFilePath, merged, resolutions);
1281
+ conflicts.push(...resolved.unresolved);
1282
+ const content = resolved.content;
1283
+ modules[moduleFilePath] = content;
1284
+ const entries = (_moduleOf6 = moduleOf(chosen)) === null || _moduleOf6 === void 0 ? void 0 : _moduleOf6.entries;
1285
+ if (entries) {
1286
+ var _moduleOf7, _moduleOf8;
1287
+ 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]));
1288
+ } else {
1289
+ files[file] = writeContent(file, text, from, content);
1290
+ }
1291
+ }
1292
+ if (conflicts.length > 0) return {
1293
+ status: "conflicts",
1294
+ conflicts
1295
+ };
1296
+ return {
1297
+ status: "merged",
1298
+ files,
1299
+ modules,
1300
+ code: Object.keys(files).filter(file => {
1301
+ const text = files[file];
1302
+ const before = site.files[file] ?? null;
1303
+ if (text === null || before === null) return text !== before;
1304
+ return codeOf(file, text) !== codeOf(file, before);
1305
+ })
1306
+ };
1307
+ }
1308
+
1309
+ /** A change pending on the site, in chain order. */
1310
+
1311
+ /**
1312
+ * The site's pending changes that conflict with going from `site` to
1313
+ * `merged`, as whole patch sets: each inner list moves together, into a
1314
+ * proposal of its own. Everything else stays pending.
1315
+ *
1316
+ * Patch sets are the Studio's own (`PatchSets`), from the schema the changes
1317
+ * were written against; sets that share a change are one, because a change
1318
+ * cannot be split. A set moves when, taken as the site's side of a three-way
1319
+ * merge with the merged commit as the other, it conflicts (`mergeValues`, so
1320
+ * the same value on both sides moves too); or when it no longer applies to
1321
+ * the merged commit, or leaves it invalid under the merged schema.
1322
+ */
1323
+ function changesToMove(input) {
1324
+ const {
1325
+ site,
1326
+ merged,
1327
+ pending
1328
+ } = input;
1329
+ const sets = new PatchSets();
1330
+ for (const change of pending) {
1331
+ var _site$modules$change$;
1332
+ 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);
1333
+ }
1334
+ const groups = joinSharedChanges(sets.serialize().map(set => set.patches.map(p => p.patchId)));
1335
+ const moves = [];
1336
+ for (const group of groups) {
1337
+ const changes = pending.filter(change => group.has(change.patchId));
1338
+ if (conflictsWithMerge(changes, site, merged)) {
1339
+ moves.push(changes.map(change => change.patchId));
1340
+ }
1341
+ }
1342
+ // In chain order, so the moved proposals are opened in the order the
1343
+ // changes were written.
1344
+ const order = ids => pending.findIndex(change => change.patchId === ids[0]);
1345
+ return moves.sort((a, b) => order(a) - order(b));
1346
+ }
1347
+
1348
+ // --- the pieces --------------------------------------------------------------
1349
+
1350
+ /**
1351
+ * A module's merged content with the resolutions written in: each field
1352
+ * conflict that has one, and any value written for the schema check (or
1353
+ * anywhere else) as given. What is left is what still needs a person.
1354
+ */
1355
+ function resolveContent(moduleFilePath, merged, resolutions) {
1356
+ let content = merged.value;
1357
+ const unresolved = [];
1358
+ for (const conflict of merged.conflicts) {
1359
+ const resolved = fieldResolution(resolutions, moduleFilePath, conflict);
1360
+ if (resolved === null) {
1361
+ unresolved.push({
1362
+ kind: "field",
1363
+ moduleFilePath,
1364
+ ...conflict
1365
+ });
1366
+ } else {
1367
+ content = setAt(content, conflict.path, resolved.value);
1368
+ }
1369
+ }
1370
+ for (const resolution of resolutions) {
1371
+ if ("moduleFilePath" in resolution && resolution.moduleFilePath === moduleFilePath && "value" in resolution && !merged.conflicts.some(c => samePath(c.path, resolution.path))) {
1372
+ content = setAt(content, resolution.path, resolution.value);
1373
+ }
1374
+ }
1375
+ return {
1376
+ content,
1377
+ unresolved
1378
+ };
1379
+ }
1380
+ function conflictsWithMerge(changes, site, merged) {
1381
+ const modules = [...new Set(changes.map(change => change.moduleFilePath))];
1382
+ for (const moduleFilePath of modules) {
1383
+ var _site$modules$moduleF;
1384
+ const ops = changes.filter(change => change.moduleFilePath === moduleFilePath).flatMap(change => change.patch).filter(op => op.op !== "file");
1385
+ const before = (_site$modules$moduleF = site.modules[moduleFilePath]) === null || _site$modules$moduleF === void 0 ? void 0 : _site$modules$moduleF.source;
1386
+ const after = merged.modules[moduleFilePath];
1387
+ if (before === undefined || after === undefined) return true;
1388
+ const written = apply(before, ops);
1389
+ if (written === undefined) return true;
1390
+ const mergedSource = after.source;
1391
+ const atomic = atomicFor(after.schema);
1392
+ if (mergeValues(before, written, mergedSource, atomic).conflicts.length) {
1393
+ return true;
1394
+ }
1395
+ // Over the merged commit: it applies, and is as valid as it was.
1396
+ const over = apply(mergedSource, ops);
1397
+ if (over === undefined) return true;
1398
+ const known = new Set(errorPaths(moduleFilePath, after, mergedSource));
1399
+ if (errorPaths(moduleFilePath, after, over).some(path => !known.has(path))) {
1400
+ return true;
1401
+ }
1402
+ }
1403
+ return false;
1404
+ }
1405
+ function apply(source, ops) {
1406
+ if (source === undefined) return undefined;
1407
+ const applied = applyPatch(deepClone(source), new JSONOps(), ops);
1408
+ return result.isOk(applied) ? applied.value : undefined;
1409
+ }
1410
+ function errorPaths(moduleFilePath, module, source) {
1411
+ return validateModule(moduleFilePath, module, source).map(error => error.path.join("/"));
1412
+ }
1413
+
1414
+ /**
1415
+ * The schema check of a merge: content in `merged` -- the project
1416
+ * {@link mergeFromSite} wrote, with its schemas evaluated -- that is invalid
1417
+ * under the schema it ends with, leaving out what was already invalid on a
1418
+ * side. A conflict, each; a resolution with a value for one is written into
1419
+ * the content by the merge, and so is checked here.
1420
+ */
1421
+ function schemaCheck(merged, sides) {
1422
+ const conflicts = [];
1423
+ for (const [path, module] of Object.entries(merged.modules)) {
1424
+ const moduleFilePath = path;
1425
+ const known = new Set(sides.flatMap(side => {
1426
+ const there = side.modules[moduleFilePath];
1427
+ return there ? errorsOfSource(moduleFilePath, there).map(e => e.path.join("/")) : [];
1428
+ }));
1429
+ for (const error of errorsOfSource(moduleFilePath, module)) {
1430
+ if (known.has(error.path.join("/"))) continue;
1431
+ conflicts.push({
1432
+ kind: "invalid",
1433
+ moduleFilePath,
1434
+ path: error.path,
1435
+ value: valueAt(module.source, error.path),
1436
+ message: error.message
1437
+ });
1438
+ }
1439
+ }
1440
+ return conflicts;
1441
+ }
1442
+
1443
+ /**
1444
+ * The values that merge whole, though they are objects: media (an image's
1445
+ * alt text describes that image, not another) and rich text.
1446
+ */
1447
+ const ATOMIC = new Set(["image", "file", "video", "font", "richtext"]);
1448
+
1449
+ /** See {@link ATOMIC}: where this schema holds a value that merges whole. */
1450
+ function atomicFor(schema) {
1451
+ if (!schema) return () => false;
1452
+ return path => {
1453
+ const types = schemaTypesOfPath(schema, path);
1454
+ return [...types].some(type => ATOMIC.has(type));
1455
+ };
1456
+ }
1457
+ const tsOps = new TSOps(document => pipe(analyzeValModule(document), result.map(({
1458
+ source
1459
+ }) => source)));
1460
+
1461
+ /**
1462
+ * `content` written into the `.val.ts` `text`, whose content is `from`: as
1463
+ * the smallest patch, through the same AST operations a save uses, so what
1464
+ * did not change is left exactly as it was.
1465
+ */
1466
+ function writeContent(file, text, from, content) {
1467
+ const ops = diffOps(from, content);
1468
+ if (ops.length === 0) return text;
1469
+ const sourceFile = ts.createSourceFile(file, text, ts.ScriptTarget.ES2015, true);
1470
+ return printed(unwrap(file, applyPatch(sourceFile, tsOps, ops)));
1471
+ }
1472
+
1473
+ /**
1474
+ * A `.jsonValues()` module, written as its files: the `.val.ts` names the
1475
+ * entries -- one added gets a `c.json(...)` line, as a save writes it, one
1476
+ * removed loses its line -- and each entry is its own `.val.json`. An entry
1477
+ * whose content did not change keeps its file's text exactly.
1478
+ */
1479
+ function writeEntries(file, text, chosenFiles, entries, from, content, others) {
1480
+ const written = {};
1481
+ const before = isRecord(from) ? from : {};
1482
+ const after = isRecord(content) ? content : {};
1483
+ const moduleDir = path.posix.dirname(file);
1484
+ let sourceFile = ts.createSourceFile(file, text, ts.ScriptTarget.ES2015, true);
1485
+ for (const key of Object.keys(before)) {
1486
+ if (key in after) continue;
1487
+ sourceFile = unwrap(file, removeValJsonEntry(sourceFile, [], key));
1488
+ written[entries[key]] = null;
1489
+ }
1490
+ for (const [key, value] of Object.entries(after)) {
1491
+ const entryFile = entries[key] ?? others.map(other => other === null || other === void 0 ? void 0 : other[key]).find(f => f !== undefined) ?? path.posix.join(moduleDir, path.posix.basename(file, ".val.ts"), `${key}.val.json`);
1492
+ if (!(key in before)) {
1493
+ const importPath = `./${path.posix.relative(moduleDir, entryFile)}`;
1494
+ sourceFile = unwrap(file, insertValJsonEntry(sourceFile, [], key, importPath));
1495
+ }
1496
+ const kept = chosenFiles[entryFile];
1497
+ written[entryFile] = key in before && diffOps(before[key], value).length === 0 && kept ? kept : JSON.stringify(value, null, 2);
1498
+ }
1499
+ written[file] = printed(sourceFile);
1500
+ return written;
1501
+ }
1502
+
1503
+ /**
1504
+ * What the AST operations said, in words: a `PatchError` or `Error` has a
1505
+ * message, a syntax error tree has one per node. `String()` of either is
1506
+ * `[object Object]`.
1507
+ */
1508
+ function writeErrorText(error) {
1509
+ if (error instanceof Error) return error.message;
1510
+ if (isSyntaxErrorTree(error)) {
1511
+ return flatMapErrors(error, e => e.message).join("; ");
1512
+ }
1513
+ if (typeof error === "object" && error !== null && "message" in error) {
1514
+ return String(error.message);
1515
+ }
1516
+ return String(error);
1517
+ }
1518
+ function isSyntaxErrorTree(error) {
1519
+ if (error instanceof ValSyntaxError) return true;
1520
+ return Array.isArray(error) && error.length > 0 && error.every(isSyntaxErrorTree);
1521
+ }
1522
+ function isRecord(value) {
1523
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1524
+ }
1525
+ function unwrap(file, written) {
1526
+ if (result.isErr(written)) {
1527
+ throw new Error(`could not write the merge into ${file}: ${writeErrorText(written.error)}`);
1528
+ }
1529
+ return written.value;
1530
+ }
1531
+
1532
+ /** As `prepare` prints: TypeScript escapes non-ASCII as \\u sequences. */
1533
+ function printed(sourceFile) {
1534
+ return unescape(sourceFile.getText(sourceFile).replace(/\\u/g, "%u"));
1535
+ }
1536
+ function fileResolution(resolutions, file) {
1537
+ for (const resolution of resolutions) {
1538
+ if ("file" in resolution && resolution.file === file) return resolution;
1539
+ }
1540
+ return null;
1541
+ }
1542
+ function resolvedText(resolution, site, proposal) {
1543
+ if ("text" in resolution) return resolution.text;
1544
+ return resolution.keep === "site" ? site : proposal;
1545
+ }
1546
+
1547
+ /** A field conflict's resolution, as the value it leaves; `null` when it has none. */
1548
+ function fieldResolution(resolutions, moduleFilePath, conflict) {
1549
+ for (const resolution of resolutions) {
1550
+ if (!("moduleFilePath" in resolution) || resolution.moduleFilePath !== moduleFilePath || !samePath(resolution.path, conflict.path)) {
1551
+ continue;
1552
+ }
1553
+ if ("value" in resolution) return {
1554
+ value: resolution.value
1555
+ };
1556
+ return {
1557
+ value: resolution.keep === "site" ? conflict.site : conflict.proposal
1558
+ };
1559
+ }
1560
+ return null;
1561
+ }
1562
+ function samePath(a, b) {
1563
+ return a.length === b.length && a.every((key, at) => key === b[at]);
1564
+ }
1565
+
1566
+ export { TSOps as T, createValModuleFileInspector as a, resolveContent as b, createNodeRequire as c, diffOps as d, valueAt as e, findDefaultExport as f, getCompilerOptions as g, atomicFor as h, insertValJsonEntry as i, mergeFromSite as j, entryFilesOf as k, loadValModules as l, mergeValues as m, changesToMove as n, loadProject as o, projectOf as p, writeEntries as q, removeValJsonEntry as r, schemaCheck as s, validateWith as v, writeContent as w };