@valbuild/server 0.146.4 → 0.147.0

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 (37) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/browser/dist/valbuild-server-browser.cjs.d.ts +2 -0
  3. package/browser/dist/valbuild-server-browser.cjs.dev.js +146 -0
  4. package/browser/dist/valbuild-server-browser.cjs.js +7 -0
  5. package/browser/dist/valbuild-server-browser.cjs.prod.js +146 -0
  6. package/browser/dist/valbuild-server-browser.esm.js +142 -0
  7. package/browser/package.json +4 -0
  8. package/dist/ValRouterCore-3fd3d444.cjs.dev.js +9897 -0
  9. package/dist/ValRouterCore-7ffcc08c.cjs.prod.js +9897 -0
  10. package/dist/ValRouterCore-f5004f8f.esm.js +9866 -0
  11. package/dist/declarations/src/ValOps.d.ts +13 -1
  12. package/dist/declarations/src/ValOpsFS.d.ts +1 -0
  13. package/dist/declarations/src/ValOpsHttp.d.ts +1 -0
  14. package/dist/declarations/src/ValOpsMemory.d.ts +9 -0
  15. package/dist/declarations/src/ValRouter.d.ts +1 -1
  16. package/dist/declarations/src/ValServer.d.ts +9 -2
  17. package/dist/declarations/src/browser/inTabFetch.d.ts +27 -0
  18. package/dist/declarations/src/browser/index.d.ts +9 -0
  19. package/dist/declarations/src/fixHandlers.d.ts +1 -1
  20. package/dist/declarations/src/linkCheck/probeUrl.d.ts +40 -0
  21. package/dist/declarations/src/platform.d.ts +39 -0
  22. package/dist/getJsonEntryAtCommit-1e08d724.esm.js +136 -0
  23. package/dist/getJsonEntryAtCommit-df65d861.cjs.prod.js +143 -0
  24. package/dist/getJsonEntryAtCommit-e96beb9e.cjs.dev.js +143 -0
  25. package/dist/jsonValuesModule-427d68c8.esm.js +273 -0
  26. package/dist/jsonValuesModule-8ae503a8.cjs.dev.js +288 -0
  27. package/dist/jsonValuesModule-d1bb8d8f.cjs.prod.js +288 -0
  28. package/dist/ops-0d05feaf.esm.js +353 -0
  29. package/dist/ops-b15239ac.cjs.prod.js +361 -0
  30. package/dist/ops-f37d18c6.cjs.dev.js +361 -0
  31. package/dist/publishKit-580f558a.cjs.prod.js +41 -0
  32. package/dist/publishKit-5865095c.cjs.dev.js +41 -0
  33. package/dist/publishKit-bc8df53d.esm.js +31 -0
  34. package/dist/valbuild-server.cjs.dev.js +7902 -18215
  35. package/dist/valbuild-server.cjs.prod.js +7902 -18215
  36. package/dist/valbuild-server.esm.js +7758 -18070
  37. package/package.json +18 -5
@@ -0,0 +1,288 @@
1
+ 'use strict';
2
+
3
+ var ts = require('typescript');
4
+ var fp = require('@valbuild/core/fp');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
7
+
8
+ var ts__default = /*#__PURE__*/_interopDefault(ts);
9
+
10
+ class ValSyntaxError {
11
+ constructor(message, node) {
12
+ this.message = message;
13
+ this.node = node;
14
+ }
15
+ }
16
+ function forEachError(tree, callback) {
17
+ if (Array.isArray(tree)) {
18
+ for (const subtree of tree) {
19
+ forEachError(subtree, callback);
20
+ }
21
+ } else {
22
+ callback(tree);
23
+ }
24
+ }
25
+ function flatMapErrors(tree, cb) {
26
+ const result = [];
27
+ forEachError(tree, error => result.push(cb(error)));
28
+ return result;
29
+ }
30
+ function formatSyntaxError(error, sourceFile) {
31
+ const pos = sourceFile.getLineAndCharacterOfPosition(error.node.pos);
32
+ return `${pos.line}:${pos.character} ${error.message}`;
33
+ }
34
+ function formatSyntaxErrorTree(tree, sourceFile) {
35
+ return flatMapErrors(tree, error => formatSyntaxError(error, sourceFile));
36
+ }
37
+ function isLiteralPropertyName(name) {
38
+ return ts__default["default"].isIdentifier(name) || ts__default["default"].isStringLiteral(name) || ts__default["default"].isNumericLiteral(name);
39
+ }
40
+ function validateObjectProperties(nodes) {
41
+ const errors = [];
42
+ for (const node of nodes) {
43
+ if (!ts__default["default"].isPropertyAssignment(node)) {
44
+ errors.push(new ValSyntaxError("Object literal element must be property assignment", node));
45
+ } else if (!isLiteralPropertyName(node.name)) {
46
+ errors.push(new ValSyntaxError("Object literal element key must be an identifier or a literal", node));
47
+ }
48
+ }
49
+ if (errors.length > 0) {
50
+ return fp.result.err(errors);
51
+ }
52
+ return fp.result.ok(nodes);
53
+ }
54
+
55
+ /**
56
+ * Validates that the expression is a JSON compatible type of expression without
57
+ * validating its children.
58
+ */
59
+ function shallowValidateExpression(value) {
60
+ return ts__default["default"].isStringLiteralLike(value) || ts__default["default"].isNumericLiteral(value) || value.kind === ts__default["default"].SyntaxKind.TrueKeyword || value.kind === ts__default["default"].SyntaxKind.FalseKeyword || value.kind === ts__default["default"].SyntaxKind.NullKeyword || ts__default["default"].isArrayLiteralExpression(value) || ts__default["default"].isObjectLiteralExpression(value) ? undefined : new ValSyntaxError("Expression must be a literal", value);
61
+ }
62
+
63
+ /**
64
+ * Evaluates the expression as a JSON value
65
+ */
66
+ function evaluateExpression(value) {
67
+ // The text property of a LiteralExpression stores the interpreted value of the literal in text form. For a StringLiteral,
68
+ // or any literal of a template, this means quotes have been removed and escapes have been converted to actual characters.
69
+ // For a NumericLiteral, the stored value is the toString() representation of the number. For example 1, 1.00, and 1e0 are all stored as just "1".
70
+ // https://github.com/microsoft/TypeScript/blob/4b794fe1dd0d184d3f8f17e94d8187eace57c91e/src/compiler/types.ts#L2127-L2131
71
+
72
+ if (ts__default["default"].isStringLiteralLike(value)) {
73
+ return fp.result.ok(value.text);
74
+ } else if (ts__default["default"].isNumericLiteral(value)) {
75
+ return fp.result.ok(Number(value.text));
76
+ } else if (value.kind === ts__default["default"].SyntaxKind.TrueKeyword) {
77
+ return fp.result.ok(true);
78
+ } else if (value.kind === ts__default["default"].SyntaxKind.FalseKeyword) {
79
+ return fp.result.ok(false);
80
+ } else if (value.kind === ts__default["default"].SyntaxKind.NullKeyword) {
81
+ return fp.result.ok(null);
82
+ } else if (ts__default["default"].isArrayLiteralExpression(value)) {
83
+ return fp.result.all(value.elements.map(evaluateExpression));
84
+ } else if (ts__default["default"].isObjectLiteralExpression(value)) {
85
+ return fp.pipe(validateObjectProperties(value.properties), fp.result.flatMap(assignments => fp.pipe(assignments.map(assignment => fp.pipe(evaluateExpression(assignment.initializer), fp.result.map(value => [assignment.name.text, value]))), fp.result.all)), fp.result.map(Object.fromEntries));
86
+ } else {
87
+ return fp.result.err(new ValSyntaxError("Expression must be a literal", value));
88
+ }
89
+ }
90
+ function findObjectPropertyAssignment(value, key) {
91
+ return fp.pipe(validateObjectProperties(value.properties), fp.result.flatMap(assignments => {
92
+ const matchingAssignments = assignments.filter(assignment => assignment.name.text === key);
93
+ if (matchingAssignments.length === 0) return fp.result.ok(undefined);
94
+ if (matchingAssignments.length > 1) {
95
+ return fp.result.err(new ValSyntaxError(`Object key "${key}" is ambiguous`, value));
96
+ }
97
+ const [assignment] = matchingAssignments;
98
+ return fp.result.ok(assignment);
99
+ }));
100
+ }
101
+ function validateInitializers(nodes) {
102
+ for (const node of nodes) {
103
+ if (ts__default["default"].isSpreadElement(node)) {
104
+ return new ValSyntaxError("Unexpected spread element", node);
105
+ }
106
+ }
107
+ return undefined;
108
+ }
109
+
110
+ function isPath(node, path) {
111
+ let currentNode = node;
112
+ for (let i = path.length - 1; i > 0; --i) {
113
+ const name = path[i];
114
+ if (!ts__default["default"].isPropertyAccessExpression(currentNode)) {
115
+ return false;
116
+ }
117
+ if (!ts__default["default"].isIdentifier(currentNode.name) || currentNode.name.text !== name) {
118
+ return false;
119
+ }
120
+ currentNode = currentNode.expression;
121
+ }
122
+ return ts__default["default"].isIdentifier(currentNode) && currentNode.text === path[0];
123
+ }
124
+ function validateArguments(node, validators) {
125
+ return fp.result.allV([node.arguments.length === validators.length ? fp.result.voidOk : fp.result.err(new ValSyntaxError(`Expected ${validators.length} arguments`, node)), ...node.arguments.slice(0, validators.length).map((argument, index) => validators[index](argument))]);
126
+ }
127
+ function analyzeDefaultExport(node) {
128
+ const cDefine = node.expression;
129
+ if (!ts__default["default"].isCallExpression(cDefine)) {
130
+ return fp.result.err(new ValSyntaxError("Expected default expression to be a call expression", cDefine));
131
+ }
132
+ if (!isPath(cDefine.expression, ["c", "define"])) {
133
+ return fp.result.err(new ValSyntaxError("Expected default expression to be calling c.define", cDefine.expression));
134
+ }
135
+ return fp.pipe(validateArguments(cDefine, [id => {
136
+ // TODO: validate ID value here?
137
+ if (!ts__default["default"].isStringLiteralLike(id)) {
138
+ return fp.result.err(new ValSyntaxError("Expected first argument to c.define to be a string literal", id));
139
+ }
140
+ return fp.result.voidOk;
141
+ }, () => {
142
+ return fp.result.voidOk;
143
+ }, () => {
144
+ return fp.result.voidOk;
145
+ }]), fp.result.map(() => {
146
+ const [, schema, source] = cDefine.arguments;
147
+ return {
148
+ schema,
149
+ source
150
+ };
151
+ }));
152
+ }
153
+ function analyzeValModule(sourceFile) {
154
+ const analysis = sourceFile.forEachChild(node => {
155
+ if (ts__default["default"].isExportAssignment(node)) {
156
+ return analyzeDefaultExport(node);
157
+ }
158
+ });
159
+ if (!analysis) {
160
+ throw Error("Failed to find fixed content node in val module");
161
+ }
162
+ return analysis;
163
+ }
164
+
165
+ /**
166
+ * Given the `source` object-literal expression of a `.jsonValues()` record /
167
+ * router (the 3rd argument to `c.define`, via {@link analyzeValModule}),
168
+ * extracts each entry's `c.json(() => import("..."))` import path, keyed by
169
+ * entry key. Entries whose value is not a `c.json(...)` call are skipped.
170
+ */
171
+ function analyzeJsonValuesEntries(source) {
172
+ const entries = new Map();
173
+ if (!ts__default["default"].isObjectLiteralExpression(source)) {
174
+ return entries;
175
+ }
176
+ for (const prop of source.properties) {
177
+ if (!ts__default["default"].isPropertyAssignment(prop)) {
178
+ continue;
179
+ }
180
+ const key = getPropertyKey(prop.name);
181
+ if (key === null) {
182
+ continue;
183
+ }
184
+ const entry = analyzeCJsonCall(prop.initializer);
185
+ if (entry) {
186
+ entries.set(key, entry);
187
+ }
188
+ }
189
+ return entries;
190
+ }
191
+
192
+ /**
193
+ * Every key of a `.jsonValues()` record's source literal, thunked or not.
194
+ *
195
+ * {@link analyzeJsonValuesEntries} answers "which entries have a file behind
196
+ * them", which is the question for resolving a path. This is the other one:
197
+ * which keys the record HAS. They differ on a value that is not a
198
+ * `c.json(...)` call - written inline, or mid-edit - and telling an existing
199
+ * key from a new one is what decides whether a whole-record write adds a
200
+ * `c.json(...)` thunk or replaces one. Using the thunk set for that would
201
+ * insert a second property with a key the literal already has.
202
+ */
203
+ function jsonValuesRecordKeys(source) {
204
+ const keys = [];
205
+ if (!ts__default["default"].isObjectLiteralExpression(source)) {
206
+ return keys;
207
+ }
208
+ for (const prop of source.properties) {
209
+ if (!ts__default["default"].isPropertyAssignment(prop)) {
210
+ continue;
211
+ }
212
+ const key = getPropertyKey(prop.name);
213
+ if (key !== null) {
214
+ keys.push(key);
215
+ }
216
+ }
217
+ return keys;
218
+ }
219
+ function getPropertyKey(name) {
220
+ if (ts__default["default"].isStringLiteralLike(name)) {
221
+ return name.text;
222
+ }
223
+ if (ts__default["default"].isIdentifier(name)) {
224
+ return name.text;
225
+ }
226
+ return null;
227
+ }
228
+ function analyzeCJsonCall(node) {
229
+ // c.json(() => import("path"))
230
+ if (!ts__default["default"].isCallExpression(node) || !isCJson(node.expression)) {
231
+ return null;
232
+ }
233
+ const [thunk] = node.arguments;
234
+ if (!thunk) {
235
+ return null;
236
+ }
237
+ const importPath = getImportPathFromThunk(thunk);
238
+ if (importPath === null) {
239
+ return null;
240
+ }
241
+ return {
242
+ importPath
243
+ };
244
+ }
245
+ function isCJson(expr) {
246
+ // c.json
247
+ return ts__default["default"].isPropertyAccessExpression(expr) && ts__default["default"].isIdentifier(expr.expression) && expr.expression.text === "c" && ts__default["default"].isIdentifier(expr.name) && expr.name.text === "json";
248
+ }
249
+ function getImportPathFromThunk(thunk) {
250
+ // () => import("path") (concise body) OR () => { return import("path"); }
251
+ if (!ts__default["default"].isArrowFunction(thunk)) {
252
+ return null;
253
+ }
254
+ let importCall;
255
+ if (ts__default["default"].isCallExpression(thunk.body)) {
256
+ importCall = thunk.body;
257
+ } else if (ts__default["default"].isBlock(thunk.body)) {
258
+ for (const stmt of thunk.body.statements) {
259
+ if (ts__default["default"].isReturnStatement(stmt) && stmt.expression && ts__default["default"].isCallExpression(stmt.expression)) {
260
+ importCall = stmt.expression;
261
+ break;
262
+ }
263
+ }
264
+ }
265
+ if (!importCall || !ts__default["default"].isCallExpression(importCall)) {
266
+ return null;
267
+ }
268
+ const isImport = importCall.expression.kind === ts__default["default"].SyntaxKind.ImportKeyword || ts__default["default"].isIdentifier(importCall.expression) && importCall.expression.text === "import";
269
+ if (!isImport) {
270
+ return null;
271
+ }
272
+ const arg = importCall.arguments[0];
273
+ if (arg && ts__default["default"].isStringLiteralLike(arg)) {
274
+ return arg.text;
275
+ }
276
+ return null;
277
+ }
278
+
279
+ exports.analyzeJsonValuesEntries = analyzeJsonValuesEntries;
280
+ exports.analyzeValModule = analyzeValModule;
281
+ exports.evaluateExpression = evaluateExpression;
282
+ exports.findObjectPropertyAssignment = findObjectPropertyAssignment;
283
+ exports.flatMapErrors = flatMapErrors;
284
+ exports.formatSyntaxError = formatSyntaxError;
285
+ exports.formatSyntaxErrorTree = formatSyntaxErrorTree;
286
+ exports.jsonValuesRecordKeys = jsonValuesRecordKeys;
287
+ exports.shallowValidateExpression = shallowValidateExpression;
288
+ exports.validateInitializers = validateInitializers;
@@ -0,0 +1,353 @@
1
+ import ts from 'typescript';
2
+ import { pipe, result } from '@valbuild/core/fp';
3
+ import { a as analyzeValModule, e as findObjectPropertyAssignment, s as shallowValidateExpression, g as evaluateExpression, v as validateInitializers } from './jsonValuesModule-427d68c8.esm.js';
4
+ import { PatchError, deepEqual, parseAndValidateArrayIndex, isNotRoot } from '@valbuild/core/patch';
5
+
6
+ function isValidIdentifier(text) {
7
+ if (text.length === 0) {
8
+ return false;
9
+ }
10
+ if (!ts.isIdentifierStart(text.charCodeAt(0), ts.ScriptTarget.ES2020)) {
11
+ return false;
12
+ }
13
+ for (let i = 1; i < text.length; ++i) {
14
+ if (!ts.isIdentifierPart(text.charCodeAt(i), ts.ScriptTarget.ES2020)) {
15
+ return false;
16
+ }
17
+ }
18
+ return true;
19
+ }
20
+ function createPropertyAssignment(key, value) {
21
+ return ts.factory.createPropertyAssignment(isValidIdentifier(key) ? ts.factory.createIdentifier(key) : ts.factory.createStringLiteral(key), toExpression(value));
22
+ }
23
+
24
+ /**
25
+ * Builds the expression `c.json(() => import("<importPath>"))` used to reference
26
+ * a lazily-loaded `*.val.json` entry of a `.jsonValues()` record.
27
+ */
28
+ function createValJsonReference(importPath) {
29
+ // () => import("<importPath>")
30
+ // NOTE: an `import` identifier prints as the dynamic-import keyword call,
31
+ // which avoids casting the ImportKeyword token (not typed as an Expression).
32
+ const importCall = ts.factory.createCallExpression(ts.factory.createIdentifier("import"), undefined, [ts.factory.createStringLiteral(importPath)]);
33
+ const thunk = ts.factory.createArrowFunction(undefined, undefined, [], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), importCall);
34
+ // c.json(<thunk>)
35
+ return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("c"), ts.factory.createIdentifier("json")), undefined, [thunk]);
36
+ }
37
+
38
+ /**
39
+ * Inserts a new `.jsonValues()` entry `"<key>": c.json(() => import("<importPath>"))`
40
+ * into the record's object literal in a `.val.ts` module. `recordPath` is the
41
+ * path from the module source to the record (empty for a root record/router).
42
+ * Fails if the entry key already exists.
43
+ */
44
+ function insertValJsonEntry(document, recordPath, key, importPath) {
45
+ return pipe(analyzeValModule(document), result.flatMap(({
46
+ source
47
+ }) => getAtPath(source, recordPath)), result.flatMap(recordNode => {
48
+ if (!ts.isObjectLiteralExpression(recordNode)) {
49
+ return result.err(new PatchError("Cannot add jsonValues entry: record source is not an object literal"));
50
+ }
51
+ return pipe(findObjectPropertyAssignment(recordNode, key), result.flatMap(assignment => {
52
+ if (assignment) {
53
+ return result.err(new PatchError(`Cannot add jsonValues entry '${key}': it already exists`));
54
+ }
55
+ const property = ts.factory.createPropertyAssignment(isValidIdentifier(key) ? ts.factory.createIdentifier(key) : ts.factory.createStringLiteral(key), createValJsonReference(importPath));
56
+ return result.ok(insertAt(document, recordNode.properties, recordNode.properties.length, property));
57
+ }));
58
+ }));
59
+ }
60
+
61
+ /**
62
+ * Removes the `.jsonValues()` entry `"<key>"` from the record's object literal
63
+ * in a `.val.ts` module. `recordPath` is the path from the module source to the
64
+ * record (empty for a root record/router). Fails if the entry key is missing.
65
+ */
66
+ function removeValJsonEntry(document, recordPath, key) {
67
+ return pipe(analyzeValModule(document), result.flatMap(({
68
+ source
69
+ }) => getAtPath(source, recordPath)), result.flatMap(recordNode => {
70
+ if (!ts.isObjectLiteralExpression(recordNode)) {
71
+ return result.err(new PatchError("Cannot remove jsonValues entry: record source is not an object literal"));
72
+ }
73
+ return pipe(findObjectPropertyAssignment(recordNode, key), result.flatMap(assignment => {
74
+ if (!assignment) {
75
+ return result.err(new PatchError(`Cannot remove jsonValues entry '${key}': it does not exist`));
76
+ }
77
+ const [doc] = removeAt(document, recordNode.properties, recordNode.properties.indexOf(assignment));
78
+ return result.ok(doc);
79
+ }));
80
+ }));
81
+ }
82
+ function toExpression(value) {
83
+ if (typeof value === "string") {
84
+ // TODO: Use configuration/heuristics to determine use of single quote or double quote
85
+ return ts.factory.createStringLiteral(value);
86
+ } else if (typeof value === "number") {
87
+ // TODO: do we want to do something like this for very large numbers?
88
+ // if (value > Number.MAX_SAFE_INTEGER) {
89
+ // return ts.factory.createBigIntLiteral(`${value}n`);
90
+ // }
91
+ // if (value < Number.MIN_SAFE_INTEGER) {
92
+ // return ts.factory.createPrefixUnaryExpression(
93
+ // ts.SyntaxKind.MinusToken,
94
+ // ts.factory.createBigIntLiteral(`${value}n`),
95
+ // );
96
+ // }
97
+ if (value < 0) {
98
+ return ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, ts.factory.createNumericLiteral(Math.abs(value)));
99
+ }
100
+ return ts.factory.createNumericLiteral(value);
101
+ } else if (typeof value === "boolean") {
102
+ return value ? ts.factory.createTrue() : ts.factory.createFalse();
103
+ } else if (value === null) {
104
+ return ts.factory.createNull();
105
+ } else if (Array.isArray(value)) {
106
+ return ts.factory.createArrayLiteralExpression(value.map(toExpression));
107
+ } else if (typeof value === "object") {
108
+ return ts.factory.createObjectLiteralExpression(Object.entries(value)
109
+ // `patch_id` is injected server-side onto a media source whose bytes are
110
+ // not committed yet. It describes the draft, not the content, and a
111
+ // whole-object write built from the client's optimistic view would
112
+ // otherwise print it into the user's file.
113
+ .filter(([key]) => key !== "patch_id").map(([key, value]) => createPropertyAssignment(key, value)));
114
+ } else {
115
+ return ts.factory.createStringLiteral(value);
116
+ }
117
+ }
118
+
119
+ // TODO: Choose newline based on project settings/heuristics/system default?
120
+ const newLine = ts.NewLineKind.LineFeed;
121
+ // TODO: Handle indentation of printed code
122
+ const printer = ts.createPrinter({
123
+ newLine: newLine
124
+ // neverAsciiEscape: true,
125
+ });
126
+ function replaceNodeValue(document, node, value) {
127
+ const replacementText = printer.printNode(ts.EmitHint.Unspecified, toExpression(value), document);
128
+ const span = ts.createTextSpanFromBounds(node.getStart(document, false), node.end);
129
+ const newText = `${document.text.substring(0, span.start)}${replacementText}${document.text.substring(ts.textSpanEnd(span))}`;
130
+ return [document.update(newText, ts.createTextChangeRange(span, replacementText.length)), node];
131
+ }
132
+ function isIndentation(s) {
133
+ for (let i = 0; i < s.length; ++i) {
134
+ const c = s.charAt(i);
135
+ if (c !== " " && c !== "\t") {
136
+ return false;
137
+ }
138
+ }
139
+ return true;
140
+ }
141
+ function newLineStr(kind) {
142
+ if (kind === ts.NewLineKind.CarriageReturnLineFeed) {
143
+ return "\r\n";
144
+ } else {
145
+ return "\n";
146
+ }
147
+ }
148
+ function getSeparator(document, neighbor) {
149
+ const startPos = neighbor.getStart(document, true);
150
+ const basis = document.getLineAndCharacterOfPosition(startPos);
151
+ const lineStartPos = document.getPositionOfLineAndCharacter(basis.line, 0);
152
+ const maybeIndentation = document.getText().substring(lineStartPos, startPos);
153
+ if (isIndentation(maybeIndentation)) {
154
+ return `,${newLineStr(newLine)}${maybeIndentation}`;
155
+ } else {
156
+ return `, `;
157
+ }
158
+ }
159
+ function insertAt(document, nodes, index, node) {
160
+ let span;
161
+ let replacementText;
162
+ if (nodes.length === 0) {
163
+ // Replace entire range of nodes
164
+ replacementText = printer.printNode(ts.EmitHint.Unspecified, node, document);
165
+ span = ts.createTextSpanFromBounds(nodes.pos, nodes.end);
166
+ } else if (index === nodes.length) {
167
+ // Insert after last node
168
+ const neighbor = nodes[nodes.length - 1];
169
+ replacementText = `${getSeparator(document, neighbor)}${printer.printNode(ts.EmitHint.Unspecified, node, document)}`;
170
+ span = ts.createTextSpan(neighbor.end, 0);
171
+ } else {
172
+ // Insert before node
173
+ const neighbor = nodes[index];
174
+ replacementText = `${printer.printNode(ts.EmitHint.Unspecified, node, document)}${getSeparator(document, neighbor)}`;
175
+ span = ts.createTextSpan(neighbor.getStart(document, true), 0);
176
+ }
177
+ const newText = `${document.text.substring(0, span.start)}${replacementText}${document.text.substring(ts.textSpanEnd(span))}`;
178
+ return document.update(newText, ts.createTextChangeRange(span, replacementText.length));
179
+ }
180
+ function removeAt(document, nodes, index) {
181
+ const node = nodes[index];
182
+ let span;
183
+ if (nodes.length === 1) {
184
+ span = ts.createTextSpanFromBounds(nodes.pos, nodes.end);
185
+ } else if (index === nodes.length - 1) {
186
+ // Remove until previous node
187
+ const neighbor = nodes[index - 1];
188
+ span = ts.createTextSpanFromBounds(neighbor.end, node.end);
189
+ } else {
190
+ // Remove before next node
191
+ const neighbor = nodes[index + 1];
192
+ span = ts.createTextSpanFromBounds(node.getStart(document, true), neighbor.getStart(document, true));
193
+ }
194
+ const newText = `${document.text.substring(0, span.start)}${document.text.substring(ts.textSpanEnd(span))}`;
195
+ return [document.update(newText, ts.createTextChangeRange(span, 0)), node];
196
+ }
197
+ function parseAndValidateArrayInsertIndex(key, nodes) {
198
+ if (key === "-") {
199
+ // For insertion, all nodes up until the insertion index must be valid
200
+ // initializers
201
+ const err = validateInitializers(nodes);
202
+ if (err) {
203
+ return result.err(err);
204
+ }
205
+ return result.ok(nodes.length);
206
+ }
207
+ return pipe(parseAndValidateArrayIndex(key), result.flatMap(index => {
208
+ // For insertion, all nodes up until the insertion index must be valid
209
+ // initializers
210
+ const err = validateInitializers(nodes.slice(0, index));
211
+ if (err) {
212
+ return result.err(err);
213
+ }
214
+ if (index > nodes.length) {
215
+ return result.err(new PatchError("Array index out of bounds"));
216
+ } else {
217
+ return result.ok(index);
218
+ }
219
+ }));
220
+ }
221
+ function parseAndValidateArrayInboundsIndex(key, nodes) {
222
+ return pipe(parseAndValidateArrayIndex(key), result.flatMap(index => {
223
+ // For in-bounds operations, all nodes up until and including the index
224
+ // must be valid initializers
225
+ const err = validateInitializers(nodes.slice(0, index + 1));
226
+ if (err) {
227
+ return result.err(err);
228
+ }
229
+ if (index >= nodes.length) {
230
+ return result.err(new PatchError("Array index out of bounds"));
231
+ } else {
232
+ return result.ok(index);
233
+ }
234
+ }));
235
+ }
236
+ function replaceInNode(document, node, key, value) {
237
+ if (ts.isArrayLiteralExpression(node)) {
238
+ return pipe(parseAndValidateArrayInboundsIndex(key, node.elements), result.map(index => replaceNodeValue(document, node.elements[index], value)));
239
+ } else if (ts.isObjectLiteralExpression(node)) {
240
+ return pipe(findObjectPropertyAssignment(node, key), result.flatMap(assignment => {
241
+ if (!assignment) {
242
+ return result.err(new PatchError("Cannot replace object element which does not exist"));
243
+ }
244
+ return result.ok(assignment);
245
+ }), result.map(assignment => replaceNodeValue(document, assignment.initializer, value)));
246
+ } else {
247
+ return result.err(shallowValidateExpression(node) ?? new PatchError("Cannot replace in non-object/array"));
248
+ }
249
+ }
250
+ function replaceAtPath(document, rootNode, path, value) {
251
+ if (isNotRoot(path)) {
252
+ return pipe(getPointerFromPath(rootNode, path), result.flatMap(([node, key]) => replaceInNode(document, node, key, value)));
253
+ } else {
254
+ return result.ok(replaceNodeValue(document, rootNode, value));
255
+ }
256
+ }
257
+ function getFromNode(node, key) {
258
+ if (ts.isArrayLiteralExpression(node)) {
259
+ return pipe(parseAndValidateArrayInboundsIndex(key, node.elements), result.map(index => node.elements[index]));
260
+ } else if (ts.isObjectLiteralExpression(node)) {
261
+ return pipe(findObjectPropertyAssignment(node, key), result.map(assignment => assignment === null || assignment === void 0 ? void 0 : assignment.initializer));
262
+ } else {
263
+ return result.err(shallowValidateExpression(node) ?? new PatchError("Cannot access non-object/array"));
264
+ }
265
+ }
266
+ function getPointerFromPath(node, path) {
267
+ let targetNode = node;
268
+ let key = path[0];
269
+ for (let i = 0; i < path.length - 1; ++i, key = path[i]) {
270
+ const childNode = getFromNode(targetNode, key);
271
+ if (result.isErr(childNode)) {
272
+ return childNode;
273
+ }
274
+ if (childNode.value === undefined) {
275
+ return result.err(new PatchError(`Path refers to non-existing object/array: ${path.join("/")}`));
276
+ }
277
+ targetNode = childNode.value;
278
+ }
279
+ return result.ok([targetNode, key]);
280
+ }
281
+ function getAtPath(rootNode, path) {
282
+ 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));
283
+ }
284
+ function removeFromNode(document, node, key) {
285
+ if (ts.isArrayLiteralExpression(node)) {
286
+ return pipe(parseAndValidateArrayInboundsIndex(key, node.elements), result.map(index => removeAt(document, node.elements, index)));
287
+ } else if (ts.isObjectLiteralExpression(node)) {
288
+ return pipe(findObjectPropertyAssignment(node, key), result.flatMap(assignment => {
289
+ if (!assignment) {
290
+ return result.err(new PatchError("Cannot remove object element which does not exist"));
291
+ }
292
+ return result.ok(assignment);
293
+ }), result.map(assignment => [removeAt(document, node.properties, node.properties.indexOf(assignment))[0], assignment.initializer]));
294
+ } else {
295
+ return result.err(shallowValidateExpression(node) ?? new PatchError("Cannot remove from non-object/array"));
296
+ }
297
+ }
298
+ function removeAtPath(document, rootNode, path) {
299
+ return pipe(getPointerFromPath(rootNode, path), result.flatMap(([node, key]) => removeFromNode(document, node, key)));
300
+ }
301
+ function addToNode(document, node, key, value) {
302
+ if (ts.isArrayLiteralExpression(node)) {
303
+ return pipe(parseAndValidateArrayInsertIndex(key, node.elements), result.map(index => [insertAt(document, node.elements, index, toExpression(value))]));
304
+ } else if (ts.isObjectLiteralExpression(node)) {
305
+ return pipe(findObjectPropertyAssignment(node, key), result.map(assignment => {
306
+ if (!assignment) {
307
+ return [insertAt(document, node.properties, node.properties.length, createPropertyAssignment(key, value))];
308
+ } else {
309
+ return replaceNodeValue(document, assignment.initializer, value);
310
+ }
311
+ }));
312
+ } else {
313
+ return result.err(shallowValidateExpression(node) ?? new PatchError("Cannot add to non-object/array"));
314
+ }
315
+ }
316
+ function addAtPath(document, rootNode, path, value) {
317
+ if (isNotRoot(path)) {
318
+ return pipe(getPointerFromPath(rootNode, path), result.flatMap(([node, key]) => addToNode(document, node, key, value)));
319
+ } else {
320
+ return result.ok(replaceNodeValue(document, rootNode, value));
321
+ }
322
+ }
323
+ function pickDocument([document]) {
324
+ return document;
325
+ }
326
+ class TSOps {
327
+ constructor(findRoot) {
328
+ this.findRoot = findRoot;
329
+ }
330
+ get(document, path) {
331
+ return pipe(document, this.findRoot, result.flatMap(rootNode => getAtPath(rootNode, path)), result.flatMap(evaluateExpression));
332
+ }
333
+ add(document, path, value) {
334
+ return pipe(document, this.findRoot, result.flatMap(rootNode => addAtPath(document, rootNode, path, value)), result.map(pickDocument));
335
+ }
336
+ remove(document, path) {
337
+ return pipe(document, this.findRoot, result.flatMap(rootNode => removeAtPath(document, rootNode, path)), result.map(pickDocument));
338
+ }
339
+ replace(document, path, value) {
340
+ return pipe(document, this.findRoot, result.flatMap(rootNode => replaceAtPath(document, rootNode, path, value)), result.map(pickDocument));
341
+ }
342
+ move(document, from, path) {
343
+ 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));
344
+ }
345
+ copy(document, from, path) {
346
+ 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));
347
+ }
348
+ test(document, path, value) {
349
+ return pipe(document, this.findRoot, result.flatMap(rootNode => getAtPath(rootNode, path)), result.flatMap(evaluateExpression), result.map(documentValue => deepEqual(value, documentValue)));
350
+ }
351
+ }
352
+
353
+ export { TSOps as T, insertValJsonEntry as i, removeValJsonEntry as r };