@decimalturn/toml-patch 3.3.2-lite → 3.3.3-dev

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 (81) hide show
  1. package/dist/dev/comment-alignment.js +371 -0
  2. package/dist/dev/comment-alignment.js.map +1 -0
  3. package/dist/dev/comment-ownership.js +672 -0
  4. package/dist/dev/comment-ownership.js.map +1 -0
  5. package/dist/dev/cst-source.js +117 -0
  6. package/dist/dev/cst-source.js.map +1 -0
  7. package/dist/dev/cst.js +67 -0
  8. package/dist/dev/cst.js.map +1 -0
  9. package/dist/dev/cursor.js +65 -0
  10. package/dist/dev/cursor.js.map +1 -0
  11. package/dist/dev/date-format.js +286 -0
  12. package/dist/dev/date-format.js.map +1 -0
  13. package/dist/dev/decode-utf8.js +26 -0
  14. package/dist/dev/decode-utf8.js.map +1 -0
  15. package/dist/dev/diff-lite.js +107 -0
  16. package/dist/dev/diff-lite.js.map +1 -0
  17. package/dist/dev/diff.js +264 -0
  18. package/dist/dev/diff.js.map +1 -0
  19. package/dist/dev/encode-lite.js +209 -0
  20. package/dist/dev/encode-lite.js.map +1 -0
  21. package/dist/dev/escape-preference.js +165 -0
  22. package/dist/dev/escape-preference.js.map +1 -0
  23. package/dist/dev/find-by-path.js +114 -0
  24. package/dist/dev/find-by-path.js.map +1 -0
  25. package/dist/dev/formatter.js +297 -0
  26. package/dist/dev/formatter.js.map +1 -0
  27. package/dist/dev/generate.js +479 -0
  28. package/dist/dev/generate.js.map +1 -0
  29. package/dist/dev/inline-comma-space.js +12 -0
  30. package/dist/dev/inline-comma-space.js.map +1 -0
  31. package/dist/dev/inline-format.js +105 -0
  32. package/dist/dev/inline-format.js.map +1 -0
  33. package/dist/dev/inline-layout.js +106 -0
  34. package/dist/dev/inline-layout.js.map +1 -0
  35. package/dist/dev/line-ending-backslash.js +319 -0
  36. package/dist/dev/line-ending-backslash.js.map +1 -0
  37. package/dist/dev/literal-string.js +45 -0
  38. package/dist/dev/literal-string.js.map +1 -0
  39. package/dist/dev/location.js +103 -0
  40. package/dist/dev/location.js.map +1 -0
  41. package/dist/dev/parse-error.js +26 -0
  42. package/dist/dev/parse-error.js.map +1 -0
  43. package/dist/dev/parse-js.js +149 -0
  44. package/dist/dev/parse-js.js.map +1 -0
  45. package/dist/dev/parse-string.js +119 -0
  46. package/dist/dev/parse-string.js.map +1 -0
  47. package/dist/dev/parse-toml.js +713 -0
  48. package/dist/dev/parse-toml.js.map +1 -0
  49. package/dist/dev/patch-lite.js +4 -0
  50. package/dist/dev/patch-lite2.js +96 -0
  51. package/dist/dev/patch-lite2.js.map +1 -0
  52. package/dist/dev/patch.js +3143 -0
  53. package/dist/dev/patch.js.map +1 -0
  54. package/dist/dev/smol-toml-date.js +60 -0
  55. package/dist/dev/smol-toml-date.js.map +1 -0
  56. package/dist/dev/to-js.js +307 -0
  57. package/dist/dev/to-js.js.map +1 -0
  58. package/dist/dev/to-toml.js +873 -0
  59. package/dist/dev/to-toml.js.map +1 -0
  60. package/dist/dev/tokenizer.js +224 -0
  61. package/dist/dev/tokenizer.js.map +1 -0
  62. package/dist/dev/toml-document.js +220 -0
  63. package/dist/dev/toml-document.js.map +1 -0
  64. package/dist/dev/toml-format.js +548 -0
  65. package/dist/dev/toml-format.js.map +1 -0
  66. package/dist/dev/toml-patch.js +93 -0
  67. package/dist/dev/toml-patch.js.map +1 -0
  68. package/dist/dev/traverse.js +60 -0
  69. package/dist/dev/traverse.js.map +1 -0
  70. package/dist/dev/truncate.js +63 -0
  71. package/dist/dev/truncate.js.map +1 -0
  72. package/dist/dev/update-order.js +234 -0
  73. package/dist/dev/update-order.js.map +1 -0
  74. package/dist/dev/utils.js +295 -0
  75. package/dist/dev/utils.js.map +1 -0
  76. package/dist/dev/writer.js +757 -0
  77. package/dist/dev/writer.js.map +1 -0
  78. package/dist/{patch.d.ts → patch-lite.d.ts} +0 -2
  79. package/dist/toml-patch.d.ts +548 -0
  80. package/package.json +11 -6
  81. package/dist/patch.js +0 -20
@@ -0,0 +1,672 @@
1
+ //! @decimalturn/toml-patch v3.3.3 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ import { hasItems, isComment, isDocument, isInlineArray, isInlineItem, isInlineTable, isKeyValue, isString, isTable, isTableArray } from "./cst.js";
3
+ import { last } from "./utils.js";
4
+ import { clonePosition } from "./location.js";
5
+ import { addExitOffset, applyWrites, getExitOffsets, insert, perLine, recalcContainerEnd, remove, shiftNode } from "./writer.js";
6
+
7
+ // src/comment-ownership.ts
8
+ const KEY_SEGMENT = String.raw`(?:[\w-]+|"[^"]*"|'[^']*')`;
9
+ /** `# key = ...`, `# a.b.c = ...`, `# "quoted key" = ...` */
10
+ const IS_COMMENTED_OUT_KEY_VALUE = new RegExp(String.raw`^#\s*${KEY_SEGMENT}(?:\s*\.\s*${KEY_SEGMENT})*\s*=`);
11
+ /** A value after `=` in a commented-out KV: a quoted string, number, boolean,
12
+ * date-like token, or a single bare word. Multi-word prose (e.g.
13
+ * `# key = 1 is something to consider`) does NOT match, so the comment
14
+ * is treated as alive prose rather than a dead entry. */
15
+ const VALUE_TOKEN = String.raw`(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|"""[\s\S]*?"""|'''[\s\S]*?'''|[^\s#]+)`;
16
+ /** Full-line match: `# key = value` where value is a single token. */
17
+ const IS_PURE_COMMENTED_OUT_KV = new RegExp(String.raw`^#\s*${KEY_SEGMENT}(?:\s*\.\s*${KEY_SEGMENT})*\s*=\s*${VALUE_TOKEN}\s*$`);
18
+ /** `# [table]`, `# [[array]]`, `# [a.b]` */
19
+ const IS_COMMENTED_OUT_HEADER = new RegExp(String.raw`^#\s*\[\[?\s*${KEY_SEGMENT}(?:\s*\.\s*${KEY_SEGMENT})*\s*\]\]?\s*$`);
20
+ function isCommentedOutEntry(comment) {
21
+ return IS_PURE_COMMENTED_OUT_KV.test(comment.raw) || IS_COMMENTED_OUT_HEADER.test(comment.raw);
22
+ }
23
+ /**
24
+ * True when a `#` appears outside of quotes after the `=` in a
25
+ * commented-out-KV line — i.e. the line has an inline trailing comment
26
+ * (`# key = val # note`). `#` inside a quoted value (e.g.
27
+ * `# key = "a # b" extra`) is NOT an inline comment.
28
+ */
29
+ function hasInlineCommentAfterValue(comment) {
30
+ const eqIdx = comment.raw.indexOf("=");
31
+ if (eqIdx < 0) return false;
32
+ let inDQuote = false;
33
+ let inSQuote = false;
34
+ for (let i = eqIdx + 1; i < comment.raw.length; i++) {
35
+ const ch = comment.raw[i];
36
+ if (ch === "\\") {
37
+ i++;
38
+ continue;
39
+ }
40
+ if (!inSQuote && ch === "\"") {
41
+ inDQuote = !inDQuote;
42
+ continue;
43
+ }
44
+ if (!inDQuote && ch === "'") {
45
+ inSQuote = !inSQuote;
46
+ continue;
47
+ }
48
+ if (!inDQuote && !inSQuote && ch === "#") return true;
49
+ }
50
+ return false;
51
+ }
52
+ /**
53
+ * True when the comment looks enough like a KV to act as a barrier in
54
+ * scanGroups. Broader than `isCommentedOutEntry`: also matches lines with
55
+ * an inline trailing comment (`# key = val # note`) and lines whose value
56
+ * part is short enough not to be obvious prose (≤3 words after `=`).
57
+ */
58
+ function looksLikeKV(comment) {
59
+ if (isCommentedOutEntry(comment)) return true;
60
+ if (!IS_COMMENTED_OUT_KEY_VALUE.test(comment.raw)) return false;
61
+ if (hasInlineCommentAfterValue(comment)) return true;
62
+ return comment.raw.replace(/^[^=]*=\s*/, "").split(/\s+/).filter(Boolean).length <= 3;
63
+ }
64
+ /** Extract the first key segment from a commented-out KV like `# key = val`. */
65
+ function commentedOutFirstKey(comment) {
66
+ const m = comment.raw.match(IS_COMMENTED_OUT_KEY_VALUE);
67
+ if (!m) return void 0;
68
+ let key = m[0].replace(/^#\s*/, "").replace(/\s*=.*$/, "").trim();
69
+ const dot = key.indexOf(".");
70
+ if (dot >= 0) key = key.substring(0, dot);
71
+ if (key.startsWith("\"") && key.endsWith("\"") || key.startsWith("'") && key.endsWith("'")) key = key.slice(1, -1);
72
+ return key || void 0;
73
+ }
74
+ /**
75
+ * True only for a genuinely multi-line InlineTable/InlineArray. Single-line
76
+ * containers can never hold hoisted interior comments in the first place
77
+ * (Non-goals in the plan doc), and — critically — `start.line === end.line`
78
+ * for a single-line container means ANY same-line trailing comment on the
79
+ * OUTER key-value (e.g. `data = [x, y] # note`) would otherwise appear to
80
+ * fall "inside" a nested single-line array's own line range too, wrongly
81
+ * treating an unrelated comment as hoisted from inside it. The element-level
82
+ * ownership machinery below (resolveInlineElementGroups / removeMember's and
83
+ * moveInlineElement's InlineTable/InlineArray branches) must only engage
84
+ * here, matching writer.ts's own `isMultilineInlineContainer` convention.
85
+ */
86
+ function isMultilineInlineContainer(node) {
87
+ return (isInlineTable(node) || isInlineArray(node)) && node.loc.end.line > node.loc.start.line;
88
+ }
89
+ function getMemberKey(member) {
90
+ if (isKeyValue(member)) return member.key.value[0];
91
+ if (isTable(member) || isTableArray(member)) return member.key.item.value[0];
92
+ if (isInlineItem(member) && isKeyValue(member.item)) return member.item.key.value[0];
93
+ }
94
+ /**
95
+ * The rule scan shared by resolveGroups (Document/Table/TableArray, where members
96
+ * and comments are already interleaved in one items array) and
97
+ * resolveInlineElementGroups (InlineTable/InlineArray, where they are merged from
98
+ * two different arrays first — see that function). `items` must already be in
99
+ * ascending line order; a `Comment` node is a comment, anything else is a member.
100
+ */
101
+ function scanGroups(items, initialLastMemberEndLine, isEligibleForLeading, memberKey = getMemberKey) {
102
+ const groups = [];
103
+ let lastMemberEndLine = initialLastMemberEndLine;
104
+ let currentMemberGroup;
105
+ let pendingRun = [];
106
+ const flushPendingAsPinned = () => {
107
+ if (!pendingRun.length) return;
108
+ groups.push({
109
+ kind: "pinned",
110
+ items: pendingRun,
111
+ startLine: pendingRun[0].loc.start.line,
112
+ endLine: last(pendingRun).loc.end.line
113
+ });
114
+ pendingRun = [];
115
+ };
116
+ for (const item of items) {
117
+ if (isComment(item)) {
118
+ if (item.loc.start.line <= lastMemberEndLine) {
119
+ if (currentMemberGroup) {
120
+ currentMemberGroup.items.push(item);
121
+ currentMemberGroup.endLine = Math.max(currentMemberGroup.endLine, item.loc.end.line);
122
+ } else groups.push({
123
+ kind: "pinned",
124
+ items: [item],
125
+ startLine: item.loc.start.line,
126
+ endLine: item.loc.end.line
127
+ });
128
+ continue;
129
+ }
130
+ const runEndLine = pendingRun.length ? last(pendingRun).loc.end.line : void 0;
131
+ if (pendingRun.length && item.loc.start.line === runEndLine + 1) pendingRun.push(item);
132
+ else {
133
+ flushPendingAsPinned();
134
+ pendingRun.push(item);
135
+ }
136
+ continue;
137
+ }
138
+ let leading = [];
139
+ if (pendingRun.length) {
140
+ if (last(pendingRun).loc.end.line + 1 === item.loc.start.line && isEligibleForLeading(item)) {
141
+ const key = memberKey(item);
142
+ if (key !== void 0) {
143
+ let lastBarrierIdx = -1;
144
+ for (let i = pendingRun.length - 1; i >= 0; i--) {
145
+ const ck = looksLikeKV(pendingRun[i]) ? commentedOutFirstKey(pendingRun[i]) : void 0;
146
+ if (ck !== void 0 && ck !== key) {
147
+ lastBarrierIdx = i;
148
+ break;
149
+ }
150
+ }
151
+ if (lastBarrierIdx >= 0) {
152
+ const pinned = pendingRun.splice(0, lastBarrierIdx + 1);
153
+ groups.push({
154
+ kind: "pinned",
155
+ items: pinned,
156
+ startLine: pinned[0].loc.start.line,
157
+ endLine: last(pinned).loc.end.line
158
+ });
159
+ }
160
+ }
161
+ leading = pendingRun;
162
+ pendingRun = [];
163
+ } else flushPendingAsPinned();
164
+ }
165
+ const groupItems = [...leading, item];
166
+ const group = {
167
+ kind: "member",
168
+ member: item,
169
+ key: memberKey(item),
170
+ items: groupItems,
171
+ startLine: groupItems[0].loc.start.line,
172
+ endLine: item.loc.end.line
173
+ };
174
+ groups.push(group);
175
+ currentMemberGroup = group;
176
+ lastMemberEndLine = item.loc.end.line;
177
+ }
178
+ flushPendingAsPinned();
179
+ return groups;
180
+ }
181
+ /**
182
+ * Partitions a container's items into ownership groups, in document order.
183
+ * Pure: does not mutate the tree.
184
+ *
185
+ * @param isEligibleForLeading - optional predicate; members that fail it cannot
186
+ * acquire leading comments via R2. Used by callers that have just inserted
187
+ * nodes which must not adopt a preceding block.
188
+ */
189
+ function resolveGroups(container, isEligibleForLeading = () => true, memberKey = getMemberKey) {
190
+ const initialLastMemberEndLine = isDocument(container) ? 0 : container.key.loc.end.line;
191
+ return scanGroups(container.items, initialLastMemberEndLine, isEligibleForLeading, memberKey);
192
+ }
193
+ /**
194
+ * The element-level analogue of resolveGroups, for a multi-line InlineTable or
195
+ * InlineArray. Unlike Document/Table/TableArray, an inline container's own
196
+ * `.items` can never hold a Comment (InlineTableItem/InlineArrayItem are both
197
+ * InlineItem<...>) — the parser hoists interior comments out into the
198
+ * *enclosing* Document/Table's `.items` instead (Background, case 4 in the
199
+ * plan doc). `hostItems` is that enclosing container's `.items`; this merges
200
+ * the comments physically inside `container`'s line range back in with
201
+ * `container.items` (sorted into true reading order) before running the same
202
+ * scan resolveGroups uses.
203
+ *
204
+ * There is no R6 analogue for bare array elements (they aren't `key = value`
205
+ * shaped), but nothing here suppresses R6 for an InlineArray's own comments —
206
+ * see docs/Comment-Ownership.md for why that's an accepted, untested edge
207
+ * case rather than a deliberate rule.
208
+ */
209
+ function resolveInlineElementGroups(container, hostItems) {
210
+ const interiorComments = hostItems.filter((item) => isComment(item) && (item.loc.start.line > container.loc.start.line || item.loc.start.line === container.loc.start.line && item.loc.start.column >= container.loc.start.column) && (item.loc.end.line < container.loc.end.line || item.loc.end.line === container.loc.end.line && item.loc.end.column <= container.loc.end.column));
211
+ return scanGroups([...container.items, ...interiorComments].sort((a, b) => a.loc.start.line - b.loc.start.line || a.loc.start.column - b.loc.start.column), container.loc.start.line, () => true);
212
+ }
213
+ /**
214
+ * Finds the nearest Document/Table/TableArray ancestor whose OWN `.items`
215
+ * holds the top-level Block from which `target` is reachable, following
216
+ * KeyValue.value / InlineTable.items / InlineArray.items / InlineItem.item
217
+ * links down through any nesting depth. This is where the parser files
218
+ * comments hoisted out of `target` (Background, case 4) — regardless of how
219
+ * deeply `target` is nested inside other inline containers, they always
220
+ * flatten up to the same enclosing Document/Table.
221
+ */
222
+ /**
223
+ * Finds the InlineItem that wraps `target` (an InlineTable/InlineArray)
224
+ * inside its own parent container's items, searching the whole tree.
225
+ */
226
+ function findWrapperItem(root, target) {
227
+ function walk(node) {
228
+ if (isKeyValue(node)) return walk(node.value);
229
+ if (!hasItems(node)) return void 0;
230
+ for (const item of node.items) if (isInlineItem(item) && item.item === target) return item;
231
+ for (const item of node.items) {
232
+ const found = walk(isInlineItem(item) ? item.item : item);
233
+ if (found) return found;
234
+ }
235
+ }
236
+ return walk(root);
237
+ }
238
+ function findHostContainer(root, target) {
239
+ function searchValue(value, container) {
240
+ if (value === target) return container;
241
+ if (isKeyValue(value)) return searchValue(value.value, container);
242
+ if (isInlineTable(value) || isInlineArray(value)) for (const inlineItem of value.items) {
243
+ if (inlineItem === target) return container;
244
+ const found = searchValue(inlineItem.item, container);
245
+ if (found) return found;
246
+ }
247
+ }
248
+ function search(container) {
249
+ for (const item of container.items) {
250
+ if (item === target) return container;
251
+ if (isKeyValue(item)) {
252
+ const found = searchValue(item.value, container);
253
+ if (found) return found;
254
+ } else if (isTable(item) || isTableArray(item)) {
255
+ const found = search(item);
256
+ if (found) return found;
257
+ }
258
+ }
259
+ }
260
+ return search(root);
261
+ }
262
+ /**
263
+ * R5, applied once as a general-purpose (non-destructive-to-text) pass: a
264
+ * comment that visually introduces the next [table]/[[array]] block is
265
+ * physically stored as a trailing item of the PREVIOUS block, because the
266
+ * parser consumes everything up to the next `[` into the current table
267
+ * (src/parse-toml.ts:517-524). This re-parents such blocks into Document.items,
268
+ * immediately before the block they visually belong to.
269
+ *
270
+ * Mutates the tree; loc-preserving, so serialized output is unchanged. NOTE:
271
+ * because the re-parenting is loc-preserving, a document normalized this way
272
+ * no longer matches what re-parsing its own serialized text would produce
273
+ * (the parser always re-derives the original, pre-normalization container
274
+ * assignment from the text). Do not call this as a blanket pre-pass before
275
+ * general patching — it is intended for callers that immediately consume the
276
+ * result without round-tripping through text (e.g. a future reorder pass that
277
+ * is about to change those lines anyway). For deletion, `removeMember` below
278
+ * computes the same R5 ownership lazily and only mutates when a comment is
279
+ * genuinely being deleted, which has no such divergence risk.
280
+ */
281
+ function normalizeSectionComments(document) {
282
+ for (let i = 0; i < document.items.length; i++) {
283
+ const block = document.items[i];
284
+ if (!isTable(block) && !isTableArray(block)) continue;
285
+ const nextBlock = document.items[i + 1];
286
+ if (!nextBlock) continue;
287
+ const runItems = trailingOwnedRun(block, nextBlock);
288
+ if (!runItems) continue;
289
+ const items = block.items;
290
+ items.splice(items.length - runItems.length, runItems.length);
291
+ document.items.splice(i + 1, 0, ...runItems);
292
+ recalcContainerEnd(block);
293
+ i += runItems.length;
294
+ }
295
+ }
296
+ /**
297
+ * R5, computed lazily: if `container`'s trailing comment block is R2-adjacent
298
+ * to `nextBlock` (and not R6-dead), returns it — these are the comments a
299
+ * removal of `nextBlock` must take along, even though they physically live
300
+ * in `container.items`. Returns undefined otherwise.
301
+ */
302
+ function trailingOwnedRun(container, nextBlock) {
303
+ const lastGroup = last(resolveGroups(container));
304
+ if (!lastGroup || lastGroup.kind !== "pinned") return void 0;
305
+ const runItems = lastGroup.items;
306
+ const adjacent = lastGroup.endLine + 1 === nextBlock.loc.start.line;
307
+ const allDead = runItems.every(isCommentedOutEntry);
308
+ if (!adjacent || allDead) return void 0;
309
+ return runItems;
310
+ }
311
+ /**
312
+ * Removes `member` from `parent.items` along with every comment it owns
313
+ * (leading block and trailing comments — see resolveGroups), plus,
314
+ * when `member` is a [table]/[[array]] block, any trailing comment block the
315
+ * parser filed under the PRECEDING sibling table but which R5 assigns to
316
+ * `member` instead. Conversely, `member`'s own trailing block that R5 assigns
317
+ * to the FOLLOWING block survives: it is re-parented into Document.items
318
+ * just above that block before `member` goes. Falls back to a plain removal
319
+ * when `parent` isn't a container the ownership model applies to (e.g.
320
+ * InlineTable/InlineArray).
321
+ */
322
+ function removeMember(root, parent, member) {
323
+ if (isDocument(parent) && (isTable(member) || isTableArray(member))) {
324
+ const index = parent.items.indexOf(member);
325
+ const previousSibling = index > 0 ? parent.items[index - 1] : void 0;
326
+ if (previousSibling && (isTable(previousSibling) || isTableArray(previousSibling))) {
327
+ const runItems = trailingOwnedRun(previousSibling, member);
328
+ if (runItems) for (const item of runItems) remove(root, previousSibling, item);
329
+ }
330
+ const nextSibling = parent.items[index + 1];
331
+ if (nextSibling && (isTable(nextSibling) || isTableArray(nextSibling))) {
332
+ const runItems = trailingOwnedRun(member, nextSibling);
333
+ if (runItems) {
334
+ const items = member.items;
335
+ items.splice(items.length - runItems.length, runItems.length);
336
+ parent.items.splice(index + 1, 0, ...runItems);
337
+ recalcContainerEnd(member);
338
+ }
339
+ }
340
+ }
341
+ if (isDocument(parent) || isTable(parent) || isTableArray(parent)) {
342
+ const group = resolveGroups(parent).find((s) => s.member === member);
343
+ if (group) {
344
+ const memberIndex = group.items.indexOf(member);
345
+ for (let i = 0; i <= memberIndex; i++) {
346
+ const item = group.items[i];
347
+ if (!parent.items.includes(item)) continue;
348
+ remove(root, parent, item);
349
+ }
350
+ for (let i = memberIndex + 1; i < group.items.length; i++) {
351
+ const item = group.items[i];
352
+ const idx = parent.items.indexOf(item);
353
+ if (idx < 0) continue;
354
+ parent.items.splice(idx, 1);
355
+ }
356
+ return;
357
+ }
358
+ }
359
+ if (isMultilineInlineContainer(parent) && isDocument(root)) {
360
+ const hostContainer = findHostContainer(root, parent);
361
+ if (hostContainer) {
362
+ const group = resolveInlineElementGroups(parent, hostContainer.items).find((s) => s.member === member);
363
+ if (group) {
364
+ const comments = group.items.filter((item) => item !== member);
365
+ for (const comment of comments) {
366
+ const idx = hostContainer.items.indexOf(comment);
367
+ if (idx < 0) continue;
368
+ hostContainer.items.splice(idx, 1);
369
+ }
370
+ if (comments.length) {
371
+ member.loc.start = group.items[0].loc.start;
372
+ member.loc.end = last(group.items).loc.end;
373
+ }
374
+ remove(root, parent, member, hostContainer.items);
375
+ applyWrites(root);
376
+ return;
377
+ }
378
+ }
379
+ }
380
+ remove(root, parent, member);
381
+ }
382
+ /**
383
+ * Relocates `node` (an element of `parent`, an InlineTable/InlineArray) from
384
+ * its current position to `toIndex`, carrying its own owned comments along
385
+ * (see resolveInlineElementGroups) rather than leaving them at their old
386
+ * absolute position — which is what plain remove()+insert() does, and why a
387
+ * Move on a commented inline array can misplace a comment onto an unrelated
388
+ * line (see "Elements inside multi-line arrays and inline tables" in
389
+ * docs/Comment-Ownership.md).
390
+ *
391
+ * It isn't enough to protect only `node`'s own comments: writer.remove()'s
392
+ * per-container "orphaned comment" cleanup reasons purely by absolute line
393
+ * number, with no notion of ownership, so relocating `node` past *other*
394
+ * elements can drag an unrelated element's own comment along as a side
395
+ * effect (or leave it stranded) even though that element never moved. Every
396
+ * commented element in the container is protected the same way: its
397
+ * comment(s) are detached before the move and re-attached afterward, based
398
+ * on how far *that specific element* actually shifted — which may differ
399
+ * from how far `node` itself moved, or be zero.
400
+ */
401
+ function moveInlineElement(root, parent, node, toIndex) {
402
+ let sharedLineContainerBeforeMove = false;
403
+ if (isMultilineInlineContainer(parent) && isDocument(root)) {
404
+ const hostContainer = findHostContainer(root, parent);
405
+ if (hostContainer) {
406
+ const groups = resolveInlineElementGroups(parent, hostContainer.items);
407
+ {
408
+ const items = parent.items;
409
+ let run = 1;
410
+ for (let i = 1; i < items.length; i++) if (items[i].loc.start.line === items[i - 1].loc.start.line) {
411
+ const prevPending = getExitOffsets(root).get(items[i - 1]);
412
+ const selfPending = getExitOffsets(root).get(items[i]);
413
+ if (prevPending || selfPending) continue;
414
+ run++;
415
+ if (run >= 3) {
416
+ sharedLineContainerBeforeMove = true;
417
+ break;
418
+ }
419
+ } else run = 1;
420
+ }
421
+ const detached = [];
422
+ let nodeOwnStart;
423
+ let nodeOwnEnd;
424
+ let nodeInnerEnd;
425
+ const anchoredDescendants = [];
426
+ const collectAnchored = (container, firstLine) => {
427
+ if (!hasItems(container)) return;
428
+ const items = container.items;
429
+ for (let i = 0; i < items.length; i++) {
430
+ const item = items[i];
431
+ const below = item.loc.start.line > firstLine;
432
+ if (below) anchoredDescendants.push({
433
+ node: item,
434
+ start: clonePosition(item.loc.start),
435
+ end: clonePosition(item.loc.end)
436
+ });
437
+ if (item.loc.end.line > firstLine && item.loc.end.line > item.loc.start.line) anchoredDescendants.push({
438
+ node: item,
439
+ start: clonePosition(item.loc.start),
440
+ end: clonePosition(item.loc.end),
441
+ endOnly: true
442
+ });
443
+ if (isInlineItem(item)) {
444
+ const inner = item.item;
445
+ if (below) {
446
+ const kv = isKeyValue(inner) ? inner : void 0;
447
+ anchoredDescendants.push({
448
+ node: inner,
449
+ start: clonePosition(inner.loc.start),
450
+ end: clonePosition(inner.loc.end),
451
+ equals: kv ? kv.equals : void 0
452
+ });
453
+ if (kv) {
454
+ anchoredDescendants.push({
455
+ node: kv.key,
456
+ start: clonePosition(kv.key.loc.start),
457
+ end: clonePosition(kv.key.loc.end)
458
+ });
459
+ anchoredDescendants.push({
460
+ node: kv.value,
461
+ start: clonePosition(kv.value.loc.start),
462
+ end: clonePosition(kv.value.loc.end)
463
+ });
464
+ }
465
+ }
466
+ if (inner.loc.end.line > firstLine && inner.loc.end.line > inner.loc.start.line) anchoredDescendants.push({
467
+ node: inner,
468
+ start: clonePosition(inner.loc.start),
469
+ end: clonePosition(inner.loc.end),
470
+ endOnly: true
471
+ });
472
+ collectAnchored(inner, firstLine);
473
+ } else if (hasItems(item)) collectAnchored(item, firstLine);
474
+ }
475
+ };
476
+ for (const group of groups) {
477
+ if (group.kind !== "member" || !group.member) continue;
478
+ const comments = group.items.filter((item) => item !== group.member);
479
+ if (group.member === node) {
480
+ nodeOwnStart = clonePosition(node.loc.start);
481
+ nodeOwnEnd = clonePosition(node.loc.end);
482
+ if (isInlineItem(node)) nodeInnerEnd = clonePosition(node.item.loc.end);
483
+ collectAnchored(isInlineItem(node) ? node.item : node, nodeOwnStart.line);
484
+ if (comments.length) {
485
+ node.loc.start = clonePosition(group.items[0].loc.start);
486
+ node.loc.end = clonePosition(last(group.items).loc.end);
487
+ }
488
+ }
489
+ if (!comments.length) continue;
490
+ detached.push({
491
+ owner: group.member,
492
+ ownerOriginalStart: clonePosition(group.member.loc.start),
493
+ comments
494
+ });
495
+ for (const comment of comments) {
496
+ const idx = hostContainer.items.indexOf(comment);
497
+ if (idx >= 0) hostContainer.items.splice(idx, 1);
498
+ }
499
+ }
500
+ const nodeIndexBeforeRemove = parent.items.indexOf(node);
501
+ const removedWasLast = nodeIndexBeforeRemove === parent.items.length - 1;
502
+ const prevBeforeRemove = nodeIndexBeforeRemove > 0 ? parent.items[nodeIndexBeforeRemove - 1] : void 0;
503
+ const movedMultilineToFront = toIndex === 0 && nodeIndexBeforeRemove > 0 && node.loc.end.line > node.loc.start.line && prevBeforeRemove !== void 0 && prevBeforeRemove.loc.start.line === node.loc.start.line;
504
+ remove(root, parent, node, hostContainer.items);
505
+ let cancelMultilineLastRemovalOffsets = false;
506
+ if (removedWasLast && prevBeforeRemove !== void 0 && node.loc.end.line > node.loc.start.line && !perLine(parent)) {
507
+ if (getExitOffsets(root).get(prevBeforeRemove)) {
508
+ getExitOffsets(root).delete(prevBeforeRemove);
509
+ cancelMultilineLastRemovalOffsets = true;
510
+ }
511
+ }
512
+ applyWrites(root);
513
+ insert(root, parent, node, toIndex, void 0, hostContainer.items);
514
+ if (cancelMultilineLastRemovalOffsets) {
515
+ const childPending = getExitOffsets(root).get(node);
516
+ if (childPending) {
517
+ childPending.lines = 0;
518
+ childPending.columns = 0;
519
+ }
520
+ }
521
+ applyWrites(root);
522
+ if (nodeOwnStart && nodeOwnEnd && node.loc.end.line > node.loc.start.line) {
523
+ node.loc.end.column = nodeOwnEnd.column;
524
+ if (isInlineItem(node) && nodeInnerEnd && node.item.loc.end.line > node.item.loc.start.line) node.item.loc.end.column = nodeInnerEnd.column;
525
+ }
526
+ for (const { node: descendant, start, end, endOnly, equals } of anchoredDescendants) {
527
+ if (endOnly) {
528
+ descendant.loc.end.column = end.column;
529
+ continue;
530
+ }
531
+ descendant.loc.start.column = start.column;
532
+ if (descendant.loc.end.line === descendant.loc.start.line) descendant.loc.end.column = end.column;
533
+ if (equals !== void 0 && isKeyValue(descendant)) descendant.equals = equals;
534
+ }
535
+ for (const { owner, ownerOriginalStart, comments } of detached) {
536
+ let delta;
537
+ if (owner === node) {
538
+ delta = {
539
+ lines: node.loc.start.line - ownerOriginalStart.line,
540
+ columns: node.loc.start.column - ownerOriginalStart.column
541
+ };
542
+ node.loc.start = {
543
+ line: nodeOwnStart.line + delta.lines,
544
+ column: nodeOwnStart.column + delta.columns
545
+ };
546
+ node.loc.end = {
547
+ line: nodeOwnEnd.line + delta.lines,
548
+ column: nodeOwnEnd.column + delta.columns
549
+ };
550
+ } else delta = {
551
+ lines: owner.loc.start.line - ownerOriginalStart.line,
552
+ columns: owner.loc.start.column - ownerOriginalStart.column
553
+ };
554
+ for (const comment of comments) {
555
+ shiftNode(comment, delta);
556
+ const insertAt = hostContainer.items.findIndex((item) => item.loc.start.line > comment.loc.start.line);
557
+ if (insertAt === -1) hostContainer.items.push(comment);
558
+ else hostContainer.items.splice(insertAt, 0, comment);
559
+ }
560
+ }
561
+ const container = parent;
562
+ if (sharedLineContainerBeforeMove || movedMultilineToFront) {
563
+ const realignInterior = (inner, wrapper) => {
564
+ let anchor;
565
+ for (const row of inner.items) {
566
+ if (!anchor) {
567
+ anchor = {
568
+ line: row.loc.end.line,
569
+ column: row.loc.end.column + 2
570
+ };
571
+ continue;
572
+ }
573
+ const d = {
574
+ lines: anchor.line - row.loc.start.line,
575
+ columns: anchor.column - row.loc.start.column
576
+ };
577
+ if (d.lines !== 0 || d.columns !== 0) {
578
+ shiftNode(row, d);
579
+ if (row.loc.end.line > row.loc.start.line) {
580
+ row.loc.end.column -= d.columns;
581
+ if (isInlineItem(row) && row.item.loc.end.line > row.item.loc.start.line) row.item.loc.end.column -= d.columns;
582
+ }
583
+ const rowInner = isInlineItem(row) ? isKeyValue(row.item) ? row.item.value : row.item : row;
584
+ if ((isInlineTable(rowInner) || isInlineArray(rowInner)) && rowInner.loc.end.line > rowInner.loc.start.line) realignInterior(rowInner, row);
585
+ }
586
+ anchor = {
587
+ line: row.loc.end.line,
588
+ column: row.loc.end.column + 2
589
+ };
590
+ }
591
+ if (anchor) {
592
+ inner.loc.end = {
593
+ line: anchor.line,
594
+ column: anchor.column - 1
595
+ };
596
+ if (wrapper && wrapper.loc.end.line === inner.loc.end.line) wrapper.loc.end.column = inner.loc.end.column;
597
+ }
598
+ };
599
+ let tailAnchor;
600
+ for (const item of container.items) {
601
+ if (item === node) {
602
+ tailAnchor = {
603
+ line: node.loc.end.line,
604
+ column: node.loc.end.column + 2
605
+ };
606
+ continue;
607
+ }
608
+ if (!tailAnchor) continue;
609
+ const delta = {
610
+ lines: tailAnchor.line - item.loc.start.line,
611
+ columns: tailAnchor.column - item.loc.start.column
612
+ };
613
+ if (delta.lines !== 0 || delta.columns !== 0) {
614
+ shiftNode(item, delta);
615
+ const itemInner = isInlineItem(item) ? isKeyValue(item.item) ? item.item.value : item.item : item;
616
+ if ((isInlineTable(itemInner) || isInlineArray(itemInner)) && itemInner.loc.end.line > itemInner.loc.start.line) realignInterior(itemInner, isInlineItem(item) ? item : void 0);
617
+ }
618
+ let itemEndLine = item.loc.end.line;
619
+ const tailInner = isInlineItem(item) ? item.item : item;
620
+ if (isString(tailInner) && tailInner.loc.end.line > tailInner.loc.start.line) {
621
+ itemEndLine = tailInner.loc.start.line + tailInner.raw.split("\n").length - 1;
622
+ tailInner.loc.end.line = itemEndLine;
623
+ item.loc.end.line = itemEndLine;
624
+ }
625
+ tailAnchor = {
626
+ line: itemEndLine,
627
+ column: item.loc.end.column + 2
628
+ };
629
+ }
630
+ if (tailAnchor) {
631
+ const endBeforeRealign = clonePosition(container.loc.end);
632
+ container.loc.end = {
633
+ line: tailAnchor.line,
634
+ column: tailAnchor.column - 1
635
+ };
636
+ const wrapper = findWrapperItem(root, container);
637
+ if (wrapper) wrapper.loc.end = {
638
+ line: container.loc.end.line,
639
+ column: container.loc.end.column
640
+ };
641
+ const endDelta = {
642
+ lines: container.loc.end.line - endBeforeRealign.line,
643
+ columns: container.loc.end.column - endBeforeRealign.column
644
+ };
645
+ if (endDelta.lines !== 0 || endDelta.columns !== 0) addExitOffset(root, wrapper ?? container, endDelta);
646
+ }
647
+ }
648
+ return;
649
+ }
650
+ }
651
+ const container = parent;
652
+ const itemsBefore = container.items;
653
+ const firstBefore = itemsBefore[0];
654
+ const lastBefore = itemsBefore[itemsBefore.length - 1];
655
+ const originalLeadingGap = firstBefore.loc.start.column - container.loc.start.column - 1;
656
+ const originalTrailingGap = container.loc.end.column - 1 - lastBefore.loc.end.column;
657
+ remove(root, parent, node);
658
+ insert(root, parent, node, toIndex);
659
+ applyWrites(root);
660
+ const itemsAfter = container.items;
661
+ const firstAfter = itemsAfter[0];
662
+ const leadingGap = firstAfter.loc.start.column - container.loc.start.column - 1;
663
+ if (leadingGap !== originalLeadingGap) shiftNode(firstAfter, {
664
+ lines: 0,
665
+ columns: originalLeadingGap - leadingGap
666
+ });
667
+ const lastAfter = itemsAfter[itemsAfter.length - 1];
668
+ if (container.loc.end.column - 1 - lastAfter.loc.end.column !== originalTrailingGap) container.loc.end.column = lastAfter.loc.end.column + 1 + originalTrailingGap;
669
+ }
670
+
671
+ export { IS_COMMENTED_OUT_HEADER, IS_COMMENTED_OUT_KEY_VALUE, findHostContainer, isCommentedOutEntry, moveInlineElement, normalizeSectionComments, removeMember, resolveGroups, resolveInlineElementGroups };
672
+ //# sourceMappingURL=comment-ownership.js.map