@decimalturn/toml-patch 3.2.1 → 3.3.0-dev
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dev/comment-alignment.js +372 -0
- package/dist/dev/comment-alignment.js.map +1 -0
- package/dist/dev/comment-ownership.js +660 -0
- package/dist/dev/comment-ownership.js.map +1 -0
- package/dist/dev/cst-source.js +118 -0
- package/dist/dev/cst-source.js.map +1 -0
- package/dist/dev/cst.js +68 -0
- package/dist/dev/cst.js.map +1 -0
- package/dist/dev/cursor.js +66 -0
- package/dist/dev/cursor.js.map +1 -0
- package/dist/dev/date-format.js +287 -0
- package/dist/dev/date-format.js.map +1 -0
- package/dist/dev/decode-utf8.js +27 -0
- package/dist/dev/decode-utf8.js.map +1 -0
- package/dist/dev/diff-lite.js +108 -0
- package/dist/dev/diff-lite.js.map +1 -0
- package/dist/dev/diff.js +265 -0
- package/dist/dev/diff.js.map +1 -0
- package/dist/dev/encode-lite.js +210 -0
- package/dist/dev/encode-lite.js.map +1 -0
- package/dist/dev/escape-preference.js +166 -0
- package/dist/dev/escape-preference.js.map +1 -0
- package/dist/dev/find-by-path.js +111 -0
- package/dist/dev/find-by-path.js.map +1 -0
- package/dist/dev/formatter.js +298 -0
- package/dist/dev/formatter.js.map +1 -0
- package/dist/dev/generate.js +466 -0
- package/dist/dev/generate.js.map +1 -0
- package/dist/dev/inline-comma-space.js +13 -0
- package/dist/dev/inline-comma-space.js.map +1 -0
- package/dist/dev/inline-format.js +106 -0
- package/dist/dev/inline-format.js.map +1 -0
- package/dist/dev/inline-layout.js +107 -0
- package/dist/dev/inline-layout.js.map +1 -0
- package/dist/dev/line-ending-backslash.js +320 -0
- package/dist/dev/line-ending-backslash.js.map +1 -0
- package/dist/dev/literal-string.js +46 -0
- package/dist/dev/literal-string.js.map +1 -0
- package/dist/dev/location.js +104 -0
- package/dist/dev/location.js.map +1 -0
- package/dist/dev/parse-error.js +27 -0
- package/dist/dev/parse-error.js.map +1 -0
- package/dist/dev/parse-js.js +150 -0
- package/dist/dev/parse-js.js.map +1 -0
- package/dist/dev/parse-string.js +122 -0
- package/dist/dev/parse-string.js.map +1 -0
- package/dist/dev/parse-toml.js +714 -0
- package/dist/dev/parse-toml.js.map +1 -0
- package/dist/dev/patch-lite.js +4 -0
- package/dist/dev/patch-lite2.js +97 -0
- package/dist/dev/patch-lite2.js.map +1 -0
- package/dist/dev/patch.js +2646 -0
- package/dist/dev/patch.js.map +1 -0
- package/dist/dev/smol-toml-date.js +61 -0
- package/dist/dev/smol-toml-date.js.map +1 -0
- package/dist/dev/to-js.js +303 -0
- package/dist/dev/to-js.js.map +1 -0
- package/dist/dev/to-toml.js +874 -0
- package/dist/dev/to-toml.js.map +1 -0
- package/dist/dev/tokenizer.js +225 -0
- package/dist/dev/tokenizer.js.map +1 -0
- package/dist/dev/toml-document.js +220 -0
- package/dist/dev/toml-document.js.map +1 -0
- package/dist/dev/toml-format.js +549 -0
- package/dist/dev/toml-format.js.map +1 -0
- package/dist/dev/toml-patch.js +94 -0
- package/dist/dev/toml-patch.js.map +1 -0
- package/dist/dev/traverse.js +61 -0
- package/dist/dev/traverse.js.map +1 -0
- package/dist/dev/truncate.js +64 -0
- package/dist/dev/truncate.js.map +1 -0
- package/dist/dev/update-order.js +235 -0
- package/dist/dev/update-order.js.map +1 -0
- package/dist/dev/utils.js +302 -0
- package/dist/dev/utils.js.map +1 -0
- package/dist/dev/writer.js +758 -0
- package/dist/dev/writer.js.map +1 -0
- package/dist/patch-lite.d.ts +18 -0
- package/dist/toml-patch.d.ts +19 -2
- package/package.json +16 -102
- package/LICENSE +0 -22
- package/README.md +0 -202
- package/dist/toml-patch.js +0 -84
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"to-toml.js","names":[],"sources":["../../src/to-toml.ts"],"sourcesContent":["import {\n getNodeSource,\n originalFirstChildStartedAfterOpener,\n sourceStructureUnchanged\n} from './cst-source';\nimport {\n NodeType,\n CST,\n TreeNode,\n Document,\n Table,\n TableKey,\n TableArray,\n TableArrayKey,\n KeyValue,\n Key,\n String as StringNode,\n Integer,\n Float,\n Boolean as BooleanNode,\n DateTime,\n InlineArray,\n InlineTable,\n InlineItem,\n Comment,\n hasItems,\n hasItem,\n isKeyValue,\n isInlineItem,\n isTable,\n isTableArray,\n isInlineTable,\n isInlineArray\n} from './cst';\nimport { Location } from './location';\nimport { SPACE } from './tokenizer';\nimport { TomlFormat } from './toml-format';\nimport { isIterable } from './utils';\nimport { getCommaSpace } from './inline-comma-space';\nimport { isGeneratedNestedTable, isGeneratedNestedTableHost, isPreservedMultilineEmpty } from './inline-format';\n\nconst BY_NEW_LINE = /(\\r\\n|\\n)/g;\n\n/**\n * Converts a Concrete Syntax Tree (CST) back to TOML format string.\n * \n * This function traverses the CST and reconstructs the original TOML document\n * by writing each node's raw content to the appropriate location coordinates.\n * It preserves the original formatting, spacing, and structure of the TOML file.\n * \n * @param cst - The Concrete Syntax Tree representing the parsed TOML document\n * @param format - The formatting options to use for the output\n * @returns The reconstructed TOML document as a string\n * \n * @example\n * ```typescript\n * const tomlString = toTOML(cst, TomlFormat.default());\n * ```\n */\nexport default function toTOML(cst: CST, format: TomlFormat): string {\n\n const lines: string[] = [];\n\n // Inline traversal for monomorphic property access (avoids generic traverse\n // visitor dispatch which causes megamorphic inline cache misses in V8)\n const closingPosition = (container: InlineArray | InlineTable): { line: number; column: number } => {\n const position = {\n line: container.loc.end.line,\n column: container.loc.end.column - 1\n };\n const last = container.items[container.items.length - 1];\n if (last && (last.loc.end.line > position.line ||\n (last.loc.end.line === position.line && last.loc.end.column > position.column))) {\n position.line = last.loc.end.line;\n position.column = last.loc.end.column + (last.comma ? 1 : 0);\n }\n return position;\n };\n\n function emitNode(node: TreeNode) {\n switch (node.type) {\n case NodeType.Document:\n for (let i = 0; i < (node as Document).items.length; i++)\n emitNode((node as Document).items[i]);\n break;\n\n case NodeType.Table: {\n const tbl = node as Table;\n emitNode(tbl.key);\n for (let i = 0; i < tbl.items.length; i++) emitNode(tbl.items[i]);\n break;\n }\n case NodeType.TableKey: {\n const tk = node as TableKey;\n // Emit \"[key]\" in one write instead of three (bracket, key, bracket).\n write(lines, tk.loc, '[' + tk.item.raw + ']');\n break;\n }\n\n case NodeType.TableArray: {\n const ta = node as TableArray;\n emitNode(ta.key);\n for (let i = 0; i < ta.items.length; i++) emitNode(ta.items[i]);\n break;\n }\n case NodeType.TableArrayKey: {\n const tak = node as TableArrayKey;\n // Emit \"[[key]]\" in one write instead of three.\n write(lines, tak.loc, '[[' + tak.item.raw + ']]');\n break;\n }\n\n case NodeType.KeyValue: {\n const kv = node as KeyValue;\n const line = kv.loc.start.line;\n writeSingle(lines, line, kv.equals, '=');\n emitNode(kv.key);\n emitNode(kv.value);\n break;\n }\n\n case NodeType.Key:\n write(lines, node.loc, (node as Key).raw);\n break;\n\n case NodeType.String:\n write(lines, node.loc, (node as StringNode).raw);\n break;\n case NodeType.Integer:\n write(lines, node.loc, (node as Integer).raw);\n break;\n case NodeType.Float:\n write(lines, node.loc, (node as Float).raw);\n break;\n case NodeType.Boolean:\n write(lines, node.loc, (node as BooleanNode).value.toString());\n break;\n case NodeType.DateTime:\n write(lines, node.loc, (node as DateTime).raw);\n break;\n\n case NodeType.InlineArray: {\n const ia = node as InlineArray;\n const { start } = ia.loc;\n const closing = closingPosition(ia);\n writeSingle(lines, start.line, start.column, '[');\n writeSingle(lines, closing.line, closing.column, ']');\n for (let i = 0; i < ia.items.length; i++) emitNode(ia.items[i]);\n break;\n }\n case NodeType.InlineTable: {\n const it = node as InlineTable;\n const { start } = it.loc;\n const closing = closingPosition(it);\n writeSingle(lines, start.line, start.column, '{');\n writeSingle(lines, closing.line, closing.column, '}');\n for (let i = 0; i < it.items.length; i++) emitNode(it.items[i]);\n break;\n }\n case NodeType.InlineItem: {\n const ii = node as InlineItem;\n emitNode(ii.item);\n if (ii.comma) {\n const end = ii.loc.end;\n writeSingle(lines, end.line, end.column, ',');\n }\n break;\n }\n\n case NodeType.Comment:\n write(lines, node.loc, (node as Comment).raw);\n break;\n default: {\n // Preserve original behavior: throw on unrecognized node types\n // to catch bugs when new node types are added or invalid nodes appear.\n const type = (node as any).type;\n throw new Error(`toTOML: Unrecognized node type: ${String(type)}`);\n }\n }\n }\n\n // Handle both Document nodes and bare iterables (document.items)\n if (isIterable(cst)) {\n for (const item of cst) emitNode(item as TreeNode);\n } else {\n emitNode(cst as unknown as TreeNode);\n }\n\n // Post-process: convert leading spaces to tabs if useTabsForIndentation is enabled\n if (format.useTabsForIndentation) {\n // Lines belonging to multiline string literals are VALUE content — the\n // indentation there is part of the string and must not be converted\n // (fuzz seed 70). The opening-delimiter line may carry structural\n // indentation, but every line from the first content line through the\n // closing delimiter is untouchable.\n const contentLines = new Set<number>();\n const collectStringLines = (node: TreeNode) => {\n if (node.type === NodeType.String && node.loc.end.line > node.loc.start.line) {\n for (let l = node.loc.start.line + 1; l <= node.loc.end.line; l++) {\n contentLines.add(l);\n }\n }\n if (hasItems(node)) {\n for (const item of node.items as TreeNode[]) collectStringLines(item);\n }\n if (isKeyValue(node)) collectStringLines(node.value);\n if (isInlineItem(node)) collectStringLines(node.item);\n };\n if (isIterable(cst)) {\n for (const item of cst) collectStringLines(item as TreeNode);\n } else {\n collectStringLines(cst as unknown as TreeNode);\n }\n\n for (let i = 0; i < lines.length; i++) {\n if (contentLines.has(i + 1)) continue;\n const line = lines[i];\n // Find the leading whitespace\n const match = line.match(/^( +)/);\n if (match) {\n const leadingSpaces = match[1];\n // Replace entire leading space sequence with equivalent tabs\n // Each space becomes a tab (preserving the visual width)\n const leadingTabs = '\\t'.repeat(leadingSpaces.length);\n lines[i] = leadingTabs + line.substring(leadingSpaces.length);\n }\n }\n }\n\n return lines.join(format.newLine) + format.newLine.repeat(format.trailingNewline);\n}\n\n/**\n * Source-aware emitter used while CST ranges replace coordinate painting.\n * Clean nodes copy their original text. Dirty nodes emit in structural order,\n * so a stale coordinate can add whitespace but cannot overwrite later text.\n */\nexport function toTOMLCursor(cst: CST, format: TomlFormat): string {\n const roots = isIterable(cst)\n ? Array.from(cst as Iterable<TreeNode>)\n : [cst as unknown as TreeNode];\n const chunks: string[] = [];\n const copiedRanges: Array<{ source: string; start: number; end: number }> = [];\n const hostedComments: Comment[] = [];\n const consumedComments = new WeakSet<Comment>();\n let line = 1;\n let column = 0;\n\n const collectComments = (node: TreeNode): void => {\n if (node.type === NodeType.Comment) hostedComments.push(node as Comment);\n if (isKeyValue(node)) collectComments(node.value);\n else if (isInlineItem(node)) collectComments(node.item);\n else if (node.type === NodeType.Table || node.type === NodeType.TableArray) {\n for (const item of (node as Table | TableArray).items) collectComments(item);\n } else if (hasItems(node)) {\n for (const item of node.items as TreeNode[]) collectComments(item);\n }\n };\n for (const root of roots) collectComments(root);\n\n // Inline containers that are direct values of block-level key-values\n // (Document, Table or TableArray). When such a container is emptied, its\n // multiline closing bracket is preserved. Nested containers keep it too when\n // writer.remove() marked them as emptied from an interior row\n // (markPreservedMultilineEmpty); any other emptied container tightens to a\n // single line.\n const blockLevelInlineContainers = new WeakSet<InlineTable | InlineArray>();\n const markBlockLevelInlineContainers = (items: TreeNode[]): void => {\n for (const item of items) {\n if (isKeyValue(item)) {\n const value = item.value;\n if (isInlineTable(value) || isInlineArray(value)) {\n blockLevelInlineContainers.add(value);\n }\n } else if (isTable(item) || isTableArray(item)) {\n markBlockLevelInlineContainers((item as Table | TableArray).items as TreeNode[]);\n }\n }\n };\n markBlockLevelInlineContainers(roots);\n\n const indentation = (width: number): string =>\n (format.useTabsForIndentation ? '\\t' : SPACE).repeat(width);\n\n const append = (text: string): void => {\n if (text.length === 0) return;\n chunks.push(text);\n const parts = text.split(/\\r\\n|\\n/);\n if (parts.length === 1) {\n column += text.length;\n } else {\n line += parts.length - 1;\n column = parts[parts.length - 1].length;\n }\n };\n\n const advanceTo = (targetLine: number, targetColumn: number): void => {\n if (targetLine > line) {\n append(format.newLine.repeat(targetLine - line));\n if (targetColumn > 0) append(indentation(targetColumn));\n } else if (targetLine === line && targetColumn > column) {\n // At the start of a line the gap up to the node is leading indentation,\n // so it must follow the document's tab/spaces preference rather than\n // always padding with spaces (a tab-indented first line would otherwise\n // be re-emitted with a space).\n append(column === 0 ? indentation(targetColumn) : SPACE.repeat(targetColumn - column));\n } else if (chunks.length > 0 &&\n (targetLine < line || (targetLine === line && targetColumn < column))) {\n append(format.newLine);\n if (targetColumn > 0) append(indentation(targetColumn));\n }\n };\n\n const leafText = (node: TreeNode): string | undefined => {\n switch (node.type) {\n case NodeType.Key: return (node as Key).raw;\n case NodeType.String: return (node as StringNode).raw;\n case NodeType.Integer: return (node as Integer).raw;\n case NodeType.Float: return (node as Float).raw;\n case NodeType.Boolean: return (node as BooleanNode).value.toString();\n case NodeType.DateTime: return (node as DateTime).raw;\n case NodeType.Comment: return (node as Comment).raw;\n default: return undefined;\n }\n };\n\n const directChildren = (node: TreeNode): TreeNode[] => {\n if (isKeyValue(node)) return [node.key, node.value];\n if (isInlineItem(node)) return [node.item];\n if (hasItem(node)) return [node.item];\n if (node.type === NodeType.Table || node.type === NodeType.TableArray) {\n const table = node as Table | TableArray;\n return [table.key, ...table.items];\n }\n return hasItems(node) ? node.items as TreeNode[] : [];\n };\n\n const sourceSubtreeReusable = (node: TreeNode): boolean => {\n const pending = [node];\n while (pending.length > 0) {\n const current = pending.pop()!;\n if (current.dirty) return false;\n const text = leafText(current);\n if (text !== undefined) {\n const source = getNodeSource(current);\n if (!source || !current.range || source.slice(current.range[0], current.range[1]) !== text) {\n return false;\n }\n } else if (!sourceStructureUnchanged(current)) {\n return false;\n }\n pending.push(...directChildren(current));\n }\n return true;\n };\n\n const canCopyWholeNode = (node: TreeNode): boolean =>\n node.type !== NodeType.Document &&\n node.type !== NodeType.InlineItem &&\n node.type !== NodeType.TableKey &&\n node.type !== NodeType.TableArrayKey &&\n (leafText(node) !== undefined || sourceStructureUnchanged(node));\n\n const appendRelativeGap = (\n from: { line: number; column: number },\n to: { line: number; column: number },\n absoluteIndent = false\n ): void => {\n if (to.line > from.line) {\n append(format.newLine.repeat(to.line - from.line));\n if (to.column > 0) append(absoluteIndent ? SPACE.repeat(to.column) : indentation(to.column));\n } else if (to.line === from.line && to.column > from.column) {\n append(SPACE.repeat(to.column - from.column));\n }\n };\n\n const sourceGap = (\n container: InlineArray | InlineTable,\n previous: InlineItem | undefined,\n current: InlineItem | undefined\n ): string | undefined => {\n const source = getNodeSource(container);\n if (!source || !container.range) return undefined;\n if (isInlineArray(container) && isGeneratedNestedTableHost(container) &&\n (!current || (previous && !previous.range) || (current && !current.range))) return undefined;\n if (previous && getNodeSource(previous) !== source) return undefined;\n if (current && getNodeSource(current) !== source) return undefined;\n const start = previous?.range?.[1] ?? container.range[0] + 1;\n const end = current?.range?.[0] ?? container.range[1] - 1;\n if (start === undefined || end === undefined || end < start) return undefined;\n\n let gap = source.slice(start, end);\n if (previous?.comma && gap.startsWith(',')) gap = gap.slice(1);\n if (!/^[\\t \\r\\n]*$/.test(gap)) return undefined;\n return gap;\n };\n\n const commentBelongsTo = (comment: Comment, container: InlineArray | InlineTable): boolean => {\n const source = getNodeSource(container);\n return source !== undefined &&\n getNodeSource(comment) === source &&\n container.range !== undefined &&\n comment.range !== undefined &&\n comment.range[0] >= container.range[0] &&\n comment.range[1] <= container.range[1];\n };\n\n const emitInlineItems = (container: InlineArray | InlineTable): void => {\n const generatedMultilineTable = isInlineTable(container) && isGeneratedNestedTable(container);\n let previous: InlineItem | undefined;\n for (const current of container.items as InlineItem[]) {\n let from = previous\n ? {\n line: previous.loc.end.line,\n column: previous.loc.end.column + (previous.comma ? 1 : 0)\n }\n : {\n line: container.loc.start.line,\n column: container.loc.start.column + 1\n };\n const commentsBefore = hostedComments\n .filter(comment => !consumedComments.has(comment) && commentBelongsTo(comment, container) &&\n comment.loc.start.line >= from.line &&\n comment.loc.end.line <= current.loc.start.line &&\n (comment.loc.start.line > from.line || comment.loc.start.column >= from.column) &&\n (comment.loc.end.line < current.loc.start.line || comment.loc.end.column <= current.loc.start.column) &&\n comment.loc.start.line >= container.loc.start.line &&\n comment.loc.end.line <= container.loc.end.line)\n .sort((left, right) =>\n left.loc.start.line - right.loc.start.line ||\n left.loc.start.column - right.loc.start.column);\n\n if (commentsBefore.length > 0) {\n for (const comment of commentsBefore) {\n appendRelativeGap(from, comment.loc.start);\n append(comment.raw);\n consumedComments.add(comment);\n from = comment.loc.end;\n }\n appendRelativeGap(from, current.loc.start);\n } else {\n const gap = sourceGap(container, previous, current);\n if (gap !== undefined) {\n append(gap);\n } else {\n const crossSource = getNodeSource(current) !== getNodeSource(container);\n if (previous && crossSource && current.loc.start.line === previous.loc.end.line) {\n const commaGap = getCommaSpace(container) ?? 2;\n const wantedSpaces = Math.max(0, commaGap - 1);\n if (wantedSpaces > 0) append(SPACE.repeat(wantedSpaces));\n } else {\n appendRelativeGap(from, current.loc.start, generatedMultilineTable);\n }\n }\n }\n emitNode(current, false);\n for (const comment of hostedComments) {\n if (consumedComments.has(comment)) continue;\n if (!commentBelongsTo(comment, container)) continue;\n if (comment.loc.start.line !== current.loc.end.line) continue;\n if (comment.loc.start.column < current.loc.end.column) continue;\n if (comment.loc.start.line < container.loc.start.line ||\n comment.loc.end.line > container.loc.end.line) continue;\n const separatorEnd = current.loc.end.column + (current.comma ? 1 : 0);\n if (comment.loc.start.column > separatorEnd) {\n append(SPACE.repeat(comment.loc.start.column - separatorEnd));\n }\n append(comment.raw);\n consumedComments.add(comment);\n }\n previous = current;\n }\n\n let trailingFrom = previous\n ? {\n line: previous.loc.end.line,\n column: previous.loc.end.column + (previous.comma ? 1 : 0)\n }\n : { line: container.loc.start.line, column: container.loc.start.column + 1 };\n const trailingComments = hostedComments\n .filter(comment => !consumedComments.has(comment) && commentBelongsTo(comment, container) &&\n comment.loc.start.line >= trailingFrom.line &&\n comment.loc.end.line <= container.loc.end.line)\n .sort((left, right) =>\n left.loc.start.line - right.loc.start.line ||\n left.loc.start.column - right.loc.start.column);\n if (trailingComments.length > 0) {\n for (const comment of trailingComments) {\n appendRelativeGap(trailingFrom, comment.loc.start);\n append(comment.raw);\n consumedComments.add(comment);\n trailingFrom = comment.loc.end;\n }\n appendRelativeGap(trailingFrom, {\n line: container.loc.end.line,\n column: container.loc.end.column - 1\n });\n } else {\n const trailingGap = sourceGap(container, previous, undefined);\n if (trailingGap !== undefined) append(trailingGap);\n else if (previous) {\n if (generatedMultilineTable && previous.comma) append(SPACE);\n appendRelativeGap(trailingFrom, {\n line: container.loc.end.line,\n column: container.loc.end.column - 1\n }, generatedMultilineTable);\n }\n else {\n const source = getNodeSource(container);\n if (source && container.range) {\n const original = source.slice(container.range[0], container.range[1]);\n const lastNewline = Math.max(original.lastIndexOf('\\n'), original.lastIndexOf('\\r'));\n const keepClosingRow = blockLevelInlineContainers.has(container) ||\n isPreservedMultilineEmpty(container);\n if (lastNewline !== -1 && keepClosingRow && originalFirstChildStartedAfterOpener(container)) {\n const closingIndent = original.slice(lastNewline + 1, -1).match(/^[\\t ]*/)?.[0] ?? '';\n append(format.newLine + closingIndent);\n }\n }\n }\n }\n };\n\n const emitNode = (node: TreeNode, place = true): void => {\n if (node.type === NodeType.Comment && consumedComments.has(node as Comment)) return;\n const source = getNodeSource(node);\n if (source !== undefined && node.range && copiedRanges.some(copied =>\n copied.source === source && copied.start <= node.range![0] && copied.end >= node.range![1]\n )) {\n return;\n }\n if (canCopyWholeNode(node) && sourceSubtreeReusable(node) && node.range && source !== undefined) {\n const slice = source.slice(node.range[0], node.range[1]);\n const expectedLeaf = leafText(node);\n if (expectedLeaf === undefined || expectedLeaf === slice) {\n if (place) advanceTo(node.loc.start.line, node.loc.start.column);\n append(slice);\n copiedRanges.push({ source, start: node.range[0], end: node.range[1] });\n return;\n }\n }\n\n switch (node.type) {\n case NodeType.Document:\n for (const item of (node as Document).items) emitNode(item);\n break;\n case NodeType.Table: {\n const table = node as Table;\n emitNode(table.key, place);\n for (const item of table.items) emitNode(item);\n break;\n }\n case NodeType.TableKey: {\n const tableKey = node as TableKey;\n if (place) advanceTo(tableKey.loc.start.line, tableKey.loc.start.column);\n append(`[${tableKey.item.raw}]`);\n break;\n }\n case NodeType.TableArray: {\n const tableArray = node as TableArray;\n emitNode(tableArray.key, place);\n for (const item of tableArray.items) emitNode(item);\n break;\n }\n case NodeType.TableArrayKey: {\n const tableArrayKey = node as TableArrayKey;\n if (place) advanceTo(tableArrayKey.loc.start.line, tableArrayKey.loc.start.column);\n append(`[[${tableArrayKey.item.raw}]]`);\n break;\n }\n case NodeType.KeyValue: {\n const keyValue = node as KeyValue;\n if (place) advanceTo(keyValue.loc.start.line, keyValue.loc.start.column);\n emitNode(keyValue.key, false);\n appendRelativeGap(keyValue.key.loc.end, {\n line: keyValue.loc.start.line,\n column: keyValue.equals\n });\n append('=');\n appendRelativeGap({ line: keyValue.loc.start.line, column: keyValue.equals + 1 }, keyValue.value.loc.start);\n emitNode(keyValue.value, false);\n break;\n }\n case NodeType.Key:\n if (place) advanceTo(node.loc.start.line, node.loc.start.column);\n append((node as Key).raw);\n break;\n case NodeType.String:\n if (place) advanceTo(node.loc.start.line, node.loc.start.column);\n append((node as StringNode).raw);\n break;\n case NodeType.Integer:\n if (place) advanceTo(node.loc.start.line, node.loc.start.column);\n append((node as Integer).raw);\n break;\n case NodeType.Float:\n if (place) advanceTo(node.loc.start.line, node.loc.start.column);\n append((node as Float).raw);\n break;\n case NodeType.Boolean:\n if (place) advanceTo(node.loc.start.line, node.loc.start.column);\n append((node as BooleanNode).value.toString());\n break;\n case NodeType.DateTime:\n if (place) advanceTo(node.loc.start.line, node.loc.start.column);\n append((node as DateTime).raw);\n break;\n case NodeType.InlineArray: {\n const array = node as InlineArray;\n if (place) advanceTo(array.loc.start.line, array.loc.start.column);\n append('[');\n emitInlineItems(array);\n append(']');\n break;\n }\n case NodeType.InlineTable: {\n const table = node as InlineTable;\n if (place) advanceTo(table.loc.start.line, table.loc.start.column);\n append('{');\n emitInlineItems(table);\n append('}');\n break;\n }\n case NodeType.InlineItem: {\n const item = node as InlineItem;\n emitNode(item.item, false);\n if (item.comma) {\n const source = getNodeSource(item);\n if (source && item.range && item.item.range && getNodeSource(item.item) === source) {\n const beforeComma = source.slice(item.item.range[1], item.range[1]);\n if (/^[\\t ]*$/.test(beforeComma)) append(beforeComma);\n }\n append(',');\n }\n break;\n }\n case NodeType.Comment:\n if (place) advanceTo(node.loc.start.line, node.loc.start.column);\n append((node as Comment).raw);\n break;\n default:\n throw new Error(`toTOMLCursor: Unrecognized node type: ${String((node as any).type)}`);\n }\n };\n\n for (const root of roots) emitNode(root);\n\n const output = chunks.join('').replace(/\\r\\n|\\n/g, format.newLine);\n return output + format.newLine.repeat(format.trailingNewline);\n}\n\n/**\n * Sequential emitter for generated CSTs. Generated nodes carry no source and\n * already have consistent positions, so text can be appended in structural\n * order and gaps filled with newlines and indentation instead of painting text\n * at recorded coordinates. Produces byte-identical output to `toTOML` for CSTs\n * produced by `parseJS`.\n */\nexport function toTOMLSequential(cst: CST, format: TomlFormat): string {\n // `stringify()` passes `document.items` (an array), so avoid Array.from's\n // eager copy of an array that is already indexable.\n const roots: TreeNode[] = Array.isArray(cst)\n ? cst\n : isIterable(cst)\n ? Array.from(cst as Iterable<TreeNode>)\n : [cst as unknown as TreeNode];\n const chunks: string[] = [];\n let line = 1;\n let column = 0;\n\n const indentation = (width: number): string =>\n (format.useTabsForIndentation ? '\\t' : SPACE).repeat(width);\n\n const append = (text: string): void => {\n if (text.length === 0) return;\n chunks.push(text);\n let count = 0;\n let lastIndex = -1;\n let index = text.indexOf('\\n');\n while (index !== -1) {\n count++;\n lastIndex = index;\n index = text.indexOf('\\n', index + 1);\n }\n if (count === 0) {\n column += text.length;\n return;\n }\n line += count;\n column = text.length - lastIndex - 1;\n };\n\n const advanceTo = (targetLine: number, targetColumn: number): void => {\n if (targetLine > line) {\n append(format.newLine.repeat(targetLine - line));\n if (targetColumn > 0) append(indentation(targetColumn));\n } else if (targetLine === line && targetColumn > column) {\n append(column === 0 ? indentation(targetColumn) : SPACE.repeat(targetColumn - column));\n } else if (chunks.length > 0 &&\n (targetLine < line || (targetLine === line && targetColumn < column))) {\n append(format.newLine);\n if (targetColumn > 0) append(indentation(targetColumn));\n }\n };\n\n const leafRaw = (node: TreeNode): string => {\n switch (node.type) {\n case NodeType.Key: return (node as Key).raw;\n case NodeType.String: return (node as StringNode).raw;\n case NodeType.Integer: return (node as Integer).raw;\n case NodeType.Float: return (node as Float).raw;\n case NodeType.Boolean: return (node as BooleanNode).value.toString();\n case NodeType.DateTime: return (node as DateTime).raw;\n case NodeType.Comment: return (node as Comment).raw;\n default: return '';\n }\n };\n\n // Iterative command stack: emits in structural order without recursion, so\n // arbitrarily deep nesting (the toml-test \"scaling\" fixtures) cannot overflow\n // the call stack. Command encoding:\n // [0, node, place] emit a node\n // [1, text] append raw text\n // [2, fl, fc, tl, tc, absolute] append a relative gap from (fl, fc) to (tl, tc)\n // [3, line, column] advance the cursor\n const stack: any[] = [];\n\n const pushNode = (node: TreeNode, place: boolean): void => {\n switch (node.type) {\n case NodeType.Document: {\n const items = (node as Document).items;\n for (let i = items.length - 1; i >= 0; i--) stack.push([0, items[i], true]);\n break;\n }\n case NodeType.Table: {\n const table = node as Table;\n const items = table.items;\n for (let i = items.length - 1; i >= 0; i--) stack.push([0, items[i], true]);\n stack.push([0, table.key, place]);\n break;\n }\n case NodeType.TableKey: {\n const tableKey = node as TableKey;\n stack.push([1, `[${tableKey.item.raw}]`]);\n if (place) stack.push([3, tableKey.loc.start.line, tableKey.loc.start.column]);\n break;\n }\n case NodeType.TableArray: {\n const tableArray = node as TableArray;\n const items = tableArray.items;\n for (let i = items.length - 1; i >= 0; i--) stack.push([0, items[i], true]);\n stack.push([0, tableArray.key, place]);\n break;\n }\n case NodeType.TableArrayKey: {\n const tableArrayKey = node as TableArrayKey;\n stack.push([1, `[[${tableArrayKey.item.raw}]]`]);\n if (place) stack.push([3, tableArrayKey.loc.start.line, tableArrayKey.loc.start.column]);\n break;\n }\n case NodeType.KeyValue: {\n const keyValue = node as KeyValue;\n stack.push([0, keyValue.value, false]);\n stack.push([2, keyValue.loc.start.line, keyValue.equals + 1, keyValue.value.loc.start.line, keyValue.value.loc.start.column, false]);\n stack.push([1, '=']);\n stack.push([2, keyValue.key.loc.end.line, keyValue.key.loc.end.column, keyValue.loc.start.line, keyValue.equals, false]);\n stack.push([0, keyValue.key, false]);\n if (place) stack.push([3, keyValue.loc.start.line, keyValue.loc.start.column]);\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 stack.push([1, leafRaw(node)]);\n if (place) stack.push([3, node.loc.start.line, node.loc.start.column]);\n break;\n }\n case NodeType.InlineArray: {\n const array = node as InlineArray;\n const items = array.items as InlineItem[];\n stack.push([1, ']']);\n if (items.length > 0) {\n const last = items[items.length - 1];\n stack.push([2, last.loc.end.line, last.loc.end.column + (last.comma ? 1 : 0), array.loc.end.line, array.loc.end.column - 1, false]);\n }\n for (let i = items.length - 1; i >= 0; i--) {\n const current = items[i];\n const previous = i > 0 ? items[i - 1] : undefined;\n stack.push([0, current, false]);\n stack.push(previous\n ? [2, previous.loc.end.line, previous.loc.end.column + (previous.comma ? 1 : 0), current.loc.start.line, current.loc.start.column, false]\n : [2, array.loc.start.line, array.loc.start.column + 1, current.loc.start.line, current.loc.start.column, false]);\n }\n stack.push([1, '[']);\n if (place) stack.push([3, array.loc.start.line, array.loc.start.column]);\n break;\n }\n case NodeType.InlineTable: {\n const table = node as InlineTable;\n const items = table.items as InlineItem[];\n const generatedMultilineTable = isGeneratedNestedTable(table);\n stack.push([1, '}']);\n if (items.length > 0) {\n const last = items[items.length - 1];\n if (generatedMultilineTable && last.comma) stack.push([1, SPACE]);\n stack.push([2, last.loc.end.line, last.loc.end.column + (last.comma ? 1 : 0), table.loc.end.line, table.loc.end.column - 1, generatedMultilineTable]);\n }\n for (let i = items.length - 1; i >= 0; i--) {\n const current = items[i];\n const previous = i > 0 ? items[i - 1] : undefined;\n stack.push([0, current, false]);\n stack.push(previous\n ? [2, previous.loc.end.line, previous.loc.end.column + (previous.comma ? 1 : 0), current.loc.start.line, current.loc.start.column, generatedMultilineTable]\n : [2, table.loc.start.line, table.loc.start.column + 1, current.loc.start.line, current.loc.start.column, generatedMultilineTable]);\n }\n stack.push([1, '{']);\n if (place) stack.push([3, table.loc.start.line, table.loc.start.column]);\n break;\n }\n case NodeType.InlineItem: {\n const item = node as InlineItem;\n if (item.comma) stack.push([1, ',']);\n stack.push([0, item.item, false]);\n break;\n }\n default:\n throw new Error(`toTOMLSequential: Unrecognized node type: ${String((node as any).type)}`);\n }\n };\n\n for (let i = roots.length - 1; i >= 0; i--) stack.push([0, roots[i], true]);\n\n while (stack.length > 0) {\n const command = stack.pop()!;\n switch (command[0]) {\n case 0:\n pushNode(command[1], command[2]);\n break;\n case 1:\n append(command[1]);\n break;\n case 2: {\n const fromLine = command[1];\n const fromColumn = command[2];\n const toLine = command[3];\n const toColumn = command[4];\n const absoluteIndent = command[5];\n if (toLine > fromLine) {\n append(format.newLine.repeat(toLine - fromLine));\n if (toColumn > 0) append(absoluteIndent ? SPACE.repeat(toColumn) : indentation(toColumn));\n } else if (toLine === fromLine && toColumn > fromColumn) {\n append(SPACE.repeat(toColumn - fromColumn));\n }\n break;\n }\n case 3:\n advanceTo(command[1], command[2]);\n break;\n }\n }\n\n return chunks.join('').replace(/\\r\\n|\\n/g, format.newLine) + format.newLine.repeat(format.trailingNewline);\n}\n\n/**\n * Writes raw string content to specific location coordinates within a lines array.\n * \n * This function is responsible for placing TOML content at precise positions within\n * the output lines, handling multi-line content and preserving existing content\n * around the target location.\n * \n * @param lines - Array of string lines representing the TOML document being built.\n * Lines are 1-indexed but stored in 0-indexed array.\n * @param loc - Location object specifying where to write the content, containing:\n * - start: { line: number, column: number } - Starting position (1-indexed line, 0-indexed column)\n * - end: { line: number, column: number } - Ending position (1-indexed line, 0-indexed column)\n * @param raw - The raw string content to write at the specified location.\n * Can contain multiple lines separated by \\n or \\r\\n.\n * \n * @throws {Error} When there's a mismatch between location span and raw string line count\n * @throws {Error} When attempting to write to an uninitialized line\n * \n * @example\n * ```typescript\n * const lines = ['', ''];\n * const location = { start: { line: 1, column: 0 }, end: { line: 1, column: 3 } };\n * write(lines, location, 'key');\n * // Result: lines[0] becomes 'key'\n * ```\n */\nfunction write(lines: string[], loc: Location, raw: string) {\n // Fast path for single-line content (the vast majority of nodes).\n // Avoids the regex split + filter that allocates two temporary arrays.\n if (loc.start.line === loc.end.line) {\n const line = getLine(lines, loc.start.line);\n\n const existingBefore = line.substring(0, loc.start.column);\n const before = existingBefore.length < loc.start.column\n ? existingBefore.padEnd(loc.start.column, SPACE)\n : existingBefore;\n const after = line.substring(loc.end.column);\n\n lines[loc.start.line - 1] = before + raw + after;\n return;\n }\n\n // Multi-line path: split and filter newline separators\n const raw_lines = raw.split(BY_NEW_LINE).filter(line => line !== '\\n' && line !== '\\r\\n');\n const expected_lines = loc.end.line - loc.start.line + 1;\n\n if (raw_lines.length !== expected_lines) {\n throw new Error(\n `Mismatch between location and raw string, expected ${expected_lines} lines for \"${raw}\"`\n );\n }\n\n for (let i = loc.start.line; i <= loc.end.line; i++) {\n const line = getLine(lines, i);\n\n const is_start_line = i === loc.start.line;\n const is_end_line = i === loc.end.line;\n\n let before = '';\n if (is_start_line) {\n const existingBefore = line.substring(0, loc.start.column);\n if (existingBefore.length < loc.start.column) {\n // Need to pad - always use spaces during write phase\n // Tab conversion happens in post-processing for leading indentation only\n before = existingBefore.padEnd(loc.start.column, SPACE);\n } else {\n before = existingBefore;\n }\n }\n const after = is_end_line ? line.substring(loc.end.column) : '';\n\n lines[i - 1] = before + raw_lines[i - loc.start.line] + after;\n }\n}\n\n/**\n * Fast path for writing a single character at a specific position.\n * Avoids creating temporary Location objects.\n */\nfunction writeSingle(lines: string[], lineNum: number, column: number, char: string) {\n const line = getLine(lines, lineNum);\n const before = line.length < column\n ? line.padEnd(column, SPACE)\n : line.substring(0, column);\n const after = line.substring(column + 1);\n lines[lineNum - 1] = before + char + after;\n}\n\n/**\n * Safely retrieves a line from the lines array, initializing empty lines as needed.\n * \n * This helper function handles the conversion between 1-indexed line numbers (used in locations)\n * and 0-indexed array positions. It ensures that accessing a line that doesn't exist yet\n * will initialize all preceding lines with empty strings.\n * \n * @param lines - Array of string lines representing the document\n * @param index - 1-indexed line number to retrieve\n * @returns The line content as a string, or empty string for new lines\n * \n * @example\n * ```typescript\n * const lines = ['first line'];\n * const line = getLine(lines, 3); // Initializes lines[1] and lines[2] as empty strings\n * // lines becomes ['first line', '', '']\n * ```\n */\nfunction getLine(lines: string[], index: number): string {\n if (!lines[index - 1]) {\n for (let i = 0; i < index; i++) {\n if (!lines[i]) lines[i] = '';\n }\n }\n\n return lines[index - 1];\n}\n"],"mappings":";;;;;;;;AAyCA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAkBpB,SAAwB,OAAO,KAAU,QAA4B;CAEnE,MAAM,QAAkB,CAAC;CAIzB,MAAM,mBAAmB,cAA2E;EAClG,MAAM,WAAW;GACf,MAAM,UAAU,IAAI,IAAI;GACxB,QAAQ,UAAU,IAAI,IAAI,SAAS;EACrC;EACA,MAAM,OAAO,UAAU,MAAM,UAAU,MAAM,SAAS;EACtD,IAAI,SAAS,KAAK,IAAI,IAAI,OAAO,SAAS,QACrC,KAAK,IAAI,IAAI,SAAS,SAAS,QAAQ,KAAK,IAAI,IAAI,SAAS,SAAS,SAAU;GACnF,SAAS,OAAO,KAAK,IAAI,IAAI;GAC7B,SAAS,SAAS,KAAK,IAAI,IAAI,UAAU,KAAK,QAAQ,IAAI;EAC5D;EACA,OAAO;CACT;CAEA,SAAS,SAAS,MAAgB;EAChC,QAAQ,KAAK,MAAb;GACE;IACE,KAAK,IAAI,IAAI,GAAG,IAAK,KAAkB,MAAM,QAAQ,KACnD,SAAU,KAAkB,MAAM,EAAE;IACtC;GAEF,cAAqB;IACnB,MAAM,MAAM;IACZ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,KAAK;CAC5B;CAGF,OAAO,MAAM,QAAQ;AACvB"}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
//! @decimalturn/toml-patch v3.3.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
|
+
import { findPosition } from "./location.js";
|
|
3
|
+
import ParseError from "./parse-error.js";
|
|
4
|
+
|
|
5
|
+
//#region src/tokenizer.ts
|
|
6
|
+
const IS_BARE_KEY = /^[\w-]+$/;
|
|
7
|
+
const DOUBLE_QUOTE = `"`;
|
|
8
|
+
const SINGLE_QUOTE = `'`;
|
|
9
|
+
const ESCAPE = "\\";
|
|
10
|
+
const IS_VALID_LEADING_CHARACTER = /[\w,\d,",',+,\-,_]/;
|
|
11
|
+
const CH_TAB = 9;
|
|
12
|
+
const CH_LF = 10;
|
|
13
|
+
const CH_CR = 13;
|
|
14
|
+
const CH_SPACE = 32;
|
|
15
|
+
const CH_HASH = 35;
|
|
16
|
+
const CH_COMMA = 44;
|
|
17
|
+
const CH_DOT = 46;
|
|
18
|
+
const CH_EQUAL = 61;
|
|
19
|
+
const CH_LBRACKET = 91;
|
|
20
|
+
const CH_RBRACKET = 93;
|
|
21
|
+
const CH_LBRACE = 123;
|
|
22
|
+
const CH_RBRACE = 125;
|
|
23
|
+
const CH_DEL = 127;
|
|
24
|
+
/** Creates an empty newline scan state for use with tokenize(). */
|
|
25
|
+
function createNewlineScanState() {
|
|
26
|
+
return {
|
|
27
|
+
reference: null,
|
|
28
|
+
mixed: false
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function* tokenize(input, newlineState) {
|
|
32
|
+
const len = input.length;
|
|
33
|
+
let pos = 0;
|
|
34
|
+
const nlState = newlineState ?? createNewlineScanState();
|
|
35
|
+
const lines = [];
|
|
36
|
+
const locate = (start, end) => ({
|
|
37
|
+
start: findPosition(lines, start),
|
|
38
|
+
end: findPosition(lines, end)
|
|
39
|
+
});
|
|
40
|
+
while (pos < len) {
|
|
41
|
+
const code = input.charCodeAt(pos);
|
|
42
|
+
if ((code <= 31 || code === CH_DEL) && code !== CH_TAB && code !== CH_CR && code !== CH_LF) throw new ParseError(input, findPosition(lines, pos), `Control char 0x${code.toString(16).toUpperCase().padStart(2, "0")} not allowed`);
|
|
43
|
+
if (code === CH_CR) {
|
|
44
|
+
if (pos + 1 >= len || input.charCodeAt(pos + 1) !== CH_LF) throw new ParseError(input, findPosition(lines, pos), "Standalone CR; must be CRLF or LF");
|
|
45
|
+
}
|
|
46
|
+
if (code === CH_SPACE || code === CH_TAB || code === CH_CR) {} else if (code === CH_LF) recordNewline(pos);
|
|
47
|
+
else if (code === CH_LBRACKET || code === CH_RBRACKET) yield {
|
|
48
|
+
type: "Bracket",
|
|
49
|
+
raw: input[pos],
|
|
50
|
+
loc: locate(pos, pos + 1)
|
|
51
|
+
};
|
|
52
|
+
else if (code === CH_LBRACE || code === CH_RBRACE) yield {
|
|
53
|
+
type: "Curly",
|
|
54
|
+
raw: input[pos],
|
|
55
|
+
loc: locate(pos, pos + 1)
|
|
56
|
+
};
|
|
57
|
+
else if (code === CH_EQUAL) yield {
|
|
58
|
+
type: "Equal",
|
|
59
|
+
raw: "=",
|
|
60
|
+
loc: locate(pos, pos + 1)
|
|
61
|
+
};
|
|
62
|
+
else if (code === CH_COMMA) yield {
|
|
63
|
+
type: "Comma",
|
|
64
|
+
raw: ",",
|
|
65
|
+
loc: locate(pos, pos + 1)
|
|
66
|
+
};
|
|
67
|
+
else if (code === CH_DOT) yield {
|
|
68
|
+
type: "Dot",
|
|
69
|
+
raw: ".",
|
|
70
|
+
loc: locate(pos, pos + 1)
|
|
71
|
+
};
|
|
72
|
+
else if (code === CH_HASH) yield comment();
|
|
73
|
+
else {
|
|
74
|
+
const multiline_char = checkThree(input, pos, SINGLE_QUOTE) || checkThree(input, pos, DOUBLE_QUOTE);
|
|
75
|
+
if (multiline_char) yield multilineToken(multiline_char);
|
|
76
|
+
else yield stringToken();
|
|
77
|
+
}
|
|
78
|
+
pos++;
|
|
79
|
+
}
|
|
80
|
+
function recordNewline(lfPos) {
|
|
81
|
+
lines.push(lfPos);
|
|
82
|
+
const style = lfPos > 0 && input.charCodeAt(lfPos - 1) === CH_CR ? "\r\n" : "\n";
|
|
83
|
+
if (nlState.reference === null) nlState.reference = style;
|
|
84
|
+
else if (nlState.reference !== style) nlState.mixed = true;
|
|
85
|
+
}
|
|
86
|
+
function comment() {
|
|
87
|
+
const start = pos;
|
|
88
|
+
while (pos + 1 < len) {
|
|
89
|
+
const nextCode = input.charCodeAt(pos + 1);
|
|
90
|
+
if (nextCode === CH_LF || nextCode === CH_CR) break;
|
|
91
|
+
pos++;
|
|
92
|
+
const cc = input.charCodeAt(pos);
|
|
93
|
+
if ((cc <= 31 || cc === CH_DEL) && cc !== CH_TAB) throw new ParseError(input, findPosition(lines, pos), `Control char 0x${cc.toString(16).toUpperCase().padStart(2, "0")} not allowed`);
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
type: "Comment",
|
|
97
|
+
raw: input.slice(start, pos + 1),
|
|
98
|
+
loc: locate(start, pos + 1)
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function multilineToken(multiline_char) {
|
|
102
|
+
const start = pos;
|
|
103
|
+
const quotes = multiline_char + multiline_char + multiline_char;
|
|
104
|
+
pos += 3;
|
|
105
|
+
while (pos < len) {
|
|
106
|
+
if (checkThree(input, pos, multiline_char)) {
|
|
107
|
+
let runLength = 3;
|
|
108
|
+
while (input[pos + runLength] === multiline_char) runLength++;
|
|
109
|
+
if (runLength >= 6) throw new ParseError(input, findPosition(lines, pos), `Invalid multiline string: ${runLength} consecutive ${multiline_char} characters`);
|
|
110
|
+
if (runLength === 3) {
|
|
111
|
+
pos += 2;
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
pos += runLength - 3;
|
|
115
|
+
pos += 2;
|
|
116
|
+
break;
|
|
117
|
+
}
|
|
118
|
+
const cc = input.charCodeAt(pos);
|
|
119
|
+
if (cc === CH_CR) {
|
|
120
|
+
if (pos + 1 >= len || input.charCodeAt(pos + 1) !== CH_LF) throw new ParseError(input, findPosition(lines, pos), "Standalone CR in multiline string; must be CRLF or LF");
|
|
121
|
+
}
|
|
122
|
+
if ((cc <= 31 || cc === CH_DEL) && cc !== CH_TAB && cc !== CH_LF && cc !== CH_CR) {
|
|
123
|
+
const stringType = multiline_char === DOUBLE_QUOTE ? "multiline basic strings" : "multiline literal strings";
|
|
124
|
+
const hexCode = `0x${cc.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
125
|
+
let charName = "";
|
|
126
|
+
if (cc === 0) charName = "Null";
|
|
127
|
+
else if (cc === CH_DEL) charName = "DEL";
|
|
128
|
+
const message = charName ? `${charName} (${hexCode}) not allowed in ${stringType}` : `Control char ${hexCode} not allowed in ${stringType}`;
|
|
129
|
+
throw new ParseError(input, findPosition(lines, pos), message);
|
|
130
|
+
}
|
|
131
|
+
if (cc === CH_LF) recordNewline(pos);
|
|
132
|
+
pos++;
|
|
133
|
+
}
|
|
134
|
+
if (pos >= len) {
|
|
135
|
+
if (multiline_char === DOUBLE_QUOTE) {
|
|
136
|
+
let bsCount = 0;
|
|
137
|
+
let bi = len - 1;
|
|
138
|
+
while (bi >= 0 && input[bi] === "\\") {
|
|
139
|
+
bsCount++;
|
|
140
|
+
bi--;
|
|
141
|
+
}
|
|
142
|
+
if (bsCount > 0 && bsCount % 2 !== 0) throw new ParseError(input, findPosition(lines, pos), `Unterminated multiline ${quotes} (possible escape issue)`);
|
|
143
|
+
}
|
|
144
|
+
throw new ParseError(input, findPosition(lines, pos), `Unterminated multiline ${quotes}`);
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
type: "Literal",
|
|
148
|
+
raw: input.slice(start, pos + 1),
|
|
149
|
+
loc: locate(start, pos + 1)
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function stringToken() {
|
|
153
|
+
const ch = input[pos];
|
|
154
|
+
if (!IS_VALID_LEADING_CHARACTER.test(ch)) throw new ParseError(input, findPosition(lines, pos), `Unexpected char "${ch}"`);
|
|
155
|
+
const start = pos;
|
|
156
|
+
let double_quoted = ch === DOUBLE_QUOTE;
|
|
157
|
+
let single_quoted = ch === SINGLE_QUOTE;
|
|
158
|
+
while (pos < len) {
|
|
159
|
+
if (pos + 1 >= len) break;
|
|
160
|
+
const nextCode = input.charCodeAt(pos + 1);
|
|
161
|
+
if (!(double_quoted || single_quoted)) {
|
|
162
|
+
if (nextCode === CH_SPACE || nextCode === CH_TAB || nextCode === CH_LF || nextCode === CH_CR || nextCode === CH_COMMA || nextCode === CH_DOT || nextCode === CH_RBRACKET || nextCode === CH_RBRACE || nextCode === CH_EQUAL || nextCode === CH_HASH) break;
|
|
163
|
+
}
|
|
164
|
+
pos++;
|
|
165
|
+
if (!(double_quoted || single_quoted)) {
|
|
166
|
+
const cc = input.charCodeAt(pos);
|
|
167
|
+
if (cc <= 31 || cc === CH_DEL) throw new ParseError(input, findPosition(lines, pos), `Control char 0x${cc.toString(16).toUpperCase().padStart(2, "0")} not allowed in unquoted value`);
|
|
168
|
+
}
|
|
169
|
+
if (double_quoted || single_quoted) {
|
|
170
|
+
const cc = input.charCodeAt(pos);
|
|
171
|
+
if ((cc <= 31 || cc === CH_DEL) && cc !== CH_TAB) {
|
|
172
|
+
const stringType = double_quoted ? "basic strings" : "literal strings";
|
|
173
|
+
const hexCode = `0x${cc.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
174
|
+
let charName = "";
|
|
175
|
+
if (cc === CH_LF) charName = "Newline";
|
|
176
|
+
else if (cc === CH_CR) charName = "Carriage return";
|
|
177
|
+
else if (cc === 0) charName = "Null";
|
|
178
|
+
else if (cc === CH_DEL) charName = "DEL";
|
|
179
|
+
const message = charName ? `${charName} (${hexCode}) not allowed in ${stringType}` : `Control char ${hexCode} not allowed in ${stringType}`;
|
|
180
|
+
throw new ParseError(input, findPosition(lines, pos), message);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const currentChar = input[pos];
|
|
184
|
+
if (currentChar === DOUBLE_QUOTE && !single_quoted) double_quoted = !double_quoted;
|
|
185
|
+
if (currentChar === SINGLE_QUOTE && !double_quoted) single_quoted = !single_quoted;
|
|
186
|
+
if (pos + 1 >= len) break;
|
|
187
|
+
if (double_quoted && currentChar === "\\") {
|
|
188
|
+
const nextChar = input[pos + 1];
|
|
189
|
+
if (nextChar === DOUBLE_QUOTE || nextChar === "\\") pos++;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (double_quoted || single_quoted) throw new ParseError(input, findPosition(lines, start), `Expected close of string with ${double_quoted ? DOUBLE_QUOTE : SINGLE_QUOTE}`);
|
|
193
|
+
return {
|
|
194
|
+
type: "Literal",
|
|
195
|
+
raw: input.slice(start, pos + 1),
|
|
196
|
+
loc: locate(start, pos + 1)
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Check if the current character and the next two characters are the same
|
|
202
|
+
* and not escaped.
|
|
203
|
+
*
|
|
204
|
+
* @param input - The input string.
|
|
205
|
+
* @param current - The current index in the input string.
|
|
206
|
+
* @param check - The character to check for.
|
|
207
|
+
* @returns ⚠️The character if found, otherwise false.
|
|
208
|
+
*/
|
|
209
|
+
function checkThree(input, current, check) {
|
|
210
|
+
if (!check) return false;
|
|
211
|
+
if (!(input[current] === check && input[current + 1] === check && input[current + 2] === check)) return false;
|
|
212
|
+
if (check === SINGLE_QUOTE) return check;
|
|
213
|
+
let bsCount = 0;
|
|
214
|
+
let i = current - 1;
|
|
215
|
+
while (i >= 0 && input[i] === "\\") {
|
|
216
|
+
bsCount++;
|
|
217
|
+
i--;
|
|
218
|
+
}
|
|
219
|
+
if (bsCount === 0) return check;
|
|
220
|
+
return bsCount % 2 !== 0 ? false : check;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
//#endregion
|
|
224
|
+
export { DOUBLE_QUOTE, IS_BARE_KEY, SINGLE_QUOTE, createNewlineScanState, tokenize };
|
|
225
|
+
//# sourceMappingURL=tokenizer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokenizer.js","names":[],"sources":["../../src/tokenizer.ts"],"sourcesContent":["import { Location, Locator, findPosition } from './location';\nimport ParseError from './parse-error';\n\nexport enum TokenType {\n Bracket = 'Bracket',\n Curly = 'Curly',\n Equal = 'Equal',\n Comma = 'Comma',\n Dot = 'Dot',\n Comment = 'Comment',\n Literal = 'Literal'\n}\n\nexport interface Token {\n type: TokenType;\n raw: string;\n loc: Location;\n}\n\nexport const IS_WHITESPACE = /\\s/;\nexport const IS_NEW_LINE = /(\\r\\n|\\n)/;\nexport const IS_BARE_KEY = /^[\\w-]+$/;\nexport const DOUBLE_QUOTE = `\"`;\nexport const SINGLE_QUOTE = `'`;\nexport const SPACE = ' ';\nexport const ESCAPE = '\\\\';\n\nconst IS_VALID_LEADING_CHARACTER = /[\\w,\\d,\",',+,\\-,_]/;\n\n// Character code constants for hot-path comparisons\nconst CH_TAB = 0x09;\nconst CH_LF = 0x0a;\nconst CH_CR = 0x0d;\nconst CH_SPACE = 0x20;\nconst CH_HASH = 0x23;\nconst CH_COMMA = 0x2c;\nconst CH_DOT = 0x2e;\nconst CH_EQUAL = 0x3d;\nconst CH_LBRACKET = 0x5b;\nconst CH_RBRACKET = 0x5d;\nconst CH_LBRACE = 0x7b;\nconst CH_RBRACE = 0x7d;\nconst CH_DEL = 0x7f;\n\n/**\n * Mutable scan state used to detect mixed line endings while tokenizing.\n * The tokenizer updates this as it encounters newlines, so no second pass\n * over the input is required.\n */\nexport interface NewlineScanState {\n /** The first newline style seen, used as the reference for the document. */\n reference: '\\n' | '\\r\\n' | null;\n /** True once a newline style different from the reference is encountered. */\n mixed: boolean;\n}\n\n/** Creates an empty newline scan state for use with tokenize(). */\nexport function createNewlineScanState(): NewlineScanState {\n return { reference: null, mixed: false };\n}\n\nexport function* tokenize(input: string, newlineState?: NewlineScanState): IterableIterator<Token> {\n const len = input.length;\n let pos = 0;\n\n // Tracks mixed line endings without an extra pass: the first newline seen\n // sets the reference style and any later newline of the other style flags\n // the document as mixed.\n const nlState = newlineState ?? createNewlineScanState();\n\n // Build line index incrementally as we scan, instead of a separate\n // upfront findLines pass. Records newline positions in the main loop\n // and inside multilineToken.\n const lines: number[] = [];\n const locate: Locator = (start: number, end: number) => ({\n start: findPosition(lines, start),\n end: findPosition(lines, end)\n });\n\n while (pos < len) {\n const code = input.charCodeAt(pos);\n\n // TOML does not allow ASCII control characters other than HT (TAB), LF, and CR.\n // CR is only allowed as part of CRLF and is validated below.\n if ((code <= 0x1f || code === CH_DEL) && code !== CH_TAB && code !== CH_CR && code !== CH_LF) {\n throw new ParseError(\n input,\n findPosition(lines, pos),\n `Control char 0x${code.toString(16).toUpperCase().padStart(2, '0')} not allowed`\n );\n }\n\n // CR (0x0D) is only allowed as part of CRLF\n if (code === CH_CR) {\n if (pos + 1 >= len || input.charCodeAt(pos + 1) !== CH_LF) {\n throw new ParseError(\n input,\n findPosition(lines, pos),\n 'Standalone CR; must be CRLF or LF'\n );\n }\n }\n\n if (code === CH_SPACE || code === CH_TAB || code === CH_CR) {\n // skip non-newline whitespace (CR is part of CRLF; LF will be next)\n } else if (code === CH_LF) {\n recordNewline(pos);\n } else if (code === CH_LBRACKET || code === CH_RBRACKET) {\n yield { type: TokenType.Bracket, raw: input[pos], loc: locate(pos, pos + 1) };\n } else if (code === CH_LBRACE || code === CH_RBRACE) {\n yield { type: TokenType.Curly, raw: input[pos], loc: locate(pos, pos + 1) };\n } else if (code === CH_EQUAL) {\n yield { type: TokenType.Equal, raw: '=', loc: locate(pos, pos + 1) };\n } else if (code === CH_COMMA) {\n yield { type: TokenType.Comma, raw: ',', loc: locate(pos, pos + 1) };\n } else if (code === CH_DOT) {\n yield { type: TokenType.Dot, raw: '.', loc: locate(pos, pos + 1) };\n } else if (code === CH_HASH) {\n yield comment();\n } else {\n const multiline_char =\n checkThree(input, pos, SINGLE_QUOTE) ||\n checkThree(input, pos, DOUBLE_QUOTE);\n\n if (multiline_char) {\n yield multilineToken(multiline_char);\n } else {\n yield stringToken();\n }\n }\n\n pos++;\n }\n\n // ── Helper closures (capture pos by reference) ──────────────────────\n\n // Records a LF position in the incremental line index and updates the\n // mixed-newline scan state: the first style seen becomes the reference\n // and any later newline of the other style flags the document as mixed.\n function recordNewline(lfPos: number) {\n lines.push(lfPos);\n const style: '\\n' | '\\r\\n' = lfPos > 0 && input.charCodeAt(lfPos - 1) === CH_CR ? '\\r\\n' : '\\n';\n if (nlState.reference === null) {\n nlState.reference = style;\n } else if (nlState.reference !== style) {\n nlState.mixed = true;\n }\n }\n\n function comment(): Token {\n const start = pos;\n\n // TOML comment ends at CR or LF.\n while (pos + 1 < len) {\n const nextCode = input.charCodeAt(pos + 1);\n if (nextCode === CH_LF || nextCode === CH_CR) break;\n pos++;\n\n const cc = input.charCodeAt(pos);\n // Disallow ASCII control characters in comments (except HT / TAB).\n if ((cc <= 0x1f || cc === CH_DEL) && cc !== CH_TAB) {\n throw new ParseError(\n input,\n findPosition(lines, pos),\n `Control char 0x${cc.toString(16).toUpperCase().padStart(2, '0')} not allowed`\n );\n }\n }\n\n // Early exit is ok for comment, no closing conditions\n return {\n type: TokenType.Comment,\n raw: input.slice(start, pos + 1),\n loc: locate(start, pos + 1)\n };\n }\n\n function multilineToken(multiline_char: string): Token {\n const start = pos;\n const quotes = multiline_char + multiline_char + multiline_char;\n\n // Skip over opening quotes\n pos += 3;\n\n // Multiline strings close on the first unescaped \"\"\" / '''.\n // A run of 4 or 5 quote characters at the end is allowed to include 1 or 2 quotes\n // immediately before the closing delimiter, but 6+ consecutive quotes is invalid.\n while (pos < len) {\n const found = checkThree(input, pos, multiline_char);\n if (found) {\n let runLength = 3;\n while (input[pos + runLength] === multiline_char) {\n runLength++;\n }\n\n if (runLength >= 6) {\n throw new ParseError(\n input,\n findPosition(lines, pos),\n `Invalid multiline string: ${runLength} consecutive ${multiline_char} characters`\n );\n }\n\n if (runLength === 3) {\n // pos at first closing quote, advance to last closing quote\n pos += 2;\n break;\n }\n\n // runLength is 4 or 5: keep the leading 1 or 2 quote chars as content,\n // and close on the last 3.\n pos += runLength - 3; // skip content quotes\n pos += 2; // advance to last closing quote\n break;\n }\n\n const cc = input.charCodeAt(pos);\n\n if (cc === CH_CR) {\n if (pos + 1 >= len || input.charCodeAt(pos + 1) !== CH_LF) {\n throw new ParseError(\n input,\n findPosition(lines, pos),\n 'Standalone CR in multiline string; must be CRLF or LF'\n );\n }\n }\n\n // Validate control characters in multiline strings\n // In multiline strings, control characters are not allowed except tab (0x09), LF (0x0A), and CR (0x0D as part of CRLF)\n // DEL (0x7F) is also not allowed\n if ((cc <= 0x1f || cc === CH_DEL) && cc !== CH_TAB && cc !== CH_LF && cc !== CH_CR) {\n const stringType = multiline_char === DOUBLE_QUOTE ? 'multiline basic strings' : 'multiline literal strings';\n const hexCode = `0x${cc.toString(16).toUpperCase().padStart(2, '0')}`;\n\n // Provide friendly names for common control characters\n let charName = '';\n if (cc === 0x00) {\n charName = 'Null';\n } else if (cc === CH_DEL) {\n charName = 'DEL';\n }\n\n const message = charName\n ? `${charName} (${hexCode}) not allowed in ${stringType}`\n : `Control char ${hexCode} not allowed in ${stringType}`;\n\n throw new ParseError(\n input,\n findPosition(lines, pos),\n message\n );\n }\n\n // Record newlines inside multiline strings for incremental line index\n if (cc === CH_LF) {\n recordNewline(pos);\n }\n\n pos++;\n }\n\n if (pos >= len) {\n // Check if the issue might be caused by escape sequences preventing proper closure\n // For multiline basic strings (\"\"\"), check if there are backslashes near the end that might be escaping quotes\n if (multiline_char === DOUBLE_QUOTE) {\n // Count trailing backslashes before EOF\n let bsCount = 0;\n let bi = len - 1;\n while (bi >= 0 && input[bi] === '\\\\') { bsCount++; bi--; }\n const hasEscapedQuotes = bsCount > 0 && bsCount % 2 !== 0;\n\n if (hasEscapedQuotes) {\n throw new ParseError(\n input,\n findPosition(lines, pos),\n `Unterminated multiline ${quotes} (possible escape issue)`\n );\n }\n }\n\n throw new ParseError(\n input,\n findPosition(lines, pos),\n `Unterminated multiline ${quotes}`\n );\n }\n\n return {\n type: TokenType.Literal,\n raw: input.slice(start, pos + 1),\n loc: locate(start, pos + 1)\n };\n }\n\n function stringToken(): Token {\n // Remaining possibilities: keys, strings, literals, integer, float, boolean\n //\n // Special cases:\n // \"...\" -> quoted\n // '...' -> quoted\n // \"...\".'...' -> bare\n // 0000-00-00 00:00:00 -> bare\n //\n // See https://github.com/toml-lang/toml#offset-date-time\n //\n // | For the sake of readability, you may replace the T delimiter between date and time with a space (as permitted by RFC 3339 section 5.6).\n // | `odt4 = 1979-05-27 07:32:00Z`\n //\n // From RFC 3339:\n //\n // | NOTE: ISO 8601 defines date and time separated by \"T\".\n // | Applications using this syntax may choose, for the sake of\n // | readability, to specify a full-date and full-time separated by\n // | (say) a space character.\n\n const ch = input[pos];\n\n // First, check for invalid characters\n if (!IS_VALID_LEADING_CHARACTER.test(ch)) {\n throw new ParseError(\n input,\n findPosition(lines, pos),\n `Unexpected char \"${ch}\"`\n );\n }\n\n const start = pos;\n let double_quoted = ch === DOUBLE_QUOTE;\n let single_quoted = ch === SINGLE_QUOTE;\n\n while (pos < len) {\n // Peek at next character – if none, we're done\n if (pos + 1 >= len) break;\n\n const nextCode = input.charCodeAt(pos + 1);\n\n // isFinished: if not inside quotes and next char is a terminator, stop\n if (!(double_quoted || single_quoted)) {\n if (\n nextCode === CH_SPACE || nextCode === CH_TAB ||\n nextCode === CH_LF || nextCode === CH_CR ||\n nextCode === CH_COMMA || nextCode === CH_DOT ||\n nextCode === CH_RBRACKET || nextCode === CH_RBRACE ||\n nextCode === CH_EQUAL || nextCode === CH_HASH\n ) {\n break;\n }\n }\n\n // Advance to next character\n pos++;\n\n // Bare literals must not contain ASCII control chars.\n if (!(double_quoted || single_quoted)) {\n const cc = input.charCodeAt(pos);\n if (cc <= 0x1f || cc === CH_DEL) {\n throw new ParseError(\n input,\n findPosition(lines, pos),\n `Control char 0x${cc.toString(16).toUpperCase().padStart(2, '0')} not allowed in unquoted value`\n );\n }\n }\n\n // Validate control characters in quoted strings\n if (double_quoted || single_quoted) {\n const cc = input.charCodeAt(pos);\n // In basic strings (double-quoted) and literal strings (single-quoted),\n // control characters are not allowed except tab (0x09)\n // DEL (0x7F) is also not allowed\n if ((cc <= 0x1f || cc === CH_DEL) && cc !== CH_TAB) {\n const stringType = double_quoted ? 'basic strings' : 'literal strings';\n const hexCode = `0x${cc.toString(16).toUpperCase().padStart(2, '0')}`;\n\n // Provide friendly names for common control characters\n let charName = '';\n if (cc === CH_LF) {\n charName = 'Newline';\n } else if (cc === CH_CR) {\n charName = 'Carriage return';\n } else if (cc === 0x00) {\n charName = 'Null';\n } else if (cc === CH_DEL) {\n charName = 'DEL';\n }\n\n const message = charName\n ? `${charName} (${hexCode}) not allowed in ${stringType}`\n : `Control char ${hexCode} not allowed in ${stringType}`;\n\n throw new ParseError(\n input,\n findPosition(lines, pos),\n message\n );\n }\n }\n\n const currentChar = input[pos];\n if (currentChar === DOUBLE_QUOTE && !single_quoted) double_quoted = !double_quoted;\n if (currentChar === SINGLE_QUOTE && !double_quoted) single_quoted = !single_quoted;\n\n if (pos + 1 >= len) break;\n\n // If next character is escape and currently double-quoted,\n // check for escaped quote\n if (double_quoted && currentChar === ESCAPE) {\n const nextChar = input[pos + 1];\n if (nextChar === DOUBLE_QUOTE || nextChar === ESCAPE) {\n pos++; // skip escaped char\n }\n }\n }\n\n if (double_quoted || single_quoted) {\n throw new ParseError(\n input,\n findPosition(lines, start),\n `Expected close of string with ${double_quoted ? DOUBLE_QUOTE : SINGLE_QUOTE}`\n );\n }\n\n return {\n type: TokenType.Literal,\n raw: input.slice(start, pos + 1),\n loc: locate(start, pos + 1)\n };\n }\n}\n\n/**\n * Check if the current character and the next two characters are the same\n * and not escaped.\n *\n * @param input - The input string.\n * @param current - The current index in the input string.\n * @param check - The character to check for.\n * @returns ⚠️The character if found, otherwise false.\n */\nfunction checkThree(input: string, current: number, check: string): false | string {\n if (!check) {\n return false;\n }\n\n const has3 =\n input[current] === check &&\n input[current + 1] === check &&\n input[current + 2] === check;\n\n if (!has3) {\n return false;\n }\n\n // Only check for escaping in basic strings (double quotes)\n // Literal strings (single quotes) don't support escape sequences\n if (check === SINGLE_QUOTE) {\n return check; // No escaping in literal strings\n }\n\n // Check if the sequence is escaped by counting preceding backslashes\n let bsCount = 0;\n let i = current - 1;\n while (i >= 0 && input[i] === '\\\\') {\n bsCount++;\n i--;\n }\n\n if (bsCount === 0) {\n return check; // No backslashes means not escaped\n }\n\n const isEscaped = bsCount % 2 !== 0; // Odd number of backslashes means escaped\n\n return isEscaped ? false : check; // Return `check` if not escaped, otherwise `false`\n}\n"],"mappings":";;;;;AAqBA,MAAa,cAAc;AAC3B,MAAa,eAAe;AAC5B,MAAa,eAAe;AAE5B,MAAa,SAAS;AAEtB,MAAM,6BAA6B;AAGnC,MAAM,SAAS;AACf,MAAM,QAAQ;AACd,MAAM,QAAQ;AACd,MAAM,WAAW;AACjB,MAAM,UAAU;AAChB,MAAM,WAAW;AACjB,MAAM,SAAS;AACf,MAAM,WAAW;AACjB,MAAM,cAAc;AACpB,MAAM,cAAc;AACpB,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,SAAS;;AAef,SAAgB,yBAA2C;CACzD,OAAO;EAAE,WAAW;EAAM,OAAO;CAAM;AACzC;AAEA,UAAiB,SAAS,OAAe,cAA0D;CACjG,MAAM,MAAM,MAAM;CAClB,IAAI,MAAM;CAKV,MAAM,UAAU,gBAAgB,uBAAuB;CAKvD,MAAM,QAAkB,CAAC;CACzB,MAAM,UAAmB,OAAe,SAAiB;EACvD,OAAO,aAAa,OAAO,KAAK;EAChC,KAAK,aAAa,OAAO,GAAG;CAC9B;CAEA,OAAO,MAAM,KAAK;EAChB,MAAM,OAAO,MAAM,WAAW,GAAG;EAIjC,KAAK,QAAQ,MAAQ,SAAS,WAAW,SAAS,UAAU,SAAS,SAAS,SAAS,OACrF,MAA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GF,OAAO;GACL;GACA,KAAK,MAAM,MAAM,OAAO,MAAM,CAAC;GAC/B,KAAK,OAAO,OAAO,MAAM,CAAC;EAC5B;CACF;AACF;;;;;;;;;;AAWA,SAAS,WAAW,OAAe,SAAiB,OAA+B;CACjF,IAAI,CAAC,OACH,OAAO;CAQT,IAAI,EAJF,MAAM,aAAa,SACnB,MAAM,UAAU,OAAO,SACvB,MAAM,UAAU,OAAO,QAGvB,OAAO;CAKT,IAAI,UAAU,cACZ,OAAO;CAIT,IAAI,UAAU;CACd,IAAI,IAAI,UAAU;CAClB,OAAO,KAAK,KAAK,MAAM,OAAO,MAAM;EAClC;EACA;CACF;CAEA,IAAI,YAAY,GACd,OAAO;CAKT,OAFkB,UAAU,MAAM,IAEf,QAAQ;AAC7B"}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
//! @decimalturn/toml-patch v3.3.0 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
|
+
import parseTOML, { continueParsingTOML } from "./parse-toml.js";
|
|
3
|
+
import { isObject } from "./utils.js";
|
|
4
|
+
import { decodeUtf8Bytes, hasLeadingBom, stripLeadingBom } from "./decode-utf8.js";
|
|
5
|
+
import { TomlFormat, detectNewline, resolveTomlFormat } from "./toml-format.js";
|
|
6
|
+
import { attachSources } from "./cst-source.js";
|
|
7
|
+
import toJS from "./to-js.js";
|
|
8
|
+
import { patchCst } from "./patch.js";
|
|
9
|
+
import { truncateCst } from "./truncate.js";
|
|
10
|
+
|
|
11
|
+
//#region src/toml-document.ts
|
|
12
|
+
/**
|
|
13
|
+
* TomlDocument encapsulates a TOML CST and provides methods to interact with it.
|
|
14
|
+
*/
|
|
15
|
+
var TomlDocument = class {
|
|
16
|
+
_cst;
|
|
17
|
+
_currentTomlString;
|
|
18
|
+
_format;
|
|
19
|
+
_integersAsBigInt;
|
|
20
|
+
_temporal;
|
|
21
|
+
/**
|
|
22
|
+
* Initializes the TomlDocument with TOML source, parsing it into a CST.
|
|
23
|
+
*
|
|
24
|
+
* When bytes are provided, they are decoded as UTF-8 in fatal mode.
|
|
25
|
+
* This rejects invalid UTF-8 sequences before parsing.
|
|
26
|
+
*
|
|
27
|
+
* @param tomlSource - The TOML source to parse (string or raw UTF-8 bytes)
|
|
28
|
+
* @param options - Optional parse options
|
|
29
|
+
* @param options.integersAsBigInt - Controls bigint vs number for TOML integers
|
|
30
|
+
* @param options.temporal - When true, returns Temporal objects for date/time values
|
|
31
|
+
*/
|
|
32
|
+
constructor(tomlSource, options) {
|
|
33
|
+
const sourceString = typeof tomlSource === "string" ? tomlSource : decodeUtf8Bytes(tomlSource);
|
|
34
|
+
const tomlString = stripLeadingBom(sourceString);
|
|
35
|
+
this._currentTomlString = tomlString;
|
|
36
|
+
this._cst = Array.from(parseTOML(tomlString));
|
|
37
|
+
this._integersAsBigInt = (options === null || options === void 0 ? void 0 : options.integersAsBigInt) ?? "asNeeded";
|
|
38
|
+
this._temporal = (options === null || options === void 0 ? void 0 : options.temporal) ?? false;
|
|
39
|
+
this._format = TomlFormat.autoDetectFormatWithCst(sourceString, this._cst);
|
|
40
|
+
}
|
|
41
|
+
get toTomlString() {
|
|
42
|
+
return this._format.leadingBom ? `${""}${this._currentTomlString}` : this._currentTomlString;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Returns the JavaScript object representation of the TOML document.
|
|
46
|
+
*/
|
|
47
|
+
get toJsObject() {
|
|
48
|
+
const jsObject = toJS(this._cst, this._currentTomlString, {
|
|
49
|
+
integersAsBigInt: this._integersAsBigInt,
|
|
50
|
+
temporal: this._temporal
|
|
51
|
+
});
|
|
52
|
+
if (this._temporal) return jsObject;
|
|
53
|
+
return convertCustomDateClasses(jsObject);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Returns the internal CST (for testing purposes).
|
|
57
|
+
* @internal
|
|
58
|
+
*/
|
|
59
|
+
get cst() {
|
|
60
|
+
return this._cst;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Applies a patch to the current CST using a modified JS object.
|
|
64
|
+
* Updates the internal CST. Use toTomlString getter to retrieve the updated TOML string.
|
|
65
|
+
*
|
|
66
|
+
* @param updatedObject - The modified JS object to patch with
|
|
67
|
+
* @param format - Optional formatting options
|
|
68
|
+
*/
|
|
69
|
+
patch(updatedObject, format) {
|
|
70
|
+
const fmt = resolveTomlFormat(format, this._format);
|
|
71
|
+
const sourceBefore = this._currentTomlString;
|
|
72
|
+
if (!this._temporal && hasPlainDate(updatedObject)) {
|
|
73
|
+
const originalObject = toJS(this._cst, sourceBefore, {
|
|
74
|
+
integersAsBigInt: this._integersAsBigInt,
|
|
75
|
+
temporal: false
|
|
76
|
+
});
|
|
77
|
+
updatedObject = restoreDateRepresentations(updatedObject, originalObject);
|
|
78
|
+
}
|
|
79
|
+
const indentWidthExplicit = format instanceof TomlFormat || format != null && Object.prototype.hasOwnProperty.call(format, "indentWidth");
|
|
80
|
+
const trailingCommaExplicit = format instanceof TomlFormat || format != null && Object.prototype.hasOwnProperty.call(format, "trailingComma");
|
|
81
|
+
attachSources(this._cst, sourceBefore);
|
|
82
|
+
const result = patchCst(this._cst, updatedObject, fmt, indentWidthExplicit, trailingCommaExplicit);
|
|
83
|
+
this._cst = Array.from(parseTOML(result.tomlString));
|
|
84
|
+
this._format = fmt;
|
|
85
|
+
this._currentTomlString = result.tomlString;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Updates the internal document by supplying a modified tomlString.
|
|
89
|
+
* Use toJsObject getter to retrieve the updated JS object representation.
|
|
90
|
+
* @param tomlString - The modified TOML string to update with
|
|
91
|
+
*/
|
|
92
|
+
update(tomlString) {
|
|
93
|
+
const tomlContent = stripLeadingBom(tomlString);
|
|
94
|
+
if (tomlContent === this._currentTomlString) {
|
|
95
|
+
this._format.leadingBom = hasLeadingBom(tomlString);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const existingLines = this._currentTomlString.split(this._format.newLine);
|
|
99
|
+
const newLineChar = detectNewline(tomlContent);
|
|
100
|
+
const newTextLines = tomlContent.split(newLineChar);
|
|
101
|
+
let firstDiffLineIndex = 0;
|
|
102
|
+
while (firstDiffLineIndex < existingLines.length && firstDiffLineIndex < newTextLines.length && existingLines[firstDiffLineIndex] === newTextLines[firstDiffLineIndex]) firstDiffLineIndex++;
|
|
103
|
+
let firstDiffColumn = 0;
|
|
104
|
+
if (firstDiffLineIndex < existingLines.length && firstDiffLineIndex < newTextLines.length) {
|
|
105
|
+
const existingLine = existingLines[firstDiffLineIndex];
|
|
106
|
+
const newLine = newTextLines[firstDiffLineIndex];
|
|
107
|
+
for (let i = 0; i < Math.max(existingLine.length, newLine.length); i++) if (existingLine[i] !== newLine[i]) {
|
|
108
|
+
firstDiffColumn = i;
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
let firstDiffLine = firstDiffLineIndex + 1;
|
|
113
|
+
const { truncatedCst, lastEndPosition } = truncateCst(this._cst, firstDiffLine, firstDiffColumn);
|
|
114
|
+
const continueFromLine = lastEndPosition ? lastEndPosition.line : 1;
|
|
115
|
+
const continueFromColumn = lastEndPosition ? lastEndPosition.column + 1 : 0;
|
|
116
|
+
const remainingLines = newTextLines.slice(continueFromLine - 1);
|
|
117
|
+
if (remainingLines.length > 0 && continueFromColumn > 0) remainingLines[0] = remainingLines[0].substring(continueFromColumn);
|
|
118
|
+
const remainingToml = remainingLines.join(this._format.newLine);
|
|
119
|
+
this._cst = Array.from(continueParsingTOML(truncatedCst, remainingToml, {
|
|
120
|
+
line: continueFromLine,
|
|
121
|
+
column: continueFromColumn
|
|
122
|
+
}));
|
|
123
|
+
this._currentTomlString = tomlContent;
|
|
124
|
+
this._format = TomlFormat.autoDetectFormatWithCst(tomlString, this._cst);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Overwrites the internal syntax tree by fully re-parsing the supplied tomlString.
|
|
128
|
+
* This is simpler but slower than update() which uses incremental parsing.
|
|
129
|
+
* @param tomlString - The TOML string to overwrite with
|
|
130
|
+
*/
|
|
131
|
+
overwrite(tomlString) {
|
|
132
|
+
const tomlContent = stripLeadingBom(tomlString);
|
|
133
|
+
if (tomlContent === this._currentTomlString) {
|
|
134
|
+
this._format.leadingBom = hasLeadingBom(tomlString);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
this._cst = Array.from(parseTOML(tomlContent));
|
|
138
|
+
this._currentTomlString = tomlContent;
|
|
139
|
+
this._format = TomlFormat.autoDetectFormatWithCst(tomlString, this._cst);
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
/**
|
|
143
|
+
* True when `value` holds a plain `Date` anywhere, i.e. one of the objects
|
|
144
|
+
* toJsObject() produced by stripping a TOML date class. Used to skip the work
|
|
145
|
+
* in restoreDateRepresentations() for the common case of a document with no
|
|
146
|
+
* dates in it. Cycle-safe.
|
|
147
|
+
*/
|
|
148
|
+
function hasPlainDate(value, seen = /* @__PURE__ */ new WeakSet()) {
|
|
149
|
+
if (value instanceof Date) return value.constructor === Date;
|
|
150
|
+
if (!value || typeof value !== "object") return false;
|
|
151
|
+
if (seen.has(value)) return false;
|
|
152
|
+
seen.add(value);
|
|
153
|
+
if (Array.isArray(value)) return value.some((item) => hasPlainDate(item, seen));
|
|
154
|
+
return Object.keys(value).some((key) => hasPlainDate(value[key], seen));
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Re-attaches the TOML date representation that toJsObject() strips.
|
|
158
|
+
*
|
|
159
|
+
* toJsObject() deliberately hands out plain `Date` objects so that callers get
|
|
160
|
+
* the standard Date contract, notably a standard toISOString(). But the writer
|
|
161
|
+
* derives a value's TOML text from toISOString(), and the TOML date classes
|
|
162
|
+
* override it to return the original spelling. A plain Date handed back in
|
|
163
|
+
* therefore writes as a full offset date-time, so read-modify-write turned
|
|
164
|
+
* `1986-03-02` into `1986-03-02T00:00:00.000Z` whenever the surrounding node was
|
|
165
|
+
* rewritten rather than preserved from the CST.
|
|
166
|
+
*
|
|
167
|
+
* Where the caller left a date alone (still a plain Date, same instant), the
|
|
168
|
+
* original typed instance goes back in so the original spelling is written. A
|
|
169
|
+
* date whose instant actually changed is left as-is: only the caller knows
|
|
170
|
+
* whether a new instant is still meant to be a local date, and they can say so
|
|
171
|
+
* by passing LocalDate / LocalTime / LocalDateTime / OffsetDateTime, which are
|
|
172
|
+
* exported for that purpose. Instances of those classes are never touched.
|
|
173
|
+
*
|
|
174
|
+
* The caller's object is not mutated; a node is copied only when something
|
|
175
|
+
* beneath it changed, so an untouched tree is returned by reference.
|
|
176
|
+
*/
|
|
177
|
+
function restoreDateRepresentations(updated, original, seen = /* @__PURE__ */ new WeakSet()) {
|
|
178
|
+
if (updated instanceof Date) return updated.constructor === Date && original instanceof Date && original.constructor !== Date && original.getTime() === updated.getTime() ? original : updated;
|
|
179
|
+
if (!updated || typeof updated !== "object" || seen.has(updated)) return updated;
|
|
180
|
+
seen.add(updated);
|
|
181
|
+
if (Array.isArray(updated)) {
|
|
182
|
+
if (!Array.isArray(original)) return updated;
|
|
183
|
+
let changed = false;
|
|
184
|
+
const restored = updated.map((item, index) => {
|
|
185
|
+
const next = restoreDateRepresentations(item, original[index], seen);
|
|
186
|
+
if (next !== item) changed = true;
|
|
187
|
+
return next;
|
|
188
|
+
});
|
|
189
|
+
return changed ? restored : updated;
|
|
190
|
+
}
|
|
191
|
+
if (!isObject(original)) return updated;
|
|
192
|
+
let changed = false;
|
|
193
|
+
const restored = {};
|
|
194
|
+
for (const key of Object.keys(updated)) {
|
|
195
|
+
const value = updated[key];
|
|
196
|
+
const next = restoreDateRepresentations(value, original[key], seen);
|
|
197
|
+
restored[key] = next;
|
|
198
|
+
if (next !== value) changed = true;
|
|
199
|
+
}
|
|
200
|
+
return changed ? restored : updated;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Recursively converts custom date classes to regular JavaScript Date objects.
|
|
204
|
+
* This ensures that the toJsObject property returns standard Date objects
|
|
205
|
+
* while preserving the custom classes internally for TOML formatting.
|
|
206
|
+
*/
|
|
207
|
+
function convertCustomDateClasses(obj) {
|
|
208
|
+
if (obj instanceof Date) return new Date(obj.getTime());
|
|
209
|
+
else if (Array.isArray(obj)) return obj.map(convertCustomDateClasses);
|
|
210
|
+
else if (obj && typeof obj === "object") {
|
|
211
|
+
const result = {};
|
|
212
|
+
for (const [key, value] of Object.entries(obj)) result[key] = convertCustomDateClasses(value);
|
|
213
|
+
return result;
|
|
214
|
+
}
|
|
215
|
+
return obj;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
//#endregion
|
|
219
|
+
export { TomlDocument };
|
|
220
|
+
//# sourceMappingURL=toml-document.js.map
|