@decimalturn/toml-patch 3.1.0 → 3.1.1-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 +104 -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 +677 -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 +10 -10
  68. package/package.json +11 -92
  69. package/LICENSE +0 -22
  70. package/README.md +0 -169
  71. package/dist/toml-patch.js +0 -54
@@ -0,0 +1,476 @@
1
+ //! @decimalturn/toml-patch v3.1.1 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ import parseTOML from "./parse-toml.js";
3
+ import { hasLeadingBom, stripLeadingBom } from "./decode-utf8.js";
4
+
5
+ //#region src/toml-format.ts
6
+ const DEFAULT_NEWLINE = "\n";
7
+ const DEFAULT_TRAILING_NEWLINE = 1;
8
+ const DEFAULT_TRAILING_COMMA = false;
9
+ const DEFAULT_BRACKET_SPACING = true;
10
+ const DEFAULT_INLINE_TABLE_START = 1;
11
+ const DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES = false;
12
+ const DEFAULT_USE_TABS_FOR_INDENTATION = false;
13
+ const DEFAULT_INDENT_WIDTH = 2;
14
+ const DEFAULT_MINIMUM_DECIMALS = 0;
15
+ const DEFAULT_LEADING_BOM = false;
16
+ const DEFAULT_UPDATE_ORDER = false;
17
+ const DEFAULT_MULTILINE_TABLE = "auto";
18
+ const DEFAULT_MULTILINE_ARRAY = "auto";
19
+ function detectTrailingComma(cst) {
20
+ for (const item of cst) {
21
+ const result = findTrailingCommaInNode(item);
22
+ if (result !== null) return result;
23
+ }
24
+ return false;
25
+ }
26
+ function detectBracketSpacing(tomlString, cst) {
27
+ for (const item of cst) {
28
+ const result = findBracketSpacingInNode(item, tomlString);
29
+ if (result !== null) return result;
30
+ }
31
+ return true;
32
+ }
33
+ function findBracketSpacingInNode(node, tomlString) {
34
+ if (!node || typeof node !== "object") return null;
35
+ if ((node.type === "InlineArray" || node.type === "InlineTable") && node.loc) {
36
+ const bracketSpacing = checkBracketSpacingInLocation(node.loc, tomlString);
37
+ if (bracketSpacing !== null) return bracketSpacing;
38
+ }
39
+ if (node.items && Array.isArray(node.items)) for (const child of node.items) {
40
+ const result = findBracketSpacingInNode(child, tomlString);
41
+ if (result !== null) return result;
42
+ if (child.item) {
43
+ const nestedResult = findBracketSpacingInNode(child.item, tomlString);
44
+ if (nestedResult !== null) return nestedResult;
45
+ }
46
+ }
47
+ for (const prop of [
48
+ "value",
49
+ "key",
50
+ "item"
51
+ ]) if (node[prop]) {
52
+ const result = findBracketSpacingInNode(node[prop], tomlString);
53
+ if (result !== null) return result;
54
+ }
55
+ return null;
56
+ }
57
+ function checkBracketSpacingInLocation(loc, tomlString) {
58
+ if (!loc || !loc.start || !loc.end) return null;
59
+ const lines = tomlString.split(/\r?\n/);
60
+ const startLine = loc.start.line - 1;
61
+ const endLine = loc.end.line - 1;
62
+ const startCol = loc.start.column;
63
+ const endCol = loc.end.column;
64
+ let rawText = "";
65
+ if (startLine === endLine) {
66
+ var _lines$startLine;
67
+ rawText = ((_lines$startLine = lines[startLine]) === null || _lines$startLine === void 0 ? void 0 : _lines$startLine.substring(startCol, endCol + 1)) || "";
68
+ } else {
69
+ if (lines[startLine]) rawText += lines[startLine].substring(startCol);
70
+ for (let i = startLine + 1; i < endLine; i++) rawText += "\n" + (lines[i] || "");
71
+ if (lines[endLine]) rawText += "\n" + lines[endLine].substring(0, endCol + 1);
72
+ }
73
+ const arrayMatch = rawText.match(/^\[(\s*)/);
74
+ const tableMatch = rawText.match(/^\{(\s*)/);
75
+ if (arrayMatch) return arrayMatch[1].length > 0;
76
+ if (tableMatch) return tableMatch[1].length > 0;
77
+ return null;
78
+ }
79
+ function findTrailingCommaInNode(node) {
80
+ if (!node || typeof node !== "object") return null;
81
+ if (node.type === "InlineArray" && node.items && Array.isArray(node.items)) return checkTrailingCommaInItems(node.items);
82
+ if (node.type === "InlineTable" && node.items && Array.isArray(node.items)) return checkTrailingCommaInItems(node.items);
83
+ if (node.type === "KeyValue" && node.value) return findTrailingCommaInNode(node.value);
84
+ if (node.items && Array.isArray(node.items)) for (const item of node.items) {
85
+ const result = findTrailingCommaInNode(item);
86
+ if (result !== null) return result;
87
+ }
88
+ return null;
89
+ }
90
+ function checkTrailingCommaInItems(items) {
91
+ if (items.length === 0) return null;
92
+ const lastItem = items[items.length - 1];
93
+ if (lastItem && typeof lastItem === "object" && "comma" in lastItem) return lastItem.comma === true;
94
+ return false;
95
+ }
96
+ function detectNewline(str) {
97
+ const lfIndex = str.indexOf("\n");
98
+ if (lfIndex > 0 && str[lfIndex - 1] === "\r") return "\r\n";
99
+ return "\n";
100
+ }
101
+ function countTrailingNewlines(str) {
102
+ let count = 0;
103
+ let pos = str.length;
104
+ while (pos > 0 && str[pos - 1] === "\n") {
105
+ count++;
106
+ pos--;
107
+ if (pos > 0 && str[pos - 1] === "\r") pos--;
108
+ }
109
+ return count;
110
+ }
111
+ function detectTabsForIndentation(str) {
112
+ const lines = str.split(/\r?\n/);
113
+ let tabCount = 0;
114
+ let spaceCount = 0;
115
+ for (const line of lines) {
116
+ if (line.length === 0) continue;
117
+ if (line[0] === " ") tabCount++;
118
+ else if (line[0] === " ") spaceCount++;
119
+ if (tabCount + spaceCount >= 5) break;
120
+ }
121
+ if (tabCount > 0) return tabCount >= spaceCount;
122
+ return false;
123
+ }
124
+ function countLeadingSpaces(line) {
125
+ let count = 0;
126
+ while (count < line.length && line[count] === " ") count++;
127
+ return count;
128
+ }
129
+ function detectIndentWidth(tomlString, syntaxTree) {
130
+ const lines = tomlString.split(/\r?\n/);
131
+ const widths = [];
132
+ const containers = /* @__PURE__ */ new Set([
133
+ "Table",
134
+ "TableArray",
135
+ "InlineTable",
136
+ "InlineArray"
137
+ ]);
138
+ const rowNodes = /* @__PURE__ */ new Set([
139
+ "Table",
140
+ "TableArray",
141
+ "InlineTable",
142
+ "InlineArray",
143
+ "KeyValue",
144
+ "InlineItem",
145
+ "Comment"
146
+ ]);
147
+ const visit = (node, containerStartLine) => {
148
+ var _node$loc, _node$loc2, _node$loc3;
149
+ if (!node || typeof node !== "object") return;
150
+ if (containerStartLine !== void 0 && rowNodes.has(node.type) && ((_node$loc = node.loc) === null || _node$loc === void 0 || (_node$loc = _node$loc.start) === null || _node$loc === void 0 ? void 0 : _node$loc.line) > containerStartLine) {
151
+ const leadingSpaces = countLeadingSpaces(lines[node.loc.start.line - 1] ?? "");
152
+ if (leadingSpaces > 0) widths.push(leadingSpaces);
153
+ }
154
+ const nextContainerStartLine = containers.has(node.type) && ((_node$loc2 = node.loc) === null || _node$loc2 === void 0 || (_node$loc2 = _node$loc2.end) === null || _node$loc2 === void 0 ? void 0 : _node$loc2.line) > ((_node$loc3 = node.loc) === null || _node$loc3 === void 0 || (_node$loc3 = _node$loc3.start) === null || _node$loc3 === void 0 ? void 0 : _node$loc3.line) ? node.loc.start.line : containerStartLine;
155
+ if (Array.isArray(node.items)) for (const item of node.items) visit(item, nextContainerStartLine);
156
+ if (node.item) visit(node.item, nextContainerStartLine);
157
+ if (node.value) visit(node.value, nextContainerStartLine);
158
+ };
159
+ const nodes = Array.isArray(syntaxTree) ? syntaxTree : Array.from(syntaxTree ?? []);
160
+ for (const node of nodes) visit(node);
161
+ if (widths.length > 0) return Math.min(...widths);
162
+ const rootIndentWidths = lines.filter((line) => line.trim().length > 0 && !line.trimStart().startsWith("#")).map(countLeadingSpaces).filter((width) => width > 0);
163
+ return rootIndentWidths.length > 0 ? Math.min(...rootIndentWidths) : 2;
164
+ }
165
+ /**
166
+ * Validates a format object and warns about unsupported properties.
167
+ * Throws errors for supported properties with invalid types.
168
+ * @param format - The format object to validate
169
+ * @returns The validated format object with only supported properties and correct types
170
+ */
171
+ /**
172
+ * Spellings accepted for `newLine`, mapped to the line ending they denote.
173
+ * A Map rather than an object literal so that a key like `constructor` cannot
174
+ * resolve through Object.prototype.
175
+ */
176
+ const NEW_LINE_ALIASES = /* @__PURE__ */ new Map([
177
+ ["\n", "\n"],
178
+ ["\r\n", "\r\n"],
179
+ ["\\n", "\n"],
180
+ ["\\r\\n", "\r\n"],
181
+ ["LF", "\n"],
182
+ ["CRLF", "\r\n"],
183
+ ["UNIX", "\n"],
184
+ ["DOS", "\r\n"]
185
+ ]);
186
+ /**
187
+ * Resolves an accepted `newLine` spelling to the literal it denotes.
188
+ *
189
+ * TOML permits only LF and CRLF, so anything else would silently produce a
190
+ * document that does not parse (a bare '\\r', or the literal text 'LF' written
191
+ * between every pair of lines). Rejecting it here means every entry point that
192
+ * resolves a format gets the check, rather than just `patch()`.
193
+ *
194
+ * @throws TypeError when the value denotes neither LF nor CRLF
195
+ */
196
+ function normalizeNewLine(value) {
197
+ const resolved = NEW_LINE_ALIASES.get(value) ?? NEW_LINE_ALIASES.get(value.toUpperCase());
198
+ if (resolved === void 0) throw new TypeError("Invalid newLine value: expected LF or CRLF");
199
+ return resolved;
200
+ }
201
+ function validateFormatObject(format) {
202
+ if (!format || typeof format !== "object") return {};
203
+ const isBool = (v) => typeof v === "boolean" ? null : `expected boolean, got ${typeof v}`;
204
+ const isMultilineContainerMode = (v) => v == null || typeof v === "boolean" || v === "auto" || v === "parent" || typeof v === "number" && Number.isInteger(v) && v >= 0 ? null : `expected boolean, non-negative integer, "auto" or "parent", got ${typeof v}`;
205
+ const schema = {
206
+ newLine: (v) => typeof v === "string" ? null : `expected string, got ${typeof v}`,
207
+ trailingNewline: (v) => typeof v === "boolean" || typeof v === "number" ? null : `expected boolean or number, got ${typeof v}`,
208
+ trailingComma: isBool,
209
+ bracketSpacing: isBool,
210
+ leadingBom: isBool,
211
+ inlineTableStart: (v) => v == null || typeof v === "number" && Number.isInteger(v) && v >= 0 ? null : `expected non-negative integer or undefined, got ${typeof v}`,
212
+ truncateZeroTimeInDates: isBool,
213
+ useTabsForIndentation: isBool,
214
+ indentWidth: (v) => v == null || typeof v === "number" && Number.isInteger(v) && v > 0 ? null : `expected positive integer or undefined, got ${typeof v}`,
215
+ minimumDecimals: (v) => v == null || typeof v === "number" && Number.isInteger(v) && v >= 0 ? null : `expected non-negative integer or undefined, got ${typeof v}`,
216
+ updateOrder: isBool,
217
+ multilineTable: isMultilineContainerMode,
218
+ multilineArray: isMultilineContainerMode
219
+ };
220
+ const validatedFormat = {};
221
+ const unsupported = [];
222
+ const invalid = [];
223
+ for (const key in format) {
224
+ const validator = Object.prototype.hasOwnProperty.call(schema, key) ? schema[key] : void 0;
225
+ if (validator) {
226
+ const value = format[key];
227
+ const error = validator(value);
228
+ if (error) invalid.push(`${key} (${error})`);
229
+ else validatedFormat[key] = value;
230
+ } else if (Object.prototype.hasOwnProperty.call(format, key)) unsupported.push(key);
231
+ }
232
+ if (unsupported.length > 0) console.warn(`toml-patch: Ignoring unsupported format properties: ${unsupported.join(", ")}. Supported properties are: ${Object.keys(schema).join(", ")}`);
233
+ if (invalid.length > 0) throw new TypeError(`Invalid types for format properties: ${invalid.join(", ")}`);
234
+ if ("newLine" in validatedFormat) validatedFormat.newLine = normalizeNewLine(validatedFormat.newLine);
235
+ return validatedFormat;
236
+ }
237
+ /**
238
+ * Resolves a format parameter to a TomlFormat instance.
239
+ * Handles TomlFormat instances and partial TomlFormat objects as well as undefined.
240
+ *
241
+ * @param format - The format parameter to resolve (TomlFormat instance, partial format object, or undefined)
242
+ * @param fallbackFormat - The fallback TomlFormat to use when no format is provided
243
+ * @returns A resolved TomlFormat instance
244
+ */
245
+ function resolveTomlFormat(format, fallbackFormat) {
246
+ if (format) {
247
+ if (format instanceof TomlFormat) return format;
248
+ else {
249
+ const validatedFormat = validateFormatObject(format);
250
+ return new TomlFormat(validatedFormat.newLine ?? fallbackFormat.newLine, validatedFormat.trailingNewline ?? fallbackFormat.trailingNewline, validatedFormat.trailingComma ?? fallbackFormat.trailingComma, validatedFormat.bracketSpacing ?? fallbackFormat.bracketSpacing, "inlineTableStart" in validatedFormat ? validatedFormat.inlineTableStart : fallbackFormat.inlineTableStart, validatedFormat.truncateZeroTimeInDates ?? fallbackFormat.truncateZeroTimeInDates, validatedFormat.useTabsForIndentation ?? fallbackFormat.useTabsForIndentation, validatedFormat.minimumDecimals ?? fallbackFormat.minimumDecimals, validatedFormat.leadingBom ?? fallbackFormat.leadingBom, validatedFormat.updateOrder ?? fallbackFormat.updateOrder, validatedFormat.indentWidth ?? fallbackFormat.indentWidth, validatedFormat.multilineTable ?? fallbackFormat.multilineTable, validatedFormat.multilineArray ?? fallbackFormat.multilineArray);
251
+ }
252
+ } else return fallbackFormat;
253
+ }
254
+ var TomlFormat = class TomlFormat {
255
+ /**
256
+ * The line ending character(s) to use in the output TOML.
257
+ * This option affects only the stringification process, not the internal representation (CST).
258
+ *
259
+ * @example
260
+ * - '\n' for Unix/Linux line endings
261
+ * - '\r\n' for Windows line endings
262
+ */
263
+ newLine;
264
+ /**
265
+ * The number of trailing newlines to add at the end of the TOML document.
266
+ * This option affects only the stringification process, not the internal representation (CST).
267
+ *
268
+ * @example
269
+ * - 0: No trailing newline
270
+ * - 1: One trailing newline (standard)
271
+ * - 2: Two trailing newlines (adds extra spacing)
272
+ */
273
+ trailingNewline;
274
+ /**
275
+ * Whether to add trailing commas after the last element in arrays and inline tables.
276
+ *
277
+ * @example
278
+ * - true: [1, 2, 3,] and { x = 1, y = 2, }
279
+ * - false: [1, 2, 3] and { x = 1, y = 2 }
280
+ */
281
+ trailingComma;
282
+ /**
283
+ * Whether to add spaces after opening brackets/braces and before closing brackets/braces
284
+ * in arrays and inline tables.
285
+ *
286
+ * @example
287
+ * - true: [ 1, 2, 3 ] and { x = 1, y = 2 }
288
+ * - false: [1, 2, 3] and {x = 1, y = 2}
289
+ */
290
+ bracketSpacing;
291
+ /**
292
+ * Whether the output should include a leading UTF-8 BOM marker (U+FEFF).
293
+ *
294
+ * This is auto-detected from the source TOML and preserved during patching.
295
+ */
296
+ leadingBom;
297
+ /**
298
+ * The nesting depth at which new tables should start being formatted as inline tables.
299
+ * When adding new tables during patching or stringifying objects:
300
+ * - Tables at depth >= inlineTableStart will be formatted as inline tables
301
+ * - Tables at depth < inlineTableStart will be formatted as separate table sections
302
+ *
303
+ * @example
304
+ * - 0: All tables are inline tables including top-level tables (root level)
305
+ * - 1: Top-level tables as sections, nested tables as inline (default)
306
+ * - 2: Two levels as sections, deeper nesting as inline
307
+ */
308
+ inlineTableStart;
309
+ /**
310
+ * Whether to truncate time components in UTC date fields when they are zero.
311
+ * This setting affects only the stringification process.
312
+ *
313
+ * @example
314
+ * - true: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15
315
+ * - false: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15T00:00:00.000Z
316
+ *
317
+ */
318
+ truncateZeroTimeInDates;
319
+ /**
320
+ * Whether to use tabs instead of spaces for indentation/padding.
321
+ * When enabled, lines that need to be indented will use tabs.
322
+ *
323
+ * @example
324
+ * - true: Uses tabs for indentation
325
+ * - false: Uses spaces for indentation (default)
326
+ *
327
+ */
328
+ useTabsForIndentation;
329
+ /**
330
+ * The number of columns used for one indentation level in generated multiline values.
331
+ * This is auto-detected when patching and defaults to two columns.
332
+ */
333
+ indentWidth;
334
+ /**
335
+ * The minimum number of decimal places to use when serializing JS numbers as TOML floats.
336
+ * When greater than 0, plain JS integer values are serialized as TOML floats padded with
337
+ * zeros to reach the specified decimal count. BigInt values are always serialized as integers
338
+ * regardless of this setting.
339
+ *
340
+ * @example
341
+ * - 0: stringify({ x: 1, y: 1.5 }) → x = 1 / y = 1.5 (default)
342
+ * - 1: stringify({ x: 1, y: 1.5 }) → x = 1.0 / y = 1.5
343
+ * - 2: stringify({ x: 1, y: 1.5 }) → x = 1.00 / y = 1.50
344
+ */
345
+ minimumDecimals;
346
+ /**
347
+ * Whether `patch()` should reorder root key-values, `[table]`/`[[array]]` section blocks,
348
+ * and rows inside table bodies to match the key order of the JS object passed to `patch()`,
349
+ * carrying each entry's owned comments along with it (see docs/CommentOwnership.md).
350
+ *
351
+ * Off by default: with the option unset or `false`, `patch()` only ever changes values that
352
+ * actually differ between the existing document and the updated object, preserving the
353
+ * existing document's order even when the JS object's key order differs.
354
+ *
355
+ * Not auto-detectable — the existing document's order says nothing about the caller's
356
+ * intent, so `autoDetectFormatWithCst` always resolves this to `false`.
357
+ *
358
+ * See docs/PLAN-Update-Order.md for the full behavior and current scope limitations.
359
+ */
360
+ updateOrder;
361
+ /**
362
+ * Whether newly generated inline tables should use multiline layout.
363
+ *
364
+ * `true` and `false` select a layout directly. A non-negative integer selects
365
+ * multiline layout at that structural container depth or deeper. `'auto'`
366
+ * keeps new containers compact and `'parent'` follows the immediate parent.
367
+ */
368
+ multilineTable;
369
+ /**
370
+ * Whether newly generated inline arrays should use multiline layout.
371
+ *
372
+ * `true` and `false` select a layout directly. A non-negative integer selects
373
+ * multiline layout at that structural container depth or deeper. `'auto'`
374
+ * keeps new containers compact and `'parent'` follows the immediate parent.
375
+ */
376
+ multilineArray;
377
+ constructor(newLine, trailingNewline, trailingComma, bracketSpacing, inlineTableStart, truncateZeroTimeInDates, useTabsForIndentation, minimumDecimals, leadingBom, updateOrder, indentWidth, multilineTable, multilineArray) {
378
+ this.newLine = newLine == null ? "\n" : normalizeNewLine(newLine);
379
+ this.trailingNewline = trailingNewline ?? 1;
380
+ this.trailingComma = trailingComma ?? false;
381
+ this.bracketSpacing = bracketSpacing ?? true;
382
+ this.inlineTableStart = inlineTableStart ?? 1;
383
+ this.truncateZeroTimeInDates = truncateZeroTimeInDates ?? false;
384
+ this.useTabsForIndentation = useTabsForIndentation ?? false;
385
+ this.indentWidth = this.useTabsForIndentation ? 1 : indentWidth ?? 2;
386
+ this.minimumDecimals = minimumDecimals ?? 0;
387
+ this.leadingBom = leadingBom ?? false;
388
+ this.updateOrder = updateOrder ?? false;
389
+ this.multilineTable = multilineTable ?? "auto";
390
+ this.multilineArray = multilineArray ?? "auto";
391
+ }
392
+ /**
393
+ * Creates a new TomlFormat instance with default formatting preferences.
394
+ *
395
+ * @returns A new TomlFormat instance with default values:
396
+ * - newLine: '\n'
397
+ * - trailingNewline: 1
398
+ * - trailingComma: false
399
+ * - bracketSpacing: true
400
+ * - leadingBom: false
401
+ * - inlineTableStart: 1
402
+ * - truncateZeroTimeInDates: false
403
+ * - useTabsForIndentation: false
404
+ * - minimumDecimals: 0
405
+ * - updateOrder: false
406
+ */
407
+ static default() {
408
+ return new TomlFormat("\n", 1, false, true, 1, false, false, 0, false, false, 2, DEFAULT_MULTILINE_TABLE, DEFAULT_MULTILINE_ARRAY);
409
+ }
410
+ /**
411
+ * Auto-detects formatting preferences from an existing TOML string.
412
+ *
413
+ * This method analyzes the provided TOML string to determine formatting
414
+ * preferences such as line endings, trailing newlines, and comma usage.
415
+ *
416
+ * @param tomlString - The TOML string to analyze for formatting patterns
417
+ * @returns A new TomlFormat instance with detected formatting preferences
418
+ *
419
+ * @example
420
+ * ```typescript
421
+ * const toml = 'array = ["a", "b", "c",]\ntable = { x = 1, y = 2, }';
422
+ * const format = TomlFormat.autoDetectFormat(toml);
423
+ * // format.trailingComma will be true
424
+ * // format.newLine will be '\n'
425
+ * // format.trailingNewline will be 0 (no trailing newline)
426
+ * ```
427
+ */
428
+ static autoDetectFormat(tomlString) {
429
+ return TomlFormat.autoDetectFormatWithCst(tomlString);
430
+ }
431
+ /**
432
+ * Internal method: Auto-detects formatting preferences from a TOML string with optional pre-parsed CST.
433
+ *
434
+ * This is used internally to avoid redundant parsing when the CST is already available.
435
+ * External callers should use `autoDetectFormat(tomlString)` instead.
436
+ *
437
+ * @internal
438
+ * @param tomlString - The TOML string to analyze for formatting patterns
439
+ * @param syntaxTree - Optional pre-parsed CST to avoid redundant parsing
440
+ * @returns A new TomlFormat instance with detected formatting preferences
441
+ */
442
+ static autoDetectFormatWithCst(tomlString, syntaxTree) {
443
+ const format = TomlFormat.default();
444
+ format.leadingBom = hasLeadingBom(tomlString);
445
+ const tomlContent = stripLeadingBom(tomlString);
446
+ let cstNodes = [];
447
+ format.newLine = detectNewline(tomlContent);
448
+ format.trailingNewline = countTrailingNewlines(tomlContent);
449
+ try {
450
+ cstNodes = Array.isArray(syntaxTree) ? syntaxTree : Array.from(syntaxTree ?? parseTOML(tomlContent));
451
+ format.trailingComma = detectTrailingComma(cstNodes);
452
+ format.bracketSpacing = detectBracketSpacing(tomlContent, cstNodes);
453
+ } catch (error) {
454
+ format.trailingComma = false;
455
+ format.bracketSpacing = true;
456
+ }
457
+ format.useTabsForIndentation = detectTabsForIndentation(tomlContent);
458
+ if (format.useTabsForIndentation) format.indentWidth = 1;
459
+ else format.indentWidth = detectIndentWidth(tomlContent, cstNodes);
460
+ format.inlineTableStart = 1;
461
+ format.truncateZeroTimeInDates = false;
462
+ format.minimumDecimals = 0;
463
+ format.updateOrder = false;
464
+ format.multilineTable = DEFAULT_MULTILINE_TABLE;
465
+ format.multilineArray = DEFAULT_MULTILINE_ARRAY;
466
+ return format;
467
+ }
468
+ /** @deprecated Use autoDetectFormatWithCst instead. */
469
+ static autoDetectFormatWithAst(tomlString, syntaxTree) {
470
+ return TomlFormat.autoDetectFormatWithCst(tomlString, syntaxTree);
471
+ }
472
+ };
473
+
474
+ //#endregion
475
+ export { DEFAULT_MULTILINE_ARRAY, DEFAULT_MULTILINE_TABLE, TomlFormat, countTrailingNewlines, detectBracketSpacing, detectIndentWidth, detectNewline, detectTabsForIndentation, detectTrailingComma, normalizeNewLine, resolveTomlFormat, validateFormatObject };
476
+ //# sourceMappingURL=toml-format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toml-format.js","names":[],"sources":["../../src/toml-format.ts"],"sourcesContent":["import { hasLeadingBom, stripLeadingBom } from './decode-utf8';\nimport parseTOML from './parse-toml';\n\n// Default formatting values\nexport const DEFAULT_NEWLINE = '\\n';\nexport const DEFAULT_TRAILING_NEWLINE = 1;\nexport const DEFAULT_TRAILING_COMMA = false;\nexport const DEFAULT_BRACKET_SPACING = true;\nexport const DEFAULT_INLINE_TABLE_START = 1;\nexport const DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES = false;\nexport const DEFAULT_USE_TABS_FOR_INDENTATION = false;\nexport const DEFAULT_INDENT_WIDTH = 2;\nexport const DEFAULT_MINIMUM_DECIMALS = 0;\nexport const DEFAULT_LEADING_BOM = false;\nexport const DEFAULT_UPDATE_ORDER = false;\nexport const DEFAULT_MULTILINE_TABLE = 'auto';\nexport const DEFAULT_MULTILINE_ARRAY = 'auto';\n\nexport type MultilineContainerMode = boolean | number | 'auto' | 'parent';\n\n// Detects if trailing commas are used in the existing TOML by examining the CST\n// Returns true if trailing commas are used, false if not or comma-separated structures found (ie. default to false)\nexport function detectTrailingComma(cst: Iterable<any>): boolean {\n // Look for the first inline array or inline table to determine trailing comma preference\n for (const item of cst) {\n const result = findTrailingCommaInNode(item);\n if (result !== null) {\n return result;\n }\n }\n // Return default if no comma-separated structures are found\n return DEFAULT_TRAILING_COMMA;\n}\n\n// Detects if bracket spacing is used in inline arrays and tables by examining the raw string\n// Returns true if bracket spacing is found, false if not or no bracket structures found (default to true)\nexport function detectBracketSpacing(tomlString: string, cst: Iterable<any>): boolean {\n // Look for inline arrays and tables\n for (const item of cst) {\n const result = findBracketSpacingInNode(item, tomlString);\n if (result !== null) {\n return result;\n }\n }\n // Return default if no bracket structures are found\n return DEFAULT_BRACKET_SPACING;\n}\n\n// Helper function to recursively search for bracket spacing in a node\nfunction findBracketSpacingInNode(node: any, tomlString: string): boolean | null {\n if (!node || typeof node !== 'object') {\n return null;\n }\n\n // Check if this is an InlineArray or InlineTable\n if ((node.type === 'InlineArray' || node.type === 'InlineTable') && node.loc) {\n const bracketSpacing = checkBracketSpacingInLocation(node.loc, tomlString);\n if (bracketSpacing !== null) {\n return bracketSpacing;\n }\n }\n\n // Recursively check nested structures\n if (node.items && Array.isArray(node.items)) {\n for (const child of node.items) {\n const result = findBracketSpacingInNode(child, tomlString);\n if (result !== null) {\n return result;\n }\n // Also check nested item if it exists\n if (child.item) {\n const nestedResult = findBracketSpacingInNode(child.item, tomlString);\n if (nestedResult !== null) {\n return nestedResult;\n }\n }\n }\n }\n\n // Check other properties that might contain nodes\n for (const prop of ['value', 'key', 'item']) {\n if (node[prop]) {\n const result = findBracketSpacingInNode(node[prop], tomlString);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n// Helper function to check bracket spacing in a specific location\nfunction checkBracketSpacingInLocation(loc: any, tomlString: string): boolean | null {\n if (!loc || !loc.start || !loc.end) {\n return null;\n }\n\n // Extract the raw text for this location\n const lines = tomlString.split(/\\r?\\n/);\n const startLine = loc.start.line - 1; // Convert to 0-based\n const endLine = loc.end.line - 1;\n const startCol = loc.start.column;\n const endCol = loc.end.column;\n\n let rawText = '';\n if (startLine === endLine) {\n rawText = lines[startLine]?.substring(startCol, endCol + 1) || '';\n } else {\n // Multi-line case\n if (lines[startLine]) {\n rawText += lines[startLine].substring(startCol);\n }\n for (let i = startLine + 1; i < endLine; i++) {\n rawText += '\\n' + (lines[i] || '');\n }\n if (lines[endLine]) {\n rawText += '\\n' + lines[endLine].substring(0, endCol + 1);\n }\n }\n\n // Check for bracket spacing patterns\n // For arrays: [ elements ] vs [elements]\n // For tables: { elements } vs {elements}\n const arrayMatch = rawText.match(/^\\[(\\s*)/);\n const tableMatch = rawText.match(/^\\{(\\s*)/);\n \n if (arrayMatch) {\n // Check if there's a space after the opening bracket\n return arrayMatch[1].length > 0;\n }\n \n if (tableMatch) {\n // Check if there's a space after the opening brace\n return tableMatch[1].length > 0;\n }\n\n return null;\n}\n\n// Helper function to recursively search for comma usage in a node\nfunction findTrailingCommaInNode(node: any): boolean | null {\n if (!node || typeof node !== 'object') {\n return null;\n }\n\n // Check if this is an InlineArray\n if (node.type === 'InlineArray' && node.items && Array.isArray(node.items)) {\n return checkTrailingCommaInItems(node.items);\n }\n\n // Check if this is an InlineTable\n if (node.type === 'InlineTable' && node.items && Array.isArray(node.items)) {\n return checkTrailingCommaInItems(node.items);\n }\n\n // Check if this is a KeyValue with a value that might contain arrays/tables\n if (node.type === 'KeyValue' && node.value) {\n return findTrailingCommaInNode(node.value);\n }\n\n // For other node types, recursively check any items array\n if (node.items && Array.isArray(node.items)) {\n for (const item of node.items) {\n const result = findTrailingCommaInNode(item);\n if (result !== null) {\n return result;\n }\n }\n }\n\n return null;\n}\n\n// Check trailing comma usage in an array of inline items\nfunction checkTrailingCommaInItems(items: any[]): boolean | null {\n if (items.length === 0) {\n return null;\n }\n\n // Check the last item to see if it has a trailing comma\n const lastItem = items[items.length - 1];\n if (lastItem && typeof lastItem === 'object' && 'comma' in lastItem) {\n return lastItem.comma === true;\n }\n\n return false;\n}\n\n// Returns the detected newline (\\n or \\r\\n) from a string, defaulting to \\n.\n// First occurrence wins: if \\r\\n appears anywhere before a bare \\n, the document\n// is considered CRLF even if later lines (or string values) use bare LF.\nexport function detectNewline(str: string): string {\n const lfIndex = str.indexOf('\\n');\n if (lfIndex > 0 && str[lfIndex - 1] === '\\r') {\n return '\\r\\n';\n }\n return '\\n';\n}\n\n// Counts consecutive trailing newlines at the end of a string.\n// Counts each \\n (whether bare or as part of \\r\\n) as one newline unit,\n// so mixed trailing line endings (e.g. a CRLF document with a bare \\n at EOF)\n// are still counted correctly.\nexport function countTrailingNewlines(str: string): number {\n let count = 0;\n let pos = str.length;\n while (pos > 0 && str[pos - 1] === '\\n') {\n count++;\n pos--;\n if (pos > 0 && str[pos - 1] === '\\r') {\n pos--; // consume the \\r as part of CRLF\n }\n }\n return count;\n}\n\n// Detects if tabs are used for indentation by checking the first few indented lines\nexport function detectTabsForIndentation(str: string): boolean {\n const lines = str.split(/\\r?\\n/);\n let tabCount = 0;\n let spaceCount = 0;\n \n for (const line of lines) {\n // Skip empty lines\n if (line.length === 0) continue;\n \n // Check the first character of non-empty lines\n if (line[0] === '\\t') {\n tabCount++;\n } else if (line[0] === ' ') {\n spaceCount++;\n }\n \n // If we've seen enough evidence, make a decision\n if (tabCount + spaceCount >= 5) {\n break;\n }\n }\n \n // Prefer tabs when they are at least as common as spaces, provided there is tab evidence.\n if (tabCount > 0) {\n return tabCount >= spaceCount;\n }\n return false; // default to spaces if no evidence\n}\n/*\n Detect the indentation width (number of spaces) used in the existing TOML by examining the CST.\n\n This function already assumes that the TOML document does not use tabs for indentation. \n Do not use this function if tabs are used for indentation!\n\n It looks for the first indented line in the CST that is part of a nested \n structure (like a table or array) and measures the number of leading spaces \n to determine the indentation width.\n*/\nfunction countLeadingSpaces(line: string): number {\n let count = 0;\n while (count < line.length && line[count] === ' ') count++;\n return count;\n}\n\nexport function detectIndentWidth(tomlString: string, syntaxTree?: Iterable<any>): number {\n const lines = tomlString.split(/\\r?\\n/);\n const widths: number[] = [];\n const containers = new Set(['Table', 'TableArray', 'InlineTable', 'InlineArray']);\n const rowNodes = new Set(['Table', 'TableArray', 'InlineTable', 'InlineArray', 'KeyValue', 'InlineItem', 'Comment']);\n\n const visit = (node: any, containerStartLine?: number): void => {\n if (!node || typeof node !== 'object') return;\n\n if (\n containerStartLine !== undefined &&\n rowNodes.has(node.type) &&\n node.loc?.start?.line > containerStartLine\n ) {\n const line = lines[node.loc.start.line - 1] ?? '';\n const leadingSpaces = countLeadingSpaces(line);\n if (leadingSpaces > 0) widths.push(leadingSpaces);\n }\n\n const nextContainerStartLine = containers.has(node.type) && node.loc?.end?.line > node.loc?.start?.line\n ? node.loc.start.line\n : containerStartLine;\n\n if (Array.isArray(node.items)) {\n for (const item of node.items) visit(item, nextContainerStartLine);\n }\n if (node.item) visit(node.item, nextContainerStartLine);\n if (node.value) visit(node.value, nextContainerStartLine);\n };\n\n const nodes = Array.isArray(syntaxTree)\n ? syntaxTree\n : Array.from(syntaxTree ?? []);\n for (const node of nodes) visit(node);\n\n if (widths.length > 0) return Math.min(...widths);\n\n // A document with only an indented root key has no nested CST row from which to\n // infer the width. Use its content indentation as a fallback, ignoring blank lines\n // and comments so a banner cannot become the detected indent.\n const rootIndentWidths = lines\n .filter(line => line.trim().length > 0 && !line.trimStart().startsWith('#'))\n .map(countLeadingSpaces)\n .filter(width => width > 0);\n return rootIndentWidths.length > 0 ? Math.min(...rootIndentWidths) : DEFAULT_INDENT_WIDTH;\n}\n\n/**\n * Validates a format object and warns about unsupported properties.\n * Throws errors for supported properties with invalid types.\n * @param format - The format object to validate\n * @returns The validated format object with only supported properties and correct types\n */\n/**\n * Spellings accepted for `newLine`, mapped to the line ending they denote.\n * A Map rather than an object literal so that a key like `constructor` cannot\n * resolve through Object.prototype.\n */\nconst NEW_LINE_ALIASES = new Map<string, string>([\n ['\\n', '\\n'],\n ['\\r\\n', '\\r\\n'],\n ['\\\\n', '\\n'],\n ['\\\\r\\\\n', '\\r\\n'],\n ['LF', '\\n'],\n ['CRLF', '\\r\\n'],\n ['UNIX', '\\n'],\n ['DOS', '\\r\\n']\n]);\n\n/**\n * Resolves an accepted `newLine` spelling to the literal it denotes.\n *\n * TOML permits only LF and CRLF, so anything else would silently produce a\n * document that does not parse (a bare '\\\\r', or the literal text 'LF' written\n * between every pair of lines). Rejecting it here means every entry point that\n * resolves a format gets the check, rather than just `patch()`.\n *\n * @throws TypeError when the value denotes neither LF nor CRLF\n */\nexport function normalizeNewLine(value: string): string {\n const resolved = NEW_LINE_ALIASES.get(value) ?? NEW_LINE_ALIASES.get(value.toUpperCase());\n if (resolved === undefined) {\n throw new TypeError('Invalid newLine value: expected LF or CRLF');\n }\n return resolved;\n}\n\nexport function validateFormatObject(format: any): any {\n if (!format || typeof format !== 'object') {\n return {};\n }\n\n // Schema-driven validation: each key maps to a validator returning an error string or null\n const isBool = (v: any): string | null =>\n typeof v === 'boolean' ? null : `expected boolean, got ${typeof v}`;\n const isMultilineContainerMode = (v: any): string | null =>\n v == null ||\n typeof v === 'boolean' ||\n v === 'auto' ||\n v === 'parent' ||\n (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null\n : `expected boolean, non-negative integer, \"auto\" or \"parent\", got ${typeof v}`;\n const schema: Record<string, (v: any) => string | null> = {\n newLine: v => typeof v === 'string' ? null : `expected string, got ${typeof v}`,\n trailingNewline: v => typeof v === 'boolean' || typeof v === 'number' ? null : `expected boolean or number, got ${typeof v}`,\n trailingComma: isBool,\n bracketSpacing: isBool,\n leadingBom: isBool,\n inlineTableStart: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null : `expected non-negative integer or undefined, got ${typeof v}`,\n truncateZeroTimeInDates: isBool,\n useTabsForIndentation: isBool,\n indentWidth: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v > 0)\n ? null : `expected positive integer or undefined, got ${typeof v}`,\n minimumDecimals: v => v == null || (typeof v === 'number' && Number.isInteger(v) && v >= 0)\n ? null : `expected non-negative integer or undefined, got ${typeof v}`,\n updateOrder: isBool,\n multilineTable: isMultilineContainerMode,\n multilineArray: isMultilineContainerMode,\n };\n\n const validatedFormat: any = {};\n const unsupported: string[] = [];\n const invalid: string[] = [];\n\n for (const key in format) {\n const validator = Object.prototype.hasOwnProperty.call(schema, key) ? schema[key] : undefined;\n if (validator) {\n const value = format[key];\n const error = validator(value);\n if (error) {\n invalid.push(`${key} (${error})`);\n } else {\n validatedFormat[key] = value;\n }\n } else if (Object.prototype.hasOwnProperty.call(format, key)) {\n unsupported.push(key);\n }\n }\n\n if (unsupported.length > 0) {\n console.warn(`toml-patch: Ignoring unsupported format properties: ${unsupported.join(', ')}. Supported properties are: ${Object.keys(schema).join(', ')}`);\n }\n if (invalid.length > 0) {\n throw new TypeError(`Invalid types for format properties: ${invalid.join(', ')}`);\n }\n\n // Runs after the type checks so a non-string newLine is still reported as a\n // type error rather than an unsupported value.\n if ('newLine' in validatedFormat) {\n validatedFormat.newLine = normalizeNewLine(validatedFormat.newLine);\n }\n\n return validatedFormat;\n}\n\n/**\n * Resolves a format parameter to a TomlFormat instance.\n * Handles TomlFormat instances and partial TomlFormat objects as well as undefined.\n * \n * @param format - The format parameter to resolve (TomlFormat instance, partial format object, or undefined)\n * @param fallbackFormat - The fallback TomlFormat to use when no format is provided\n * @returns A resolved TomlFormat instance\n */\nexport function resolveTomlFormat(format: Partial<TomlFormat> | TomlFormat | undefined, fallbackFormat: TomlFormat): TomlFormat {\n if (format) {\n // If format is provided, validate and merge it with fallback\n if (format instanceof TomlFormat) {\n return format;\n } else {\n // Validate the format object and warn about unsupported properties\n const validatedFormat = validateFormatObject(format);\n \n // Create a new TomlFormat instance with validated properties\n return new TomlFormat(\n validatedFormat.newLine ?? fallbackFormat.newLine,\n validatedFormat.trailingNewline ?? fallbackFormat.trailingNewline,\n validatedFormat.trailingComma ?? fallbackFormat.trailingComma,\n validatedFormat.bracketSpacing ?? fallbackFormat.bracketSpacing,\n 'inlineTableStart' in validatedFormat ? validatedFormat.inlineTableStart : fallbackFormat.inlineTableStart,\n validatedFormat.truncateZeroTimeInDates ?? fallbackFormat.truncateZeroTimeInDates,\n validatedFormat.useTabsForIndentation ?? fallbackFormat.useTabsForIndentation,\n validatedFormat.minimumDecimals ?? fallbackFormat.minimumDecimals,\n validatedFormat.leadingBom ?? fallbackFormat.leadingBom,\n validatedFormat.updateOrder ?? fallbackFormat.updateOrder,\n validatedFormat.indentWidth ?? fallbackFormat.indentWidth,\n validatedFormat.multilineTable ?? fallbackFormat.multilineTable,\n validatedFormat.multilineArray ?? fallbackFormat.multilineArray,\n );\n }\n } else {\n // Use fallback format when no format is provided\n return fallbackFormat;\n }\n}\n\nexport class TomlFormat {\n \n /**\n * The line ending character(s) to use in the output TOML.\n * This option affects only the stringification process, not the internal representation (CST).\n * \n * @example\n * - '\\n' for Unix/Linux line endings\n * - '\\r\\n' for Windows line endings\n */\n newLine: string;\n \n /**\n * The number of trailing newlines to add at the end of the TOML document.\n * This option affects only the stringification process, not the internal representation (CST).\n * \n * @example\n * - 0: No trailing newline\n * - 1: One trailing newline (standard)\n * - 2: Two trailing newlines (adds extra spacing)\n */\n trailingNewline: number;\n \n /**\n * Whether to add trailing commas after the last element in arrays and inline tables.\n * \n * @example\n * - true: [1, 2, 3,] and { x = 1, y = 2, }\n * - false: [1, 2, 3] and { x = 1, y = 2 }\n */\n trailingComma: boolean;\n \n /**\n * Whether to add spaces after opening brackets/braces and before closing brackets/braces\n * in arrays and inline tables.\n * \n * @example\n * - true: [ 1, 2, 3 ] and { x = 1, y = 2 }\n * - false: [1, 2, 3] and {x = 1, y = 2}\n */\n bracketSpacing: boolean;\n\n /**\n * Whether the output should include a leading UTF-8 BOM marker (U+FEFF).\n *\n * This is auto-detected from the source TOML and preserved during patching.\n */\n leadingBom: boolean;\n\n /**\n * The nesting depth at which new tables should start being formatted as inline tables.\n * When adding new tables during patching or stringifying objects:\n * - Tables at depth >= inlineTableStart will be formatted as inline tables\n * - Tables at depth < inlineTableStart will be formatted as separate table sections\n * \n * @example\n * - 0: All tables are inline tables including top-level tables (root level)\n * - 1: Top-level tables as sections, nested tables as inline (default)\n * - 2: Two levels as sections, deeper nesting as inline\n */\n inlineTableStart?: number;\n\n /**\n * Whether to truncate time components in UTC date fields when they are zero.\n * This setting affects only the stringification process.\n * \n * @example \n * - true: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15\n * - false: Date('2024-01-15T00:00:00.000Z') serializes as 2024-01-15T00:00:00.000Z\n * \n */\n truncateZeroTimeInDates?: boolean;\n\n /**\n * Whether to use tabs instead of spaces for indentation/padding.\n * When enabled, lines that need to be indented will use tabs.\n * \n * @example \n * - true: Uses tabs for indentation\n * - false: Uses spaces for indentation (default)\n * \n */\n useTabsForIndentation?: boolean;\n\n /**\n * The number of columns used for one indentation level in generated multiline values.\n * This is auto-detected when patching and defaults to two columns.\n */\n indentWidth: number;\n\n /**\n * The minimum number of decimal places to use when serializing JS numbers as TOML floats.\n * When greater than 0, plain JS integer values are serialized as TOML floats padded with\n * zeros to reach the specified decimal count. BigInt values are always serialized as integers\n * regardless of this setting.\n *\n * @example\n * - 0: stringify({ x: 1, y: 1.5 }) → x = 1 / y = 1.5 (default)\n * - 1: stringify({ x: 1, y: 1.5 }) → x = 1.0 / y = 1.5\n * - 2: stringify({ x: 1, y: 1.5 }) → x = 1.00 / y = 1.50\n */\n minimumDecimals?: number;\n\n /**\n * Whether `patch()` should reorder root key-values, `[table]`/`[[array]]` section blocks,\n * and rows inside table bodies to match the key order of the JS object passed to `patch()`,\n * carrying each entry's owned comments along with it (see docs/CommentOwnership.md).\n *\n * Off by default: with the option unset or `false`, `patch()` only ever changes values that\n * actually differ between the existing document and the updated object, preserving the\n * existing document's order even when the JS object's key order differs.\n *\n * Not auto-detectable — the existing document's order says nothing about the caller's\n * intent, so `autoDetectFormatWithCst` always resolves this to `false`.\n *\n * See docs/PLAN-Update-Order.md for the full behavior and current scope limitations.\n */\n updateOrder?: boolean;\n\n /**\n * Whether newly generated inline tables should use multiline layout.\n *\n * `true` and `false` select a layout directly. A non-negative integer selects\n * multiline layout at that structural container depth or deeper. `'auto'`\n * keeps new containers compact and `'parent'` follows the immediate parent.\n */\n multilineTable: MultilineContainerMode;\n\n /**\n * Whether newly generated inline arrays should use multiline layout.\n *\n * `true` and `false` select a layout directly. A non-negative integer selects\n * multiline layout at that structural container depth or deeper. `'auto'`\n * keeps new containers compact and `'parent'` follows the immediate parent.\n */\n multilineArray: MultilineContainerMode;\n\n // These options were part of the original TimHall's version and are not yet implemented\n //printWidth?: number;\n //tabWidth?: number;\n\n constructor(\n newLine?: string,\n trailingNewline?: number,\n trailingComma?: boolean,\n bracketSpacing?: boolean,\n inlineTableStart?: number,\n truncateZeroTimeInDates?: boolean,\n useTabsForIndentation?: boolean,\n minimumDecimals?: number,\n leadingBom?: boolean,\n updateOrder?: boolean,\n indentWidth?: number,\n multilineTable?: MultilineContainerMode | null,\n multilineArray?: MultilineContainerMode | null\n ) {\n // Use provided values or fall back to defaults\n this.newLine = newLine == null ? DEFAULT_NEWLINE : normalizeNewLine(newLine);\n this.trailingNewline = trailingNewline ?? DEFAULT_TRAILING_NEWLINE;\n this.trailingComma = trailingComma ?? DEFAULT_TRAILING_COMMA;\n this.bracketSpacing = bracketSpacing ?? DEFAULT_BRACKET_SPACING;\n this.inlineTableStart = inlineTableStart ?? DEFAULT_INLINE_TABLE_START;\n this.truncateZeroTimeInDates = truncateZeroTimeInDates ?? DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES;\n this.useTabsForIndentation = useTabsForIndentation ?? DEFAULT_USE_TABS_FOR_INDENTATION;\n this.indentWidth = this.useTabsForIndentation ? 1 : indentWidth ?? DEFAULT_INDENT_WIDTH;\n this.minimumDecimals = minimumDecimals ?? DEFAULT_MINIMUM_DECIMALS;\n this.leadingBom = leadingBom ?? DEFAULT_LEADING_BOM;\n this.updateOrder = updateOrder ?? DEFAULT_UPDATE_ORDER;\n this.multilineTable = multilineTable ?? DEFAULT_MULTILINE_TABLE;\n this.multilineArray = multilineArray ?? DEFAULT_MULTILINE_ARRAY;\n }\n\n /**\n * Creates a new TomlFormat instance with default formatting preferences.\n * \n * @returns A new TomlFormat instance with default values:\n * - newLine: '\\n'\n * - trailingNewline: 1\n * - trailingComma: false\n * - bracketSpacing: true\n * - leadingBom: false\n * - inlineTableStart: 1\n * - truncateZeroTimeInDates: false\n * - useTabsForIndentation: false\n * - minimumDecimals: 0\n * - updateOrder: false\n */\n static default(): TomlFormat {\n return new TomlFormat(\n DEFAULT_NEWLINE,\n DEFAULT_TRAILING_NEWLINE,\n DEFAULT_TRAILING_COMMA,\n DEFAULT_BRACKET_SPACING,\n DEFAULT_INLINE_TABLE_START,\n DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES,\n DEFAULT_USE_TABS_FOR_INDENTATION,\n DEFAULT_MINIMUM_DECIMALS,\n DEFAULT_LEADING_BOM,\n DEFAULT_UPDATE_ORDER,\n DEFAULT_INDENT_WIDTH,\n DEFAULT_MULTILINE_TABLE,\n DEFAULT_MULTILINE_ARRAY\n );\n }\n\n /**\n * Auto-detects formatting preferences from an existing TOML string.\n * \n * This method analyzes the provided TOML string to determine formatting\n * preferences such as line endings, trailing newlines, and comma usage.\n * \n * @param tomlString - The TOML string to analyze for formatting patterns\n * @returns A new TomlFormat instance with detected formatting preferences\n * \n * @example\n * ```typescript\n * const toml = 'array = [\"a\", \"b\", \"c\",]\\ntable = { x = 1, y = 2, }';\n * const format = TomlFormat.autoDetectFormat(toml);\n * // format.trailingComma will be true\n * // format.newLine will be '\\n'\n * // format.trailingNewline will be 0 (no trailing newline)\n * ```\n */\n static autoDetectFormat(tomlString: string): TomlFormat {\n return TomlFormat.autoDetectFormatWithCst(tomlString);\n }\n\n /**\n * Internal method: Auto-detects formatting preferences from a TOML string with optional pre-parsed CST.\n * \n * This is used internally to avoid redundant parsing when the CST is already available.\n * External callers should use `autoDetectFormat(tomlString)` instead.\n * \n * @internal\n * @param tomlString - The TOML string to analyze for formatting patterns\n * @param syntaxTree - Optional pre-parsed CST to avoid redundant parsing\n * @returns A new TomlFormat instance with detected formatting preferences\n */\n static autoDetectFormatWithCst(tomlString: string, syntaxTree?: Iterable<any>): TomlFormat {\n const format = TomlFormat.default();\n format.leadingBom = hasLeadingBom(tomlString);\n // Strip the BOM before other formatting detection to avoid interference.\n const tomlContent = stripLeadingBom(tomlString);\n let cstNodes: any[] = [];\n \n // Detect line ending style\n format.newLine = detectNewline(tomlContent);\n \n // Detect trailing newline count\n format.trailingNewline = countTrailingNewlines(tomlContent);\n \n // Get TOML syntax tree to detect comma and bracket spacing usage patterns\n try {\n // Materialize only when needed so we can traverse the same CST twice.\n cstNodes = Array.isArray(syntaxTree)\n ? syntaxTree\n : Array.from(syntaxTree ?? parseTOML(tomlContent));\n format.trailingComma = detectTrailingComma(cstNodes);\n format.bracketSpacing = detectBracketSpacing(tomlContent, cstNodes);\n } catch (error) {\n // If parsing fails, fall back to defaults\n // This ensures the method is robust against malformed TOML\n format.trailingComma = DEFAULT_TRAILING_COMMA;\n format.bracketSpacing = DEFAULT_BRACKET_SPACING;\n }\n \n // Detect if tabs are used for indentation\n format.useTabsForIndentation = detectTabsForIndentation(tomlContent);\n if (format.useTabsForIndentation) {\n // If tabs are used, indentWidth is effectively 1 (one tab character)\n format.indentWidth = 1;\n } else {\n // Otherwise, detect the number of spaces used for indentation\n format.indentWidth = detectIndentWidth(tomlContent, cstNodes);\n }\n \n \n // inlineTableStart uses default value since auto-detection would require\n // complex analysis of nested table formatting preferences\n format.inlineTableStart = DEFAULT_INLINE_TABLE_START;\n\n // truncateZeroTimeInDates uses default value as well\n // We could always implement detection logic if needed\n // That would imply checking if all dates have no time component in the TOML.\n // However, it's not because all dates have no time component that a new key-value can't be introduced where the time component corresponds to midnight.\n format.truncateZeroTimeInDates = DEFAULT_TRUNCATE_ZERO_TIME_IN_DATES;\n\n // minimumDecimals uses default value (0) — caller must set explicitly\n format.minimumDecimals = DEFAULT_MINIMUM_DECIMALS;\n\n // updateOrder uses default value (false) as well — the existing document's order says\n // nothing about the caller's intent, so this is never auto-detected.\n format.updateOrder = DEFAULT_UPDATE_ORDER;\n\n // Multiline container layout is caller intent, so it is never auto-detected.\n format.multilineTable = DEFAULT_MULTILINE_TABLE;\n format.multilineArray = DEFAULT_MULTILINE_ARRAY;\n\n return format;\n }\n\n /** @deprecated Use autoDetectFormatWithCst instead. */\n static autoDetectFormatWithAst(tomlString: string, syntaxTree?: Iter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AQ,UAAU,IAC/B,aACA,MAAM,KAAK,cAAc,UAAU,WAAW,CAAC;GACnD,OAAO,gBAAgB,oBAAoB,QAAQ;GACnD,OAAO,iBAAiB,qBAAqB,aAAa,QAAQ;EACpE,SAAS,OAAO;GAGd,OAAO;GACP,OAAO;EACT;EAGA,OAAO,wBAAwB,yBAAyB,WAAW;EACnE,IAAI,OAAO,uBAET,OAAO,cAAc;OAGrB,OAAO,cAAc,kBAAkB,aAAa,QAAQ;EAM9D,OAAO;EAMP,OAAO;EAGP,OAAO;EAIP,OAAO;EAGP,OAAO,iBAAiB;EACxB,OAAO,iBAAiB;EAExB,OAAO;CACT;;CAGA,OAAO,wBAAwB,YAAoB,YAAwC;EACzF,OAAO,WAAW,wBAAwB,YAAY,UAAU;CAClE;AACF"}
@@ -0,0 +1,84 @@
1
+ //! @decimalturn/toml-patch v3.1.1 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
+ import { LocalDate, LocalDateTime, LocalTime, OffsetDateTime } from "./date-format.js";
3
+ import parseTOML from "./parse-toml.js";
4
+ import { decodeUtf8Bytes, stripLeadingBom } from "./decode-utf8.js";
5
+ import { TomlFormat, resolveTomlFormat } from "./toml-format.js";
6
+ import parseJS from "./parse-js.js";
7
+ import toTOML from "./to-toml.js";
8
+ import toJS from "./to-js.js";
9
+ import patch from "./patch.js";
10
+ import { TomlDocument } from "./toml-document.js";
11
+
12
+ //#region src/index.ts
13
+ /**
14
+ * Parses a TOML string or raw UTF-8 bytes into a JavaScript object.
15
+ *
16
+ * When raw bytes (Uint8Array / Buffer) are provided, they are decoded with
17
+ * the WHATWG TextDecoder in fatal mode, which rejects any invalid UTF-8
18
+ * byte sequences before parsing begins. This matches the TOML spec requirement
19
+ * that "A TOML file must be a valid UTF-8 encoded Unicode document."
20
+ *
21
+ * The string path has zero overhead — the bytes path incurs one TextDecoder
22
+ * decode (which also produces the string needed for parsing).
23
+ *
24
+ * By default (`options.integersAsBigInt` unset or `'asNeeded'`), integers that
25
+ * fit within the JavaScript safe-integer range are returned as `number`; integers
26
+ * outside that range are returned as `bigint` to preserve precision. Set
27
+ * `options.integersAsBigInt` to `true` to always return `bigint` for all integers,
28
+ * or `false` to always return `number` (large integers will lose precision).
29
+ *
30
+ * Note: the `'asNeeded'` default is a behavioral change from prior versions (<=1.0.7). If
31
+ * your code serializes the result to JSON or performs arithmetic mixing `number`
32
+ * and `bigint`, set `integersAsBigInt: false` to restore the previous behavior.
33
+ *
34
+ * By default (`options.temporal` unset or `false`), TOML date/time values are
35
+ * returned as custom Date subclasses (LocalDate, LocalTime, LocalDateTime,
36
+ * OffsetDateTime). Set `options.temporal` to `true` to return Temporal API
37
+ * objects instead (Temporal.PlainDate, Temporal.PlainTime, Temporal.PlainDateTime,
38
+ * Temporal.ZonedDateTime). The Temporal API must be available in the runtime.
39
+ *
40
+ * @param value - TOML source as a string or raw UTF-8 bytes
41
+ * @param options - Optional parse options
42
+ * @param options.integersAsBigInt - Controls `bigint` vs `number` for integers.
43
+ * `'asNeeded'` (default) | `true` | `false`
44
+ * @param options.temporal - When true, returns Temporal objects for date/time values.
45
+ * Default: false.
46
+ * @returns The parsed JavaScript object
47
+ */
48
+ function parse(value, options) {
49
+ const rawString = typeof value === "string" ? value : decodeUtf8Bytes(value);
50
+ const tomlString = stripLeadingBom(rawString);
51
+ return toJS(parseTOML(tomlString), tomlString, {
52
+ integersAsBigInt: (options === null || options === void 0 ? void 0 : options.integersAsBigInt) ?? "asNeeded",
53
+ temporal: (options === null || options === void 0 ? void 0 : options.temporal) ?? false
54
+ });
55
+ }
56
+ /**
57
+ * Converts a JavaScript object to a TOML string.
58
+ *
59
+ * @param value - The JavaScript object to stringify
60
+ * @param format - Optional formatting options for the resulting TOML
61
+ * @returns The stringified TOML representation
62
+ */
63
+ function stringify(value, format) {
64
+ const fmt = resolveTomlFormat(format, TomlFormat.default());
65
+ const document = parseJS(value, fmt);
66
+ const tomlString = toTOML(document.items, fmt);
67
+ return fmt.leadingBom ? `${""}${tomlString}` : tomlString;
68
+ }
69
+ /**
70
+ * Parses a TOML string or raw UTF-8 bytes into a {@link TomlDocument}.
71
+ *
72
+ * This is a convenience alternative to `new TomlDocument(value, options)`.
73
+ *
74
+ * @param value - TOML source as a string or raw UTF-8 bytes
75
+ * @param options - Optional parse options
76
+ * @returns A {@link TomlDocument} representing the parsed TOML
77
+ */
78
+ function parseDocument(value, options) {
79
+ return new TomlDocument(value, options);
80
+ }
81
+
82
+ //#endregion
83
+ export { LocalDate, LocalDateTime, LocalTime, OffsetDateTime, TomlDocument, TomlFormat, parse, parseDocument, patch, stringify };
84
+ //# sourceMappingURL=toml-patch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toml-patch.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import parseTOML from './parse-toml';\nimport parseJS from './parse-js';\nimport toTOML from './to-toml';\nimport toJS from './to-js';\nimport { TomlFormat, resolveTomlFormat } from './toml-format';\nimport type { ParseOptions } from './parse-options';\nimport { decodeUtf8Bytes, stripLeadingBom, UTF8_BOM } from './decode-utf8';\nimport { TomlDocument } from './toml-document';\n\nexport type { IntegersAsBigInt, ParseOptions } from './parse-options';\n\n/**\n * Parses a TOML string or raw UTF-8 bytes into a JavaScript object.\n *\n * When raw bytes (Uint8Array / Buffer) are provided, they are decoded with\n * the WHATWG TextDecoder in fatal mode, which rejects any invalid UTF-8\n * byte sequences before parsing begins. This matches the TOML spec requirement\n * that \"A TOML file must be a valid UTF-8 encoded Unicode document.\"\n *\n * The string path has zero overhead — the bytes path incurs one TextDecoder\n * decode (which also produces the string needed for parsing).\n *\n * By default (`options.integersAsBigInt` unset or `'asNeeded'`), integers that\n * fit within the JavaScript safe-integer range are returned as `number`; integers\n * outside that range are returned as `bigint` to preserve precision. Set\n * `options.integersAsBigInt` to `true` to always return `bigint` for all integers,\n * or `false` to always return `number` (large integers will lose precision).\n *\n * Note: the `'asNeeded'` default is a behavioral change from prior versions (<=1.0.7). If\n * your code serializes the result to JSON or performs arithmetic mixing `number`\n * and `bigint`, set `integersAsBigInt: false` to restore the previous behavior.\n *\n * By default (`options.temporal` unset or `false`), TOML date/time values are\n * returned as custom Date subclasses (LocalDate, LocalTime, LocalDateTime,\n * OffsetDateTime). Set `options.temporal` to `true` to return Temporal API\n * objects instead (Temporal.PlainDate, Temporal.PlainTime, Temporal.PlainDateTime,\n * Temporal.ZonedDateTime). The Temporal API must be available in the runtime.\n *\n * @param value - TOML source as a string or raw UTF-8 bytes\n * @param options - Optional parse options\n * @param options.integersAsBigInt - Controls `bigint` vs `number` for integers.\n * `'asNeeded'` (default) | `true` | `false`\n * @param options.temporal - When true, returns Temporal objects for date/time values.\n * Default: false.\n * @returns The parsed JavaScript object\n */\nexport function parse(value: string | Uint8Array, options?: ParseOptions): any {\n const rawString = typeof value === 'string'\n ? value\n : decodeUtf8Bytes(value);\n const tomlString = stripLeadingBom(rawString);\n return toJS(parseTOML(tomlString), tomlString, {\n integersAsBigInt: options?.integersAsBigInt ?? 'asNeeded',\n temporal: options?.temporal ?? false\n });\n}\n\n/**\n * Converts a JavaScript object to a TOML string.\n * \n * @param value - The JavaScript object to stringify\n * @param format - Optional formatting options for the resulting TOML\n * @returns The stringified TOML representation\n */\nexport function stringify(value: any, format?: Partial<TomlFormat> | TomlFormat): string {\n const fmt = resolveTomlFormat(format, TomlFormat.default());\n \n const document = parseJS(value, fmt);\n const tomlString = toTOML(document.items, fmt);\n return fmt.leadingBom ? `${UTF8_BOM}${tomlString}` : tomlString;\n}\n\nexport { default as patch } from './patch';\nexport { LocalDate, LocalTime, LocalDateTime, OffsetDateTime } from './parse-toml';\n\n/**\n * TomlFormat class for configuring TOML formatting options.\n * \n * This class allows you to customize how TOML documents are formatted when using\n * the stringify() and patch() functions. It provides control over line endings,\n * spacing, trailing commas, and other formatting preferences.\n * \n * @example\n * ```typescript\n * import { patch, TomlFormat } from '@decimalturn/toml-patch';\n * \n * // Create a custom format configuration\n * const format = TomlFormat.default();\n * format.newLine = '\\r\\n'; // Windows line endings\n * format.trailingNewline = 0; // No trailing newline\n * format.trailingComma = true; // Add trailing commas\n * format.bracketSpacing = false; // No spaces in brackets\n * \n * // Apply the patch with custom formatting\n * const result = patch(existingToml, updatedData, format);\n * ```\n */\nexport { TomlFormat, type MultilineContainerMode } from './toml-format';\n\n/**\n * TomlDocument encapsulates a TOML CST and provides methods to interact with it.\n */\nexport { TomlDocument } from './toml-document';\n\n/**\n * Parses a TOML string or raw UTF-8 bytes into a {@link TomlDocument}.\n *\n * This is a convenience alternative to `new TomlDocument(value, options)`.\n *\n * @param value - TOML source as a string or raw UTF-8 bytes\n * @param options - Optional parse options\n * @returns A {@link TomlDocument} representing the parsed TOML\n */\nexport function parseDocument(value: string | Uint8Array, options?: ParseOptions): TomlDocument {\n return new TomlDocument(value, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAgB,MAAM,OAA4B,SAA6B;CAC7E,MAAM,YAAY,OAAO,UAAU,WAC/B,QACA,gBAAgB,KAAK;CACzB,MAAM,aAAa,gBAAgB,SAAS;CAC5C,OAAO,KAAK,UAAU,UAAU,GAAG,YAAY;EAC7C,qEAAkB,QAAS,qBAAoB;EAC/C,6DAAU,QAAS,aAAY;CACjC,CAAC;AACH;;;;;;;;AASA,SAAgB,UAAU,OAAY,QAAmD;CACvF,MAAM,MAAM,kBAAkB,QAAQ,WAAW,QAAQ,CAAC;CAE1D,MAAM,WAAW,QAAQ,OAAO,GAAG;CACnC,MAAM,aAAa,OAAO,SAAS,OAAO,GAAG;CAC7C,OAAO,IAAI,aAAa,SAAc,eAAe;AACvD;;;;;;;;;;AA2CA,SAAgB,cAAc,OAA4B,SAAsC;CAC9F,OAAO,IAAI,aAAa,OAAO,OAAO;AACxC"}