@jjanczur/tyran 0.1.23 → 0.1.24

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.
@@ -0,0 +1,350 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * yaml-patch — change ONE value in a YAML-subset file and keep the file.
4
+ *
5
+ * `yaml-lite.stringify` can serialize a whole document, and using it here
6
+ * would be the obvious move and the wrong one. `templates/config.yaml` is 90
7
+ * lines of which 63 are comments, and those comments are the only place an
8
+ * operator is told that bare `off` is the boolean false, or why `autonomy:`
9
+ * being AUTO is a trade rather than an oversight. Round-tripping the document
10
+ * through a serializer deletes all of it, silently, the first time anyone
11
+ * moves a slider in a web page.
12
+ *
13
+ * So this module edits TEXT, not data: it finds the line that owns a path and
14
+ * rewrites the value on it, leaving every other byte — comments, blank lines,
15
+ * key order, the operator's own spacing — exactly where it was.
16
+ *
17
+ * ## Why a text edit is safe here
18
+ *
19
+ * Because it is verified rather than trusted. Every patch is applied and then
20
+ * PROVED, by parsing the result and comparing it to the document we meant to
21
+ * produce: the target path holds the new value, and every other path is
22
+ * byte-for-byte the value it held before. A locator bug cannot ship a wrong
23
+ * file; it can only fail loudly. That inverts the usual risk of hand-editing
24
+ * structured text, where the damage is silent and found later.
25
+ *
26
+ * The guarantee, stated exactly: if `patch()` returns, the returned text
27
+ * parses to the intended document. If it cannot prove that, it throws and the
28
+ * caller writes nothing.
29
+ *
30
+ * ## What it deliberately will not do
31
+ *
32
+ * - **Create keys.** A path that does not already exist is refused. Adding a
33
+ * key means choosing where it goes and what comment explains it, which is
34
+ * authoring, not editing.
35
+ * - **Eat comments inside a list it replaces.** Replacing a block sequence
36
+ * rewrites its lines, so a comment among the items would vanish. That is
37
+ * refused instead, with the line number, because the alternative is the
38
+ * silent loss this whole module exists to prevent.
39
+ */
40
+ import { YamlLiteError, formatScalar, parse, splitInlineComment } from './yaml-lite.mjs';
41
+
42
+ export class YamlPatchError extends Error {}
43
+
44
+ /**
45
+ * Lines with their code half, comment half, indentation and line ending.
46
+ *
47
+ * The `\r` is carried separately so a rewritten line in a CRLF file keeps the
48
+ * ending every other line has. Dropping it produced a file with mixed endings
49
+ * — correct data, and a diff that looks like the whole file moved.
50
+ */
51
+ function scan(text) {
52
+ return text.split('\n').map((line, i) => {
53
+ const eol = line.endsWith('\r') ? '\r' : '';
54
+ const raw = eol === '' ? line : line.slice(0, -1);
55
+ const { code, comment } = splitInlineComment(raw, i + 1);
56
+ const trimmed = code.trim();
57
+ return {
58
+ i,
59
+ raw,
60
+ eol,
61
+ code,
62
+ comment,
63
+ trimmed,
64
+ blank: trimmed === '',
65
+ indent: code.length - code.trimStart().length,
66
+ };
67
+ });
68
+ }
69
+
70
+ /**
71
+ * A sequence item carries its first key on the dash line (`- path: x`), so the
72
+ * dash line is presented to the locator as an ordinary key line at the indent
73
+ * its siblings use. Without this the first key of every rule would be
74
+ * unreachable by the same code that reaches the rest.
75
+ */
76
+ function asKeyLine(line, dashIndent, keyIndent) {
77
+ if (dashIndent >= 0 && line.indent === dashIndent && line.trimmed.startsWith('- ')) {
78
+ return { ...line, indent: keyIndent, trimmed: line.trimmed.slice(2).trim(), dash: true };
79
+ }
80
+ return line;
81
+ }
82
+
83
+ /**
84
+ * How far in the block under `from` is indented, or -1 if there is no block.
85
+ *
86
+ * DISCOVERED, never assumed. `yaml-lite` recurses with `parseBlock(next.indent)`
87
+ * — whatever the next line happens to be indented by, as long as it is deeper
88
+ * and even — so a config indented four spaces is as legal as one indented two,
89
+ * and `validateConfig` accepts it. A hardcoded step here made every nested key
90
+ * in such a file report "is not in this file" while the page, which reads the
91
+ * PARSED document, rendered all fifteen controls enabled. The operator got a
92
+ * false error under a live control telling them to add a key that was already
93
+ * there.
94
+ *
95
+ * The one step that genuinely is fixed is a sequence item's siblings, at
96
+ * exactly dash + 2 — that is `yaml-lite.parseBlock`'s `indent + 2`, and it
97
+ * follows from `- ` being two characters wide.
98
+ */
99
+ function childIndentOf(lines, from, to, parentIndent) {
100
+ for (let i = from; i < to; i += 1) {
101
+ if (lines[i].blank) continue;
102
+ return lines[i].indent > parentIndent ? lines[i].indent : -1;
103
+ }
104
+ return -1;
105
+ }
106
+
107
+ /** The indent step this document uses, for a block that has no children yet. */
108
+ function documentStep(lines, topIndent) {
109
+ let step = -1;
110
+ for (const line of lines) {
111
+ if (line.blank || line.indent <= topIndent) continue;
112
+ if (step === -1 || line.indent < step) step = line.indent;
113
+ }
114
+ return step === -1 ? 2 : step - topIndent;
115
+ }
116
+
117
+ /**
118
+ * One past the last line belonging to the block that starts at `from`.
119
+ *
120
+ * The last CONTENT line, not the last line before the next key: a blank line
121
+ * and the comment introducing the following section sit between the two, and
122
+ * counting them as part of this block is how a list replacement would eat the
123
+ * next section's heading.
124
+ */
125
+ function blockEnd(lines, from, indent) {
126
+ let end = from;
127
+ for (let i = from; i < lines.length; i += 1) {
128
+ if (lines[i].blank) continue;
129
+ if (lines[i].indent <= indent) break;
130
+ end = i + 1;
131
+ }
132
+ return end;
133
+ }
134
+
135
+ /**
136
+ * Find the line that owns `path`, and where on it the value sits.
137
+ *
138
+ * `path` segments are keys, or integers for a position in a block sequence.
139
+ */
140
+ function locate(lines, path) {
141
+ const first = lines.find((line) => !line.blank);
142
+ const topIndent = first === undefined ? 0 : first.indent;
143
+ let from = 0;
144
+ let to = lines.length;
145
+ let indent = topIndent;
146
+ let dashIndent = -1;
147
+ let found = null;
148
+
149
+ for (let depth = 0; depth < path.length; depth += 1) {
150
+ const segment = path[depth];
151
+ const where = `${path.slice(0, depth + 1).join('.')}`;
152
+
153
+ if (typeof segment === 'number') {
154
+ let seen = -1;
155
+ let hit = -1;
156
+ for (let i = from; i < to; i += 1) {
157
+ const line = lines[i];
158
+ if (line.blank || line.indent !== indent || !line.trimmed.startsWith('- ')) continue;
159
+ seen += 1;
160
+ if (seen === segment) {
161
+ hit = i;
162
+ break;
163
+ }
164
+ }
165
+ if (hit === -1) throw new YamlPatchError(`no item ${segment} in the list at "${path.slice(0, depth).join('.')}"`);
166
+ dashIndent = lines[hit].indent;
167
+ found = { line: hit, dash: false, keyIndent: dashIndent + 2 };
168
+ from = hit;
169
+ to = blockEnd(lines, hit + 1, dashIndent);
170
+ // A sequence item's sibling keys sit at exactly dash + 2, and the FIRST
171
+ // of them shares the dash line — `- path: x`. This is the one step that
172
+ // is not discovered, because it is not a style choice: `- ` is two
173
+ // characters, and yaml-lite reads siblings at `indent + 2` for that
174
+ // reason.
175
+ indent = dashIndent + 2;
176
+ continue;
177
+ }
178
+
179
+ let hit = -1;
180
+ let view = null;
181
+ for (let i = from; i < to; i += 1) {
182
+ const line = asKeyLine(lines[i], dashIndent, indent);
183
+ if (line.blank || line.indent !== indent) continue;
184
+ const colon = line.trimmed.indexOf(':');
185
+ if (colon === -1) continue;
186
+ if (line.trimmed.slice(0, colon).trim().replace(/^['"]|['"]$/g, '') !== segment) continue;
187
+ hit = i;
188
+ view = line;
189
+ break;
190
+ }
191
+ if (hit === -1) throw new YamlPatchError(`"${where}" is not in this file — yaml-patch edits existing keys, it does not add them`);
192
+ found = { line: hit, dash: view.dash === true, keyIndent: indent };
193
+ const parentIndent = lines[hit].indent;
194
+ from = hit + 1;
195
+ to = blockEnd(lines, from, parentIndent);
196
+ indent = childIndentOf(lines, from, to, parentIndent);
197
+ if (indent === -1) indent = parentIndent + documentStep(lines, topIndent);
198
+ dashIndent = -1;
199
+ }
200
+
201
+ if (found === null) throw new YamlPatchError('an empty path addresses nothing');
202
+ return found;
203
+ }
204
+
205
+ /**
206
+ * Deep structural equality over the plain data yaml-lite produces.
207
+ *
208
+ * Exported so the proof at the end of `patch()` can be tested directly. It is
209
+ * defence in depth with no input known to reach it — every wrong case found so
210
+ * far is refused earlier, by the locator, by the comment guard, or by
211
+ * `formatScalar` — so a test that goes through `patch()` cannot make it fire,
212
+ * and this is the mutable logic the guarantee actually rests on.
213
+ */
214
+ export function sameValue(a, b) {
215
+ if (a === b) return true;
216
+ if (Array.isArray(a) || Array.isArray(b)) {
217
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
218
+ return a.every((item, i) => sameValue(item, b[i]));
219
+ }
220
+ if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;
221
+ const ka = Object.keys(a);
222
+ const kb = Object.keys(b);
223
+ if (ka.length !== kb.length) return false;
224
+ return ka.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k]));
225
+ }
226
+
227
+ function readAt(doc, path) {
228
+ let node = doc;
229
+ for (const segment of path) {
230
+ if (node === null || typeof node !== 'object') return undefined;
231
+ node = node[segment];
232
+ }
233
+ return node;
234
+ }
235
+
236
+ function writeAt(doc, path, value) {
237
+ let node = doc;
238
+ for (const segment of path.slice(0, -1)) node = node[segment];
239
+ node[path.at(-1)] = value;
240
+ }
241
+
242
+ /** Rewrite the value on a `key: value` line, keeping indent, comment and ending. */
243
+ function scalarLine(line, target, value) {
244
+ const body = target.dash ? line.trimmed.slice(2).trim() : line.trimmed;
245
+ const colon = body.indexOf(':');
246
+ const head = `${' '.repeat(line.indent)}${target.dash ? '- ' : ''}${body.slice(0, colon + 1)}`;
247
+ const tail = line.comment === '' ? '' : ` ${line.comment}`;
248
+ return `${head} ${formatScalar(value)}${tail}${line.eol}`;
249
+ }
250
+
251
+ /**
252
+ * Set `path` to `value` in `text`, returning the new text.
253
+ *
254
+ * Throws `YamlPatchError` if the path is absent, if the change cannot be made
255
+ * without losing a comment, or — the one that matters — if the result does not
256
+ * parse back to exactly the document intended.
257
+ */
258
+ export function patch(text, path, value) {
259
+ let before;
260
+ try {
261
+ before = parse(text);
262
+ } catch (err) {
263
+ if (err instanceof YamlLiteError) throw new YamlPatchError(`this file does not parse, so it cannot be edited safely: ${err.message}`);
264
+ throw err;
265
+ }
266
+ if (readAt(before, path) === undefined) {
267
+ throw new YamlPatchError(`"${path.join('.')}" is not in this file — yaml-patch edits existing keys, it does not add them`);
268
+ }
269
+
270
+ return build(text, path, value, before);
271
+ }
272
+
273
+ /**
274
+ * The edit itself, with every refusal this module makes reported as one error
275
+ * type.
276
+ *
277
+ * `formatScalar` throws `YamlLiteError` for a value the subset cannot spell —
278
+ * a newline, an invisible codepoint — and that is ordinary rejected input, not
279
+ * a fault. Letting it escape made the caller classify it as a server error:
280
+ * HTTP 500 and a line in the terminal the docs designate as the audit trail,
281
+ * for someone pasting a model name with a stray newline in it.
282
+ */
283
+ function build(text, path, value, before) {
284
+ try {
285
+ return edit(text, path, value, before);
286
+ } catch (err) {
287
+ if (err instanceof YamlLiteError) throw new YamlPatchError(err.message);
288
+ throw err;
289
+ }
290
+ }
291
+
292
+ function edit(text, path, value, before) {
293
+ const lines = scan(text);
294
+ const first = lines.find((l) => !l.blank);
295
+ const target = locate(lines, path);
296
+ const line = lines[target.line];
297
+
298
+ const out = text.split('\n');
299
+ if (Array.isArray(value)) {
300
+ const body = target.dash ? line.trimmed.slice(2).trim() : line.trimmed;
301
+ const colon = body.indexOf(':');
302
+ const inlineValue = body.slice(colon + 1).trim();
303
+ const end = inlineValue === '' ? blockEnd(lines, target.line + 1, line.indent) : target.line + 1;
304
+ // The items' indent is the one they already have; a list with none yet
305
+ // (`shared_zones: []`) takes the step the rest of the document uses.
306
+ const discovered = childIndentOf(lines, target.line + 1, end, line.indent);
307
+ const childIndent = discovered === -1
308
+ ? line.indent + documentStep(lines, first === undefined ? 0 : first.indent)
309
+ : discovered;
310
+ // Rewriting the block rewrites its lines, so a comment living among the
311
+ // items would disappear. Refusing keeps the promise this module is for.
312
+ for (let i = target.line + 1; i < end; i += 1) {
313
+ if (lines[i].comment !== '') {
314
+ throw new YamlPatchError(
315
+ `line ${i + 1} of this list is a comment, and replacing the list would delete it — ` +
316
+ `edit ${path.join('.')} in the file by hand instead`,
317
+ );
318
+ }
319
+ }
320
+ const head = `${' '.repeat(line.indent)}${target.dash ? '- ' : ''}${body.slice(0, colon + 1)}`;
321
+ const tail = line.comment === '' ? '' : ` ${line.comment}`;
322
+ const rendered = value.length === 0
323
+ ? [`${head} []${tail}${line.eol}`]
324
+ : [`${head}${tail}${line.eol}`, ...value.map((item) => `${' '.repeat(childIndent)}- ${formatScalar(item)}${line.eol}`)];
325
+ out.splice(target.line, end - target.line, ...rendered);
326
+ } else {
327
+ out[target.line] = scalarLine(line, target, value);
328
+ }
329
+ const next = out.join('\n');
330
+
331
+ // The proof. A locator that picked the wrong line, a quoting rule that read
332
+ // back as a different type, a list block whose extent was misjudged — each
333
+ // shows up here as a mismatch, before anything reaches the disk.
334
+ const expected = structuredClone(before);
335
+ writeAt(expected, path, value);
336
+ let after;
337
+ try {
338
+ after = parse(next);
339
+ } catch (err) {
340
+ throw new YamlPatchError(`the edit produced a file that no longer parses (${err.message}) — nothing was written`);
341
+ }
342
+ if (!sameValue(after, expected)) {
343
+ throw new YamlPatchError(
344
+ `the edit did not produce the intended document — nothing was written. ` +
345
+ `Wanted ${path.join('.')} = ${JSON.stringify(value)}, got ${JSON.stringify(readAt(after, path))}` +
346
+ (sameValue(readAt(after, path), value) ? ', and something else in the file changed too' : ''),
347
+ );
348
+ }
349
+ return next;
350
+ }