@decimalturn/toml-patch 3.0.4 → 3.1.0-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 (71) hide show
  1. package/dist/dev/comment-alignment.js +372 -0
  2. package/dist/dev/comment-alignment.js.map +1 -0
  3. package/dist/dev/comment-ownership.js +660 -0
  4. package/dist/dev/comment-ownership.js.map +1 -0
  5. package/dist/dev/cst-source.js +108 -0
  6. package/dist/dev/cst-source.js.map +1 -0
  7. package/dist/dev/cst.js +59 -0
  8. package/dist/dev/cst.js.map +1 -0
  9. package/dist/dev/cursor.js +66 -0
  10. package/dist/dev/cursor.js.map +1 -0
  11. package/dist/dev/date-format.js +196 -0
  12. package/dist/dev/date-format.js.map +1 -0
  13. package/dist/dev/decode-utf8.js +27 -0
  14. package/dist/dev/decode-utf8.js.map +1 -0
  15. package/dist/dev/diff.js +269 -0
  16. package/dist/dev/diff.js.map +1 -0
  17. package/dist/dev/escape-preference.js +144 -0
  18. package/dist/dev/escape-preference.js.map +1 -0
  19. package/dist/dev/find-by-path.js +111 -0
  20. package/dist/dev/find-by-path.js.map +1 -0
  21. package/dist/dev/formatter.js +295 -0
  22. package/dist/dev/formatter.js.map +1 -0
  23. package/dist/dev/generate.js +451 -0
  24. package/dist/dev/generate.js.map +1 -0
  25. package/dist/dev/inline-comma-space.js +13 -0
  26. package/dist/dev/inline-comma-space.js.map +1 -0
  27. package/dist/dev/inline-format.js +106 -0
  28. package/dist/dev/inline-format.js.map +1 -0
  29. package/dist/dev/inline-layout.js +107 -0
  30. package/dist/dev/inline-layout.js.map +1 -0
  31. package/dist/dev/line-ending-backslash.js +320 -0
  32. package/dist/dev/line-ending-backslash.js.map +1 -0
  33. package/dist/dev/location.js +77 -0
  34. package/dist/dev/location.js.map +1 -0
  35. package/dist/dev/parse-error.js +27 -0
  36. package/dist/dev/parse-error.js.map +1 -0
  37. package/dist/dev/parse-js.js +103 -0
  38. package/dist/dev/parse-js.js.map +1 -0
  39. package/dist/dev/parse-string.js +122 -0
  40. package/dist/dev/parse-string.js.map +1 -0
  41. package/dist/dev/parse-toml.js +669 -0
  42. package/dist/dev/parse-toml.js.map +1 -0
  43. package/dist/dev/patch.js +2537 -0
  44. package/dist/dev/patch.js.map +1 -0
  45. package/dist/dev/to-js.js +303 -0
  46. package/dist/dev/to-js.js.map +1 -0
  47. package/dist/dev/to-toml.js +569 -0
  48. package/dist/dev/to-toml.js.map +1 -0
  49. package/dist/dev/tokenizer.js +225 -0
  50. package/dist/dev/tokenizer.js.map +1 -0
  51. package/dist/dev/toml-document.js +215 -0
  52. package/dist/dev/toml-document.js.map +1 -0
  53. package/dist/dev/toml-format.js +476 -0
  54. package/dist/dev/toml-format.js.map +1 -0
  55. package/dist/dev/toml-patch.js +84 -0
  56. package/dist/dev/toml-patch.js.map +1 -0
  57. package/dist/dev/traverse.js +61 -0
  58. package/dist/dev/traverse.js.map +1 -0
  59. package/dist/dev/truncate.js +64 -0
  60. package/dist/dev/truncate.js.map +1 -0
  61. package/dist/dev/update-order.js +235 -0
  62. package/dist/dev/update-order.js.map +1 -0
  63. package/dist/dev/utils.js +223 -0
  64. package/dist/dev/utils.js.map +1 -0
  65. package/dist/dev/writer.js +758 -0
  66. package/dist/dev/writer.js.map +1 -0
  67. package/dist/toml-patch.d.ts +28 -13
  68. package/package.json +12 -88
  69. package/LICENSE +0 -22
  70. package/README.md +0 -161
  71. package/dist/toml-patch.js +0 -54
@@ -0,0 +1,660 @@
1
+ //! @decimalturn/toml-patch v3.1.0 - 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 { clonePosition } from "./location.js";
4
+ import { last } from "./utils.js";
5
+ import { addExitOffset, applyWrites, getExitOffsets, insert, perLine, recalcContainerEnd, remove, shiftNode } from "./writer.js";
6
+
7
+ //#region 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
+ * scanSlots. 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 (resolveInlineElementSlots / 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 resolveSlots (Document/Table/TableArray, where members
96
+ * and comments are already interleaved in one items array) and
97
+ * resolveInlineElementSlots (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 scanSlots(items, initialLastMemberEndLine, isEligibleForLeading, memberKey = getMemberKey) {
102
+ const slots = [];
103
+ let lastMemberEndLine = initialLastMemberEndLine;
104
+ let currentMemberSlot;
105
+ let pendingRun = [];
106
+ const flushPendingAsPinned = () => {
107
+ if (!pendingRun.length) return;
108
+ slots.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 (currentMemberSlot) {
120
+ currentMemberSlot.items.push(item);
121
+ currentMemberSlot.endLine = Math.max(currentMemberSlot.endLine, item.loc.end.line);
122
+ } else slots.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
+ slots.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 slotItems = [...leading, item];
166
+ const slot = {
167
+ kind: "member",
168
+ member: item,
169
+ key: memberKey(item),
170
+ items: slotItems,
171
+ startLine: slotItems[0].loc.start.line,
172
+ endLine: item.loc.end.line
173
+ };
174
+ slots.push(slot);
175
+ currentMemberSlot = slot;
176
+ lastMemberEndLine = item.loc.end.line;
177
+ }
178
+ flushPendingAsPinned();
179
+ return slots;
180
+ }
181
+ /**
182
+ * Partitions a container's items into ownership slots, 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 run.
188
+ */
189
+ function resolveSlots(container, isEligibleForLeading = () => true, memberKey = getMemberKey) {
190
+ const initialLastMemberEndLine = isDocument(container) ? 0 : container.key.loc.end.line;
191
+ return scanSlots(container.items, initialLastMemberEndLine, isEligibleForLeading, memberKey);
192
+ }
193
+ /**
194
+ * The element-level analogue of resolveSlots, 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 resolveSlots 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/PLAN-Comment-Ownership.md for why that's an accepted, untested edge
207
+ * case rather than a deliberate rule.
208
+ */
209
+ function resolveInlineElementSlots(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 scanSlots([...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 runs 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 run 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 lastSlot = last(resolveSlots(container));
304
+ if (!lastSlot || lastSlot.kind !== "pinned") return void 0;
305
+ const runItems = lastSlot.items;
306
+ const adjacent = lastSlot.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 run and right-side/trailing comments — see resolveSlots), plus,
314
+ * when `member` is a [table]/[[array]] block, any trailing comment run the
315
+ * parser filed under the PRECEDING sibling table but which R5 assigns to
316
+ * `member` instead. Falls back to a plain removal when `parent` isn't a
317
+ * container the ownership model applies to (e.g. InlineTable/InlineArray).
318
+ */
319
+ function removeMember(root, parent, member) {
320
+ if (isDocument(parent) && (isTable(member) || isTableArray(member))) {
321
+ const index = parent.items.indexOf(member);
322
+ const previousSibling = index > 0 ? parent.items[index - 1] : void 0;
323
+ if (previousSibling && (isTable(previousSibling) || isTableArray(previousSibling))) {
324
+ const runItems = trailingOwnedRun(previousSibling, member);
325
+ if (runItems) for (const item of runItems) remove(root, previousSibling, item);
326
+ }
327
+ }
328
+ if (isDocument(parent) || isTable(parent) || isTableArray(parent)) {
329
+ const slot = resolveSlots(parent).find((s) => s.member === member);
330
+ if (slot) {
331
+ const memberIndex = slot.items.indexOf(member);
332
+ for (let i = 0; i <= memberIndex; i++) {
333
+ const item = slot.items[i];
334
+ if (!parent.items.includes(item)) continue;
335
+ remove(root, parent, item);
336
+ }
337
+ for (let i = memberIndex + 1; i < slot.items.length; i++) {
338
+ const item = slot.items[i];
339
+ const idx = parent.items.indexOf(item);
340
+ if (idx < 0) continue;
341
+ parent.items.splice(idx, 1);
342
+ }
343
+ return;
344
+ }
345
+ }
346
+ if (isMultilineInlineContainer(parent) && isDocument(root)) {
347
+ const hostContainer = findHostContainer(root, parent);
348
+ if (hostContainer) {
349
+ const slot = resolveInlineElementSlots(parent, hostContainer.items).find((s) => s.member === member);
350
+ if (slot) {
351
+ const comments = slot.items.filter((item) => item !== member);
352
+ for (const comment of comments) {
353
+ const idx = hostContainer.items.indexOf(comment);
354
+ if (idx < 0) continue;
355
+ hostContainer.items.splice(idx, 1);
356
+ }
357
+ if (comments.length) {
358
+ member.loc.start = slot.items[0].loc.start;
359
+ member.loc.end = last(slot.items).loc.end;
360
+ }
361
+ remove(root, parent, member, hostContainer.items);
362
+ applyWrites(root);
363
+ return;
364
+ }
365
+ }
366
+ }
367
+ remove(root, parent, member);
368
+ }
369
+ /**
370
+ * Relocates `node` (an element of `parent`, an InlineTable/InlineArray) from
371
+ * its current position to `toIndex`, carrying its own owned comments along
372
+ * (see resolveInlineElementSlots) rather than leaving them at their old
373
+ * absolute position — which is what plain remove()+insert() does, and why a
374
+ * Move on a commented inline array can misplace a comment onto an unrelated
375
+ * line (see "Extending to elements inside multi-line arrays" in
376
+ * docs/PLAN-Comment-Ownership.md).
377
+ *
378
+ * It isn't enough to protect only `node`'s own comments: writer.remove()'s
379
+ * per-container "orphaned comment" cleanup reasons purely by absolute line
380
+ * number, with no notion of ownership, so relocating `node` past *other*
381
+ * elements can drag an unrelated element's own comment along as a side
382
+ * effect (or leave it stranded) even though that element never moved. Every
383
+ * commented element in the container is protected the same way: its
384
+ * comment(s) are detached before the move and re-attached afterward, based
385
+ * on how far *that specific element* actually shifted — which may differ
386
+ * from how far `node` itself moved, or be zero.
387
+ */
388
+ function moveInlineElement(root, parent, node, toIndex) {
389
+ let sharedLineContainerBeforeMove = false;
390
+ if (isMultilineInlineContainer(parent) && isDocument(root)) {
391
+ const hostContainer = findHostContainer(root, parent);
392
+ if (hostContainer) {
393
+ const slots = resolveInlineElementSlots(parent, hostContainer.items);
394
+ {
395
+ const items = parent.items;
396
+ let run = 1;
397
+ for (let i = 1; i < items.length; i++) if (items[i].loc.start.line === items[i - 1].loc.start.line) {
398
+ const prevPending = getExitOffsets(root).get(items[i - 1]);
399
+ const selfPending = getExitOffsets(root).get(items[i]);
400
+ if (prevPending || selfPending) continue;
401
+ run++;
402
+ if (run >= 3) {
403
+ sharedLineContainerBeforeMove = true;
404
+ break;
405
+ }
406
+ } else run = 1;
407
+ }
408
+ const detached = [];
409
+ let nodeOwnStart;
410
+ let nodeOwnEnd;
411
+ let nodeInnerEnd;
412
+ const anchoredDescendants = [];
413
+ const collectAnchored = (container, firstLine) => {
414
+ if (!hasItems(container)) return;
415
+ const items = container.items;
416
+ for (let i = 0; i < items.length; i++) {
417
+ const item = items[i];
418
+ const below = item.loc.start.line > firstLine;
419
+ if (below) anchoredDescendants.push({
420
+ node: item,
421
+ start: clonePosition(item.loc.start),
422
+ end: clonePosition(item.loc.end)
423
+ });
424
+ if (item.loc.end.line > firstLine && item.loc.end.line > item.loc.start.line) anchoredDescendants.push({
425
+ node: item,
426
+ start: clonePosition(item.loc.start),
427
+ end: clonePosition(item.loc.end),
428
+ endOnly: true
429
+ });
430
+ if (isInlineItem(item)) {
431
+ const inner = item.item;
432
+ if (below) {
433
+ const kv = isKeyValue(inner) ? inner : void 0;
434
+ anchoredDescendants.push({
435
+ node: inner,
436
+ start: clonePosition(inner.loc.start),
437
+ end: clonePosition(inner.loc.end),
438
+ equals: kv ? kv.equals : void 0
439
+ });
440
+ if (kv) {
441
+ anchoredDescendants.push({
442
+ node: kv.key,
443
+ start: clonePosition(kv.key.loc.start),
444
+ end: clonePosition(kv.key.loc.end)
445
+ });
446
+ anchoredDescendants.push({
447
+ node: kv.value,
448
+ start: clonePosition(kv.value.loc.start),
449
+ end: clonePosition(kv.value.loc.end)
450
+ });
451
+ }
452
+ }
453
+ if (inner.loc.end.line > firstLine && inner.loc.end.line > inner.loc.start.line) anchoredDescendants.push({
454
+ node: inner,
455
+ start: clonePosition(inner.loc.start),
456
+ end: clonePosition(inner.loc.end),
457
+ endOnly: true
458
+ });
459
+ collectAnchored(inner, firstLine);
460
+ } else if (hasItems(item)) collectAnchored(item, firstLine);
461
+ }
462
+ };
463
+ for (const slot of slots) {
464
+ if (slot.kind !== "member" || !slot.member) continue;
465
+ const comments = slot.items.filter((item) => item !== slot.member);
466
+ if (slot.member === node) {
467
+ nodeOwnStart = clonePosition(node.loc.start);
468
+ nodeOwnEnd = clonePosition(node.loc.end);
469
+ if (isInlineItem(node)) nodeInnerEnd = clonePosition(node.item.loc.end);
470
+ collectAnchored(isInlineItem(node) ? node.item : node, nodeOwnStart.line);
471
+ if (comments.length) {
472
+ node.loc.start = clonePosition(slot.items[0].loc.start);
473
+ node.loc.end = clonePosition(last(slot.items).loc.end);
474
+ }
475
+ }
476
+ if (!comments.length) continue;
477
+ detached.push({
478
+ owner: slot.member,
479
+ ownerOriginalStart: clonePosition(slot.member.loc.start),
480
+ comments
481
+ });
482
+ for (const comment of comments) {
483
+ const idx = hostContainer.items.indexOf(comment);
484
+ if (idx >= 0) hostContainer.items.splice(idx, 1);
485
+ }
486
+ }
487
+ const nodeIndexBeforeRemove = parent.items.indexOf(node);
488
+ const removedWasLast = nodeIndexBeforeRemove === parent.items.length - 1;
489
+ const prevBeforeRemove = nodeIndexBeforeRemove > 0 ? parent.items[nodeIndexBeforeRemove - 1] : void 0;
490
+ 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;
491
+ remove(root, parent, node, hostContainer.items);
492
+ let cancelMultilineLastRemovalOffsets = false;
493
+ if (removedWasLast && prevBeforeRemove !== void 0 && node.loc.end.line > node.loc.start.line && !perLine(parent)) {
494
+ if (getExitOffsets(root).get(prevBeforeRemove)) {
495
+ getExitOffsets(root).delete(prevBeforeRemove);
496
+ cancelMultilineLastRemovalOffsets = true;
497
+ }
498
+ }
499
+ applyWrites(root);
500
+ insert(root, parent, node, toIndex, void 0, hostContainer.items);
501
+ if (cancelMultilineLastRemovalOffsets) {
502
+ const childPending = getExitOffsets(root).get(node);
503
+ if (childPending) {
504
+ childPending.lines = 0;
505
+ childPending.columns = 0;
506
+ }
507
+ }
508
+ applyWrites(root);
509
+ if (nodeOwnStart && nodeOwnEnd && node.loc.end.line > node.loc.start.line) {
510
+ node.loc.end.column = nodeOwnEnd.column;
511
+ if (isInlineItem(node) && nodeInnerEnd && node.item.loc.end.line > node.item.loc.start.line) node.item.loc.end.column = nodeInnerEnd.column;
512
+ }
513
+ for (const { node: descendant, start, end, endOnly, equals } of anchoredDescendants) {
514
+ if (endOnly) {
515
+ descendant.loc.end.column = end.column;
516
+ continue;
517
+ }
518
+ descendant.loc.start.column = start.column;
519
+ if (descendant.loc.end.line === descendant.loc.start.line) descendant.loc.end.column = end.column;
520
+ if (equals !== void 0 && isKeyValue(descendant)) descendant.equals = equals;
521
+ }
522
+ for (const { owner, ownerOriginalStart, comments } of detached) {
523
+ let delta;
524
+ if (owner === node) {
525
+ delta = {
526
+ lines: node.loc.start.line - ownerOriginalStart.line,
527
+ columns: node.loc.start.column - ownerOriginalStart.column
528
+ };
529
+ node.loc.start = {
530
+ line: nodeOwnStart.line + delta.lines,
531
+ column: nodeOwnStart.column + delta.columns
532
+ };
533
+ node.loc.end = {
534
+ line: nodeOwnEnd.line + delta.lines,
535
+ column: nodeOwnEnd.column + delta.columns
536
+ };
537
+ } else delta = {
538
+ lines: owner.loc.start.line - ownerOriginalStart.line,
539
+ columns: owner.loc.start.column - ownerOriginalStart.column
540
+ };
541
+ for (const comment of comments) {
542
+ shiftNode(comment, delta);
543
+ const insertAt = hostContainer.items.findIndex((item) => item.loc.start.line > comment.loc.start.line);
544
+ if (insertAt === -1) hostContainer.items.push(comment);
545
+ else hostContainer.items.splice(insertAt, 0, comment);
546
+ }
547
+ }
548
+ const container = parent;
549
+ if (sharedLineContainerBeforeMove || movedMultilineToFront) {
550
+ const realignInterior = (inner, wrapper) => {
551
+ let anchor;
552
+ for (const row of inner.items) {
553
+ if (!anchor) {
554
+ anchor = {
555
+ line: row.loc.end.line,
556
+ column: row.loc.end.column + 2
557
+ };
558
+ continue;
559
+ }
560
+ const d = {
561
+ lines: anchor.line - row.loc.start.line,
562
+ columns: anchor.column - row.loc.start.column
563
+ };
564
+ if (d.lines !== 0 || d.columns !== 0) {
565
+ shiftNode(row, d);
566
+ if (row.loc.end.line > row.loc.start.line) {
567
+ row.loc.end.column -= d.columns;
568
+ if (isInlineItem(row) && row.item.loc.end.line > row.item.loc.start.line) row.item.loc.end.column -= d.columns;
569
+ }
570
+ const rowInner = isInlineItem(row) ? isKeyValue(row.item) ? row.item.value : row.item : row;
571
+ if ((isInlineTable(rowInner) || isInlineArray(rowInner)) && rowInner.loc.end.line > rowInner.loc.start.line) realignInterior(rowInner, row);
572
+ }
573
+ anchor = {
574
+ line: row.loc.end.line,
575
+ column: row.loc.end.column + 2
576
+ };
577
+ }
578
+ if (anchor) {
579
+ inner.loc.end = {
580
+ line: anchor.line,
581
+ column: anchor.column - 1
582
+ };
583
+ if (wrapper && wrapper.loc.end.line === inner.loc.end.line) wrapper.loc.end.column = inner.loc.end.column;
584
+ }
585
+ };
586
+ let tailAnchor;
587
+ for (const item of container.items) {
588
+ if (item === node) {
589
+ tailAnchor = {
590
+ line: node.loc.end.line,
591
+ column: node.loc.end.column + 2
592
+ };
593
+ continue;
594
+ }
595
+ if (!tailAnchor) continue;
596
+ const delta = {
597
+ lines: tailAnchor.line - item.loc.start.line,
598
+ columns: tailAnchor.column - item.loc.start.column
599
+ };
600
+ if (delta.lines !== 0 || delta.columns !== 0) {
601
+ shiftNode(item, delta);
602
+ const itemInner = isInlineItem(item) ? isKeyValue(item.item) ? item.item.value : item.item : item;
603
+ if ((isInlineTable(itemInner) || isInlineArray(itemInner)) && itemInner.loc.end.line > itemInner.loc.start.line) realignInterior(itemInner, isInlineItem(item) ? item : void 0);
604
+ }
605
+ let itemEndLine = item.loc.end.line;
606
+ const tailInner = isInlineItem(item) ? item.item : item;
607
+ if (isString(tailInner) && tailInner.loc.end.line > tailInner.loc.start.line) {
608
+ itemEndLine = tailInner.loc.start.line + tailInner.raw.split("\n").length - 1;
609
+ tailInner.loc.end.line = itemEndLine;
610
+ item.loc.end.line = itemEndLine;
611
+ }
612
+ tailAnchor = {
613
+ line: itemEndLine,
614
+ column: item.loc.end.column + 2
615
+ };
616
+ }
617
+ if (tailAnchor) {
618
+ const endBeforeRealign = clonePosition(container.loc.end);
619
+ container.loc.end = {
620
+ line: tailAnchor.line,
621
+ column: tailAnchor.column - 1
622
+ };
623
+ const wrapper = findWrapperItem(root, container);
624
+ if (wrapper) wrapper.loc.end = {
625
+ line: container.loc.end.line,
626
+ column: container.loc.end.column
627
+ };
628
+ const endDelta = {
629
+ lines: container.loc.end.line - endBeforeRealign.line,
630
+ columns: container.loc.end.column - endBeforeRealign.column
631
+ };
632
+ if (endDelta.lines !== 0 || endDelta.columns !== 0) addExitOffset(root, wrapper ?? container, endDelta);
633
+ }
634
+ }
635
+ return;
636
+ }
637
+ }
638
+ const container = parent;
639
+ const itemsBefore = container.items;
640
+ const firstBefore = itemsBefore[0];
641
+ const lastBefore = itemsBefore[itemsBefore.length - 1];
642
+ const originalLeadingGap = firstBefore.loc.start.column - container.loc.start.column - 1;
643
+ const originalTrailingGap = container.loc.end.column - 1 - lastBefore.loc.end.column;
644
+ remove(root, parent, node);
645
+ insert(root, parent, node, toIndex);
646
+ applyWrites(root);
647
+ const itemsAfter = container.items;
648
+ const firstAfter = itemsAfter[0];
649
+ const leadingGap = firstAfter.loc.start.column - container.loc.start.column - 1;
650
+ if (leadingGap !== originalLeadingGap) shiftNode(firstAfter, {
651
+ lines: 0,
652
+ columns: originalLeadingGap - leadingGap
653
+ });
654
+ const lastAfter = itemsAfter[itemsAfter.length - 1];
655
+ if (container.loc.end.column - 1 - lastAfter.loc.end.column !== originalTrailingGap) container.loc.end.column = lastAfter.loc.end.column + 1 + originalTrailingGap;
656
+ }
657
+
658
+ //#endregion
659
+ export { IS_COMMENTED_OUT_HEADER, IS_COMMENTED_OUT_KEY_VALUE, findHostContainer, isCommentedOutEntry, moveInlineElement, normalizeSectionComments, removeMember, resolveInlineElementSlots, resolveSlots };
660
+ //# sourceMappingURL=comment-ownership.js.map