@decimalturn/toml-patch 3.2.1 → 3.3.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 (83) 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 +118 -0
  6. package/dist/dev/cst-source.js.map +1 -0
  7. package/dist/dev/cst.js +68 -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 +287 -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-lite.js +108 -0
  16. package/dist/dev/diff-lite.js.map +1 -0
  17. package/dist/dev/diff.js +265 -0
  18. package/dist/dev/diff.js.map +1 -0
  19. package/dist/dev/encode-lite.js +210 -0
  20. package/dist/dev/encode-lite.js.map +1 -0
  21. package/dist/dev/escape-preference.js +166 -0
  22. package/dist/dev/escape-preference.js.map +1 -0
  23. package/dist/dev/find-by-path.js +111 -0
  24. package/dist/dev/find-by-path.js.map +1 -0
  25. package/dist/dev/formatter.js +298 -0
  26. package/dist/dev/formatter.js.map +1 -0
  27. package/dist/dev/generate.js +466 -0
  28. package/dist/dev/generate.js.map +1 -0
  29. package/dist/dev/inline-comma-space.js +13 -0
  30. package/dist/dev/inline-comma-space.js.map +1 -0
  31. package/dist/dev/inline-format.js +106 -0
  32. package/dist/dev/inline-format.js.map +1 -0
  33. package/dist/dev/inline-layout.js +107 -0
  34. package/dist/dev/inline-layout.js.map +1 -0
  35. package/dist/dev/line-ending-backslash.js +320 -0
  36. package/dist/dev/line-ending-backslash.js.map +1 -0
  37. package/dist/dev/literal-string.js +46 -0
  38. package/dist/dev/literal-string.js.map +1 -0
  39. package/dist/dev/location.js +104 -0
  40. package/dist/dev/location.js.map +1 -0
  41. package/dist/dev/parse-error.js +27 -0
  42. package/dist/dev/parse-error.js.map +1 -0
  43. package/dist/dev/parse-js.js +150 -0
  44. package/dist/dev/parse-js.js.map +1 -0
  45. package/dist/dev/parse-string.js +122 -0
  46. package/dist/dev/parse-string.js.map +1 -0
  47. package/dist/dev/parse-toml.js +714 -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 +97 -0
  51. package/dist/dev/patch-lite2.js.map +1 -0
  52. package/dist/dev/patch.js +2646 -0
  53. package/dist/dev/patch.js.map +1 -0
  54. package/dist/dev/smol-toml-date.js +61 -0
  55. package/dist/dev/smol-toml-date.js.map +1 -0
  56. package/dist/dev/to-js.js +303 -0
  57. package/dist/dev/to-js.js.map +1 -0
  58. package/dist/dev/to-toml.js +874 -0
  59. package/dist/dev/to-toml.js.map +1 -0
  60. package/dist/dev/tokenizer.js +225 -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 +549 -0
  65. package/dist/dev/toml-format.js.map +1 -0
  66. package/dist/dev/toml-patch.js +94 -0
  67. package/dist/dev/toml-patch.js.map +1 -0
  68. package/dist/dev/traverse.js +61 -0
  69. package/dist/dev/traverse.js.map +1 -0
  70. package/dist/dev/truncate.js +64 -0
  71. package/dist/dev/truncate.js.map +1 -0
  72. package/dist/dev/update-order.js +235 -0
  73. package/dist/dev/update-order.js.map +1 -0
  74. package/dist/dev/utils.js +302 -0
  75. package/dist/dev/utils.js.map +1 -0
  76. package/dist/dev/writer.js +758 -0
  77. package/dist/dev/writer.js.map +1 -0
  78. package/dist/patch-lite.d.ts +18 -0
  79. package/dist/toml-patch.d.ts +19 -2
  80. package/package.json +16 -102
  81. package/LICENSE +0 -22
  82. package/README.md +0 -202
  83. package/dist/toml-patch.js +0 -84
@@ -0,0 +1,166 @@
1
+ //! @decimalturn/toml-patch v3.3.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ //#region src/escape-preference.ts
3
+ /**
4
+ * @file Escape-style helpers used to preserve escape sequences as preferred encoding (e.g. \u263A)
5
+ * when rewriting TOML basic strings and quoted key parts.
6
+ *
7
+ * @module escape-preference
8
+ *
9
+ * Summary:
10
+ * The problem with naive parsing + re-serializing of TOML strings is that it normalizes
11
+ * all escape sequences to their decoded character values.
12
+ *
13
+ * For example, if a TOML string contains `\u263A`, the JS string value will contain the raw ☺ character.
14
+ * If we then naively return that string for TOML output, we would get `☺` instead of the original `\u263A`.
15
+ * This module provides functions to scan existing raw TOML strings to infer the preferred representation of certain characters
16
+ * and then reuse those preferred escapes when generating new TOML output, thus preserving the original style where possible.
17
+ *
18
+ * Note that we are taking the presence of a single instance of an escape sequence in the original raw string as
19
+ * an indication of the user's preferred rendering for that character. A more faithful preservation of style
20
+ * would be to track all instances of each character and their various rendered forms, but this would add
21
+ * complexity and overhead. The current approach tries to balance things out by capturing the first seen
22
+ * escape for each character, which should cover the vast majority of use cases for TOML.
23
+ *
24
+ */
25
+ /**
26
+ * Decodes a TOML single-character escape code to its JS character.
27
+ *
28
+ * @param ch - Escape code character (without the leading backslash).
29
+ * @returns The decoded character, or null if the code is not a supported simple escape.
30
+ */
31
+ function decodeSimpleEscape(ch) {
32
+ switch (ch) {
33
+ case "b": return "\b";
34
+ case "t": return " ";
35
+ case "n": return "\n";
36
+ case "f": return "\f";
37
+ case "r": return "\r";
38
+ case "\"": return "\"";
39
+ case "\\": return "\\";
40
+ default: return null;
41
+ }
42
+ }
43
+ function isDisallowedControl(code, mode) {
44
+ if (mode === "singleline-basic") return code <= 31 || code === 127;
45
+ return code >= 0 && code <= 7 || code === 11 || code >= 14 && code <= 31 || code === 127;
46
+ }
47
+ function mandatoryEscaping(ch, mode, escapeSequenceUpperCase) {
48
+ switch (ch) {
49
+ case "\\": return "\\\\";
50
+ case "\b": return "\\b";
51
+ case " ": return "\\t";
52
+ case "\f": return "\\f";
53
+ case "\"": return mode === "singleline-basic" ? "\\\"" : "\"";
54
+ case "\n": return mode === "singleline-basic" ? "\\n" : "\n";
55
+ case "\r": return mode === "singleline-basic" ? "\\r" : "\r";
56
+ default: {
57
+ const code = ch.charCodeAt(0);
58
+ if (isDisallowedControl(code, mode)) {
59
+ const hex = code.toString(16).padStart(4, "0");
60
+ return `\\u${escapeSequenceUpperCase ? hex.toUpperCase() : hex}`;
61
+ }
62
+ return ch;
63
+ }
64
+ }
65
+ }
66
+ /**
67
+ * Uppercases the hex digits of the `\uXXXX` escapes in string content that has
68
+ * already been escaped, for example `\u007f` to `\u007F`.
69
+ *
70
+ * Only escapes are rewritten. A `\uXXXX` that is content rather than an escape
71
+ * is preceded by an escaped backslash, so its run of backslashes has an even
72
+ * length and the sequence is left as written. Uppercasing those would change
73
+ * the value: a string holding the text `\u000c` must not come back as `\u000C`.
74
+ *
75
+ * @param escaped - Content that has already been escaped for a basic string.
76
+ * @returns The content with the hex digits of its escapes uppercased.
77
+ */
78
+ function upperCaseHexEscapes(escaped) {
79
+ return escaped.replace(/(\\+)u([0-9a-f]{4})/g, (match, backslashes, hex) => backslashes.length % 2 === 1 ? `${backslashes}u${hex.toUpperCase()}` : match);
80
+ }
81
+ /**
82
+ * Scans a raw TOML string token and records preferred escape sequence representations for characters.
83
+ *
84
+ * Example: if `existingRaw` contains `\u263A`, this map stores `☺ -> "\\u263A"`.
85
+ * The first seen escape for a character wins to preserve original style.
86
+ *
87
+ * @param existingRaw - Raw TOML string content including escape sequences.
88
+ * @returns A map from decoded character to preferred TOML escape sequence representation.
89
+ */
90
+ function collectPreferredEscapes(existingRaw) {
91
+ const preferred = /* @__PURE__ */ new Map();
92
+ for (let i = 0; i < existingRaw.length; i++) {
93
+ if (existingRaw[i] !== "\\") continue;
94
+ const n1 = existingRaw[i + 1];
95
+ if (!n1) continue;
96
+ const simple = decodeSimpleEscape(n1);
97
+ if (simple !== null) {
98
+ if (simple !== "\n" && simple !== "\r" && !preferred.has(simple)) preferred.set(simple, "\\" + n1);
99
+ i += 1;
100
+ continue;
101
+ }
102
+ if (n1 === "x" && /^[0-9A-Fa-f]{2}$/.test(existingRaw.slice(i + 2, i + 4))) {
103
+ const rawEscape = existingRaw.slice(i, i + 4);
104
+ const code = Number.parseInt(existingRaw.slice(i + 2, i + 4), 16);
105
+ const decoded = String.fromCharCode(code);
106
+ if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);
107
+ i += 3;
108
+ continue;
109
+ }
110
+ if (n1 === "u" && /^[0-9A-Fa-f]{4}$/.test(existingRaw.slice(i + 2, i + 6))) {
111
+ const rawEscape = existingRaw.slice(i, i + 6);
112
+ const code = Number.parseInt(existingRaw.slice(i + 2, i + 6), 16);
113
+ const decoded = String.fromCodePoint(code);
114
+ if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);
115
+ i += 5;
116
+ continue;
117
+ }
118
+ if (n1 === "U" && /^[0-9A-Fa-f]{8}$/.test(existingRaw.slice(i + 2, i + 10))) {
119
+ const rawEscape = existingRaw.slice(i, i + 10);
120
+ const code = Number.parseInt(existingRaw.slice(i + 2, i + 10), 16);
121
+ const decoded = String.fromCodePoint(code);
122
+ if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);
123
+ i += 9;
124
+ continue;
125
+ }
126
+ }
127
+ return preferred;
128
+ }
129
+ function applyPreferredAndMandatoryEscapes(value, preferred, mode, escapeSequenceUpperCase) {
130
+ let escaped = "";
131
+ for (const ch of value) {
132
+ const preferredEscape = preferred.get(ch);
133
+ if (preferredEscape) {
134
+ escaped += preferredEscape;
135
+ continue;
136
+ }
137
+ escaped += mandatoryEscaping(ch, mode, escapeSequenceUpperCase);
138
+ }
139
+ return escaped;
140
+ }
141
+ /**
142
+ * Escapes TOML basic-string content while preserving preferred escape sequences representation from existing raw text.
143
+ *
144
+ * In `singleline-basic` mode, output is suitable for `"..."` strings.
145
+ * In `multiline-basic` mode, output is suitable for `"""..."""` strings and additionally
146
+ * escapes standalone carriage returns and protects embedded triple quotes.
147
+ *
148
+ * @param value - Unescaped JS string value.
149
+ * @param existingRaw - Existing TOML raw string used to infer preferred escapes.
150
+ * @param mode - String rendering mode (`singleline-basic` or `multiline-basic`).
151
+ * @returns Escaped TOML string content without surrounding delimiters.
152
+ */
153
+ function escapeStringContent(value, existingRaw, mode, escapeSequenceUpperCase = true) {
154
+ const preferred = collectPreferredEscapes(existingRaw);
155
+ if (preferred.size === 0 && mode === "singleline-basic") {
156
+ const withDel = JSON.stringify(value).slice(1, -1).replace(/\x7f/g, "\\u007f");
157
+ return escapeSequenceUpperCase ? upperCaseHexEscapes(withDel) : withDel;
158
+ }
159
+ const escaped = applyPreferredAndMandatoryEscapes(value, preferred, mode, escapeSequenceUpperCase);
160
+ if (mode !== "multiline-basic") return escaped;
161
+ return escaped.replace(/\r(?!\n)/g, "\\r").replace(/"""/g, "\"\"\\\"");
162
+ }
163
+
164
+ //#endregion
165
+ export { collectPreferredEscapes, escapeStringContent, upperCaseHexEscapes };
166
+ //# sourceMappingURL=escape-preference.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"escape-preference.js","names":[],"sources":["../../src/escape-preference.ts"],"sourcesContent":["/**\n * @file Escape-style helpers used to preserve escape sequences as preferred encoding (e.g. \\u263A)\n * when rewriting TOML basic strings and quoted key parts.\n * \n * @module escape-preference\n * \n * Summary:\n * The problem with naive parsing + re-serializing of TOML strings is that it normalizes \n * all escape sequences to their decoded character values.\n * \n * For example, if a TOML string contains `\\u263A`, the JS string value will contain the raw ☺ character.\n * If we then naively return that string for TOML output, we would get `☺` instead of the original `\\u263A`.\n * This module provides functions to scan existing raw TOML strings to infer the preferred representation of certain characters\n * and then reuse those preferred escapes when generating new TOML output, thus preserving the original style where possible.\n * \n * Note that we are taking the presence of a single instance of an escape sequence in the original raw string as \n * an indication of the user's preferred rendering for that character. A more faithful preservation of style \n * would be to track all instances of each character and their various rendered forms, but this would add \n * complexity and overhead. The current approach tries to balance things out by capturing the first seen \n * escape for each character, which should cover the vast majority of use cases for TOML.\n * \n */\n\n/**\n * Decodes a TOML single-character escape code to its JS character.\n *\n * @param ch - Escape code character (without the leading backslash).\n * @returns The decoded character, or null if the code is not a supported simple escape.\n */\nfunction decodeSimpleEscape(ch: string): string | null {\n switch (ch) {\n case 'b': return '\\b';\n case 't': return '\\t';\n case 'n': return '\\n';\n case 'f': return '\\f';\n case 'r': return '\\r';\n case '\"': return '\"'; // Note that double quotes don't need escaping in JS.\n // Note that single quotes are not escaped in TOML basic strings, so no case for '\\'' is needed.\n case '\\\\': return '\\\\';\n default: return null;\n }\n}\n\nexport type EscapeMode = 'singleline-basic' | 'multiline-basic';\n\nfunction isDisallowedControl(code: number, mode: EscapeMode): boolean {\n if (mode === 'singleline-basic') {\n return code <= 0x1f || code === 0x7f;\n }\n\n return (\n (code >= 0x00 && code <= 0x07) ||\n code === 0x0b ||\n (code >= 0x0e && code <= 0x1f) ||\n code === 0x7f\n );\n}\n\nfunction mandatoryEscaping(ch: string, mode: EscapeMode, escapeSequenceUpperCase: boolean): string {\n switch (ch) {\n case '\\\\':\n return '\\\\\\\\';\n case '\\b':\n return '\\\\b';\n case '\\t':\n return '\\\\t';\n case '\\f':\n return '\\\\f';\n case '\"':\n return mode === 'singleline-basic' ? '\\\\\"' : '\"';\n case '\\n':\n return mode === 'singleline-basic' ? '\\\\n' : '\\n';\n case '\\r':\n return mode === 'singleline-basic' ? '\\\\r' : '\\r';\n default: {\n const code = ch.charCodeAt(0);\n if (isDisallowedControl(code, mode)) {\n const hex = code.toString(16).padStart(4, '0');\n return `\\\\u${escapeSequenceUpperCase ? hex.toUpperCase() : hex}`;\n }\n return ch;\n }\n }\n}\n\n/**\n * Uppercases the hex digits of the `\\uXXXX` escapes in string content that has\n * already been escaped, for example `\\u007f` to `\\u007F`.\n *\n * Only escapes are rewritten. A `\\uXXXX` that is content rather than an escape\n * is preceded by an escaped backslash, so its run of backslashes has an even\n * length and the sequence is left as written. Uppercasing those would change\n * the value: a string holding the text `\\u000c` must not come back as `\\u000C`.\n *\n * @param escaped - Content that has already been escaped for a basic string.\n * @returns The content with the hex digits of its escapes uppercased.\n */\nexport function upperCaseHexEscapes(escaped: string): string {\n return escaped.replace(/(\\\\+)u([0-9a-f]{4})/g, (match, backslashes: string, hex: string) =>\n backslashes.length % 2 === 1 ? `${backslashes}u${hex.toUpperCase()}` : match\n );\n}\n\n/**\n * Scans a raw TOML string token and records preferred escape sequence representations for characters.\n *\n * Example: if `existingRaw` contains `\\u263A`, this map stores `☺ -> \"\\\\u263A\"`.\n * The first seen escape for a character wins to preserve original style.\n *\n * @param existingRaw - Raw TOML string content including escape sequences.\n * @returns A map from decoded character to preferred TOML escape sequence representation.\n */\nexport function collectPreferredEscapes(existingRaw: string): Map<string, string> {\n const preferred = new Map<string, string>();\n\n for (let i = 0; i < existingRaw.length; i++) {\n if (existingRaw[i] !== '\\\\') continue;\n\n const n1 = existingRaw[i + 1];\n if (!n1) continue;\n\n const simple = decodeSimpleEscape(n1);\n if (simple !== null) {\n // Newlines (\\n, \\r) are handled separately and excluded from preference tracking.\n if (simple !== '\\n' && simple !== '\\r' && !preferred.has(simple)) {\n preferred.set(simple, '\\\\' + n1);\n }\n i += 1;\n continue;\n }\n\n if (n1 === 'x' && /^[0-9A-Fa-f]{2}$/.test(existingRaw.slice(i + 2, i + 4))) {\n const rawEscape = existingRaw.slice(i, i + 4);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 4), 16);\n const decoded = String.fromCharCode(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 3;\n continue;\n }\n\n if (n1 === 'u' && /^[0-9A-Fa-f]{4}$/.test(existingRaw.slice(i + 2, i + 6))) {\n const rawEscape = existingRaw.slice(i, i + 6);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 6), 16);\n const decoded = String.fromCodePoint(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 5;\n continue;\n }\n\n if (n1 === 'U' && /^[0-9A-Fa-f]{8}$/.test(existingRaw.slice(i + 2, i + 10))) {\n const rawEscape = existingRaw.slice(i, i + 10);\n const code = Number.parseInt(existingRaw.slice(i + 2, i + 10), 16);\n const decoded = String.fromCodePoint(code);\n if (!preferred.has(decoded)) preferred.set(decoded, rawEscape);\n i += 9;\n continue;\n }\n }\n\n return preferred;\n}\n\nfunction applyPreferredAndMandatoryEscapes(\n value: string,\n preferred: Map<string, string>,\n mode: EscapeMode,\n escapeSequenceUpperCase: boolean\n): string {\n let escaped = '';\n\n for (const ch of value) {\n const preferredEscape = preferred.get(ch);\n if (preferredEscape) {\n escaped += preferredEscape;\n continue;\n }\n\n escaped += mandatoryEscaping(ch, mode, escapeSequenceUpperCase);\n }\n\n return escaped;\n}\n\n/**\n * Escapes TOML basic-string content while preserving preferred escape sequences representation from existing raw text.\n *\n * In `singleline-basic` mode, output is suitable for `\"...\"` strings.\n * In `multiline-basic` mode, output is suitable for `\"\"\"...\"\"\"` strings and additionally\n * escapes standalone carriage returns and protects embedded triple quotes.\n *\n * @param value - Unescaped JS string value.\n * @param existingRaw - Existing TOML raw string used to infer preferred escapes.\n * @param mode - String rendering mode (`singleline-basic` or `multiline-basic`).\n * @returns Escaped TOML string content without surrounding delimiters.\n */\nexport function escapeStringContent(\n value: string,\n existingRaw: string,\n mode: EscapeMode,\n escapeSequenceUpperCase = true\n): string {\n const preferred = collectPreferredEscapes(existingRaw);\n\n if (preferred.size === 0 && mode === 'singleline-basic') {\n const escaped = JSON.stringify(value).slice(1, -1);\n // JSON.stringify only escapes U+0000–U+001F, but TOML also forbids U+007F (DEL).\n const withDel = escaped.replace(/\\x7f/g, '\\\\u007f');\n return escapeSequenceUpperCase ? upperCaseHexEscapes(withDel) : withDel;\n }\n\n const escaped = applyPreferredAndMandatoryEscapes(value, preferred, mode, escapeSequenceUpperCase);\n\n if (mode !== 'multiline-basic') {\n return escaped;\n }\n\n // A carriage return is only allowed in a multiline string as part of CRLF, so a\n // standalone one is escaped rather than written out raw, which would produce a\n // document that cannot be parsed back.\n return escaped.replace(/\\r(?!\\n)/g, '\\\\r').replace(/\"\"\"/g, '\"\"\\\\\"');\n}\n"],"mappings":"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"}
@@ -0,0 +1,111 @@
1
+ //! @decimalturn/toml-patch v3.3.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ import { hasItems, isDocument, isInlineItem, isKeyValue, isTable, isTableArray } from "./cst.js";
3
+ import { arraysEqual, stableStringify } from "./utils.js";
4
+
5
+ //#region src/find-by-path.ts
6
+ function findByPath(node, path) {
7
+ if (!path.length) {
8
+ if (isInlineItem(node) && isKeyValue(node.item)) return node.item;
9
+ return node;
10
+ }
11
+ if (isKeyValue(node)) return findByPath(node.value, path);
12
+ const indexes = {};
13
+ let found;
14
+ let prefixCandidate;
15
+ if (hasItems(node)) node.items.some((item, itemIndex) => {
16
+ try {
17
+ let key = [];
18
+ if (isKeyValue(item)) key = item.key.value;
19
+ else if (isTable(item)) key = item.key.item.value;
20
+ else if (isTableArray(item)) {
21
+ key = item.key.item.value;
22
+ const key_string = stableStringify(key);
23
+ if (!indexes[key_string]) indexes[key_string] = 0;
24
+ const array_index = indexes[key_string]++;
25
+ key = key.concat(array_index);
26
+ } else if (isInlineItem(item) && isKeyValue(item.item)) key = item.item.key.value;
27
+ else if (isInlineItem(item)) key = [itemIndex];
28
+ if (key.length && arraysEqual(key, path.slice(0, key.length))) {
29
+ const remainingPath = path.slice(key.length);
30
+ if (isDocument(node) && isTableArray(item) && remainingPath.length > 0) {
31
+ const aotKey = item.key.item.value;
32
+ const doc = node;
33
+ const nextSameKeyDocIndex = doc.items.findIndex((sibling, i) => i > itemIndex && isTableArray(sibling) && arraysEqual(sibling.key.item.value, aotKey));
34
+ const scopeEnd = nextSameKeyDocIndex === -1 ? doc.items.length : nextSameKeyDocIndex;
35
+ found = findByPathInAotScope(item, remainingPath, aotKey, doc.items.slice(itemIndex + 1, scopeEnd));
36
+ } else if (isInlineItem(item) && isKeyValue(item.item)) {
37
+ if (path.length === key.length) found = item;
38
+ else found = findByPath(item.item.value, remainingPath);
39
+ } else if (isInlineItem(item) && path.length > key.length) found = findByPath(item.item, remainingPath);
40
+ else found = findByPath(item, remainingPath);
41
+ return true;
42
+ } else if ((isKeyValue(item) || isInlineItem(item) && isKeyValue(item.item)) && key.length > path.length && arraysEqual(key.slice(0, path.length), path)) {
43
+ if (!prefixCandidate) prefixCandidate = item;
44
+ return false;
45
+ } else return false;
46
+ } catch (err) {
47
+ return false;
48
+ }
49
+ });
50
+ if (!found && prefixCandidate) found = prefixCandidate;
51
+ if (!found) throw new Error(`Node not found at ${path.join(".")}`);
52
+ return found;
53
+ }
54
+ /**
55
+ * Searches for a path within an AOT entry's logical scope.
56
+ *
57
+ * In the TOML CST, sub-tables and sub-AOTs under a [[name]] entry are stored
58
+ * as siblings in the Document rather than as children of the entry node.
59
+ * This function first tries the entry's own items, then falls back to the
60
+ * scoped document items (those between this [[name]] and the next [[name]]).
61
+ *
62
+ * @param entry - The TableArray entry node (e.g. the first [[fruit]])
63
+ * @param remainingPath - The path segments still to be resolved (e.g. ['variety', 1, 'name'])
64
+ * @param entryKey - The full key of the entry (e.g. ['fruit'])
65
+ * @param scopedItems - Document items logically belonging to this entry's scope
66
+ */
67
+ function findByPathInAotScope(entry, remainingPath, entryKey, scopedItems) {
68
+ try {
69
+ return findByPath(entry, remainingPath);
70
+ } catch {}
71
+ const indexes = {};
72
+ for (const item of scopedItems) {
73
+ let key = [];
74
+ if (isTable(item)) {
75
+ const fullKey = item.key.item.value;
76
+ if (fullKey.length > entryKey.length && arraysEqual(fullKey.slice(0, entryKey.length), entryKey)) key = fullKey.slice(entryKey.length);
77
+ } else if (isTableArray(item)) {
78
+ const fullKey = item.key.item.value;
79
+ if (fullKey.length > entryKey.length && arraysEqual(fullKey.slice(0, entryKey.length), entryKey)) {
80
+ const relativeKey = fullKey.slice(entryKey.length);
81
+ const key_string = stableStringify(relativeKey);
82
+ if (!indexes[key_string]) indexes[key_string] = 0;
83
+ const array_index = indexes[key_string]++;
84
+ key = relativeKey.concat(array_index);
85
+ }
86
+ }
87
+ if (key.length && arraysEqual(key, remainingPath.slice(0, key.length))) try {
88
+ return findByPath(item, remainingPath.slice(key.length));
89
+ } catch {}
90
+ }
91
+ throw new Error(`Node not found at (aot scope) ${remainingPath.join(".")}`);
92
+ }
93
+ function tryFindByPath(node, path) {
94
+ try {
95
+ return findByPath(node, path);
96
+ } catch (err) {}
97
+ }
98
+ function findParent(node, path) {
99
+ let parent_path = path;
100
+ let parent;
101
+ while (parent_path.length && !parent) {
102
+ parent_path = parent_path.slice(0, -1);
103
+ parent = tryFindByPath(node, parent_path);
104
+ }
105
+ if (!parent) throw new Error(`Parent not found for ${path.join(".")}`);
106
+ return parent;
107
+ }
108
+
109
+ //#endregion
110
+ export { findByPath as default, findParent, tryFindByPath };
111
+ //# sourceMappingURL=find-by-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"find-by-path.js","names":[],"sources":["../../src/find-by-path.ts"],"sourcesContent":["import { TreeNode, isKeyValue, isTable, isTableArray, isDocument, hasItems, isInlineItem, Document, Table, TableArray, Block } from './cst';\nimport { arraysEqual, stableStringify } from './utils';\n\nexport type Path = Array<string | number>;\n\nexport default function findByPath(node: TreeNode, path: Path): TreeNode {\n if (!path.length) {\n // If this is an InlineItem containing a KeyValue, return the KeyValue\n if (isInlineItem(node) && isKeyValue(node.item)) {\n return node.item;\n }\n return node;\n }\n\n if (isKeyValue(node)) {\n return findByPath(node.value, path);\n }\n\n const indexes: { [key: string]: number } = {};\n let found;\n // Strict-prefix matches (key longer than the path) are deferred: an exact\n // key match elsewhere in the container must win. Otherwise a dotted row\n // like `\"\".\"\".\"mfn31vru\"` shadows the plain `\"\"` row the path points at,\n // and the caller edits the wrong key (fuzz seed 13057).\n let prefixCandidate: TreeNode | undefined;\n if (hasItems(node)) {\n node.items.some((item, itemIndex) => {\n try {\n let key: Path = [];\n if (isKeyValue(item)) {\n key = item.key.value;\n } else if (isTable(item)) {\n key = item.key.item.value;\n } else if (isTableArray(item)) {\n key = item.key.item.value;\n\n const key_string = stableStringify(key);\n if (!indexes[key_string]) {\n indexes[key_string] = 0;\n }\n const array_index = indexes[key_string]++;\n\n key = key.concat(array_index);\n } else if (isInlineItem(item) && isKeyValue(item.item)) {\n // For InlineItems wrapping KeyValues, extract the key\n key = item.item.key.value;\n } else if (isInlineItem(item)) {\n key = [itemIndex];\n }\n\n if (key.length && arraysEqual(key, path.slice(0, key.length))) {\n const remainingPath = path.slice(key.length);\n\n // Special handling for TableArray items within a Document:\n // sub-tables ([fruit.physical]) and sub-AOTs ([[fruit.variety]]) under\n // this entry are siblings in the Document, not children of the entry node.\n // When the remaining path can't be satisfied by the entry's own items,\n // fall back to a scoped search over the document items that logically\n // belong to this AOT entry (everything between this entry and the next\n // entry with the same key).\n if (isDocument(node) && isTableArray(item) && remainingPath.length > 0) {\n const aotKey = (item as TableArray).key.item.value;\n const doc = node as Document;\n const nextSameKeyDocIndex = doc.items.findIndex((sibling, i) =>\n i > itemIndex &&\n isTableArray(sibling) &&\n arraysEqual((sibling as TableArray).key.item.value, aotKey)\n );\n const scopeEnd = nextSameKeyDocIndex === -1 ? doc.items.length : nextSameKeyDocIndex;\n const scopedItems = doc.items.slice(itemIndex + 1, scopeEnd) as Block[];\n\n found = findByPathInAotScope(item as TableArray, remainingPath, aotKey, scopedItems);\n } else if (isInlineItem(item) && isKeyValue(item.item)) {\n if (path.length === key.length) {\n // If we've matched the full path, return the InlineItem itself\n // so it can be found and replaced in the parent's items array\n found = item;\n } else {\n // Continue searching within the KeyValue's value\n found = findByPath(item.item.value, remainingPath);\n }\n } else if (isInlineItem(item) && path.length > key.length) {\n // For non-KeyValue InlineItems (e.g. an InlineTable inside an array),\n // when there is still path to resolve, recurse into the inner node.\n // Without this, findByPath(InlineItem, ['key']) would fail because\n // InlineItem itself has no .items to traverse.\n found = findByPath(item.item, remainingPath);\n } else {\n found = findByPath(item, remainingPath);\n }\n return true;\n } else if ((isKeyValue(item) ||\n (isInlineItem(item) && isKeyValue(item.item))) &&\n key.length > path.length && arraysEqual(key.slice(0, path.length), path)) {\n // Path is a prefix of a dotted KeyValue's key (e.g. path ['a','b']\n // matching key ['a','b','c']) — or of a dotted key inside an\n // InlineTableItem. The path is fully consumed; the caller can\n // handle the key-length mismatch as a structural edit. Deferred:\n // keep scanning, an exact key match must take precedence.\n if (!prefixCandidate) prefixCandidate = item;\n return false;\n } else {\n return false;\n }\n } catch (err) {\n return false;\n }\n });\n }\n\n if (!found && prefixCandidate) {\n found = prefixCandidate;\n }\n\n if (!found) {\n throw new Error(`Node not found at ${path.join('.')}`);\n }\n\n return found;\n}\n\n/**\n * Searches for a path within an AOT entry's logical scope.\n *\n * In the TOML CST, sub-tables and sub-AOTs under a [[name]] entry are stored\n * as siblings in the Document rather than as children of the entry node.\n * This function first tries the entry's own items, then falls back to the\n * scoped document items (those between this [[name]] and the next [[name]]).\n *\n * @param entry - The TableArray entry node (e.g. the first [[fruit]])\n * @param remainingPath - The path segments still to be resolved (e.g. ['variety', 1, 'name'])\n * @param entryKey - The full key of the entry (e.g. ['fruit'])\n * @param scopedItems - Document items logically belonging to this entry's scope\n */\nfunction findByPathInAotScope(\n entry: TableArray,\n remainingPath: Path,\n entryKey: string[],\n scopedItems: Block[]\n): TreeNode {\n // First try the entry's own items (normal path resolution)\n try {\n return findByPath(entry, remainingPath);\n } catch {}\n\n // Search scoped document items for sub-tables and sub-AOTs whose keys\n // start with the AOT entry key and match the remaining path.\n const indexes: { [key: string]: number } = {};\n\n for (const item of scopedItems) {\n let key: Path = [];\n\n if (isTable(item)) {\n const fullKey = (item as Table).key.item.value;\n if (\n fullKey.length > entryKey.length &&\n arraysEqual(fullKey.slice(0, entryKey.length), entryKey)\n ) {\n key = fullKey.slice(entryKey.length);\n }\n } else if (isTableArray(item)) {\n const fullKey = (item as TableArray).key.item.value;\n if (\n fullKey.length > entryKey.length &&\n arraysEqual(fullKey.slice(0, entryKey.length), entryKey)\n ) {\n const relativeKey = fullKey.slice(entryKey.length);\n const key_string = stableStringify(relativeKey);\n if (!indexes[key_string]) indexes[key_string] = 0;\n const array_index = indexes[key_string]++;\n key = (relativeKey as Path).concat(array_index);\n }\n }\n\n if (key.length && arraysEqual(key, remainingPath.slice(0, key.length))) {\n try {\n return findByPath(item, remainingPath.slice(key.length));\n } catch {}\n }\n }\n\n throw new Error(`Node not found at (aot scope) ${remainingPath.join('.')}`);\n}\n\n\nexport function tryFindByPath(node: TreeNode, path: Path): TreeNode | undefined {\n try {\n return findByPath(node, path);\n } catch (err) {}\n}\n\nexport function findParent(node: TreeNode, path: Path): TreeNode {\n let parent_path = path;\n let parent;\n while (parent_path.length && !parent) {\n parent_path = parent_path.slice(0, -1);\n parent = tryFindByPath(node, parent_path);\n }\n\n if (!parent) {\n throw new Error(`Parent not found for ${path.join('.')}`);\n }\n\n return parent;\n}\n"],"mappings":";;;;;AAKA,SAAwB,WAAW,MAAgB,MAAsB;CACvE,IAAI,CAAC,KAAK,QAAQ;EAEhB,IAAI,aAAa,IAAI,KAAK,WAAW,KAAK,IAAI,GAC5C,OAAO,KAAK;EAEd,OAAO;CACT;CAEA,IAAI,WAAW,IAAI,GACjB,OAAO,WAAW,KAAK,OAAO,IAAI;CAGpC,MAAM,UAAqC,CAAC;CAC5C,IAAI;CAKJ,IAAI;CACJ,IAAI,SAAS,IAAI,GACf,KAAK,MAAM,MAAM,MAAM,cAAc;EACnC,IAAI;GACF,IAAI,MAAY,CAAC;GACjB,IAAI,WAAW,IAAI,GACjB,MAAM,KAAK,IAAI;QACV,IAAI,QAAQ,IAAI,GACrB,MAAM,KAAK,IAAI,KAAK;QACf,IAAI,aAAa,IAAI,GAAG;IAC7B,MAAM,KAAK,IAAI,KAAK;IAEpB,MAAM,aAAa,gBAAgB,GAAG;IACtC,IAAI,CAAC,QAAQ,aACX,QAAQ,cAAc;IAExB,MAAM,cAAc,QAAQ,WAAW;IAEvC,MAAM,IAAI,OAAO,WAAW;GAC9B,OAAO,IAAI,aAAa,IAAI,KAAK,WAAW,KAAK,IAAI,GAEnD,MAAM,KAAK,KAAK,IAAI;QACf,IAAI,aAAa,IAAI,GAC1B,MAAM,CAAC,SAAS;GAGlB,IAAI,IAAI,UAAU,YAAY,KAAK,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,GAAG;IAC7D,MAAM,gBAAgB,KAAK,MAAM,IAAI,MAAM;IAS3C,IAAI,WAAW,IAAI,KAAK,aAAa,IAAI,KAAK,cAAc,SAAS,GAAG;KACtE,MAAM,SAAU,KAAoB,IAAI,KAAK;KAC7C,MAAM,MAAM;KACZ,MAAM,sBAAsB,IAAI,MAAM,WAAW,SAAS,MACxD,IAAI,aACJ,aAAa,OAAO,KACpB,YAAa,QAAuB,IAAI,KAAK,OAAO,MAAM,CAC5D;KACA,MAAM,WAAW,wBAAwB,KAAK,IAAI,MAAM,SAAS;KAGjE,QAAQ,qBAAqB,MAAoB,eAAe,QAF5C,IAAI,MAAM,MAAM,YAAY,GAAG,QAE+B,CAAC;IACrF,OAAO,IAAI,aAAa,IAAI,KAAK,WAAW,KAAK,IAAI,GAAG;KACtD,IAAI,KAAK,WAAW,IAAI,QAGtB,QAAQ;UAGR,QAAQ,WAAW,KAAK,KAAK,OAAO,aAAa;IAErD,OAAO,IAAI,aAAa,IAAI,KAAK,KAAK,SAAS,IAAI,QAKjD,QAAQ,WAAW,KAAK,MAAM,aAAa;SAE3C,QAAQ,WAAW,MAAM,aAAa;IAExC,OAAO;GACT,OAAO,KAAK,WAAW,IAAI,KACd,aAAa,IAAI,KAAK,WAAW,KAAK,IAAI,MAC5C,IAAI,SAAS,KAAK,UAAU,YAAY,IAAI,MAAM,GAAG,KAAK,MAAM,GAAG,IAAI,GAAG;IAMnF,IAAI,CAAC,iBAAiB,kBAAkB;IACxC,OAAO;GACT,OACE,OAAO;EAEX,SAAS,KAAK;GACZ,OAAO;EACT;CACF,CAAC;CAGH,IAAI,CAAC,SAAS,iBACZ,QAAQ;CAGV,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,qBAAqB,KAAK,KAAK,GAAG,GAAG;CAGvD,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAS,qBACP,OACA,eACA,UACA,aACU;CAEV,IAAI;EACF,OAAO,WAAW,OAAO,aAAa;CACxC,QAAQ,CAAC;CAIT,MAAM,UAAqC,CAAC;CAE5C,KAAK,MAAM,QAAQ,aAAa;EAC9B,IAAI,MAAY,CAAC;EAEjB,IAAI,QAAQ,IAAI,GAAG;GACjB,MAAM,UAAW,KAAe,IAAI,KAAK;GACzC,IACE,QAAQ,SAAS,SAAS,UAC1B,YAAY,QAAQ,MAAM,GAAG,SAAS,MAAM,GAAG,QAAQ,GAEvD,MAAM,QAAQ,MAAM,SAAS,MAAM;EAEvC,OAAO,IAAI,aAAa,IAAI,GAAG;GAC7B,MAAM,UAAW,KAAoB,IAAI,KAAK;GAC9C,IACE,QAAQ,SAAS,SAAS,UAC1B,YAAY,QAAQ,MAAM,GAAG,SAAS,MAAM,GAAG,QAAQ,GACvD;IACA,MAAM,cAAc,QAAQ,MAAM,SAAS,MAAM;IACjD,MAAM,aAAa,gBAAgB,WAAW;IAC9C,IAAI,CAAC,QAAQ,aAAa,QAAQ,cAAc;IAChD,MAAM,cAAc,QAAQ,WAAW;IACvC,MAAO,YAAqB,OAAO,WAAW;GAChD;EACF;EAEA,IAAI,IAAI,UAAU,YAAY,KAAK,cAAc,MAAM,GAAG,IAAI,MAAM,CAAC,GACnE,IAAI;GACF,OAAO,WAAW,MAAM,cAAc,MAAM,IAAI,MAAM,CAAC;EACzD,QAAQ,CAAC;CAEb;CAEA,MAAM,IAAI,MAAM,iCAAiC,cAAc,KAAK,GAAG,GAAG;AAC5E;AAGA,SAAgB,cAAc,MAAgB,MAAkC;CAC9E,IAAI;EACF,OAAO,WAAW,MAAM,IAAI;CAC9B,SAAS,KAAK,CAAC;AACjB;AAEA,SAAgB,WAAW,MAAgB,MAAsB;CAC/D,IAAI,cAAc;CAClB,IAAI;CACJ,OAAO,YAAY,UAAU,CAAC,QAAQ;EACpC,cAAc,YAAY,MAAM,GAAG,EAAE;EACrC,SAAS,cAAc,MAAM,WAAW;CAC1C;CAEA,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,wBAAwB,KAAK,KAAK,GAAG,GAAG;CAG1D,OAAO;AACT"}
@@ -0,0 +1,298 @@
1
+ //! @decimalturn/toml-patch v3.3.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ import { isInlineArray, isInlineItem, isInlineTable, isKeyValue, isTable, isTableArray } from "./cst.js";
3
+ import { getCommaSpace } from "./inline-comma-space.js";
4
+ import { getInlineContainerLayout, hasStructuralMultilineRows } from "./inline-format.js";
5
+ import { applyWrites, insert, markStringifyRoot, remove, shiftNode } from "./writer.js";
6
+ import { generateDocument, generateTable, generateTableArray } from "./generate.js";
7
+
8
+ //#region src/formatter.ts
9
+ function arrayHadTrailingCommas(node) {
10
+ if (!isInlineArray(node)) return false;
11
+ if (node.items.length === 0) return false;
12
+ return node.items[node.items.length - 1].comma === true;
13
+ }
14
+ function tableHadTrailingCommas(node) {
15
+ if (!isInlineTable(node)) return false;
16
+ if (node.items.length === 0) return false;
17
+ return node.items[node.items.length - 1].comma === true;
18
+ }
19
+ function formatTopLevel(document, format) {
20
+ if (format.inlineTableStart === 0) return document;
21
+ document.items.filter((item) => {
22
+ if (!isKeyValue(item)) return false;
23
+ const is_inline_table = isInlineTable(item.value);
24
+ const is_inline_array = isInlineArray(item.value) && item.value.items.length > 0 && item.value.items.every((i) => isInlineTable(i.item));
25
+ if (is_inline_table || is_inline_array) {
26
+ const depth = calculateTableDepth(item.key.value);
27
+ return format.inlineTableStart === void 0 || depth < format.inlineTableStart;
28
+ }
29
+ return false;
30
+ }).forEach((node) => {
31
+ remove(document, document, node);
32
+ if (isInlineTable(node.value)) {
33
+ if (node.value.items.length === 0) insert(document, document, generateTable(node.key.value));
34
+ else insert(document, document, formatTable(node, format.bracketSpacing, format.escapeSequenceUpperCase));
35
+ } else formatTableArray(node, format.bracketSpacing, format.escapeSequenceUpperCase).forEach((table_array) => {
36
+ insert(document, document, table_array);
37
+ });
38
+ });
39
+ applyWrites(document);
40
+ return document;
41
+ }
42
+ function formatTable(key_value, bracketSpacing, escapeSequenceUpperCase) {
43
+ const table = generateTable(key_value.key.value, escapeSequenceUpperCase);
44
+ markStringifyRoot(table);
45
+ for (const item of key_value.value.items) insert(table, table, item.item, void 0, void 0, void 0, void 0, true);
46
+ applyWrites(table);
47
+ normalizeGeneratedInlineRows(table, 1, bracketSpacing);
48
+ return table;
49
+ }
50
+ function formatTableArray(key_value, bracketSpacing, escapeSequenceUpperCase) {
51
+ const root = generateDocument();
52
+ markStringifyRoot(root);
53
+ for (const inline_array_item of key_value.value.items) {
54
+ const table_array = generateTableArray(key_value.key.value, escapeSequenceUpperCase);
55
+ insert(root, root, table_array);
56
+ for (const inline_table_item of inline_array_item.item.items) insert(root, table_array, inline_table_item.item, void 0, void 0, void 0, void 0, true);
57
+ }
58
+ applyWrites(root);
59
+ for (const item of root.items) if (isTable(item) || isTableArray(item)) normalizeGeneratedInlineRows(item, 1, bracketSpacing);
60
+ return root.items;
61
+ }
62
+ /**
63
+ * Whether an inline container lays its items out one per row. A container
64
+ * regenerated through a TOML round-trip carries no layout flag, so fall back to
65
+ * the physical rows: a row on a later line than the previous item's end means
66
+ * multiline. A compact container whose items merely SPAN several lines (because
67
+ * one of them is a multiline value) stays compact — its closing bracket still
68
+ * follows its last item.
69
+ */
70
+ function isMultilineInlineContainer(container) {
71
+ const layout = getInlineContainerLayout(container);
72
+ return layout !== void 0 ? layout : hasStructuralMultilineRows(container);
73
+ }
74
+ /**
75
+ * Row indent for a container that is an array ELEMENT (no key of its own).
76
+ * Keyless rows keep the historical minimum of two columns, matching
77
+ * positionGeneratedNestedInlineTables so element rows and their closing
78
+ * bracket stay aligned the same way no matter which path laid them out.
79
+ */
80
+ function elementIndentWidth(indentWidth) {
81
+ return Math.max(indentWidth, 2);
82
+ }
83
+ /**
84
+ * Lays out a generated inline container so that its rows and closing bracket
85
+ * line up with the key (or, for an array element, the element) that owns it:
86
+ *
87
+ * - a multiline container puts one row per line at `anchorColumn + indentWidth`
88
+ * and its closing bracket at `anchorColumn`;
89
+ * - a nested multiline container inside a row does the same, using that row's
90
+ * key column as its own anchor.
91
+ *
92
+ * `anchorColumn` is the column of the owning key's start. It only has to be
93
+ * correct for containers the generator built: containers parsed from an
94
+ * existing document keep their own formatting, so callers must restrict this
95
+ * to freshly generated/replaced subtrees.
96
+ *
97
+ * Returns whether a nested container's end position moved.
98
+ */
99
+ function normalizeInlineContainerRows(container, anchorColumn, indentWidth, bracketSpacing = true) {
100
+ const multiline = isMultilineInlineContainer(container);
101
+ let nestedEndChanged = false;
102
+ if (multiline) {
103
+ const rowIndent = anchorColumn + indentWidth;
104
+ for (const item of container.items) {
105
+ shiftNode(item, {
106
+ lines: 0,
107
+ columns: rowIndent - item.loc.start.column
108
+ });
109
+ if (isInlineItem(item)) {
110
+ if (isInlineArray(item.item) || isInlineTable(item.item)) {
111
+ if (normalizeInlineContainerRows(item.item, item.item.loc.start.column, elementIndentWidth(indentWidth), bracketSpacing)) {
112
+ item.loc.end = { ...item.item.loc.end };
113
+ nestedEndChanged = true;
114
+ }
115
+ } else if (isKeyValue(item.item) && (isInlineArray(item.item.value) || isInlineTable(item.item.value))) {
116
+ if (normalizeInlineContainerRows(item.item.value, item.item.loc.start.column, indentWidth, bracketSpacing)) {
117
+ item.item.loc.end = { ...item.item.value.loc.end };
118
+ item.loc.end = { ...item.item.loc.end };
119
+ nestedEndChanged = true;
120
+ }
121
+ }
122
+ }
123
+ }
124
+ container.loc.end.column = anchorColumn + 1;
125
+ nestedEndChanged = true;
126
+ }
127
+ for (const item of container.items) {
128
+ if (!isInlineItem(item)) continue;
129
+ if (isInlineArray(item.item) || isInlineTable(item.item)) {
130
+ if (normalizeInlineContainerRows(item.item, item.item.loc.start.column, elementIndentWidth(indentWidth), bracketSpacing)) {
131
+ item.loc.end = { ...item.item.loc.end };
132
+ nestedEndChanged = true;
133
+ }
134
+ } else if (isKeyValue(item.item) && (isInlineArray(item.item.value) || isInlineTable(item.item.value))) {
135
+ const value = item.item.value;
136
+ const anchorColumn = item.item.loc.start.column;
137
+ const valueMultiline = isMultilineInlineContainer(value);
138
+ if (normalizeInlineContainerRows(value, anchorColumn, indentWidth, bracketSpacing)) {
139
+ if (valueMultiline) value.loc.end.column = anchorColumn + 1;
140
+ item.item.loc.end = { ...value.loc.end };
141
+ item.loc.end = { ...item.item.loc.end };
142
+ nestedEndChanged = true;
143
+ }
144
+ }
145
+ }
146
+ const commaSpace = getCommaSpace(container) ?? 2;
147
+ for (let index = 1; index < container.items.length; index++) {
148
+ const previous = container.items[index - 1];
149
+ const next = container.items[index];
150
+ if (previous.loc.end.line !== next.loc.start.line) continue;
151
+ const targetColumn = previous.loc.end.column + (previous.comma ? commaSpace : 1);
152
+ shiftNode(next, {
153
+ lines: 0,
154
+ columns: targetColumn - next.loc.start.column
155
+ });
156
+ }
157
+ if (nestedEndChanged && !multiline && container.items.length > 0) {
158
+ const lastItem = container.items[container.items.length - 1];
159
+ container.loc.end = {
160
+ line: lastItem.loc.end.line,
161
+ column: lastItem.loc.end.column + (lastItem.comma ? 1 : 0) + (bracketSpacing ? 2 : 1)
162
+ };
163
+ }
164
+ return nestedEndChanged;
165
+ }
166
+ function normalizeGeneratedInlineRows(block, indentWidth, bracketSpacing = true) {
167
+ const rows = isKeyValue(block) ? [block] : block.items;
168
+ for (const item of rows) {
169
+ if (!isKeyValue(item)) continue;
170
+ if (isInlineArray(item.value) || isInlineTable(item.value)) normalizeInlineContainerRows(item.value, item.loc.start.column, indentWidth, bracketSpacing);
171
+ }
172
+ }
173
+ function normalizeGeneratedInlineContainerRows(container, indentWidth) {
174
+ const normalize = (current, normalizeCurrent) => {
175
+ if (normalizeCurrent) {
176
+ delete current.range;
177
+ if (getInlineContainerLayout(current) === true || hasStructuralMultilineRows(current)) {
178
+ const rowIndent = current.loc.start.column + indentWidth;
179
+ for (const item of current.items) shiftNode(item, {
180
+ lines: 0,
181
+ columns: rowIndent - item.loc.start.column
182
+ });
183
+ current.loc.end.column = current.loc.start.column + 1;
184
+ }
185
+ }
186
+ for (const item of current.items) {
187
+ if (!isInlineItem(item)) continue;
188
+ if (isInlineArray(item.item) || isInlineTable(item.item)) normalize(item.item, isInlineArray(current) && isInlineTable(item.item));
189
+ else if (isKeyValue(item.item) && (isInlineArray(item.item.value) || isInlineTable(item.item.value))) normalize(item.item.value, false);
190
+ }
191
+ };
192
+ normalize(container, false);
193
+ }
194
+ /**
195
+ * Updates a table's location end position after removing inline table items.
196
+ * When inline table content is removed from a parent table, the parent table's
197
+ * end position needs to be adjusted to reflect where the content actually ends.
198
+ *
199
+ * @param table - The table whose end position should be updated
200
+ */
201
+ function postInlineItemRemovalAdjustment(table) {
202
+ if (table.items.length > 0) {
203
+ const lastItem = table.items[table.items.length - 1];
204
+ table.loc.end.line = lastItem.loc.end.line;
205
+ table.loc.end.column = lastItem.loc.end.column;
206
+ } else {
207
+ table.loc.end.line = table.key.loc.end.line;
208
+ table.loc.end.column = table.key.loc.end.column;
209
+ }
210
+ }
211
+ /**
212
+ * Calculates the nesting depth of a table based on its key path.
213
+ * Root level tables (e.g., [table]) have depth 0.
214
+ * First level nested tables (e.g., [table.nested]) have depth 1.
215
+ *
216
+ * @param keyPath - Array representing the table key path (e.g., ['table', 'nested'])
217
+ * @returns The nesting depth (0 for root level, 1+ for nested levels)
218
+ */
219
+ function calculateTableDepth(keyPath) {
220
+ return Math.max(0, keyPath.length - 1);
221
+ }
222
+ /**
223
+ * Converts nested inline tables to separate table sections based on the inlineTableStart depth setting.
224
+ * This function recursively processes all tables in the document and extracts inline tables that are
225
+ * at a depth less than the inlineTableStart threshold.
226
+ */
227
+ function formatNestedTablesMultiline(document, format) {
228
+ if (format.inlineTableStart === void 0 || format.inlineTableStart === 0) return document;
229
+ const additionalTables = [];
230
+ for (const item of document.items) if (isKeyValue(item) && isInlineTable(item.value)) {
231
+ if (calculateTableDepth(item.key.value) < format.inlineTableStart) {
232
+ const table = formatTable(item, format.bracketSpacing, format.escapeSequenceUpperCase);
233
+ remove(document, document, item);
234
+ insert(document, document, table);
235
+ processTableForNestedInlines(table, additionalTables, format);
236
+ }
237
+ } else if (item.type === "Table") processTableForNestedInlines(item, additionalTables, format);
238
+ else if (isTableArray(item)) processTableForNestedInlines(item, additionalTables, format);
239
+ const insertedAfter = /* @__PURE__ */ new Map();
240
+ for (const { table, parent } of additionalTables) {
241
+ const index = document.items.indexOf(parent);
242
+ const offset = (insertedAfter.get(parent) ?? 0) + 1;
243
+ insertedAfter.set(parent, offset);
244
+ insert(document, document, table, index + offset);
245
+ }
246
+ applyWrites(document);
247
+ return document;
248
+ }
249
+ /**
250
+ * Recursively processes a table for nested inline tables and extracts them as separate tables
251
+ * when they are at a depth less than the inlineTableStart threshold.
252
+ */
253
+ function processTableForNestedInlines(table, additionalTables, format) {
254
+ const toExtract = [];
255
+ for (let i = 0; i < table.items.length; i++) {
256
+ const item = table.items[i];
257
+ if (isKeyValue(item) && isInlineTable(item.value)) {
258
+ const nestedTableKey = [...table.key.item.value, ...item.key.value];
259
+ if (calculateTableDepth(nestedTableKey) < (format.inlineTableStart ?? 1)) toExtract.push({
260
+ item,
261
+ nestedTableKey
262
+ });
263
+ }
264
+ }
265
+ for (const { item, nestedTableKey } of toExtract) {
266
+ const separateTable = generateTable(nestedTableKey, format.escapeSequenceUpperCase);
267
+ markStringifyRoot(separateTable);
268
+ const inlineTable = item.value;
269
+ for (const inlineItem of inlineTable.items) insert(separateTable, separateTable, inlineItem.item);
270
+ applyWrites(separateTable);
271
+ remove(table, table, item);
272
+ postInlineItemRemovalAdjustment(table);
273
+ additionalTables.push({
274
+ table: separateTable,
275
+ parent: table
276
+ });
277
+ processTableForNestedInlines(separateTable, additionalTables, format);
278
+ }
279
+ if (toExtract.length > 0) applyWrites(table);
280
+ }
281
+ function formatEmptyLines(document) {
282
+ let shift = 0;
283
+ let previous = 0;
284
+ for (const item of document.items) {
285
+ if (previous === 0 && item.loc.start.line > 1) shift = 1 - item.loc.start.line;
286
+ else if (item.loc.start.line + shift > previous + 2) shift += previous + 2 - (item.loc.start.line + shift);
287
+ shiftNode(item, {
288
+ lines: shift,
289
+ columns: 0
290
+ });
291
+ previous = item.loc.end.line;
292
+ }
293
+ return document;
294
+ }
295
+
296
+ //#endregion
297
+ export { arrayHadTrailingCommas, calculateTableDepth, formatEmptyLines, formatNestedTablesMultiline, formatTopLevel, normalizeGeneratedInlineContainerRows, normalizeGeneratedInlineRows, normalizeInlineContainerRows, postInlineItemRemovalAdjustment, tableHadTrailingCommas };
298
+ //# sourceMappingURL=formatter.js.map