@decimalturn/toml-patch 3.1.1-dev → 3.1.2-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 +1 -1
- package/dist/dev/comment-ownership.js +1 -1
- package/dist/dev/cst-source.js +12 -2
- package/dist/dev/cst-source.js.map +1 -1
- package/dist/dev/cst.js +1 -1
- package/dist/dev/cursor.js +1 -1
- package/dist/dev/date-format.js +1 -1
- package/dist/dev/decode-utf8.js +1 -1
- package/dist/dev/diff.js +1 -1
- package/dist/dev/escape-preference.js +1 -1
- package/dist/dev/find-by-path.js +1 -1
- package/dist/dev/formatter.js +5 -2
- package/dist/dev/formatter.js.map +1 -1
- package/dist/dev/generate.js +1 -1
- package/dist/dev/inline-comma-space.js +1 -1
- package/dist/dev/inline-format.js +1 -1
- package/dist/dev/inline-layout.js +1 -1
- package/dist/dev/line-ending-backslash.js +1 -1
- package/dist/dev/location.js +1 -1
- package/dist/dev/parse-error.js +1 -1
- package/dist/dev/parse-js.js +8 -4
- package/dist/dev/parse-js.js.map +1 -1
- package/dist/dev/parse-string.js +1 -1
- package/dist/dev/parse-toml.js +47 -10
- package/dist/dev/parse-toml.js.map +1 -1
- package/dist/dev/patch.js +5 -2
- package/dist/dev/patch.js.map +1 -1
- package/dist/dev/to-js.js +1 -1
- package/dist/dev/to-toml.js +308 -3
- package/dist/dev/to-toml.js.map +1 -1
- package/dist/dev/tokenizer.js +1 -1
- package/dist/dev/toml-document.js +7 -2
- package/dist/dev/toml-document.js.map +1 -1
- package/dist/dev/toml-format.js +1 -1
- package/dist/dev/toml-patch.js +14 -4
- package/dist/dev/toml-patch.js.map +1 -1
- package/dist/dev/traverse.js +1 -1
- package/dist/dev/truncate.js +1 -1
- package/dist/dev/update-order.js +1 -1
- package/dist/dev/utils.js +1 -1
- package/dist/dev/writer.js +5 -5
- package/dist/dev/writer.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toml-document.js","names":[],"sources":["../../src/toml-document.ts"],"sourcesContent":["import parseTOML, { continueParsingTOML } from './parse-toml';\nimport toJS from './to-js';\nimport { TomlFormat } from './toml-format';\nimport { Block } from './cst';\nimport { patchCst } from './patch';\nimport { detectNewline, resolveTomlFormat } from './toml-format';\nimport { truncateCst } from './truncate';\nimport type { ParseOptions, IntegersAsBigInt } from './parse-options';\nimport { decodeUtf8Bytes, hasLeadingBom, stripLeadingBom, UTF8_BOM } from './decode-utf8';\nimport { isObject } from './utils';\n\n/**\n * TomlDocument encapsulates a TOML CST and provides methods to interact with it.\n */\nexport class TomlDocument {\n private _cst: Block[];\n private _currentTomlString: string;\n private _format: TomlFormat;\n private _integersAsBigInt: IntegersAsBigInt;\n private _temporal: boolean;\n\n /**\n * Initializes the TomlDocument with TOML source, parsing it into a CST.\n *\n * When bytes are provided, they are decoded as UTF-8 in fatal mode.\n * This rejects invalid UTF-8 sequences before parsing.\n *\n * @param tomlSource - The TOML source to parse (string or raw UTF-8 bytes)\n * @param options - Optional parse options\n * @param options.integersAsBigInt - Controls bigint vs number for TOML integers\n * @param options.temporal - When true, returns Temporal objects for date/time values\n */\n constructor(tomlSource: string | Uint8Array, options?: ParseOptions) {\n const sourceString = typeof tomlSource === 'string'\n ? tomlSource\n : decodeUtf8Bytes(tomlSource);\n const tomlString = stripLeadingBom(sourceString);\n\n this._currentTomlString = tomlString;\n this._cst = Array.from(parseTOML(tomlString));\n this._integersAsBigInt = options?.integersAsBigInt ?? 'asNeeded';\n this._temporal = options?.temporal ?? false;\n // Auto-detect formatting preferences from the original TOML string\n this._format = TomlFormat.autoDetectFormatWithCst(sourceString, this._cst);\n }\n\n get toTomlString(): string {\n return this._format.leadingBom ? `${UTF8_BOM}${this._currentTomlString}` : this._currentTomlString;\n }\n\n /**\n * Returns the JavaScript object representation of the TOML document.\n */\n get toJsObject(): any {\n const jsObject = toJS(this._cst, this._currentTomlString, {\n integersAsBigInt: this._integersAsBigInt,\n temporal: this._temporal\n });\n // When temporal is enabled, Temporal objects are already returned — no conversion needed.\n // When temporal is disabled, convert custom date classes to regular JavaScript Date objects.\n if (this._temporal) {\n return jsObject;\n }\n return convertCustomDateClasses(jsObject);\n }\n\n /**\n * Returns the internal CST (for testing purposes).\n * @internal\n */\n get cst(): Block[] {\n return this._cst;\n }\n\n /**\n * Applies a patch to the current CST using a modified JS object.\n * Updates the internal CST. Use toTomlString getter to retrieve the updated TOML string.\n *\n * @param updatedObject - The modified JS object to patch with\n * @param format - Optional formatting options\n */\n patch(updatedObject: any, format?: Partial<TomlFormat> | TomlFormat) : void {\n\n const fmt = resolveTomlFormat(format, this._format);\n\n const sourceBefore = this._currentTomlString;\n\n // Only worth deriving the pre-patch values when a stripped date could\n // actually be present; temporal mode hands out Temporal objects untouched.\n if (!this._temporal && hasPlainDate(updatedObject)) {\n const originalObject = toJS(this._cst, sourceBefore, {\n integersAsBigInt: this._integersAsBigInt,\n temporal: false\n });\n updatedObject = restoreDateRepresentations(updatedObject, originalObject);\n }\n\n const indentWidthExplicit = format instanceof TomlFormat ||\n (format != null && Object.prototype.hasOwnProperty.call(format, 'indentWidth'));\n const trailingCommaExplicit = format instanceof TomlFormat ||\n (format != null && Object.prototype.hasOwnProperty.call(format, 'trailingComma'));\n const result = patchCst(\n this._cst,\n updatedObject,\n fmt,\n indentWidthExplicit,\n trailingCommaExplicit\n );\n this._cst = Array.from(parseTOML(result.tomlString));\n this._format = fmt;\n this._currentTomlString = result.tomlString;\n }\n\n /**\n * Updates the internal document by supplying a modified tomlString.\n * Use toJsObject getter to retrieve the updated JS object representation.\n * @param tomlString - The modified TOML string to update with\n */\n update(tomlString: string): void {\n const tomlContent = stripLeadingBom(tomlString);\n\n if (tomlContent === this._currentTomlString) {\n this._format.leadingBom = hasLeadingBom(tomlString);\n return;\n }\n\n // Now, let's check where the first difference is\n const existingLines = this._currentTomlString.split(this._format.newLine);\n const newLineChar = detectNewline(tomlContent);\n const newTextLines = tomlContent.split(newLineChar);\n let firstDiffLineIndex = 0;\n while (\n firstDiffLineIndex < existingLines.length &&\n firstDiffLineIndex < newTextLines.length &&\n existingLines[firstDiffLineIndex] === newTextLines[firstDiffLineIndex]\n ) {\n firstDiffLineIndex++;\n }\n\n // Calculate the 1-based line number and 0-based column where the first difference occurs\n \n let firstDiffColumn = 0;\n \n // If we're within the bounds of both arrays, find the column where they differ\n if (firstDiffLineIndex < existingLines.length && firstDiffLineIndex < newTextLines.length) {\n const existingLine = existingLines[firstDiffLineIndex];\n const newLine = newTextLines[firstDiffLineIndex];\n \n // Find the first character position where the lines differ\n for (let i = 0; i < Math.max(existingLine.length, newLine.length); i++) {\n if (existingLine[i] !== newLine[i]) {\n firstDiffColumn = i;\n break;\n }\n }\n }\n\n let firstDiffLine = firstDiffLineIndex + 1; // Convert to 1-based\n const { truncatedCst, lastEndPosition } = truncateCst(this._cst, firstDiffLine, firstDiffColumn);\n\n // Determine where to continue parsing from in the new string\n // If lastEndPosition exists, continue from there; otherwise from the start of the document\n const continueFromLine = lastEndPosition ? lastEndPosition.line : 1;\n const continueFromColumn = lastEndPosition ? lastEndPosition.column + 1 : 0;\n\n // Based on the first difference, we can re-parse only the affected part\n // We will need to supply the remaining string after where the CST was truncated\n const remainingLines = newTextLines.slice(continueFromLine - 1);\n \n // If there's a partial line match, we need to extract only the part after the continuation column\n if (remainingLines.length > 0 && continueFromColumn > 0) {\n remainingLines[0] = remainingLines[0].substring(continueFromColumn);\n }\n \n const remainingToml = remainingLines.join(this._format.newLine);\n \n this._cst = Array.from(continueParsingTOML(truncatedCst, remainingToml));\n this._currentTomlString = tomlContent;\n \n // Update the auto-detected format with the new string's characteristics\n this._format = TomlFormat.autoDetectFormatWithCst(tomlString, this._cst);\n }\n\n /**\n * Overwrites the internal syntax tree by fully re-parsing the supplied tomlString.\n * This is simpler but slower than update() which uses incremental parsing.\n * @param tomlString - The TOML string to overwrite with\n */\n overwrite(tomlString: string): void {\n const tomlContent = stripLeadingBom(tomlString);\n\n if (tomlContent === this._currentTomlString) {\n this._format.leadingBom = hasLeadingBom(tomlString);\n return;\n }\n\n // Re-parse the entire document\n this._cst = Array.from(parseTOML(tomlContent));\n this._currentTomlString = tomlContent;\n \n // Update the auto-detected format with the new string's characteristics\n this._format = TomlFormat.autoDetectFormatWithCst(tomlString, this._cst);\n }\n}\n\n/**\n * True when `value` holds a plain `Date` anywhere, i.e. one of the objects\n * toJsObject() produced by stripping a TOML date class. Used to skip the work\n * in restoreDateRepresentations() for the common case of a document with no\n * dates in it. Cycle-safe.\n */\nfunction hasPlainDate(value: any, seen: WeakSet<object> = new WeakSet()): boolean {\n if (value instanceof Date) return value.constructor === Date;\n if (!value || typeof value !== 'object') return false;\n if (seen.has(value)) return false;\n seen.add(value);\n if (Array.isArray(value)) return value.some(item => hasPlainDate(item, seen));\n return Object.keys(value).some(key => hasPlainDate(value[key], seen));\n}\n\n/**\n * Re-attaches the TOML date representation that toJsObject() strips.\n *\n * toJsObject() deliberately hands out plain `Date` objects so that callers get\n * the standard Date contract, notably a standard toISOString(). But the writer\n * derives a value's TOML text from toISOString(), and the TOML date classes\n * override it to return the original spelling. A plain Date handed back in\n * therefore writes as a full offset date-time, so read-modify-write turned\n * `1986-03-02` into `1986-03-02T00:00:00.000Z` whenever the surrounding node was\n * rewritten rather than preserved from the CST.\n *\n * Where the caller left a date alone (still a plain Date, same instant), the\n * original typed instance goes back in so the original spelling is written. A\n * date whose instant actually changed is left as-is: only the caller knows\n * whether a new instant is still meant to be a local date, and they can say so\n * by passing LocalDate / LocalTime / LocalDateTime / OffsetDateTime, which are\n * exported for that purpose. Instances of those classes are never touched.\n *\n * The caller's object is not mutated; a node is copied only when something\n * beneath it changed, so an untouched tree is returned by reference.\n */\nfunction restoreDateRepresentations(updated: any, original: any, seen: WeakSet<object> = new WeakSet()): any {\n if (updated instanceof Date) {\n const erased = updated.constructor === Date\n && original instanceof Date\n && original.constructor !== Date\n && original.getTime() === updated.getTime();\n return erased ? original : updated;\n }\n if (!updated || typeof updated !== 'object' || seen.has(updated)) return updated;\n seen.add(updated);\n\n if (Array.isArray(updated)) {\n if (!Array.isArray(original)) return updated;\n let changed = false;\n const restored = updated.map((item, index) => {\n const next = restoreDateRepresentations(item, original[index], seen);\n if (next !== item) changed = true;\n return next;\n });\n return changed ? restored : updated;\n }\n\n if (!isObject(original)) return updated;\n let changed = false;\n const restored: Record<string, any> = {};\n for (const key of Object.keys(updated)) {\n const value = updated[key];\n const next = restoreDateRepresentations(value, original[key], seen);\n restored[key] = next;\n if (next !== value) changed = true;\n }\n return changed ? restored : updated;\n}\n\n/**\n * Recursively converts custom date classes to regular JavaScript Date objects.\n * This ensures that the toJsObject property returns standard Date objects\n * while preserving the custom classes internally for TOML formatting.\n */\nfunction convertCustomDateClasses(obj: any): any {\n if (obj instanceof Date) {\n // Convert custom date classes to regular Date objects\n return new Date(obj.getTime());\n } else if (Array.isArray(obj)) {\n return obj.map(convertCustomDateClasses);\n } else if (obj && typeof obj === 'object') {\n const result: any = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = convertCustomDateClasses(value);\n }\n return result;\n }\n return obj;\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,IAAa,eAAb,MAA0B;CACxB,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;;;;;;;;;;;;CAaR,YAAY,YAAiC,SAAwB;EACnE,MAAM,eAAe,OAAO,eAAe,WACvC,aACA,gBAAgB,UAAU;EAC9B,MAAM,aAAa,gBAAgB,YAAY;EAE/C,KAAK,qBAAqB;EAC1B,KAAK,OAAO,MAAM,KAAK,UAAU,UAAU,CAAC;EAC5C,KAAK,uEAAoB,QAAS,qBAAoB;EACtD,KAAK,+DAAY,QAAS,aAAY;EAEtC,KAAK,UAAU,WAAW,wBAAwB,cAAc,KAAK,IAAI;CAC3E;CAEA,IAAI,eAAuB;EACzB,OAAO,KAAK,QAAQ,aAAa,SAAc,KAAK,uBAAuB,KAAK;CAClF;;;;C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M,QAAQ,GAAG,GAC1B,OAAO,IAAI,IAAI,wBAAwB;MAClC,IAAI,OAAO,OAAO,QAAQ,UAAU;EACzC,MAAM,SAAc,CAAC;EACrB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAC3C,OAAO,OAAO,yBAAyB,KAAK;EAE9C,OAAO;CACT;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"toml-document.js","names":[],"sources":["../../src/toml-document.ts"],"sourcesContent":["import parseTOML, { continueParsingTOML } from './parse-toml';\nimport toJS from './to-js';\nimport { TomlFormat } from './toml-format';\nimport { Block } from './cst';\nimport { patchCst } from './patch';\nimport { attachSources } from './cst-source';\nimport { detectNewline, resolveTomlFormat } from './toml-format';\nimport { truncateCst } from './truncate';\nimport type { ParseOptions, IntegersAsBigInt } from './parse-options';\nimport { decodeUtf8Bytes, hasLeadingBom, stripLeadingBom, UTF8_BOM } from './decode-utf8';\nimport { isObject } from './utils';\n\n/**\n * TomlDocument encapsulates a TOML CST and provides methods to interact with it.\n */\nexport class TomlDocument {\n private _cst: Block[];\n private _currentTomlString: string;\n private _format: TomlFormat;\n private _integersAsBigInt: IntegersAsBigInt;\n private _temporal: boolean;\n\n /**\n * Initializes the TomlDocument with TOML source, parsing it into a CST.\n *\n * When bytes are provided, they are decoded as UTF-8 in fatal mode.\n * This rejects invalid UTF-8 sequences before parsing.\n *\n * @param tomlSource - The TOML source to parse (string or raw UTF-8 bytes)\n * @param options - Optional parse options\n * @param options.integersAsBigInt - Controls bigint vs number for TOML integers\n * @param options.temporal - When true, returns Temporal objects for date/time values\n */\n constructor(tomlSource: string | Uint8Array, options?: ParseOptions) {\n const sourceString = typeof tomlSource === 'string'\n ? tomlSource\n : decodeUtf8Bytes(tomlSource);\n const tomlString = stripLeadingBom(sourceString);\n\n this._currentTomlString = tomlString;\n this._cst = Array.from(parseTOML(tomlString));\n this._integersAsBigInt = options?.integersAsBigInt ?? 'asNeeded';\n this._temporal = options?.temporal ?? false;\n // Auto-detect formatting preferences from the original TOML string\n this._format = TomlFormat.autoDetectFormatWithCst(sourceString, this._cst);\n }\n\n get toTomlString(): string {\n return this._format.leadingBom ? `${UTF8_BOM}${this._currentTomlString}` : this._currentTomlString;\n }\n\n /**\n * Returns the JavaScript object representation of the TOML document.\n */\n get toJsObject(): any {\n const jsObject = toJS(this._cst, this._currentTomlString, {\n integersAsBigInt: this._integersAsBigInt,\n temporal: this._temporal\n });\n // When temporal is enabled, Temporal objects are already returned — no conversion needed.\n // When temporal is disabled, convert custom date classes to regular JavaScript Date objects.\n if (this._temporal) {\n return jsObject;\n }\n return convertCustomDateClasses(jsObject);\n }\n\n /**\n * Returns the internal CST (for testing purposes).\n * @internal\n */\n get cst(): Block[] {\n return this._cst;\n }\n\n /**\n * Applies a patch to the current CST using a modified JS object.\n * Updates the internal CST. Use toTomlString getter to retrieve the updated TOML string.\n *\n * @param updatedObject - The modified JS object to patch with\n * @param format - Optional formatting options\n */\n patch(updatedObject: any, format?: Partial<TomlFormat> | TomlFormat) : void {\n\n const fmt = resolveTomlFormat(format, this._format);\n\n const sourceBefore = this._currentTomlString;\n\n // Only worth deriving the pre-patch values when a stripped date could\n // actually be present; temporal mode hands out Temporal objects untouched.\n if (!this._temporal && hasPlainDate(updatedObject)) {\n const originalObject = toJS(this._cst, sourceBefore, {\n integersAsBigInt: this._integersAsBigInt,\n temporal: false\n });\n updatedObject = restoreDateRepresentations(updatedObject, originalObject);\n }\n\n const indentWidthExplicit = format instanceof TomlFormat ||\n (format != null && Object.prototype.hasOwnProperty.call(format, 'indentWidth'));\n const trailingCommaExplicit = format instanceof TomlFormat ||\n (format != null && Object.prototype.hasOwnProperty.call(format, 'trailingComma'));\n attachSources(this._cst, sourceBefore);\n const result = patchCst(\n this._cst,\n updatedObject,\n fmt,\n indentWidthExplicit,\n trailingCommaExplicit\n );\n this._cst = Array.from(parseTOML(result.tomlString));\n this._format = fmt;\n this._currentTomlString = result.tomlString;\n }\n\n /**\n * Updates the internal document by supplying a modified tomlString.\n * Use toJsObject getter to retrieve the updated JS object representation.\n * @param tomlString - The modified TOML string to update with\n */\n update(tomlString: string): void {\n const tomlContent = stripLeadingBom(tomlString);\n\n if (tomlContent === this._currentTomlString) {\n this._format.leadingBom = hasLeadingBom(tomlString);\n return;\n }\n\n // Now, let's check where the first difference is\n const existingLines = this._currentTomlString.split(this._format.newLine);\n const newLineChar = detectNewline(tomlContent);\n const newTextLines = tomlContent.split(newLineChar);\n let firstDiffLineIndex = 0;\n while (\n firstDiffLineIndex < existingLines.length &&\n firstDiffLineIndex < newTextLines.length &&\n existingLines[firstDiffLineIndex] === newTextLines[firstDiffLineIndex]\n ) {\n firstDiffLineIndex++;\n }\n\n // Calculate the 1-based line number and 0-based column where the first difference occurs\n \n let firstDiffColumn = 0;\n \n // If we're within the bounds of both arrays, find the column where they differ\n if (firstDiffLineIndex < existingLines.length && firstDiffLineIndex < newTextLines.length) {\n const existingLine = existingLines[firstDiffLineIndex];\n const newLine = newTextLines[firstDiffLineIndex];\n \n // Find the first character position where the lines differ\n for (let i = 0; i < Math.max(existingLine.length, newLine.length); i++) {\n if (existingLine[i] !== newLine[i]) {\n firstDiffColumn = i;\n break;\n }\n }\n }\n\n let firstDiffLine = firstDiffLineIndex + 1; // Convert to 1-based\n const { truncatedCst, lastEndPosition } = truncateCst(this._cst, firstDiffLine, firstDiffColumn);\n\n // Determine where to continue parsing from in the new string\n // If lastEndPosition exists, continue from there; otherwise from the start of the document\n const continueFromLine = lastEndPosition ? lastEndPosition.line : 1;\n const continueFromColumn = lastEndPosition ? lastEndPosition.column + 1 : 0;\n\n // Based on the first difference, we can re-parse only the affected part\n // We will need to supply the remaining string after where the CST was truncated\n const remainingLines = newTextLines.slice(continueFromLine - 1);\n \n // If there's a partial line match, we need to extract only the part after the continuation column\n if (remainingLines.length > 0 && continueFromColumn > 0) {\n remainingLines[0] = remainingLines[0].substring(continueFromColumn);\n }\n \n const remainingToml = remainingLines.join(this._format.newLine);\n \n this._cst = Array.from(continueParsingTOML(truncatedCst, remainingToml, {\n line: continueFromLine,\n column: continueFromColumn\n }));\n this._currentTomlString = tomlContent;\n \n // Update the auto-detected format with the new string's characteristics\n this._format = TomlFormat.autoDetectFormatWithCst(tomlString, this._cst);\n }\n\n /**\n * Overwrites the internal syntax tree by fully re-parsing the supplied tomlString.\n * This is simpler but slower than update() which uses incremental parsing.\n * @param tomlString - The TOML string to overwrite with\n */\n overwrite(tomlString: string): void {\n const tomlContent = stripLeadingBom(tomlString);\n\n if (tomlContent === this._currentTomlString) {\n this._format.leadingBom = hasLeadingBom(tomlString);\n return;\n }\n\n // Re-parse the entire document\n this._cst = Array.from(parseTOML(tomlContent));\n this._currentTomlString = tomlContent;\n \n // Update the auto-detected format with the new string's characteristics\n this._format = TomlFormat.autoDetectFormatWithCst(tomlString, this._cst);\n }\n}\n\n/**\n * True when `value` holds a plain `Date` anywhere, i.e. one of the objects\n * toJsObject() produced by stripping a TOML date class. Used to skip the work\n * in restoreDateRepresentations() for the common case of a document with no\n * dates in it. Cycle-safe.\n */\nfunction hasPlainDate(value: any, seen: WeakSet<object> = new WeakSet()): boolean {\n if (value instanceof Date) return value.constructor === Date;\n if (!value || typeof value !== 'object') return false;\n if (seen.has(value)) return false;\n seen.add(value);\n if (Array.isArray(value)) return value.some(item => hasPlainDate(item, seen));\n return Object.keys(value).some(key => hasPlainDate(value[key], seen));\n}\n\n/**\n * Re-attaches the TOML date representation that toJsObject() strips.\n *\n * toJsObject() deliberately hands out plain `Date` objects so that callers get\n * the standard Date contract, notably a standard toISOString(). But the writer\n * derives a value's TOML text from toISOString(), and the TOML date classes\n * override it to return the original spelling. A plain Date handed back in\n * therefore writes as a full offset date-time, so read-modify-write turned\n * `1986-03-02` into `1986-03-02T00:00:00.000Z` whenever the surrounding node was\n * rewritten rather than preserved from the CST.\n *\n * Where the caller left a date alone (still a plain Date, same instant), the\n * original typed instance goes back in so the original spelling is written. A\n * date whose instant actually changed is left as-is: only the caller knows\n * whether a new instant is still meant to be a local date, and they can say so\n * by passing LocalDate / LocalTime / LocalDateTime / OffsetDateTime, which are\n * exported for that purpose. Instances of those classes are never touched.\n *\n * The caller's object is not mutated; a node is copied only when something\n * beneath it changed, so an untouched tree is returned by reference.\n */\nfunction restoreDateRepresentations(updated: any, original: any, seen: WeakSet<object> = new WeakSet()): any {\n if (updated instanceof Date) {\n const erased = updated.constructor === Date\n && original instanceof Date\n && original.constructor !== Date\n && original.getTime() === updated.getTime();\n return erased ? original : updated;\n }\n if (!updated || typeof updated !== 'object' || seen.has(updated)) return updated;\n seen.add(updated);\n\n if (Array.isArray(updated)) {\n if (!Array.isArray(original)) return updated;\n let changed = false;\n const restored = updated.map((item, index) => {\n const next = restoreDateRepresentations(item, original[index], seen);\n if (next !== item) changed = true;\n return next;\n });\n return changed ? restored : updated;\n }\n\n if (!isObject(original)) return updated;\n let changed = false;\n const restored: Record<string, any> = {};\n for (const key of Object.keys(updated)) {\n const value = updated[key];\n const next = restoreDateRepresentations(value, original[key], seen);\n restored[key] = next;\n if (next !== value) changed = true;\n }\n return changed ? restored : updated;\n}\n\n/**\n * Recursively converts custom date classes to regular JavaScript Date objects.\n * This ensures that the toJsObject property returns standard Date objects\n * while preserving the custom classes internally for TOML formatting.\n */\nfunction convertCustomDateClasses(obj: any): any {\n if (obj instanceof Date) {\n // Convert custom date classes to regular Date objects\n return new Date(obj.getTime());\n } else if (Array.isArray(obj)) {\n return obj.map(convertCustomDateClasses);\n } else if (obj && typeof obj === 'object') {\n const result: any = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = convertCustomDateClasses(value);\n }\n return result;\n }\n return obj;\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,IAAa,eAAb,MAA0B;CACxB,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;;;;;;;;;;;;CAaR,YAAY,YAAiC,SAAwB;EACnE,MAAM,eAAe,OAAO,eAAe,WACvC,aACA,gBAAgB,UAAU;EAC9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,GAAG,OAAO;CAChC,IAAI,UAAU;CACd,MAAM,WAAgC,CAAC;CACvC,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,GAAG;EACtC,MAAM,QAAQ,QAAQ;EACtB,MAAM,OAAO,2BAA2B,OAAO,SAAS,MAAM,IAAI;EAClE,SAAS,OAAO;EAChB,IAAI,SAAS,OAAO,UAAU;CAChC;CACA,OAAO,UAAU,WAAW;AAC9B;;;;;;AAOA,SAAS,yBAAyB,KAAe;CAC/C,IAAI,eAAe,MAEjB,OAAO,IAAI,KAAK,IAAI,QAAQ,CAAC;MACxB,IAAI,MAAM,QAAQ,GAAG,GAC1B,OAAO,IAAI,IAAI,wBAAwB;MAClC,IAAI,OAAO,OAAO,QAAQ,UAAU;EACzC,MAAM,SAAc,CAAC;EACrB,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,GAAG,GAC3C,OAAO,OAAO,yBAAyB,KAAK;EAE9C,OAAO;CACT;CACA,OAAO;AACT"}
|
package/dist/dev/toml-format.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.1.
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
import parseTOML from "./parse-toml.js";
|
|
3
3
|
import { hasLeadingBom, stripLeadingBom } from "./decode-utf8.js";
|
|
4
4
|
|
package/dist/dev/toml-patch.js
CHANGED
|
@@ -1,16 +1,26 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.1.
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
import { LocalDate, LocalDateTime, LocalTime, OffsetDateTime } from "./date-format.js";
|
|
3
3
|
import parseTOML from "./parse-toml.js";
|
|
4
4
|
import { decodeUtf8Bytes, stripLeadingBom } from "./decode-utf8.js";
|
|
5
5
|
import { TomlFormat, resolveTomlFormat } from "./toml-format.js";
|
|
6
6
|
import parseJS from "./parse-js.js";
|
|
7
|
-
import toTOML from "./to-toml.js";
|
|
7
|
+
import toTOML, { toTOMLSequential } from "./to-toml.js";
|
|
8
8
|
import toJS from "./to-js.js";
|
|
9
9
|
import patch from "./patch.js";
|
|
10
10
|
import { TomlDocument } from "./toml-document.js";
|
|
11
11
|
|
|
12
12
|
//#region src/index.ts
|
|
13
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.leadingBom === d.leadingBom && fmt.updateOrder === d.updateOrder && fmt.multilineTable === d.multilineTable && fmt.multilineArray === d.multilineArray;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
14
24
|
* Parses a TOML string or raw UTF-8 bytes into a JavaScript object.
|
|
15
25
|
*
|
|
16
26
|
* When raw bytes (Uint8Array / Buffer) are provided, they are decoded with
|
|
@@ -61,9 +71,9 @@ function parse(value, options) {
|
|
|
61
71
|
* @returns The stringified TOML representation
|
|
62
72
|
*/
|
|
63
73
|
function stringify(value, format) {
|
|
64
|
-
const fmt = resolveTomlFormat(format, TomlFormat.default());
|
|
74
|
+
const fmt = format == null ? DEFAULT_STRINGIFY_FORMAT : resolveTomlFormat(format, TomlFormat.default());
|
|
65
75
|
const document = parseJS(value, fmt);
|
|
66
|
-
const tomlString = toTOML(document.items, fmt);
|
|
76
|
+
const tomlString = isDefaultFormat(fmt) ? toTOMLSequential(document.items, fmt) : toTOML(document.items, fmt);
|
|
67
77
|
return fmt.leadingBom ? `${""}${tomlString}` : tomlString;
|
|
68
78
|
}
|
|
69
79
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toml-patch.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import parseTOML from './parse-toml';\nimport parseJS from './parse-js';\nimport toTOML from './to-toml';\nimport toJS from './to-js';\nimport { TomlFormat, resolveTomlFormat } from './toml-format';\nimport type { ParseOptions } from './parse-options';\nimport { decodeUtf8Bytes, stripLeadingBom, UTF8_BOM } from './decode-utf8';\nimport { TomlDocument } from './toml-document';\n\nexport type { IntegersAsBigInt, ParseOptions } from './parse-options';\n\n/**\n * Parses a TOML string or raw UTF-8 bytes into a JavaScript object.\n *\n * When raw bytes (Uint8Array / Buffer) are provided, they are decoded with\n * the WHATWG TextDecoder in fatal mode, which rejects any invalid UTF-8\n * byte sequences before parsing begins. This matches the TOML spec requirement\n * that \"A TOML file must be a valid UTF-8 encoded Unicode document.\"\n *\n * The string path has zero overhead — the bytes path incurs one TextDecoder\n * decode (which also produces the string needed for parsing).\n *\n * By default (`options.integersAsBigInt` unset or `'asNeeded'`), integers that\n * fit within the JavaScript safe-integer range are returned as `number`; integers\n * outside that range are returned as `bigint` to preserve precision. Set\n * `options.integersAsBigInt` to `true` to always return `bigint` for all integers,\n * or `false` to always return `number` (large integers will lose precision).\n *\n * Note: the `'asNeeded'` default is a behavioral change from prior versions (<=1.0.7). If\n * your code serializes the result to JSON or performs arithmetic mixing `number`\n * and `bigint`, set `integersAsBigInt: false` to restore the previous behavior.\n *\n * By default (`options.temporal` unset or `false`), TOML date/time values are\n * returned as custom Date subclasses (LocalDate, LocalTime, LocalDateTime,\n * OffsetDateTime). Set `options.temporal` to `true` to return Temporal API\n * objects instead (Temporal.PlainDate, Temporal.PlainTime, Temporal.PlainDateTime,\n * Temporal.ZonedDateTime). The Temporal API must be available in the runtime.\n *\n * @param value - TOML source as a string or raw UTF-8 bytes\n * @param options - Optional parse options\n * @param options.integersAsBigInt - Controls `bigint` vs `number` for integers.\n * `'asNeeded'` (default) | `true` | `false`\n * @param options.temporal - When true, returns Temporal objects for date/time values.\n * Default: false.\n * @returns The parsed JavaScript object\n */\nexport function parse(value: string | Uint8Array, options?: ParseOptions): any {\n const rawString = typeof value === 'string'\n ? value\n : decodeUtf8Bytes(value);\n const tomlString = stripLeadingBom(rawString);\n return toJS(parseTOML(tomlString), tomlString, {\n integersAsBigInt: options?.integersAsBigInt ?? 'asNeeded',\n temporal: options?.temporal ?? false\n });\n}\n\n/**\n * Converts a JavaScript object to a TOML string.\n * \n * @param value - The JavaScript object to stringify\n * @param format - Optional formatting options for the resulting TOML\n * @returns The stringified TOML representation\n */\nexport function stringify(value: any, format?: Partial<TomlFormat> | TomlFormat): string {\n const fmt = resolveTomlFormat(format, TomlFormat.default());\n \n const document = parseJS(value, fmt);\n const tomlString = toTOML(document.items, fmt);\n return fmt.leadingBom ? `${UTF8_BOM}${tomlString}` : tomlString;\n}\n\nexport { default as patch } from './patch';\nexport { LocalDate, LocalTime, LocalDateTime, OffsetDateTime } from './parse-toml';\n\n/**\n * TomlFormat class for configuring TOML formatting options.\n * \n * This class allows you to customize how TOML documents are formatted when using\n * the stringify() and patch() functions. It provides control over line endings,\n * spacing, trailing commas, and other formatting preferences.\n * \n * @example\n * ```typescript\n * import { patch, TomlFormat } from '@decimalturn/toml-patch';\n * \n * // Create a custom format configuration\n * const format = TomlFormat.default();\n * format.newLine = '\\r\\n'; // Windows line endings\n * format.trailingNewline = 0; // No trailing newline\n * format.trailingComma = true; // Add trailing commas\n * format.bracketSpacing = false; // No spaces in brackets\n * \n * // Apply the patch with custom formatting\n * const result = patch(existingToml, updatedData, format);\n * ```\n */\nexport { TomlFormat, type MultilineContainerMode } from './toml-format';\n\n/**\n * TomlDocument encapsulates a TOML CST and provides methods to interact with it.\n */\nexport { TomlDocument } from './toml-document';\n\n/**\n * Parses a TOML string or raw UTF-8 bytes into a {@link TomlDocument}.\n *\n * This is a convenience alternative to `new TomlDocument(value, options)`.\n *\n * @param value - TOML source as a string or raw UTF-8 bytes\n * @param options - Optional parse options\n * @returns A {@link TomlDocument} representing the parsed TOML\n */\nexport function parseDocument(value: string | Uint8Array, options?: ParseOptions): TomlDocument {\n return new TomlDocument(value, options);\n}\n"],"mappings":"
|
|
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.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,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"}
|
package/dist/dev/traverse.js
CHANGED
package/dist/dev/truncate.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.1.
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
//#region src/truncate.ts
|
|
3
3
|
/**
|
|
4
4
|
* Compares two positions to determine their ordering.
|
package/dist/dev/update-order.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.1.
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
import { hasItem, isDocument, isInlineItem, isKeyValue, isTable, isTableArray } from "./cst.js";
|
|
3
3
|
import { recalcContainerEnd, shiftNode } from "./writer.js";
|
|
4
4
|
import { tryFindByPath } from "./find-by-path.js";
|
package/dist/dev/utils.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.1.
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
//#region src/utils.ts
|
|
3
3
|
/**
|
|
4
4
|
* @file Utility functions for the TOML patch library.
|
package/dist/dev/writer.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
//! @decimalturn/toml-patch v3.1.
|
|
1
|
+
//! @decimalturn/toml-patch v3.1.2 - https://github.com/DecimalTurn/toml-patch - @license: MIT
|
|
2
2
|
import { hasItem, hasItems, isBlock, isComment, isDocument, isInlineArray, isInlineItem, isInlineTable, isKeyValue, isTable, isTableArray } from "./cst.js";
|
|
3
3
|
import { clonePosition, getSpan } from "./location.js";
|
|
4
4
|
import { getCommaSpace } from "./inline-comma-space.js";
|
|
5
|
-
import { markMutation, markTreeDirty } from "./cst-source.js";
|
|
6
5
|
import { last } from "./utils.js";
|
|
7
6
|
import traverse from "./traverse.js";
|
|
7
|
+
import { markMutation, markTreeDirty } from "./cst-source.js";
|
|
8
8
|
import { getInlineContainerLayout, isInlineContainerPositioned, markPreservedMultilineEmpty } from "./inline-format.js";
|
|
9
9
|
|
|
10
10
|
//#region src/writer.ts
|
|
@@ -93,7 +93,7 @@ function replace(root, parent, existing, replacement) {
|
|
|
93
93
|
lines: replacement_span.lines - existing_span.lines,
|
|
94
94
|
columns: replacement_span.columns - existing_span.columns
|
|
95
95
|
}, getExitOffsets(root), replacement, existing);
|
|
96
|
-
markMutation(root, parent, replacement);
|
|
96
|
+
if (!stringifyRoots.has(root)) markMutation(root, parent, replacement);
|
|
97
97
|
dirty_roots.add(root);
|
|
98
98
|
}
|
|
99
99
|
/**
|
|
@@ -137,7 +137,7 @@ function insert(root, parent, child, index, forceInline, hostItems, leadingLines
|
|
|
137
137
|
}
|
|
138
138
|
}
|
|
139
139
|
getExitOffsets(root).set(child, offset);
|
|
140
|
-
markMutation(root, parent, child);
|
|
140
|
+
if (!stringifyRoots.has(root)) markMutation(root, parent, child);
|
|
141
141
|
dirty_roots.add(root);
|
|
142
142
|
}
|
|
143
143
|
function enclosingInlineValue(parent, hostItems) {
|
|
@@ -338,7 +338,7 @@ function insertInlineAtRoot(parent, child, index) {
|
|
|
338
338
|
}
|
|
339
339
|
function remove(root, parent, node, hostItems) {
|
|
340
340
|
if (!hasItems(parent)) throw new Error(`Unsupported parent type "${parent.type}" for remove`);
|
|
341
|
-
markMutation(root, parent);
|
|
341
|
+
if (!stringifyRoots.has(root)) markMutation(root, parent);
|
|
342
342
|
let index = parent.items.indexOf(node);
|
|
343
343
|
if (index < 0) {
|
|
344
344
|
index = parent.items.findIndex((item) => hasItem(item) && item.item === node);
|