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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/patch.js +20 -0
  2. package/package.json +6 -11
  3. package/dist/dev/comment-alignment.js +0 -372
  4. package/dist/dev/comment-alignment.js.map +0 -1
  5. package/dist/dev/comment-ownership.js +0 -673
  6. package/dist/dev/comment-ownership.js.map +0 -1
  7. package/dist/dev/cst-source.js +0 -118
  8. package/dist/dev/cst-source.js.map +0 -1
  9. package/dist/dev/cst.js +0 -68
  10. package/dist/dev/cst.js.map +0 -1
  11. package/dist/dev/cursor.js +0 -66
  12. package/dist/dev/cursor.js.map +0 -1
  13. package/dist/dev/date-format.js +0 -287
  14. package/dist/dev/date-format.js.map +0 -1
  15. package/dist/dev/decode-utf8.js +0 -27
  16. package/dist/dev/decode-utf8.js.map +0 -1
  17. package/dist/dev/diff-lite.js +0 -108
  18. package/dist/dev/diff-lite.js.map +0 -1
  19. package/dist/dev/diff.js +0 -265
  20. package/dist/dev/diff.js.map +0 -1
  21. package/dist/dev/encode-lite.js +0 -210
  22. package/dist/dev/encode-lite.js.map +0 -1
  23. package/dist/dev/escape-preference.js +0 -166
  24. package/dist/dev/escape-preference.js.map +0 -1
  25. package/dist/dev/find-by-path.js +0 -115
  26. package/dist/dev/find-by-path.js.map +0 -1
  27. package/dist/dev/formatter.js +0 -298
  28. package/dist/dev/formatter.js.map +0 -1
  29. package/dist/dev/generate.js +0 -480
  30. package/dist/dev/generate.js.map +0 -1
  31. package/dist/dev/inline-comma-space.js +0 -13
  32. package/dist/dev/inline-comma-space.js.map +0 -1
  33. package/dist/dev/inline-format.js +0 -106
  34. package/dist/dev/inline-format.js.map +0 -1
  35. package/dist/dev/inline-layout.js +0 -107
  36. package/dist/dev/inline-layout.js.map +0 -1
  37. package/dist/dev/line-ending-backslash.js +0 -320
  38. package/dist/dev/line-ending-backslash.js.map +0 -1
  39. package/dist/dev/literal-string.js +0 -46
  40. package/dist/dev/literal-string.js.map +0 -1
  41. package/dist/dev/location.js +0 -104
  42. package/dist/dev/location.js.map +0 -1
  43. package/dist/dev/parse-error.js +0 -27
  44. package/dist/dev/parse-error.js.map +0 -1
  45. package/dist/dev/parse-js.js +0 -150
  46. package/dist/dev/parse-js.js.map +0 -1
  47. package/dist/dev/parse-string.js +0 -120
  48. package/dist/dev/parse-string.js.map +0 -1
  49. package/dist/dev/parse-toml.js +0 -714
  50. package/dist/dev/parse-toml.js.map +0 -1
  51. package/dist/dev/patch-lite.js +0 -4
  52. package/dist/dev/patch-lite2.js +0 -97
  53. package/dist/dev/patch-lite2.js.map +0 -1
  54. package/dist/dev/patch.js +0 -3128
  55. package/dist/dev/patch.js.map +0 -1
  56. package/dist/dev/smol-toml-date.js +0 -61
  57. package/dist/dev/smol-toml-date.js.map +0 -1
  58. package/dist/dev/to-js.js +0 -308
  59. package/dist/dev/to-js.js.map +0 -1
  60. package/dist/dev/to-toml.js +0 -874
  61. package/dist/dev/to-toml.js.map +0 -1
  62. package/dist/dev/tokenizer.js +0 -225
  63. package/dist/dev/tokenizer.js.map +0 -1
  64. package/dist/dev/toml-document.js +0 -221
  65. package/dist/dev/toml-document.js.map +0 -1
  66. package/dist/dev/toml-format.js +0 -549
  67. package/dist/dev/toml-format.js.map +0 -1
  68. package/dist/dev/toml-patch.js +0 -94
  69. package/dist/dev/toml-patch.js.map +0 -1
  70. package/dist/dev/traverse.js +0 -61
  71. package/dist/dev/traverse.js.map +0 -1
  72. package/dist/dev/truncate.js +0 -64
  73. package/dist/dev/truncate.js.map +0 -1
  74. package/dist/dev/update-order.js +0 -235
  75. package/dist/dev/update-order.js.map +0 -1
  76. package/dist/dev/utils.js +0 -296
  77. package/dist/dev/utils.js.map +0 -1
  78. package/dist/dev/writer.js +0 -758
  79. package/dist/dev/writer.js.map +0 -1
  80. package/dist/toml-patch.d.ts +0 -564
  81. /package/dist/{patch-lite.d.ts → patch.d.ts} +0 -0
@@ -1 +0,0 @@
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_MINIMUM_TIME_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';\nexport const DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE = true;\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// Returns the case (uppercase vs lowercase) of the first hex escape sequence found in a\n// string's raw text, or null when the string contains no hex escape sequences.\nfunction escapeCaseOfRaw(raw: string): boolean | null {\n for (let i = 0; i < raw.length; i++) {\n if (raw[i] !== '\\\\') continue;\n const n1 = raw[i + 1];\n if (!n1) return null;\n\n if (n1 === '\\\\') {\n // An escaped backslash: the character after it is content, so the second\n // backslash does not start a hex escape. `\\\\uabcd` is the text `\\uabcd`\n // and must not decide the case of the escapes the library generates.\n i++;\n continue;\n }\n\n if (n1 === 'x' && /^[0-9A-Fa-f]{2}$/.test(raw.slice(i + 2, i + 4))) {\n return /[A-F]/.test(raw.slice(i + 2, i + 4));\n }\n if (n1 === 'u' && /^[0-9A-Fa-f]{4}$/.test(raw.slice(i + 2, i + 6))) {\n return /[A-F]/.test(raw.slice(i + 2, i + 6));\n }\n if (n1 === 'U' && /^[0-9A-Fa-f]{8}$/.test(raw.slice(i + 2, i + 10))) {\n return /[A-F]/.test(raw.slice(i + 2, i + 10));\n }\n // Simple escapes (\\b, \\t, \\n, \\f, \\r, \\\", \\\\) carry no hex digits, so they\n // cannot inform the case preference and are skipped.\n }\n return null;\n}\n\nfunction findEscapeCaseInNode(node: any): boolean | null {\n if (!node || typeof node !== 'object') return null;\n\n if (node.type === 'String' && typeof node.raw === 'string') {\n const result = escapeCaseOfRaw(node.raw);\n if (result !== null) return result;\n }\n\n for (const prop of ['key', 'item', 'value']) {\n if (node[prop] && typeof node[prop] === 'object') {\n const result = findEscapeCaseInNode(node[prop]);\n if (result !== null) return result;\n }\n }\n if (Array.isArray(node.items)) {\n for (const child of node.items) {\n const result = findEscapeCaseInNode(child);\n if (result !== null) return result;\n }\n }\n\n return null;\n}\n\n// Detects whether escape sequences in existing string values use uppercase hex digits.\n// The first hex escape sequence encountered in document order wins: uppercase hex (A-F)\n// selects uppercase output, lowercase selects lowercase output.\nexport function detectEscapeSequenceUpperCase(cstNodes: Iterable<any>): boolean {\n for (const node of cstNodes) {\n const result = findEscapeCaseInNode(node);\n if (result !== null) return result;\n }\n return DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE;\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 minimumTimeDecimals: 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 escapeSequenceUpperCase: isBool,\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 validatedFormat.escapeSequenceUpperCase ?? fallbackFormat.escapeSequenceUpperCase,\n validatedFormat.minimumTimeDecimals ?? fallbackFormat.minimumTimeDecimals,\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 * The minimum number of fractional-second digits to write for date/time values.\n *\n * When greater than 0, a time or datetime is padded with zeros to reach the specified digit\n * count, and a time written as `HH:MM` gains `:00` before its fraction. Digits already written\n * are never removed, so a value with more digits keeps them, and a date-only value is\n * unaffected because it carries no time. This is separate from `minimumDecimals`, which\n * applies to numbers, so the two can be set independently.\n *\n * Not auto-detectable — caller must set explicitly.\n *\n * @example\n * - 0: t = 07:32:00 (default)\n * - 3: t = 07:32:00.000\n */\n minimumTimeDecimals?: 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 /**\n * Whether to write `\\uXXXX` / `\\UXXXXXXXX` / `\\xHH` escape sequences with\n * uppercase hex digits. Auto-detected from the first hex escape sequence in\n * the document during patching; defaults to `true` (uppercase hex).\n */\n escapeSequenceUpperCase: boolean;\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 escapeSequenceUpperCase?: boolean,\n minimumTimeDecimals?: number\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.minimumTimeDecimals = minimumTimeDecimals ?? DEFAULT_MINIMUM_TIME_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 this.escapeSequenceUpperCase = escapeSequenceUpperCase ?? DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE;\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 * - minimumTimeDecimals: 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 DEFAULT_ESCAPE_SEQUENCE_UPPER_CASE,\n DEFAULT_MINIMUM_TIME_DECIMALS\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 // minimumTimeDecimals uses default value (0) too — caller must set explicitly\n format.minimumTimeDecimals = DEFAULT_MINIMUM_TIME_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 // Escape sequence case follows the first hex escape found in the document.\n format.escapeSequenceUpperCase = detectEscapeSequenceUpperCase(cstNodes);\n\n return format;\n }\n\n /** @deprecated Use autoDetectFormatWithCst instead. */\n static autoDetectFormatWithAst(tomlString: string, syntaxTree?: Iterable<any>): TomlFormat {\n return TomlFormat.autoDetectFormatWithCst(tomlString, syntaxTree);\n }\n}\n"],"mappings":";;;;;AAIA,MAAa,kBAAkB;AAC/B,MAAa,2BAA2B;AACxC,MAAa,yBAAyB;AACtC,MAAa,0BAA0B;AACvC,MA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W,wBAAwB,UAAU;CACtD;;;;;;;;;;;;CAaA,OAAO,wBAAwB,YAAoB,YAAwC;EACzF,MAAM,SAAS,WAAW,QAAQ;EAClC,OAAO,aAAa,cAAc,UAAU;EAE5C,MAAM,cAAc,gBAAgB,UAAU;EAC9C,IAAI,WAAkB,CAAC;EAGvB,OAAO,UAAU,cAAc,WAAW;EAG1C,OAAO,kBAAkB,sBAAsB,WAAW;EAG1D,IAAI;GAEF,WAAW,MAAM,QAAQ,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;EAGP,OAAO;EAIP,OAAO;EAGP,OAAO,iBAAiB;EACxB,OAAO,iBAAiB;EAGxB,OAAO,0BAA0B,8BAA8B,QAAQ;EAEvE,OAAO;CACT;;CAGA,OAAO,wBAAwB,YAAoB,YAAwC;EACzF,OAAO,WAAW,wBAAwB,YAAY,UAAU;CAClE;AACF"}
@@ -1,94 +0,0 @@
1
- //! @decimalturn/toml-patch v3.3.2 - 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, { toTOMLSequential } 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
- * Frozen default format reused for stringify() calls that pass no format
15
- * object, avoiding a TomlFormat allocation on every call.
16
- */
17
- const DEFAULT_STRINGIFY_FORMAT = Object.freeze(TomlFormat.default());
18
- /** True when a resolved format produces byte-identical output to the defaults. */
19
- function isDefaultFormat(fmt) {
20
- const d = DEFAULT_STRINGIFY_FORMAT;
21
- return fmt.newLine === d.newLine && fmt.trailingNewline === d.trailingNewline && fmt.trailingComma === d.trailingComma && fmt.bracketSpacing === d.bracketSpacing && fmt.inlineTableStart === d.inlineTableStart && fmt.truncateZeroTimeInDates === d.truncateZeroTimeInDates && fmt.useTabsForIndentation === d.useTabsForIndentation && fmt.indentWidth === d.indentWidth && fmt.minimumDecimals === d.minimumDecimals && fmt.minimumTimeDecimals === d.minimumTimeDecimals && fmt.leadingBom === d.leadingBom && fmt.updateOrder === d.updateOrder && fmt.multilineTable === d.multilineTable && fmt.multilineArray === d.multilineArray;
22
- }
23
- /**
24
- * Parses a TOML string or raw UTF-8 bytes into a JavaScript object.
25
- *
26
- * When raw bytes (Uint8Array / Buffer) are provided, they are decoded with
27
- * the WHATWG TextDecoder in fatal mode, which rejects any invalid UTF-8
28
- * byte sequences before parsing begins. This matches the TOML spec requirement
29
- * that "A TOML file must be a valid UTF-8 encoded Unicode document."
30
- *
31
- * The string path has zero overhead — the bytes path incurs one TextDecoder
32
- * decode (which also produces the string needed for parsing).
33
- *
34
- * By default (`options.integersAsBigInt` unset or `'asNeeded'`), integers that
35
- * fit within the JavaScript safe-integer range are returned as `number`; integers
36
- * outside that range are returned as `bigint` to preserve precision. Set
37
- * `options.integersAsBigInt` to `true` to always return `bigint` for all integers,
38
- * or `false` to always return `number` (large integers will lose precision).
39
- *
40
- * Note: the `'asNeeded'` default is a behavioral change from prior versions (<=1.0.7). If
41
- * your code serializes the result to JSON or performs arithmetic mixing `number`
42
- * and `bigint`, set `integersAsBigInt: false` to restore the previous behavior.
43
- *
44
- * By default (`options.temporal` unset or `false`), TOML date/time values are
45
- * returned as custom Date subclasses (LocalDate, LocalTime, LocalDateTime,
46
- * OffsetDateTime). Set `options.temporal` to `true` to return Temporal API
47
- * objects instead (Temporal.PlainDate, Temporal.PlainTime, Temporal.PlainDateTime,
48
- * Temporal.ZonedDateTime). The Temporal API must be available in the runtime.
49
- *
50
- * @param value - TOML source as a string or raw UTF-8 bytes
51
- * @param options - Optional parse options
52
- * @param options.integersAsBigInt - Controls `bigint` vs `number` for integers.
53
- * `'asNeeded'` (default) | `true` | `false`
54
- * @param options.temporal - When true, returns Temporal objects for date/time values.
55
- * Default: false.
56
- * @returns The parsed JavaScript object
57
- */
58
- function parse(value, options) {
59
- const rawString = typeof value === "string" ? value : decodeUtf8Bytes(value);
60
- const tomlString = stripLeadingBom(rawString);
61
- return toJS(parseTOML(tomlString), tomlString, {
62
- integersAsBigInt: (options === null || options === void 0 ? void 0 : options.integersAsBigInt) ?? "asNeeded",
63
- temporal: (options === null || options === void 0 ? void 0 : options.temporal) ?? false
64
- });
65
- }
66
- /**
67
- * Converts a JavaScript object to a TOML string.
68
- *
69
- * @param value - The JavaScript object to stringify
70
- * @param format - Optional formatting options for the resulting TOML
71
- * @returns The stringified TOML representation
72
- */
73
- function stringify(value, format) {
74
- const fmt = format == null ? DEFAULT_STRINGIFY_FORMAT : resolveTomlFormat(format, TomlFormat.default());
75
- const document = parseJS(value, fmt);
76
- const tomlString = isDefaultFormat(fmt) ? toTOMLSequential(document.items, fmt) : toTOML(document.items, fmt);
77
- return fmt.leadingBom ? `${""}${tomlString}` : tomlString;
78
- }
79
- /**
80
- * Parses a TOML string or raw UTF-8 bytes into a {@link TomlDocument}.
81
- *
82
- * This is a convenience alternative to `new TomlDocument(value, options)`.
83
- *
84
- * @param value - TOML source as a string or raw UTF-8 bytes
85
- * @param options - Optional parse options
86
- * @returns A {@link TomlDocument} representing the parsed TOML
87
- */
88
- function parseDocument(value, options) {
89
- return new TomlDocument(value, options);
90
- }
91
-
92
- //#endregion
93
- export { LocalDate, LocalDateTime, LocalTime, OffsetDateTime, TomlDocument, TomlFormat, parse, parseDocument, patch, stringify };
94
- //# sourceMappingURL=toml-patch.js.map
@@ -1 +0,0 @@
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, { toTOMLSequential } 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 * Frozen default format reused for stringify() calls that pass no format\n * object, avoiding a TomlFormat allocation on every call.\n */\nconst DEFAULT_STRINGIFY_FORMAT: TomlFormat = Object.freeze(TomlFormat.default()) as TomlFormat;\n\n/** True when a resolved format produces byte-identical output to the defaults. */\nfunction isDefaultFormat(fmt: TomlFormat): boolean {\n const d = DEFAULT_STRINGIFY_FORMAT;\n return fmt.newLine === d.newLine &&\n fmt.trailingNewline === d.trailingNewline &&\n fmt.trailingComma === d.trailingComma &&\n fmt.bracketSpacing === d.bracketSpacing &&\n fmt.inlineTableStart === d.inlineTableStart &&\n fmt.truncateZeroTimeInDates === d.truncateZeroTimeInDates &&\n fmt.useTabsForIndentation === d.useTabsForIndentation &&\n fmt.indentWidth === d.indentWidth &&\n fmt.minimumDecimals === d.minimumDecimals &&\n fmt.minimumTimeDecimals === d.minimumTimeDecimals &&\n fmt.leadingBom === d.leadingBom &&\n fmt.updateOrder === d.updateOrder &&\n fmt.multilineTable === d.multilineTable &&\n fmt.multilineArray === d.multilineArray;\n}\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 = format == null\n ? DEFAULT_STRINGIFY_FORMAT\n : resolveTomlFormat(format, TomlFormat.default());\n \n const document = parseJS(value, fmt);\n const tomlString = isDefaultFormat(fmt)\n ? toTOMLSequential(document.items, fmt)\n : 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":";;;;;;;;;;;;;;;;AAeA,MAAM,2BAAuC,OAAO,OAAO,WAAW,QAAQ,CAAC;;AAG/E,SAAS,gBAAgB,KAA0B;CACjD,MAAM,IAAI;CACV,OAAO,IAAI,YAAY,EAAE,WACvB,IAAI,oBAAoB,EAAE,mBAC1B,IAAI,kBAAkB,EAAE,iBACxB,IAAI,mBAAmB,EAAE,kBACzB,IAAI,qBAAqB,EAAE,oBAC3B,IAAI,4BAA4B,EAAE,2BAClC,IAAI,0BAA0B,EAAE,yBAChC,IAAI,gBAAgB,EAAE,eACtB,IAAI,oBAAoB,EAAE,mBAC1B,IAAI,wBAAwB,EAAE,uBAC9B,IAAI,eAAe,EAAE,cACrB,IAAI,gBAAgB,EAAE,eACtB,IAAI,mBAAmB,EAAE,kBACzB,IAAI,mBAAmB,EAAE;AAC7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,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,UAAU,OAClB,2BACA,kBAAkB,QAAQ,WAAW,QAAQ,CAAC;CAElD,MAAM,WAAW,QAAQ,OAAO,GAAG;CACnC,MAAM,aAAa,gBAAgB,GAAG,IAClC,iBAAiB,SAAS,OAAO,GAAG,IACpC,OAAO,SAAS,OAAO,GAAG;CAC9B,OAAO,IAAI,aAAa,SAAc,eAAe;AACvD;;;;;;;;;;AA2CA,SAAgB,cAAc,OAA4B,SAAsC;CAC9F,OAAO,IAAI,aAAa,OAAO,OAAO;AACxC"}
@@ -1,61 +0,0 @@
1
- //! @decimalturn/toml-patch v3.3.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
- import { isIterable } from "./utils.js";
3
-
4
- //#region src/traverse.ts
5
- function traverse(cst, visitor) {
6
- if (isIterable(cst)) traverseArray(cst, null);
7
- else traverseNode(cst, null);
8
- function traverseArray(array, parent) {
9
- for (const node of array) traverseNode(node, parent);
10
- }
11
- function traverseNode(node, parent) {
12
- const visit = visitor[node.type];
13
- if (visit && typeof visit === "function") visit(node, parent);
14
- if (visit && visit.enter) visit.enter(node, parent);
15
- switch (node.type) {
16
- case "Document":
17
- traverseArray(node.items, node);
18
- break;
19
- case "Table":
20
- traverseNode(node.key, node);
21
- traverseArray(node.items, node);
22
- break;
23
- case "TableKey":
24
- traverseNode(node.item, node);
25
- break;
26
- case "TableArray":
27
- traverseNode(node.key, node);
28
- traverseArray(node.items, node);
29
- break;
30
- case "TableArrayKey":
31
- traverseNode(node.item, node);
32
- break;
33
- case "KeyValue":
34
- traverseNode(node.key, node);
35
- traverseNode(node.value, node);
36
- break;
37
- case "InlineArray":
38
- traverseArray(node.items, node);
39
- break;
40
- case "InlineItem":
41
- traverseNode(node.item, node);
42
- break;
43
- case "InlineTable":
44
- traverseArray(node.items, node);
45
- break;
46
- case "Key":
47
- case "String":
48
- case "Integer":
49
- case "Float":
50
- case "Boolean":
51
- case "DateTime":
52
- case "Comment": break;
53
- default: throw new Error(`Unrecognized node type "${node.type}"`);
54
- }
55
- if (visit && visit.exit) visit.exit(node, parent);
56
- }
57
- }
58
-
59
- //#endregion
60
- export { traverse as default };
61
- //# sourceMappingURL=traverse.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"traverse.js","names":[],"sources":["../../src/traverse.ts"],"sourcesContent":["import {\n NodeType,\n CST,\n TreeNode,\n Document,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n KeyValue,\n Key,\n String,\n Integer,\n Float,\n Boolean,\n DateTime,\n Comment,\n InlineArray,\n InlineTable,\n InlineItem\n} from './cst';\nimport { isIterable } from './utils';\n\nexport type Visit<TNode = TreeNode> = (node: TNode, parent: TNode | null) => void;\nexport type EnterExit<TNode = TreeNode> = { enter?: Visit<TNode>; exit?: Visit<TNode> };\n\nexport type Visitor = {\n Document?: Visit<Document> | EnterExit<Document>;\n Table?: Visit<Table> | EnterExit<Table>;\n TableKey?: Visit<TableKey> | EnterExit<TableKey>;\n TableArray?: Visit<TableArray> | EnterExit<TableArray>;\n TableArrayKey?: Visit<TableArrayKey> | EnterExit<TableArrayKey>;\n KeyValue?: Visit<KeyValue> | EnterExit<KeyValue>;\n Key?: Visit<Key> | EnterExit<Key>;\n String?: Visit<String> | EnterExit<String>;\n Integer?: Visit<Integer> | EnterExit<Integer>;\n Float?: Visit<Float> | EnterExit<Float>;\n Boolean?: Visit<Boolean> | EnterExit<Boolean>;\n DateTime?: Visit<DateTime> | EnterExit<DateTime>;\n InlineArray?: Visit<InlineArray> | EnterExit<InlineArray>;\n InlineItem?: Visit<InlineItem> | EnterExit<InlineItem>;\n InlineTable?: Visit<InlineTable> | EnterExit<InlineTable>;\n Comment?: Visit<Comment> | EnterExit<Comment>;\n};\n\n////////////////////////////////////////////////////////////////////////////////\n// The traverse function is used to walk the CST and call the visitor functions\n////////////////////////////////////////////////////////////////////////////////\nexport default function traverse(cst: CST | TreeNode, visitor: Visitor) {\n if (isIterable(cst)) {\n traverseArray(cst, null);\n } else {\n traverseNode(cst, null);\n }\n\n function traverseArray(array: Iterable<TreeNode>, parent: TreeNode | null) {\n for (const node of array) {\n traverseNode(node, parent);\n }\n }\n\n function traverseNode(node: TreeNode, parent: TreeNode | null) {\n const visit = visitor[node.type];\n\n if (visit && typeof visit === 'function') {\n (visit as Visit)(node, parent);\n }\n\n if (visit && (visit as EnterExit).enter) {\n (visit as EnterExit).enter!(node, parent);\n }\n\n switch (node.type) {\n case NodeType.Document:\n traverseArray((node as Document).items, node);\n break;\n\n case NodeType.Table:\n traverseNode((node as Table).key, node);\n traverseArray((node as Table).items, node);\n break;\n case NodeType.TableKey:\n traverseNode((node as TableKey).item, node);\n break;\n\n case NodeType.TableArray:\n traverseNode((node as TableArray).key, node);\n traverseArray((node as TableArray).items, node);\n break;\n case NodeType.TableArrayKey:\n traverseNode((node as TableArrayKey).item, node);\n break;\n\n case NodeType.KeyValue:\n traverseNode((node as KeyValue).key, node);\n traverseNode((node as KeyValue).value, node);\n break;\n\n case NodeType.InlineArray:\n traverseArray((node as InlineArray).items, node);\n break;\n case NodeType.InlineItem:\n traverseNode((node as InlineItem).item, node);\n break;\n\n case NodeType.InlineTable:\n traverseArray((node as InlineTable).items, node);\n break;\n\n case NodeType.Key:\n case NodeType.String:\n case NodeType.Integer:\n case NodeType.Float:\n case NodeType.Boolean:\n case NodeType.DateTime:\n case NodeType.Comment:\n break;\n\n default:\n throw new Error(`Unrecognized node type \"${node.type}\"`);\n }\n\n if (visit && (visit as EnterExit).exit) {\n (visit as EnterExit).exit!(node, parent);\n }\n }\n}\n"],"mappings":";;;;AAgDA,SAAwB,SAAS,KAAqB,SAAkB;CACtE,IAAI,WAAW,GAAG,GAChB,cAAc,KAAK,IAAI;MAEvB,aAAa,KAAK,IAAI;CAGxB,SAAS,cAAc,OAA2B,QAAyB;EACzE,KAAK,MAAM,QAAQ,OACjB,aAAa,MAAM,MAAM;CAE7B;CAEA,SAAS,aAAa,MAAgB,QAAyB;EAC7D,MAAM,QAAQ,QAAQ,KAAK;EAE3B,IAAI,SAAS,OAAO,UAAU,YAC5B,AAAC,MAAgB,MAAM,MAAM;EAG/B,IAAI,SAAU,MAAoB,OAChC,AAAC,MAAoB,MAAO,MAAM,MAAM;EAG1C,QAAQ,KAAK,MAAb;GACE;IACE,cAAe,KAAkB,OAAO,IAAI;IAC5C;GAEF;IACE,aAAc,KAAe,KAAK,IAAI;IACtC,cAAe,KAAe,OAAO,IAAI;IACzC;GACF;IACE,aAAc,KAAkB,MAAM,IAAI;IAC1C;GAEF;IACE,aAAc,KAAoB,KAAK,IAAI;IAC3C,cAAe,KAAoB,OAAO,IAAI;IAC9C;GACF;IACE,aAAc,KAAuB,MAAM,IAAI;IAC/C;GAEF;IACE,aAAc,KAAkB,KAAK,IAAI;IACzC,aAAc,KAAkB,OAAO,IAAI;IAC3C;GAEF;IACE,cAAe,KAAqB,OAAO,IAAI;IAC/C;GACF;IACE,aAAc,KAAoB,MAAM,IAAI;IAC5C;GAEF;IACE,cAAe,KAAqB,OAAO,IAAI;IAC/C;GAEF;GACA;GACA;GACA;GACA;GACA;GACA,gBACE;GAEF,SACE,MAAM,IAAI,MAAM,2BAA2B,KAAK,KAAK,EAAE;EAC3D;EAEA,IAAI,SAAU,MAAoB,MAChC,AAAC,MAAoB,KAAM,MAAM,MAAM;CAE3C;AACF"}
@@ -1,64 +0,0 @@
1
- //! @decimalturn/toml-patch v3.3.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
- //#region src/truncate.ts
3
- /**
4
- * Compares two positions to determine their ordering.
5
- * @param pos1 - First position
6
- * @param pos2 - Second position
7
- * @returns Negative if pos1 < pos2, 0 if equal, positive if pos1 > pos2
8
- */
9
- function comparePositions(pos1, pos2) {
10
- if (pos1.line !== pos2.line) return pos1.line - pos2.line;
11
- return pos1.column - pos2.column;
12
- }
13
- /**
14
- * Truncates a CST based on a position (line, column) in the source string.
15
- *
16
- * This function filters the CST to include only the nodes that end before
17
- * the specified position. This ensures that blocks containing changes are
18
- * excluded and can be reparsed. This is useful for incremental parsing scenarios
19
- * where you want to keep only the unchanged portion of the CST.
20
- *
21
- * Special handling: If the truncation point falls within a Table or TableArray
22
- * (e.g., in a comment inside the table), the entire table is excluded to ensure
23
- * proper reparsing.
24
- *
25
- * @param cst - The CST to truncate
26
- * @param line - The line number (1-indexed) at which to truncate
27
- * @param column - The column number (0-indexed) at which to truncate
28
- * @returns An object containing the truncated CST and the end position of the last included node
29
- *
30
- * @example
31
- * ```typescript
32
- * const cst = parseTOML(tomlString);
33
- * // Get CST up to line 5, column 10 (only nodes that end before this position)
34
- * const { truncatedCst, lastEndPosition } = truncateCst(cst, 5, 10);
35
- * for (const node of truncatedCst) {
36
- * // process node
37
- * }
38
- * ```
39
- */
40
- function truncateCst(cst, line, column) {
41
- const limit = {
42
- line,
43
- column
44
- };
45
- const nodes = [];
46
- let lastEndPosition = null;
47
- for (const node of cst) {
48
- const nodeEndsBeforeLimit = comparePositions(node.loc.end, limit) < 0;
49
- const nodeStartsBeforeLimit = comparePositions(node.loc.start, limit) < 0;
50
- if (nodeEndsBeforeLimit) {
51
- nodes.push(node);
52
- lastEndPosition = node.loc.end;
53
- } else if (nodeStartsBeforeLimit && !nodeEndsBeforeLimit) break;
54
- else break;
55
- }
56
- return {
57
- truncatedCst: nodes,
58
- lastEndPosition
59
- };
60
- }
61
-
62
- //#endregion
63
- export { truncateCst };
64
- //# sourceMappingURL=truncate.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"truncate.js","names":[],"sources":["../../src/truncate.ts"],"sourcesContent":["import { CST, Block } from './cst';\nimport { Position } from './location';\n\n/**\n * Compares two positions to determine their ordering.\n * @param pos1 - First position\n * @param pos2 - Second position\n * @returns Negative if pos1 < pos2, 0 if equal, positive if pos1 > pos2\n */\nfunction comparePositions(pos1: Position, pos2: Position): number {\n if (pos1.line !== pos2.line) {\n return pos1.line - pos2.line;\n }\n return pos1.column - pos2.column;\n}\n\n/**\n * Checks if a block node should be included based on its location.\n * A block is included if its end position is before the limit position.\n * This ensures that only complete blocks that don't contain the change are kept.\n * @param node - The block node to check\n * @param limit - The position limit\n * @returns true if the block should be included\n */\nfunction shouldIncludeBlock(node: Block, limit: Position): boolean {\n return comparePositions(node.loc.end, limit) < 0;\n}\n\n/**\n * Truncates a CST based on a position (line, column) in the source string.\n * \n * This function filters the CST to include only the nodes that end before\n * the specified position. This ensures that blocks containing changes are\n * excluded and can be reparsed. This is useful for incremental parsing scenarios\n * where you want to keep only the unchanged portion of the CST.\n * \n * Special handling: If the truncation point falls within a Table or TableArray\n * (e.g., in a comment inside the table), the entire table is excluded to ensure\n * proper reparsing.\n * \n * @param cst - The CST to truncate\n * @param line - The line number (1-indexed) at which to truncate\n * @param column - The column number (0-indexed) at which to truncate\n * @returns An object containing the truncated CST and the end position of the last included node\n * \n * @example\n * ```typescript\n * const cst = parseTOML(tomlString);\n * // Get CST up to line 5, column 10 (only nodes that end before this position)\n * const { truncatedCst, lastEndPosition } = truncateCst(cst, 5, 10);\n * for (const node of truncatedCst) {\n * // process node\n * }\n * ```\n */\nexport function truncateCst(cst: CST, line: number, column: number): {\n truncatedCst: CST;\n lastEndPosition: Position | null \n} {\n const limit: Position = { line, column };\n const nodes: Block[] = [];\n let lastEndPosition: Position | null = null;\n \n for (const node of cst) {\n const nodeEndsBeforeLimit = comparePositions(node.loc.end, limit) < 0;\n const nodeStartsBeforeLimit = comparePositions(node.loc.start, limit) < 0;\n \n if (nodeEndsBeforeLimit) {\n // Node completely ends before the limit - include it\n nodes.push(node);\n lastEndPosition = node.loc.end;\n } else if (nodeStartsBeforeLimit && !nodeEndsBeforeLimit) {\n // Node starts before the limit but ends at or after it\n // This means the truncation point is within this node\n // For Table/TableArray nodes, don't include them if the change is inside\n // This ensures the entire table gets reparsed\n break;\n } else {\n // Node starts at or after the limit - stop\n break;\n }\n }\n \n return {\n truncatedCst: nodes,\n lastEndPosition\n };\n}\n\n/**\n * Finds the last block node in a CST that ends before the specified position.\n * \n * @param cst - The CST to search\n * @param line - The line number (1-indexed)\n * @param column - The column number (0-indexed)\n * @returns The last block node that ends before the position, or undefined if no such node exists\n * \n * @example\n * ```typescript\n * const cst = parseTOML(tomlString);\n * const lastNode = findLastNodeBeforePosition(cst, 5, 10);\n * if (lastNode) {\n * console.log('Last node type:', lastNode.type);\n * }\n * ```\n */\nexport function findLastNodeBeforePosition(cst: CST, line: number, column: number): Block | undefined {\n const limit: Position = { line, column };\n let lastNode: Block | undefined = undefined;\n \n for (const node of cst) {\n if (shouldIncludeBlock(node, limit)) {\n lastNode = node;\n } else {\n // Once we encounter a node that starts after the limit, we can stop\n break;\n }\n }\n \n return lastNode;\n}\n"],"mappings":";;;;;;;;AASA,SAAS,iBAAiB,MAAgB,MAAwB;CAChE,IAAI,KAAK,SAAS,KAAK,MACrB,OAAO,KAAK,OAAO,KAAK;CAE1B,OAAO,KAAK,SAAS,KAAK;AAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,YAAY,KAAU,MAAc,QAGlD;CACA,MAAM,QAAkB;EAAE;EAAM;CAAO;CACvC,MAAM,QAAiB,CAAC;CACxB,IAAI,kBAAmC;CAEvC,KAAK,MAAM,QAAQ,KAAK;EACtB,MAAM,sBAAsB,iBAAiB,KAAK,IAAI,KAAK,KAAK,IAAI;EACpE,MAAM,wBAAwB,iBAAiB,KAAK,IAAI,OAAO,KAAK,IAAI;EAExE,IAAI,qBAAqB;GAEvB,MAAM,KAAK,IAAI;GACf,kBAAkB,KAAK,IAAI;EAC7B,OAAO,IAAI,yBAAyB,CAAC,qBAKnC;OAGA;CAEJ;CAEA,OAAO;EACL,cAAc;EACd;CACF;AACF"}
@@ -1,235 +0,0 @@
1
- //! @decimalturn/toml-patch v3.3.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
2
- import { hasItem, isDocument, isInlineItem, isKeyValue, isTable, isTableArray } from "./cst.js";
3
- import { recalcContainerEnd, shiftNode } from "./writer.js";
4
- import { tryFindByPath } from "./find-by-path.js";
5
- import { normalizeSectionComments, resolveGroups } from "./comment-ownership.js";
6
-
7
- //#region src/update-order.ts
8
- function buildUnits(groups) {
9
- const units = [];
10
- for (const group of groups) {
11
- if (group.kind === "pinned") {
12
- units.push({
13
- kind: "pinned",
14
- isSection: false,
15
- movable: false,
16
- groups: [group],
17
- startLine: group.startLine,
18
- endLine: group.endLine,
19
- items: group.items
20
- });
21
- continue;
22
- }
23
- const isSection = isTable(group.member) || isTableArray(group.member);
24
- const previous = units[units.length - 1];
25
- if (previous && previous.kind === "member" && group.key !== void 0 && previous.key === group.key) {
26
- previous.groups.push(group);
27
- previous.endLine = group.endLine;
28
- previous.items = previous.items.concat(group.items);
29
- continue;
30
- }
31
- units.push({
32
- kind: "member",
33
- key: group.key,
34
- isSection,
35
- movable: group.key !== void 0,
36
- groups: [group],
37
- startLine: group.startLine,
38
- endLine: group.endLine,
39
- items: [...group.items]
40
- });
41
- }
42
- const countByKey = /* @__PURE__ */ new Map();
43
- for (const unit of units) {
44
- if (unit.kind !== "member" || unit.key === void 0) continue;
45
- countByKey.set(unit.key, (countByKey.get(unit.key) ?? 0) + 1);
46
- }
47
- for (const unit of units) if (unit.kind === "member" && unit.key !== void 0 && countByKey.get(unit.key) > 1) unit.movable = false;
48
- return units;
49
- }
50
- /** Replays `moves` against `currentOrder` using the same simulate-and-splice approach
51
- * compareObjects used to generate them, reconstructing the full requested key order. */
52
- function computeTargetOrder(currentOrder, moves) {
53
- const sim = [...currentOrder];
54
- for (const move of moves) {
55
- if (move.key === void 0) continue;
56
- const from = sim.indexOf(move.key);
57
- if (from === -1) continue;
58
- const to = Math.max(0, Math.min(move.to, sim.length - 1));
59
- if (from === to) continue;
60
- sim.splice(from, 1);
61
- sim.splice(to, 0, move.key);
62
- }
63
- return sim;
64
- }
65
- /** Full dotted path to the entry a Move targets (its container path plus its own key), for
66
- * warning messages -- clearer than the bare key alone once anything is nested more than one
67
- * level deep (e.g. "t.hello.moon" rather than just "moon"). */
68
- function describeMovePath(move) {
69
- return [...move.path, move.key].join(".");
70
- }
71
- function resolveImplicitDottedContainer(document, path, moveKey, commentEligibleNodes) {
72
- if (path.some((segment) => typeof segment !== "string")) return void 0;
73
- const target = [...path, moveKey];
74
- const candidates = [{
75
- container: document,
76
- prefix: []
77
- }];
78
- for (const item of document.items) if (isTable(item) || isTableArray(item)) candidates.push({
79
- container: item,
80
- prefix: item.key.item.value
81
- });
82
- for (const candidate of candidates) for (const item of candidate.container.items) {
83
- if (!isKeyValue(item) || item.key.value.length < 2) continue;
84
- if (commentEligibleNodes.has(item)) continue;
85
- const fullKey = [...candidate.prefix, ...item.key.value];
86
- if (fullKey.length !== target.length) continue;
87
- if (!fullKey.every((segment, index) => segment === target[index])) continue;
88
- return {
89
- container: candidate.container,
90
- dottedPrefix: item.key.value.slice(0, -1)
91
- };
92
- }
93
- }
94
- function resolveContainer(document, path, moveKey, commentEligibleNodes) {
95
- if (path.length === 0) return { container: document };
96
- let node;
97
- try {
98
- node = tryFindByPath(document, path);
99
- } catch {
100
- return;
101
- }
102
- if (!node) return void 0;
103
- if (isKeyValue(node)) node = node.value;
104
- if (node && hasItem(node)) node = node.item;
105
- if (node && (isDocument(node) || isTable(node) || isTableArray(node))) return { container: node };
106
- if (moveKey === void 0) return void 0;
107
- const implicit = resolveImplicitDottedContainer(document, path, moveKey, commentEligibleNodes);
108
- if (implicit) return implicit;
109
- let numericIndex = -1;
110
- for (let i = path.length - 1; i >= 0; i--) if (typeof path[i] === "number") {
111
- numericIndex = i;
112
- break;
113
- }
114
- if (numericIndex < 0) return void 0;
115
- const dottedPrefix = path.slice(numericIndex + 1);
116
- if (dottedPrefix.length === 0 || dottedPrefix.some((segment) => typeof segment !== "string")) return;
117
- const entry = tryFindByPath(document, path.slice(0, numericIndex + 1));
118
- if (!entry || !isTableArray(entry)) return void 0;
119
- const targetKey = [...dottedPrefix, moveKey];
120
- return entry.items.some((item) => isKeyValue(item) && item.key.value.length === targetKey.length && item.key.value.every((segment, index) => segment === targetKey[index])) ? {
121
- container: entry,
122
- dottedPrefix
123
- } : void 0;
124
- }
125
- function isNewMoveTarget(document, move, commentEligibleNodes) {
126
- if (move.key === void 0) return false;
127
- let target;
128
- try {
129
- target = tryFindByPath(document, move.path.concat(move.key));
130
- } catch {
131
- return false;
132
- }
133
- return target !== void 0 && isInlineItem(target) && !commentEligibleNodes.has(target);
134
- }
135
- function applyContainerMoves(container, moves, commentEligibleNodes, warnings, dottedPrefix) {
136
- const units = buildUnits(resolveGroups(container, (node) => commentEligibleNodes.has(node), dottedPrefix ? (member) => {
137
- if (!isKeyValue(member)) return void 0;
138
- const key = member.key.value;
139
- if (key.length !== dottedPrefix.length + 1) return void 0;
140
- for (let i = 0; i < dottedPrefix.length; i++) if (key[i] !== dottedPrefix[i]) return void 0;
141
- return key[dottedPrefix.length];
142
- } : void 0));
143
- const movableUnitsByKey = /* @__PURE__ */ new Map();
144
- for (const unit of units) if (unit.kind === "member" && unit.movable && unit.key !== void 0) movableUnitsByKey.set(unit.key, unit);
145
- const memberKeys = new Set(units.filter((u) => u.kind === "member" && u.key !== void 0).map((u) => u.key));
146
- for (const move of moves) if (move.key !== void 0 && memberKeys.has(move.key) && !movableUnitsByKey.has(move.key)) warnings.push(`"${describeMovePath(move)}" -- its entries are not contiguous in the document (e.g. the TOML spec's own "valid but discouraged" out-of-order table pattern), so reordering was skipped for it`);
147
- if (movableUnitsByKey.size === 0) return;
148
- const currentOrder = dottedPrefix ? units.filter((u) => u.kind === "member" && u.movable).map((u) => u.key) : units.filter((u) => u.kind === "member").map((u, index) => u.movable ? u.key : `\u0000anchor:${index}`);
149
- const relevantMoves = moves.filter((m) => m.key !== void 0 && movableUnitsByKey.has(m.key));
150
- if (relevantMoves.length === 0) return;
151
- const targetOrder = computeTargetOrder(currentOrder, relevantMoves).filter((k) => movableUnitsByKey.has(k));
152
- const rootKvTargetOrder = targetOrder.filter((k) => !movableUnitsByKey.get(k).isSection);
153
- const sectionTargetOrder = targetOrder.filter((k) => movableUnitsByKey.get(k).isSection);
154
- let sawSection = false;
155
- for (const key of targetOrder) if (movableUnitsByKey.get(key).isSection) sawSection = true;
156
- else if (sawSection) {
157
- warnings.push("the requested order asked for a root key-value to be positioned after a section header, which TOML cannot represent -- each group (root key-values, section blocks) was reordered to match its own requested relative order instead");
158
- break;
159
- }
160
- let rootKvCursor = 0;
161
- let sectionCursor = 0;
162
- const finalUnits = units.map((unit) => {
163
- if (unit.kind !== "member" || !unit.movable) return unit;
164
- const key = unit.isSection ? sectionTargetOrder[sectionCursor++] : rootKvTargetOrder[rootKvCursor++];
165
- return movableUnitsByKey.get(key);
166
- });
167
- if (finalUnits.every((u, i) => u === units[i])) return;
168
- const containerFirstLine = isDocument(container) ? 1 : container.key.loc.end.line;
169
- const gapBefore = units.map((unit, i) => {
170
- if (i === 0) return unit.startLine - containerFirstLine;
171
- return unit.startLine - units[i - 1].endLine - 1;
172
- });
173
- let cursorEnd = containerFirstLine;
174
- for (let i = 0; i < finalUnits.length; i++) {
175
- const unit = finalUnits[i];
176
- const gap = gapBefore[i];
177
- const delta = (i === 0 ? cursorEnd : cursorEnd + 1) + gap - unit.startLine;
178
- if (delta !== 0) for (const item of unit.items) shiftNode(item, {
179
- lines: delta,
180
- columns: 0
181
- });
182
- cursorEnd = unit.endLine + delta;
183
- }
184
- const newItems = finalUnits.flatMap((u) => u.items);
185
- const items = container.items;
186
- items.splice(0, items.length, ...newItems);
187
- recalcContainerEnd(container);
188
- }
189
- /**
190
- * Reorders `document`'s root key-values, [table]/[[array]] section blocks, and table-body
191
- * rows to match `moves` (object-key Moves collected from the isMove branch in patch.ts),
192
- * carrying each entry's owned comments with it. See docs/PLAN-Update-Order.md.
193
- *
194
- * Must run after every other structural change in this patch has already been applied to
195
- * `document` (Add/Remove/Rename/array-Move/structural-edit) — it does no insertion or
196
- * deletion of its own, only permutes and relays out what's already there.
197
- */
198
- function applyKeyOrderMoves(document, moves, commentEligibleNodes) {
199
- if (moves.length === 0) return;
200
- normalizeSectionComments(document);
201
- const warnings = [];
202
- const movesByContainer = /* @__PURE__ */ new Map();
203
- for (const move of moves) {
204
- var _resolved$dottedPrefi;
205
- if (move.key === void 0) continue;
206
- const resolved = resolveContainer(document, move.path, move.key, commentEligibleNodes);
207
- if (!resolved) {
208
- if (isNewMoveTarget(document, move, commentEligibleNodes)) continue;
209
- warnings.push(`"${describeMovePath(move)}" -- unsupported location for reordering (e.g. a dotted-key implicit table, or an interior of an inline table/array-of-tables entry)`);
210
- continue;
211
- }
212
- const scopeKey = ((_resolved$dottedPrefi = resolved.dottedPrefix) === null || _resolved$dottedPrefi === void 0 ? void 0 : _resolved$dottedPrefi.join("\0")) ?? "";
213
- let scopedMoves = movesByContainer.get(resolved.container);
214
- if (!scopedMoves) {
215
- scopedMoves = /* @__PURE__ */ new Map();
216
- movesByContainer.set(resolved.container, scopedMoves);
217
- }
218
- const bucket = scopedMoves.get(scopeKey);
219
- if (bucket) bucket.moves.push(move);
220
- else scopedMoves.set(scopeKey, {
221
- ...resolved,
222
- moves: [move]
223
- });
224
- }
225
- for (const scopedMoves of movesByContainer.values()) for (const target of scopedMoves.values()) applyContainerMoves(target.container, target.moves, commentEligibleNodes, warnings, target.dottedPrefix);
226
- if (warnings.length > 0) {
227
- const unique = [...new Set(warnings)];
228
- console.warn(`toml-patch: updateOrder could not honor the requested position for ${unique.length === 1 ? "1 entry" : `${unique.length} entries`}, left unchanged:\n` + unique.map((w) => ` - ${w}`).join("\n"));
229
- }
230
- recalcContainerEnd(document);
231
- }
232
-
233
- //#endregion
234
- export { applyKeyOrderMoves };
235
- //# sourceMappingURL=update-order.js.map