@isdk/json-repair 0.1.3 → 0.3.0

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/CHANGELOG.md CHANGED
@@ -2,21 +2,77 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
4
4
 
5
- ## [0.1.3](https://github.com///compare/v0.1.2...v0.1.3) (2026-11-30)
5
+ ## [0.3.0](///compare/v0.2.0...v0.3.0) (2026-12-04)
6
+
7
+ ### ⚠ BREAKING CHANGES
8
+
9
+ * **options:** RepairOptions.additionalProperties no longer takes 'keep' |
10
+ 'remove'. A Schema stating `additionalProperties: false` now drops undeclared
11
+ keys (listed in `discarded`, flagged `undeclared-keys-dropped`) instead of
12
+ keeping them and reporting a validation error. Migrate
13
+ `additionalProperties: 'remove'` to `false`, and `'keep'` to omitting the
14
+ option.
15
+
16
+ ### Features
17
+
18
+ * **key-matching:** name the forms a key may vary by a8106c4
19
+ * **options:** make additionalProperties the JSON Schema keyword itself ee52b9a
20
+ * **walker:** read patternProperties as a declaration of keys 84b6779
21
+
22
+ ### Bug Fixes
23
+
24
+ * **key-matching:** read the key forms from the walker that owns them 7ad76f7
25
+ * **parser:** match JSON's own literals as whole tokens dcc2a9b
26
+ * **pkg:** keep the generated docs in the repository, out of the package 44ee6f9
27
+ * **pkg:** name one repository, and ship the changelog bd11cdb
28
+ * **walker:** read what a combinator declares about a level 2d6220a
29
+
30
+ ## [0.2.0](https://github.com/isdk/json-repair.js/compare/v0.1.3...v0.2.0) (2026-12-01)
31
+
32
+ ### ⚠ BREAKING CHANGES
33
+
34
+ * `jsonRepair` now locates the JSON inside the input by default
35
+ (opt out with `locate: false`), and a record the Schema expects inside a list is
36
+ read as one item (opt out with `wrapArrays: false`).
37
+
38
+ ### Features
39
+
40
+ * locate JSON inside LLM output, rank fragments, report diagnostics ([508b580](https://github.com/isdk/json-repair.js/commit/508b580b60dfb0efb5c7823ee23bdbb2d6760bf3))
41
+ * **parser:** name a comment that ended up inside a value ([5f3d3d7](https://github.com/isdk/json-repair.js/commit/5f3d3d7d594b58abccc2ea6ecb8f9723d8fa2e77))
42
+ * **parser:** read bare tokens as the literal the model meant ([9fe502e](https://github.com/isdk/json-repair.js/commit/9fe502e159341d3871cdf357267e46b631875354))
43
+ * **parser:** report an escape strict JSON rejects, and set how far it is trusted ([947d570](https://github.com/isdk/json-repair.js/commit/947d570e73e21644d866a2edae3ed443fd6f670b))
44
+ * **parser:** report the text a number coercion gives up ([8a4b9f6](https://github.com/isdk/json-repair.js/commit/8a4b9f675fcc9cc7f5a0ac8155464db0ddead2c0))
45
+ * **parser:** say where a quoted value ends when its quote was left open ([f28938c](https://github.com/isdk/json-repair.js/commit/f28938c83b3088ab669e3c0af3a0272e99c42404))
46
+ * **parser:** skip the comments a model adds between members ([7706b49](https://github.com/isdk/json-repair.js/commit/7706b49483f99602275719ad07355392389bfe06))
47
+
48
+ ### Bug Fixes
49
+
50
+ * **cache:** bound the compiled key patterns ([cdd1927](https://github.com/isdk/json-repair.js/commit/cdd19273199060a8ee22c01d8f570d981895a7eb))
51
+ * decode JSON string escapes exactly like JSON.parse ([4fa74fd](https://github.com/isdk/json-repair.js/commit/4fa74fd354f0d5b230300897ed62a0473c247a4c))
52
+ * **parser:** a URL scheme or a path is not a property key ([27e0843](https://github.com/isdk/json-repair.js/commit/27e08430493558f329ac09469544d85b850cda52))
53
+ * **parser:** end the document where the output was cut off ([854d8cd](https://github.com/isdk/json-repair.js/commit/854d8cd201adc0d8dd6b63cd53d11734d020d2ae))
54
+ * **parser:** finish what a heuristic starts without damaging the rest ([975b505](https://github.com/isdk/json-repair.js/commit/975b5058210888c1fb8dae24668180a634239819))
55
+ * **parser:** keep the boundary probe from re-reading the value ([290439c](https://github.com/isdk/json-repair.js/commit/290439cb9a1430c797494be8b5e5234177472b8d))
56
+ * **parser:** stop at a nesting limit instead of overflowing the stack ([f66f069](https://github.com/isdk/json-repair.js/commit/f66f069e3699212f03d9327af89880a82ef7f56a))
57
+ * **validate:** compare a listed value by content, in const and enum alike ([5923b17](https://github.com/isdk/json-repair.js/commit/5923b1750e0225a76f0e391961ea9f4d4eb3907a))
58
+ * **validate:** match an enum entry by value, not by its string form ([b0280a9](https://github.com/isdk/json-repair.js/commit/b0280a94f2e1ff56ada9f5005543edd8ec76323e))
59
+ * **walker:** import the ref parser by name so require() can load it ([eaaa867](https://github.com/isdk/json-repair.js/commit/eaaa867aa1a267b87104dfff15b41510ad922c31))
60
+
61
+ ## [0.1.3](https://github.com/isdk/json-repair.js/compare/v0.1.2...v0.1.3) (2026-11-30)
6
62
 
7
63
  ### Features
8
64
 
9
- * wire up keyMatching, additionalProperties and stringCaptureStrategy ([3aea142](https://github.com///commit/3aea14276d07fc71ad86f4d26d768f071b1ee21c))
65
+ * wire up keyMatching, additionalProperties and stringCaptureStrategy ([3aea142](https://github.com/isdk/json-repair.js/commit/3aea14276d07fc71ad86f4d26d768f071b1ee21c))
10
66
 
11
67
  ### Bug Fixes
12
68
 
13
- * honour Schema-declared types that the parser used to ignore ([bd99943](https://github.com///commit/bd999430e5a6ec831a040451c76463ff7791a09a))
14
- * keep clean parses and recognize quoted keys containing whitespace ([fbe4973](https://github.com///commit/fbe49736f3862b38354f93edf3dee294dbc2ed1e))
15
- * never touch the prototype chain and dereference a copy of the Schema ([681d40f](https://github.com///commit/681d40f72400a92a50431dd5576db64ef7f1073c))
16
- * parse scientific notation and stop a number at the end of the literal ([49ac3f4](https://github.com///commit/49ac3f403ff4bd148e118dd8fa506af1f3eec264))
17
- * recognise Schema-declared multi-word keys in unquoted documents ([59c6d36](https://github.com///commit/59c6d36037a5cf1865954685d9201a03bb3231c6))
18
- * take the first numeric token when coercing a noisy number ([d3b5f1b](https://github.com///commit/d3b5f1be9194cc880aea62ac3cdbb40d14ed2d29))
19
- * use hasOwnProperty.call for the duplicate-key check ([e575794](https://github.com///commit/e575794cf3a652c9a872ea13f965453a797ddef5))
69
+ * honour Schema-declared types that the parser used to ignore ([bd99943](https://github.com/isdk/json-repair.js/commit/bd999430e5a6ec831a040451c76463ff7791a09a))
70
+ * keep clean parses and recognize quoted keys containing whitespace ([fbe4973](https://github.com/isdk/json-repair.js/commit/fbe49736f3862b38354f93edf3dee294dbc2ed1e))
71
+ * never touch the prototype chain and dereference a copy of the Schema ([681d40f](https://github.com/isdk/json-repair.js/commit/681d40f72400a92a50431dd5576db64ef7f1073c))
72
+ * parse scientific notation and stop a number at the end of the literal ([49ac3f4](https://github.com/isdk/json-repair.js/commit/49ac3f403ff4bd148e118dd8fa506af1f3eec264))
73
+ * recognise Schema-declared multi-word keys in unquoted documents ([59c6d36](https://github.com/isdk/json-repair.js/commit/59c6d36037a5cf1865954685d9201a03bb3231c6))
74
+ * take the first numeric token when coercing a noisy number ([d3b5f1b](https://github.com/isdk/json-repair.js/commit/d3b5f1be9194cc880aea62ac3cdbb40d14ed2d29))
75
+ * use hasOwnProperty.call for the duplicate-key check ([e575794](https://github.com/isdk/json-repair.js/commit/e575794cf3a652c9a872ea13f965453a797ddef5))
20
76
 
21
77
  ## [0.1.2](https://github.com/isdk/json-repair.js/compare/v0.1.1...v0.1.2) (2026-01-30)
22
78
 
package/README.cn.md CHANGED
@@ -33,17 +33,21 @@ LLM 生成的 JSON 经常包含语法错误或语义噪声。常见问题包括
33
33
  - **布尔值变体**:识别 `yes/no`、`on/off`、`1/0`、`确定/取消`、`是/否` 为布尔值。
34
34
  - **声明为 string 的值保持文本**:`{ Population: 12 }` 在 `{ type: 'string' }` 下得到 `"12"`;数字取自文档原文,所以 `{ id: 01234 }` 得到 `"01234"`。
35
35
  - **隐式结构支持**:自动修复对象或数组中缺失的花括号。
36
+ - **转义保真的字符串**:解析器读到的字符串,解码结果与 `JSON.parse` 完全一致(`\n`、`\t`、`\/`、`\uXXXX`、代理对);JSON5 风格的 `\xNN` 解码为它所指的字元;对不需要转义的字元做的多余转义会被拆包(`"\$10"` → `"$10"`);凡是严格 JSON 会拒绝的转义,都会报 `invalid-escape`。当反斜杠是内容而不是转义时,用 `escapes` 声明。
36
37
  - **稳当的属性边界**:带引号的键名可以含空格与标点(`"Official language": "Italian"`);Schema 声明过的多词键名,即使文档里没加引号也能被识别;能完整解析的值不会被重新切分,因此合法 JSON 的产物与 `JSON.parse` 完全一致。
37
38
  - **模糊键名匹配**:`user_name`、`userName`、`USER NAME` 都会归位到 Schema 声明的属性名,输出里用的就是声明的名字。
39
+ - **读懂 Schema 组合关键字**:`$ref` 与 `allOf` / `anyOf` / `oneOf` 会先被折叠到它们所描述的层级,再去遍历;所以写在分支里的类型和属性,照样触发强制转换、照样参与校验 —— `{ anyOf: [{ type: 'string' }] }` 会把 `12` 变成 `"12"`。
38
40
  - **原型安全的输出**:`__proto__`、`constructor` 这类键名存为自身的普通属性,与 `JSON.parse` 的处理一致。
39
41
  - **高性能**:支持复用 `SchemaWalker` 实例,适用于高吞吐量的批处理场景。
40
42
 
41
43
  ## 📦 安装
42
44
 
43
45
  ```bash
44
- pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
46
+ pnpm add @isdk/json-repair
45
47
  ```
46
48
 
49
+ `@apidevtools/json-schema-ref-parser` 会随之安装 —— 它是本包的 `$ref` 解析依赖,不是 peer 依赖,自己再钉一次只会多一份副本。
50
+
47
51
  ## 🛠 用法
48
52
 
49
53
  ### 1. Schema 引导修复 (推荐)
@@ -118,6 +122,80 @@ for (const item of brokenItems) {
118
122
  }
119
123
  ```
120
124
 
125
+ ## 🧭 先定位 JSON 从哪里开始
126
+
127
+ 模型的回复是文本,不是文档:JSON 外面套着围栏,前后还裹着句子。`jsonRepair` 先定位 JSON,
128
+ 再修它:
129
+
130
+ ````typescript
131
+ await jsonRepair('```json\n{ name: Ada }\n```', schema)
132
+ // { name: 'Ada' } flags: ['markdown-fence', 'prose-prefix', 'trailing-chatter']
133
+ // discarded: ['```json', '```'] —— 围栏本身也算作文本
134
+
135
+ await jsonRepair('```json\n{ name: Ada }\n```\nHope this helps!', schema)
136
+ // 值与 flags 同上;那句话只是追加到 discarded 里 closing fence 的后面:
137
+ // discarded: ['```json', '```\nHope this helps!']
138
+
139
+ await jsonRepair('Here you go:\nname: Ada', schema)
140
+ // { name: 'Ada' } flags: ['implicit-structure', 'prose-prefix']
141
+ ````
142
+
143
+ - 定位扫描感知引号与括号配平,所以 `{ "code": "```json\n{}\n```" }` 的内容完好无损——
144
+ 而一个剥离围栏的正则会把 `{}` 交给你。
145
+ - 已经能解析的输入永远不会被重新定位,这正是「合法 JSON 与 `JSON.parse` 结果完全一致」的前提。
146
+ - 定位阶段丢掉的内容——包裹散文、围栏、落选片段——都会列在 `discarded` 里;`onDiscard: 'throw'` 会让任何有丢弃的修复直接失败,
147
+ 供丢不起内容的调用方使用。强制转换在值内部舍掉的文本则由 flag 报告,规则见[注意事项与歧义说明](#-注意事项与歧义说明)。
148
+
149
+ ### 多个 JSON 片段
150
+
151
+ 回复里常常有好几个 JSON 片段:草稿加最终答案、诱饵,或者 schema 期待数组时并排放着的若干条记录。
152
+ 选哪一个由 schema 决定,所以这是度量而不是猜测。片段按下列顺序比较:
153
+
154
+ | 先比 | 再比 |
155
+ | --- | --- |
156
+ | schema 违规更少(`errors`) | `required` 字段里带真实值的更多(`""` 等于没有) |
157
+ | 声明字段里带真实值的更多 | 答案里复刻的 JSON Schema 关键字更少(`schemaEchoKeys`) |
158
+
159
+ 打平时按位置裁决——**最后**一个优先,因为模型通常先推理再作答——并且以
160
+ `ambiguous-candidates` 上报,而不是悄悄替你做决定。`onMultiple` 可以改成 `'first'`、`'last'`
161
+ 或 `'throw'`。没有 schema 时排序没有信息可用,于是退化为位置规则;如果这点对你的日志很重要,
162
+ 请自己标注。
163
+
164
+ 在 `array` schema 下并排摆放的记录(`{"name": "Noah"} {"name": "Ada"}`,或者连花括号都没有的
165
+ 同样记录)会被读成「一个文档、两个元素」(`sibling-objects-merged`)——结构是声明过的,
166
+ 这同样不是猜测。
167
+
168
+ ### 审查修复结果:合法不等于正确
169
+
170
+ 一个值可以完全满足 schema 却什么也没说:`"name": ""`、占位的电话号码、默认选中的第一个枚举项。
171
+ 所以 `jsonRepairResult()` 在返回值之外,还把注意到的事情一起交给你:
172
+
173
+ ```typescript
174
+ import { jsonRepairResult, renderValidatorErrors } from '@isdk/json-repair'
175
+
176
+ const { value, errors, flags, candidates, discarded } = await jsonRepairResult(
177
+ reply,
178
+ schema
179
+ )
180
+
181
+ flags
182
+ // ['markdown-fence', 'prose-prefix', 'empty-required']
183
+ errors
184
+ // [{ path: ['email'], message: 'missing required property' }]
185
+
186
+ renderValidatorErrors(errors, 6)
187
+ // - email: missing required property
188
+ ```
189
+
190
+ `errors` 正是重试提示词需要的东西,`renderValidatorErrors` 把它压到小模型还跟得上的几行。
191
+ 先修复,后重试:语法、类型、结构都由确定性代码解决,成本为零;第二次模型调用只该花在代码无从得知的地方——
192
+ 一个格式正确但内容错误的答案。
193
+
194
+ 重试也看不见占位符。`"name": ""` 满足 schema,让模型去修一个它并不存在的错误,它只会再写一遍,
195
+ 所以修复过程自己会点名:`empty-required`(必填字符串留空)、`schema-echo-detected`(把 schema 原样抄回来当答案,抄得完全合法也会点名)、
196
+ `ambiguous-candidates`(两个片段同样合规)、`coerced-text-dropped`(强制转换保留了值的一部分,舍掉了它周围的文本)。修复过程做过的每个决定都在 `flags` 里(完整列表见 [API 文档](https://github.com/isdk/json-repair.js/blob/main/docs/type-aliases/RepairFlag.md) 里的 `RepairFlag`),
197
+ 因此接受、重试还是换更大的模型,是依据证据决定,而不是因为“它解析成功了”。
198
+
121
199
  ## 🧭 属性边界是如何判定的
122
200
 
123
201
  在修复一个值的过程中,解析器必须在每个位置上判断接下来的 `"foo":` 是**下一个属性**的起点,还是**当前值**的一部分。它分为两种模式:
@@ -146,10 +224,47 @@ for (const item of brokenItems) {
146
224
  - 如果值里可能合法地出现 `word:` 或 `"phrase":`,要么让模型输出正确转义的 JSON(严格解析直接胜出),要么在 Schema 里声明该层级的属性。
147
225
  - 如果某个值在“看起来像键”的地方被截断,通常是你的 Schema 在该层级缺少 `properties` —— 补上后重试。
148
226
 
227
+ 另一类歧义是模型写了一半的引号:`{"t": "The "Best" Paper", "y": 2020}`。默认 `unescapedQuotes: 'keep'`,值会保留文档里写的引号。`'declared'` 在“引号之后紧跟 schema 声明过的成员”的位置结束该值——被声明的成员就是锚点,边界于是是被读出来的,而不是猜出来的。`'lookahead'` 只凭文本形状套用同一规则,适用于没有 schema 的文档。
228
+
149
229
  数字字面量支持科学计数法(`1e5`、`-2E2`),也容忍 LLM 常见的 `+5`、`.5`、`5.`。而 `1.2.3` 这种不完整的字面量会先作为字符串保留,再按 Schema 做强制转换。
150
230
 
151
231
  反方向同样成立:Schema 声明 `type: 'string'` 时 `12` 会被转成 `"12"`;并且文本取自文档原文而非解析后的数字,所以前导零不会丢失(`{ id: 01234 }` → `"01234"`)。`null` 与对象/数组不会被转成字符串。
152
232
 
233
+ 某层级的 `additionalProperties` 为 `false` 时 —— 无论它是 Schema 自己写的,还是由 `RepairOptions.additionalProperties` 代所有未声明它的层级补上的 —— 该层级未声明的键会被从结果里写掉而不是留在里面,这样严格 Schema 得到的就是符合它的值。被写掉的内容列入 `discarded` 并带 `undeclared-keys-dropped` 标记;完全没有声明属性名的自由层级不会被清空。
234
+
235
+ `patternProperties` 按形状而不是按名字描述键,修复把它当作它所声明的那样读取:被某个 pattern 覆盖的键,其值按该 pattern 背后的 Schema 做类型转换与校验;被覆盖的键不算 `additionalProperties` 眼中的多余键;匹配的键和声明过的属性名一样能成为贪婪捕获的断点。因此,唯一声明就是 `patternProperties` 的层级不算自由结构 —— 该处的 `additionalProperties: false` 确实会丢弃没有任何 pattern 覆盖的键。宿主引擎无法编译的 pattern(`(?i)` 这类旗标来自别的方言)不会算在文档头上:它覆盖所有键,但不为任何键定义类型。 两个 pattern 同时匹配一个键时,由先匹配到的那个定义其值 —— 用一个值同时满足多个 Schema 不是这个校验器会做的事。
236
+
237
+ ### 转义是如何读取的
238
+
239
+ 转义是解码,不是猜测:
240
+
241
+ | 文档里写的 | 值里的内容 |
242
+ | --- | --- |
243
+ | `"a\nb"`、`"\t"`、`"\/"` | 控制字元、`/` —— 与 `JSON.parse` 的结果完全一致 |
244
+ | `"café"`、`"\ud83d\ude00"` | `é`、`😀`;落单的代理项也留在 `JSON.parse` 会在的位置 |
245
+ | `"\xa0"`(JSON5 风格的十六进制转义) | 字元 U+00A0 |
246
+ | `"\$10"`、`"a\qb"`(给不需要转义的字元加了转义) | `$10`、`aqb` |
247
+ | `note: first line\nsecond`(被捕获的无引号值) | 按原文保留,反斜杠也在 —— 贪婪捕获不做解码 |
248
+
249
+ 解码到此为止。文档里写下的 NBSP、零宽空格、弯引号都原样留在值里:改写它们是在改动模型的内容,而不是在修复它的语法。
250
+
251
+ 凡是严格 JSON 会拒绝的转义,无论怎么处理,都会报 `invalid-escape`:值少了一个或多了一个反斜杠,
252
+ 调用方有权知道。`escapes` 决定反斜杠在多大程度上被当成转义:
253
+
254
+ | `escapes` | `"\$10"` | `"C:\Users"` | `"C:\temp"` | `"\x41"` | `"a\nb"` |
255
+ | --- | --- | --- | --- | --- | --- |
256
+ | `'json5'`(默认) | `$10` | `C:Users` | `C:`、制表符、`emp` | `A` | 换行 |
257
+ | `'json'` | `\$10` | `C:\Users` | `C:`、制表符、`emp` | `\x41` | 换行 |
258
+ | `'raw'` | `\$10` | `C:\Users` | `C:\temp` | `\x41` | `\n` —— 两个字元 |
259
+
260
+ `'json'` 只修复它确定的语法,JSON 没有定义的转义一律按原文保留——这正是 markdown 与 LaTeX 训练出来的
261
+ 模型习惯写的写法。`'raw'` 把每个反斜杠都当作内容,适用于值本身就是 Windows 路径、正则表达式或 LaTeX
262
+ 的文档(`"C:\temp"` 是路径不是制表符,`"\frac{a}{b}"` 是命令不是换页符),代价也写得很清楚:值里不
263
+ 再可能出现换行。
264
+
265
+ 任何设置下反斜杠都仍然是结构性的——它始终是下一个字元留在字符串里的理由——所以这个选择不会改变值
266
+ 在哪里结束。写坏了的十六进制转义(`"\xg"`、`"\uZZ"`)在任何设置下都不做解码,原样保留。
267
+
153
268
  ## ⚠️ 注意事项与歧义说明
154
269
 
155
270
  - **“奇偶判定法”逻辑**:当字符串被引号包裹且内部包含引号时,我们会计算内部引号的数量。
@@ -161,18 +276,31 @@ for (const item of brokenItems) {
161
276
  声明该层级的 `properties` 后,贪婪捕获只在真正的键名处断开,才能还原成 `{ note: 'see "foo bar": baz here', b: 2 }`(参见[如何理解这套启发式](#如何理解这套启发式))。
162
277
  - **未加引号的多词键名必须有声明。** `{ Capital: Berlin, Official language: Italian }` 能拆成两个属性,是因为 Schema 声明了 `Official language`。若文档里的带空格键名 _没有_ 声明,它就不是键:`{ Capital: Berlin, Official Lang: Italian }` 在默认的 `'aggressive'` 策略下会把整段都留在 `Capital` 里;改用 `'conservative'` 则会在空格处断开(`{ Capital: 'Berlin, Official', Lang: 'Italian' }`)。
163
278
  - **值里重复出现已声明的键名时会被截断。** 声明过的键就是断点,所以 `{ summary: the Official language: Italian is wrong, Official language: Italian }` 会读成 `summary = 'the'`。如果值确实可能重复某个已声明的键名,就让模型给键加引号,或者换一个不会碰撞的属性名。
164
- - **Markdown 代码块**:本库专注于 JSON 内容修复。如果 LLM 的输出包含 `json ...` 标记,请在传入前自行剥离。
279
+ - **当作路径分隔符的反斜杠无法被认出来。** `{ "path": "C:\new\test" }` 里确实就是 `\n` 和 `\t` 两个转义,所以默认会读成 `C:`、换行、`ew`、制表符、`est`;只有 `"C:\\new\\test"` 才是 Windows 路径。没有任何修复器能区分两者,我们也不猜。可以选择的是反斜杠被当成转义的程度:`escapes: 'json'` 保留 JSON 没有定义的转义(`"C:\Users"` 仍是 `C:\Users`),`escapes: 'raw'` 保留每一个反斜杠——这是唯一能让 `C:\temp` 完整活下来的设置,代价是 `"\n"` 不再是换行。无论选哪个,`invalid-escape` 都会告诉你文档里有这种转义。
280
+ - **没有花括号的记录,其后的散文会被保留**:`Here you go:\nname: Ada\nHope this helps!` 会得到 `name = 'Ada\nHope this helps!'`。没有花括号的值只能在 schema 点名下一个键的地方切断——后面跟 `city:` 能切,后面是一句话则无从判断它是散文。
281
+ - **转成数字时,值在数字结束处被切断**:`{ "age": 30 more words }` 读作 `age = 30`——值只保留第一个合法的数字片段,周围的文本被舍掉,`约 1,200.50 元` 变 `1200.5` 靠的就是这一点。贪婪捕获也可能把值一路延伸到模型随后写的散文(`{ age: 30\n\nHope this helps!}`),所以舍掉了什么必须说明:一律标 `coerced-text-dropped`;当舍掉的文本读起来是一句话而不是一处单位时,它还进入 `RepairResult.discarded`(判据:三个词,或没有空格可数的 20 个字符——`Approx. USD` 不进,`Hope this helps!` 进)。
282
+ - **围栏与散文是被定位、被丢弃的**:JSON 外面的包裹文本会被丢掉,并列入 `RepairResult.discarded`。设为 `locate: false` 时,整个字符串被当成一个 JSON 文档——不做定位,定位这一步就不丢任何东西(强制转换舍掉一句话时仍会报告)。
283
+ - **嵌套超过 1000 层会停止解析。** 写到几千层的 `{"a": {"a": …` 是模型陷入循环,而不是值得读的文档;继续递归只会以栈溢出收场。解析器会闭合已经读到的部分,标记 `nesting-limited`,并把没读到的内容列在 `discarded` 里。
165
284
 
166
285
  ## ⚙️ 修复选项
167
286
 
168
287
  `jsonRepair(input, schema, options)` 的第三个参数就是 `RepairOptions`:
169
288
 
170
- | 选项 | 默认值 | 作用 |
171
- | ----------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
172
- | `coerceTypes` | `true` | 按 Schema 声明的类型做强制转换:`"约 1,200.50 元"` → `1200.5`、`"yes"` → `true`、枚举内的 `"Processing!"` → `"processing"`、`type: 'string'` 下的 `12` → `"12"`(数字取自文档原文,故 `{ id: 01234 }` → `"01234"`)。`null` 与对象/数组不会被转成字符串。 |
173
- | `keyMatching` | `false` | 把输入键名解析成 Schema 声明的属性名。`true` 忽略大小写和分隔符,`user_name`、`userName`、`USER NAME` 均匹配 `userName`;也可以传 `(key, properties) => string \| undefined` 自定义映射(返回 `undefined` 则保留原键名)。命中后输出里的键名会被改写,该子树的类型转换也随之生效。开启 `true` 时它同时决定贪婪捕获在哪里断开:Schema 声明了 `userName`,那么 `user_name:` 就会结束一个值。 |
174
- | `additionalProperties` | `'keep'` | `'remove'` 丢弃 Schema 未声明的键,且只在确实声明了 `properties` 的层级生效 —— 自由结构没有“多余键”的概念,保持原样。它与 JSON Schema 关键字 `additionalProperties: false` 互不影响,后者单独生效。 |
175
- | `stringCaptureStrategy` | `'aggressive'` | `'conservative'`:贪婪捕获在任意“键形状 + `:`”处结束,而不再只在 Schema 声明的键名处结束。代价是值更容易被截断,好处是一个破碎的值不会吞掉后面的一大片内容。 |
289
+ | 选项 | 默认值 | 作用 |
290
+ | --- | --- | --- |
291
+ | `coerceTypes` | `true` | 按 Schema 声明的类型做强制转换:`"约 1,200.50 元"` → `1200.5`、`"yes"` → `true`、枚举内的 `"Processing!"` → `"processing"`、`type: 'string'` 下的 `12` → `"12"`(数字取自文档原文,故 `{ id: 01234 }` → `"01234"`)。`null` 与对象/数组不会被转成字符串。强制转换舍掉值周围的文本时会标 `coerced-text-dropped`;那段文本读起来是一句话而非单位时,还会列入 `discarded`。 |
292
+ | `keyMatching` | `false` | 把输入键名解析成 Schema 声明的属性名。`true` 选中全部形式,`user_name`、`userName`、`USER NAME` 均匹配 `userName`。`{ forms: [...] }` 逐个选择形式 —— `case`(`USERNAME` → `userName`)与 `separators`(`user_name` → `user name`;camelCase 把边界写成大小写变化,所以还要 `case`)—— `separators: [...]` 指定哪些字符算分隔符,`aliases: { 正式名: ['另一个名字'] }` 声明 Schema 写在本库不读的关键词下的拼写。也可以传 `(key, properties) => string \| undefined` 自定义映射(返回 `undefined` 则保留原键名)。命中后输出里的键名会被改写,该子树的类型转换也随之生效。选中某个形式同时决定贪婪捕获在哪里断开:Schema 声明了 `userName`,那么 `user_name:` 就会结束一个值。 |
293
+ | `additionalProperties` | `true` | 就是 JSON Schema 的同名关键字,作为所有未自行声明它的层级的默认值 —— 一个关键字,一条规则。`false` 丢弃该层级未声明的键,其文本列入 `discarded` 并带 `undeclared-keys-dropped` 标记;给一个 Schema(如 `{ type: 'string' }`)则成为这些未声明键的取值规则:保留其值,并按该 Schema 做类型转换与校验。层级自己声明的 `additionalProperties` 优先于默认值;未声明任何属性名的自由层级不会被清空。 |
294
+ | `stringCaptureStrategy` | `'aggressive'` | `'conservative'`:贪婪捕获在任意“键形状 + `:`”处结束,而不再只在 Schema 声明的键名处结束。代价是值更容易被截断,好处是一个破碎的值不会吞掉后面的一大片内容。 |
295
+ | `locate` | `true` | 是否先在文本里定位 JSON(围栏、散文、多个片段)。`false` 则把整个字符串当成一个 JSON 文档——即 0.1.x 之前的行为。两种情况下,本来就能解析的输入都不会被重新定位。 |
296
+ | `onMultiple` | `'best'` | 文本里有多个片段时如何取舍:`'best'` 按对 schema 的契合度排序取胜者(打平时取最后一个,并以 `ambiguous-candidates` 上报);`'last'` / `'first'` 无视排序纯按位置;`'throw'` 直接拒绝输入,并附带各片段的评分。 |
297
+ | `onDiscard` | `'report'` | `'throw'`:只要修复过程中丢弃了散文、落选片段,或某个值吞下的一句话就直接失败;`'ignore'`:丢弃且不在 `RepairResult.discarded` 里列出。 |
298
+ | `wrapArrays` | `true` | schema 期待位于列表内部的记录是否按元素读取:数组 schema 下的 `{ name: Ada }` 会变成 `[{ name: 'Ada' }]`,并排书写的多条记录会成为该列表的元素。设为 `false` 则保留文档原样,代价是该记录的键不再按 `items` 解析(不再强制类型,值可能粘连)。 |
299
+ | `dangling` | `true` | 丢弃输出被截断时留下的键或分隔符(`{"a": 1, "b"` → `{ a: 1 }`),残片会列入 `discarded` 并带上 `dangling-dropped` 标记。设为 `false` 则把残片留在前面的字段里。丢弃不会中断解析:右花括号之后的那条记录仍会被读取,因此在声明了列表的 Schema 下,`{"a": 1, "b"} {"c": 2}` 会得到 `[{ a: 1 }, { c: 2 }]`;没有这条声明时两条记录是互相竞争的片段,失败的一方进入 `discarded` 而不是被合并进来。 |
300
+ | `literals` | `true` | 哪些未加引号的裸 token 按另一种语言的字面量读取:`'python'`(`True`/`False`/`None`)、`'js'`(`undefined`)、`true` 两者都读、`false` 或 `[]` 都不读。该路径上 schema 声明了类型时以 schema 为准;加引号的 `"True"` 永远是字符串。 |
301
+ | `comments` | `false` | 成员之间会跳过哪些注释风格:`'line'`(`//`)、`'block'`(`/* */`,且必须闭合)、`'hash'`(`#`)、`true` 三者全开。字符串内部与裸 token 内部永远不会被识别为注释,因此任何设置下 `https://x` 与 `#123` 都安全;在应当出现值的位置(`:` 之后)也不会识别注释——那里的文本属于模型,可能带注释形状并落入值中;一旦如此,修复会以 `comment-in-value` 点名。 |
302
+ | `unescapedQuotes` | `'keep'` | 模型漏写引号时,引号值在哪里结束:`'declared'` 以引号之后 schema 声明过的成员作为锚点,`'lookahead'` 仅凭文本形状判断,`'keep'` 不做任何推断。 |
303
+ | `escapes` | `'json5'` | 反斜杠在多大程度上被当成转义:`'json5'` 解码 JSON 自己的转义加 `\xNN`,其余拆包(`"\$10"` → `$10`);`'json'` 把 JSON 没有定义的转义按原文保留(`"C:\Users"` → `C:\Users`);`'raw'` 完全不解码,路径、正则、LaTeX 得以完整保留,`"\n"` 则是两个字元。任何设置下反斜杠都仍是结构性的;严格 JSON 拒绝的转义都会报 `invalid-escape`。 |
176
304
 
177
305
  ```typescript
178
306
  const schema = {
@@ -190,10 +318,16 @@ await jsonRepair('{ user_name: "Ada", user_age: "36" }', schema, {
190
318
  // { userName: 'Ada', userAge: 36 }
191
319
 
192
320
  await jsonRepair('{ userName: "Ada", reasoning: "让我想想…" }', schema, {
193
- additionalProperties: 'remove',
321
+ additionalProperties: false,
194
322
  })
195
323
  // { userName: 'Ada' }
196
324
 
325
+ // 一处声明,覆盖 Schema 未点名的一切键
326
+ await jsonRepair('{ userName: "Ada", score: "12" }', schema, {
327
+ additionalProperties: { type: 'number' },
328
+ })
329
+ // { userName: 'Ada', score: 12 }
330
+
197
331
  const querySchema = {
198
332
  type: 'object',
199
333
  properties: { query: { type: 'string' }, intent: { type: 'string' } },
package/README.md CHANGED
@@ -33,19 +33,27 @@ Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses you
33
33
  - **Boolean Variants**: Recognizes `yes/no`, `on/off`, `1/0`, `确定/取消` as booleans.
34
34
  - **Declared Strings Stay Text**: `{ Population: 12 }` against `{ type: 'string' }` yields `"12"`, and the digits are taken from the document, so `{ id: 01234 }` yields `"01234"`.
35
35
  - **Implicit Structure Support**: Automatically repairs missing braces in objects and arrays.
36
+ - **Escape-Faithful Strings**: a string the parser reads decodes exactly as `JSON.parse` does (`\n`, `\t`, `\/`, `\uXXXX`, surrogate pairs). JSON5-style `\xNN` decodes to the character it names, an escape of a character that never needs one is unwrapped (`"\$10"` → `"$10"`), and every escape strict JSON would reject is reported as `invalid-escape`. Set `escapes` when a backslash is content rather than an escape.
36
37
  - **Robust Property Boundaries**: quoted keys may contain spaces and punctuation (`"Official language": "Italian"`), and a multi-word key the Schema declares is recognised even when the document leaves it unquoted; a value that parses cleanly is never re-tokenized, so valid JSON round-trips exactly like `JSON.parse`.
37
38
  - **Fuzzy Key Matching**: `user_name`, `userName` and `USER NAME` resolve to the property your Schema declares, and the output carries the declared name.
39
+ - **Schema Composition Is Read**: `$ref` and `allOf` / `anyOf` / `oneOf` are folded into the level they describe before the Schema is walked, so a type or a property declared inside a branch still coerces and still validates — `{ anyOf: [{ type: 'string' }] }` turns `12` into `"12"`.
38
40
  - **Prototype-Safe Output**: keys such as `__proto__` or `constructor` are stored as own data properties, exactly as `JSON.parse` leaves them.
41
+ - **Locates the JSON First**: Markdown fences, `Sure! Here is the JSON:` preambles and trailing chatter are found and set aside — quote-aware, so a fence that lives _inside_ a string value survives.
42
+ - **Structure Is Split and Merged**: records written side by side under an `array` Schema become items; when a reply holds several fragments, the one that fits the Schema best wins.
43
+ - **Diagnostics, Not Only a Value**: `jsonRepairResult()` reports what it noticed (`flags`), what still fails (`errors`, ready to feed a retry), what it chose between (`candidates`) and what it threw away (`discarded`).
39
44
  - **Performance**: Support for reusing `SchemaWalker` instances for high-throughput batch processing.
40
45
 
41
46
  ## 📦 Installation
42
47
 
43
48
  ```bash
44
- npm install @isdk/json-repair @apidevtools/json-schema-ref-parser
49
+ npm install @isdk/json-repair
45
50
  # or
46
- pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
51
+ pnpm add @isdk/json-repair
47
52
  ```
48
53
 
54
+ `@apidevtools/json-schema-ref-parser` comes with it — it is the `$ref` resolver, not a peer
55
+ dependency, and pinning it yourself only risks a second copy.
56
+
49
57
  ## 🛠 Usage
50
58
 
51
59
  ### 1. Schema-Guided Repair (Recommended)
@@ -120,6 +128,90 @@ for (const item of brokenItems) {
120
128
  }
121
129
  ```
122
130
 
131
+ ## 🧭 Where the JSON Starts
132
+
133
+ A model's reply is text, not a document. It wraps the JSON in a fence, and dresses it up in
134
+ sentences. `jsonRepair` finds the JSON first, then repairs it:
135
+
136
+ ````typescript
137
+ await jsonRepair('```json\n{ name: Ada }\n```', schema)
138
+ // { name: 'Ada' } flags: ['markdown-fence', 'prose-prefix', 'trailing-chatter']
139
+ // discarded: ['```json', '```'] — the fence is text too
140
+
141
+ await jsonRepair('```json\n{ name: Ada }\n```\nHope this helps!', schema)
142
+ // the same value and the same flags; the sentence joins the closing fence in
143
+ // discarded: ['```json', '```\nHope this helps!']
144
+
145
+ await jsonRepair('Here you go:\nname: Ada', schema)
146
+ // { name: 'Ada' } flags: ['implicit-structure', 'prose-prefix']
147
+ ````
148
+
149
+ - The scan is quote-aware and bracket-aware, so `{ "code": "```json\n{}\n```" }` keeps its
150
+ content intact. A regular expression that strips fences would hand you `{}` instead.
151
+ - Input that already parses as JSON is never relocated, which is what keeps valid JSON
152
+ round-tripping exactly like `JSON.parse`.
153
+ - Everything the locating step threw away — wrapper prose, fences, losing fragments — is
154
+ listed in `discarded`. `onDiscard: 'throw'` refuses a repair that discards anything, for
155
+ callers that cannot afford to lose content. What a coercion gives up from inside a value is
156
+ reported by a flag, and follows the rule described under
157
+ [Known Limitations](#-known-limitations--disambiguation).
158
+
159
+ ### More than one fragment
160
+
161
+ A reply often holds several JSON fragments: a draft and a final answer, a decoy, or records laid
162
+ out side by side where the Schema expects an array. The Schema says which one to keep, so it is a
163
+ measurement rather than a guess. Fragments are ranked by:
164
+
165
+ | Compared first | Then |
166
+ | --- | --- |
167
+ | fewer Schema violations (`errors`) | more `required` fields carrying a real value (`""` carries nothing) |
168
+ | more declared fields carrying a real value | fewer JSON Schema keywords reproduced into the answer (`schemaEchoKeys`) |
169
+
170
+ A tie is decided by position — the **last** fragment first, because a model normally drafts
171
+ before it answers — and is reported as `ambiguous-candidates` instead of being hidden.
172
+ `onMultiple` changes the policy to `'first'`, `'last'`, or `'throw'`. Without a Schema the
173
+ ranking has no information to work with, so it collapses to the position rule; say so in your
174
+ own logs if that matters to you.
175
+
176
+ Records sitting side by side under an `array` Schema — `{"name": "Noah"} {"name": "Ada"}`, or the
177
+ same records without any braces — are read as one document holding two items
178
+ (`sibling-objects-merged`). The structure was declared, so that is not a guess either.
179
+
180
+ ### Auditing the repair: valid is not correct
181
+
182
+ A value can satisfy the Schema and still say nothing: `"name": ""`, a placeholder phone number,
183
+ the first enum entry picked by default. `jsonRepairResult()` returns what it noticed along with
184
+ the value:
185
+
186
+ ```typescript
187
+ import { jsonRepairResult, renderValidatorErrors } from '@isdk/json-repair'
188
+
189
+ const { value, errors, flags, candidates, discarded } = await jsonRepairResult(
190
+ reply,
191
+ schema
192
+ )
193
+
194
+ flags
195
+ // ['markdown-fence', 'prose-prefix', 'empty-required']
196
+ errors
197
+ // [{ path: ['email'], message: 'missing required property' }]
198
+
199
+ renderValidatorErrors(errors, 6)
200
+ // - email: missing required property
201
+ ```
202
+
203
+ `errors` is what a retry prompt needs, and `renderValidatorErrors` keeps it to the few lines a
204
+ small model actually follows. Repair first, then retry: syntax, type and structure are settled
205
+ deterministically and cost nothing, so a second model call is spent only on what no code can
206
+ know — an answer that is well formed and wrong.
207
+
208
+ A retry cannot see a placeholder either. `"name": ""` satisfies the Schema, and a model asked to
209
+ fix an error it does not have writes the placeholder again, so the repair names it:
210
+ `empty-required` (a required string left empty), `schema-echo-detected` (the Schema copied back as the answer, even when the copy
211
+ parses perfectly), `ambiguous-candidates` (two fragments that fit equally well), `coerced-text-dropped` (a coercion kept part of a value and gave up the text around it), `undeclared-keys-dropped` (a key the level's `additionalProperties` forbids was dropped, with its text in `discarded`). Every decision the
212
+ repair made is in `flags` — the full list is [`RepairFlag`](https://github.com/isdk/json-repair.js/blob/main/docs/type-aliases/RepairFlag.md) in the API docs — so accepting,
213
+ retrying or escalating is a decision made on evidence, not on "it parsed".
214
+
123
215
  ## 🧭 How Property Boundaries Are Detected
124
216
 
125
217
  While repairing a value, the parser must decide at every position whether an upcoming
@@ -170,6 +262,13 @@ parser follows are:
170
262
  - If a value looks truncated right at something key-shaped, that level is probably missing
171
263
  `properties` in your Schema — add them and re-run.
172
264
 
265
+ A value that stops at a quote the model never closed is the other ambiguous case:
266
+ `{"t": "The "Best" Paper", "y": 2020}`. By default (`unescapedQuotes: 'keep'`) it keeps the
267
+ delimiters the document spelled. `'declared'` ends it at the first quote after which a member
268
+ the Schema declares begins — the declared member is the anchor, so the boundary is read rather
269
+ than guessed. `'lookahead'` applies the same rule to the text alone, for documents with no
270
+ Schema.
271
+
173
272
  Numeric literals support scientific notation (`1e5`, `-2E2`) as well as the lax LLM forms
174
273
  `+5`, `.5` and `5.`. A partial literal such as `1.2.3` is kept as a string and then coerced
175
274
  according to the Schema.
@@ -178,6 +277,57 @@ A declared `type: 'string'` is honoured in the other direction too: `12` becomes
178
277
  because the text comes from the document rather than the parsed number, a leading zero
179
278
  survives (`{ id: 01234 }` → `"01234"`). `null` and structures are never stringified.
180
279
 
280
+ A level whose `additionalProperties` is `false` — the Schema writing it or
281
+ `RepairOptions.additionalProperties` supplying it for every level that does not — has its
282
+ undeclared keys written out of the answer instead of kept in it, so a strict Schema yields a
283
+ value that satisfies it. What went is listed in `discarded` and flagged
284
+ `undeclared-keys-dropped`; a level that declares no property names at all is never emptied.
285
+
286
+ `patternProperties` describes keys by shape instead of by name, and the repair reads it as the
287
+ declaration it is: the value of a key a pattern covers is coerced and validated against the
288
+ Schema behind that pattern, a covered key is not an extra one for `additionalProperties`, and a
289
+ matching key anchors a value the way a declared name does. A level whose only declaration is
290
+ `patternProperties` is therefore not free-form — `additionalProperties: false` there does drop
291
+ the keys no pattern covers. A pattern the host engine cannot compile (`(?i)` flags come from
292
+ another dialect) is not held against the document: it covers every key and describes none. Where
293
+ two patterns match one key, the first describes its value - reading one value through several
294
+ Schemas at once is not something this validator does.
295
+
296
+ ### How Escapes Are Read
297
+
298
+ Escapes are decoded, not guessed:
299
+
300
+ | The document writes | The value contains |
301
+ | --- | --- |
302
+ | `"a\nb"`, `"\t"`, `"\/"` | the control character, `/` — exactly what `JSON.parse` yields |
303
+ | `"café"`, `"\ud83d\ude00"` | `é`, `😀`; an unpaired surrogate stays where `JSON.parse` puts it |
304
+ | `"\xa0"` (the JSON5-style hex escape) | the character U+00A0 |
305
+ | `"\$10"`, `"a\qb"` (an escape of a character that needs none) | `$10`, `aqb` |
306
+ | `note: first line\nsecond` (a captured, unquoted value) | the text as written, backslash included — greedy capture does not decode |
307
+
308
+ Decoding stops at decoding. An NBSP, a zero-width space or a smart quote that the document
309
+ wrote stays in the value: rewriting those would change the model's content, not its syntax.
310
+
311
+ An escape strict JSON would reject is always reported as `invalid-escape`, whatever is done
312
+ with it: a value gained or lost a backslash, and the caller is owed that information.
313
+ `escapes` decides how far a backslash is trusted:
314
+
315
+ | `escapes` | `"\$10"` | `"C:\Users"` | `"C:\temp"` | `"\x41"` | `"a\nb"` |
316
+ | --- | --- | --- | --- | --- | --- |
317
+ | `'json5'` (default) | `$10` | `C:Users` | `C:`, tab, `emp` | `A` | a newline |
318
+ | `'json'` | `\$10` | `C:\Users` | `C:`, tab, `emp` | `\x41` | a newline |
319
+ | `'raw'` | `\$10` | `C:\Users` | `C:\temp` | `\x41` | `\n` — two characters |
320
+
321
+ `'json'` repairs only the syntax it is sure of and leaves every escape JSON does not define as
322
+ the document wrote it, which is what markdown- and LaTeX-trained models write. `'raw'` treats
323
+ every backslash as content, which is what a document of Windows paths, regular expressions or
324
+ LaTeX wants (`"C:\temp"` is a path, not a tab; `"\frac{a}{b}"` is a command, not a form feed)
325
+ at the price it names: no value can carry a newline any more.
326
+
327
+ A backslash stays structural at every setting — it is always the reason the character behind it
328
+ remains inside the string — so the choice cannot change where a value ends. An incomplete hex
329
+ escape (`"\xg"`, `"\uZZ"`) decodes nothing in every setting and is left exactly as written.
330
+
181
331
  ## ⚠️ Known Limitations & Disambiguation
182
332
 
183
333
  - **The "Parity Rule"**: When a string is wrapped in quotes and contains internal quotes, we count the internal ones.
@@ -188,18 +338,31 @@ survives (`{ id: 01234 }` → `"01234"`). `null` and structures are never string
188
338
  `{ "note": see "foo bar": baz here, "b": 2 }` without a schema is therefore read as `{ note: 'see', 'foo bar': 'baz here', b: 2 }`. Declaring that level's `properties` makes greedy capture stop only at real keys and restores `{ note: 'see "foo bar": baz here', b: 2 }` (see [Thinking about the heuristic](#thinking-about-the-heuristic)).
189
339
  - **Unquoted multi-word keys need a declaration.** `{ Capital: Berlin, Official language: Italian }` becomes two properties because the Schema declares `Official language`. A spaced key that is _not_ declared is not a key: `{ Capital: Berlin, Official Lang: Italian }` keeps the whole text in `Capital` under the default `'aggressive'` strategy, and splits at the space (`{ Capital: 'Berlin, Official', Lang: 'Italian' }`) under `'conservative'`.
190
340
  - **Prose that repeats a declared key is cut there.** Declared keys are breakpoints, so `{ summary: the Official language: Italian is wrong, Official language: Italian }` reads `summary = 'the'`. If a value may legitimately repeat a declared key, have the model quote its keys or pick a less colliding property name.
191
- - **Markdown Blocks**: This library focuses on the JSON content. Please strip `json ...` markers before passing the string if your LLM includes them.
341
+ - **A backslash that was meant as a path separator cannot be recognised as one.** `{ "path": "C:\new\test" }` really does contain the escapes `\n` and `\t`, so the default reads `C:`, a newline, `ew`, a tab and `est`; only `"C:\\new\\test"` is a Windows path, and no repairer can tell the two apart, so we do not guess. What you can choose is how much a backslash is trusted: `escapes: 'json'` keeps an escape JSON does not define (`"C:\Users"` stays `C:\Users`), and `escapes: 'raw'` keeps every backslash, which is the only setting that survives `C:\temp` intact — at the cost of `"\n"` no longer being a newline. Either way `invalid-escape` says the document contained one.
342
+ - **Trailing prose after a record that has no braces is kept**: `Here you go:\nname: Ada\nHope this helps!` yields `name = 'Ada\nHope this helps!'`. A brace-less value can only be cut where the Schema names the next key — a `city:` after it would cut, a sentence after it cannot be known to be prose.
343
+ - **A number coercion cuts a value where the number ends.** `{ "age": 30 more words }` reads `age = 30`: the value keeps the first well-formed numeric token and gives up the text around it, which is what makes `约 1,200.50 元` read as `1200.5`. Greedy capture can run a value into the prose a model wrote after it (`{ age: 30\n\nHope this helps!}`), so what the coercion gave up is reported: `coerced-text-dropped` always, and the text itself in `RepairResult.discarded` when it reads as a sentence rather than as a qualifier — three words, or twenty characters with no space to count them by. `Approx. USD` stays out of `discarded`; `Hope this helps!` does not.
344
+ - **Fences and prose are located, not rewritten**: the wrapper text around the JSON is dropped and listed in `RepairResult.discarded`. Set `locate: false` to treat the whole string as one JSON document — nothing is located, so the locating step discards nothing (a coercion that gives up a sentence still says so).
345
+ - **Nesting deeper than 1000 levels stops the parse.** A document written `{"a": {"a": …` thousands deep is a model caught in a loop rather than a document worth reading, and walking it recursively would end in a stack overflow instead of an answer. The parser closes what it opened, flags `nesting-limited`, and lists the text it never read in `discarded`.
192
346
 
193
347
  ## ⚙️ Repair Options
194
348
 
195
- `jsonRepair(input, schema, options)` takes a fourth argument of type `RepairOptions`:
196
-
197
- | Option | Default | What it does |
198
- | ----------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
199
- | `coerceTypes` | `true` | Converts a value to the type the Schema declares: `"Approx. 1,200.50 USD"` → `1200.5`, `"yes"` → `true`, `"Processing!"` → `"processing"` when the enum says so, `12` → `"12"` under `type: 'string'` (the digits come from the document, so `{ id: 01234 }` → `"01234"`). `null` and structures are never stringified. |
200
- | `keyMatching` | `false` | Resolves incoming keys to the names the Schema declares. `true` ignores case and separators, so `user_name`, `userName` and `USER NAME` all match `userName`; a function `(key, properties) => string \| undefined` decides itself (`undefined` keeps the key as it is). A match renames the key in the output, which also re-enables coercion for that subtree. With `true` it also decides where greedy capture stops: `user_name:` ends a value when the Schema declares `userName`. |
201
- | `additionalProperties` | `'keep'` | `'remove'` drops keys the Schema does not declare. Applied only at levels that do declare `properties` — a free-form level has no “extra” keys and is left untouched. Independent of the JSON Schema keyword `additionalProperties: false`, which is honoured on its own. |
202
- | `stringCaptureStrategy` | `'aggressive'` | `'conservative'` ends greedy capture at any key-shaped token instead of only at declared Schema keys: less risk of one broken value swallowing the rest of the document, at the cost of cutting values short. |
349
+ `jsonRepair(input, schema, options)` takes a third argument of type `RepairOptions`:
350
+
351
+ | Option | Default | What it does |
352
+ | --- | --- | --- |
353
+ | `coerceTypes` | `true` | Converts a value to the type the Schema declares: `"Approx. 1,200.50 USD"` → `1200.5`, `"yes"` → `true`, `"Processing!"` → `"processing"` when the enum says so, `12` → `"12"` under `type: 'string'` (the digits come from the document, so `{ id: 01234 }` → `"01234"`). `null` and structures are never stringified. A coercion that gives up text around the value it keeps flags `coerced-text-dropped`; text long enough to read as a sentence, rather than as a unit, is listed in `discarded` too. |
354
+ | `keyMatching` | `false` | Resolves incoming keys to the names the Schema declares. `true` selects every form, so `user_name`, `userName` and `USER NAME` all match `userName`. `{ forms: [...] }` selects them one at a time — `case` (`USERNAME` → `userName`) and `separators` (`user_name` → `user name`; camelCase needs `case` as well, because it writes the boundary as a case change) — with `separators: [...]` naming which characters count and `aliases: { canonical: ['Other name'] }` declaring the spellings the Schema keeps under a keyword this library does not read. A function `(key, properties) => string \| undefined` decides itself (`undefined` keeps the key as it is). A match renames the key in the output, which also re-enables coercion for that subtree. A selected form also decides where greedy capture stops: `user_name:` ends a value when the Schema declares `userName`. |
355
+ | `additionalProperties` | `true` | The JSON Schema keyword, supplied as the default for every level that does not state it itself — one keyword, one rule. `false` drops keys a level does not declare, lists them in `discarded` and flags `undeclared-keys-dropped`; a Schema (`{ type: 'string' }`) keeps those keys and describes their values, which are then coerced and validated against it. A level that states its own `additionalProperties` outranks the default, and a level that declares no property names is never emptied. |
356
+ | `stringCaptureStrategy` | `'aggressive'` | `'conservative'` ends greedy capture at any key-shaped token instead of only at declared Schema keys: less risk of one broken value swallowing the rest of the document, at the cost of cutting values short. |
357
+ | `locate` | `true` | Whether to look for the JSON inside the text first (fences, prose, several fragments). `false` treats the whole string as one JSON document - the behaviour up to 0.1.x. Input that already parses is never relocated either way. |
358
+ | `onMultiple` | `'best'` | How to choose when the text holds more than one fragment: `'best'` ranks them by how well they fit the Schema and takes the winner (ties go to the last fragment, reported as `ambiguous-candidates`); `'last'` / `'first'` ignore the ranking; `'throw'` rejects the input and lists the fragments with their scores. |
359
+ | `onDiscard` | `'report'` | `'throw'` refuses a repair that had to drop prose, a losing fragment, or a sentence a value had swallowed; `'ignore'` drops them without listing them in `RepairResult.discarded`. |
360
+ | `wrapArrays` | `true` | Whether a record the Schema expects inside a list is read as an item: `{ name: Ada }` under an array Schema becomes `[{ name: 'Ada' }]`, and sibling records written side by side become the items. `false` keeps what the document wrote, at the cost of the record's keys no longer being resolved against `items` (no coercion, values can run together). |
361
+ | `dangling` | `true` | Drops a key or separator the output was cut off at (`{"a": 1, "b"` → `{ a: 1 }`), listing the fragment in `discarded` and flagging `dangling-dropped`. `false` keeps the fragment inside the field in front of it. Dropping does not stop the parse: a record written after the closing brace is still read, so under a Schema that expects a list `{"a": 1, "b"} {"c": 2}` becomes `[{ a: 1 }, { c: 2 }]`. Without that declaration the two records are competing fragments, and the loser is reported in `discarded` rather than joined. |
362
+ | `literals` | `true` | Which bare tokens are read as a literal of another language: `'python'` (`True`/`False`/`None`), `'js'` (`undefined`), `true` for both, `false` or `[]` for neither. A Schema that names a type at the path outranks it, and a quoted `"True"` is always a string. |
363
+ | `comments` | `false` | Which comment styles are skipped between members: `'line'` (`//`), `'block'` (`/* */`, only when closed), `'hash'` (`#`), `true` for all three. Never read inside a string or a bare token, so `https://x` and `#123` are safe at every setting; nor is one read where a value belongs - after a `:` the text is the model's, comment-shaped or not, and can end up inside the value. When one does, the repair flags `comment-in-value`. |
364
+ | `unescapedQuotes` | `'keep'` | Where a quoted value ends when the model left a quote unescaped: `'declared'` uses a Schema-declared member after the quote as the anchor, `'lookahead'` judges by the text alone. `'keep'` infers nothing. |
365
+ | `escapes` | `'json5'` | How much a backslash is trusted. `'json5'` decodes JSON's escapes plus `\xNN` and unwraps the rest (`"\$10"` → `$10`); `'json'` leaves anything JSON does not define as written (`"C:\Users"` → `C:\Users`); `'raw'` decodes nothing, so paths, regular expressions and LaTeX survive whole and `"\n"` is two characters. A backslash is structural in all three, and an escape strict JSON rejects raises `invalid-escape`. |
203
366
 
204
367
  ```typescript
205
368
  const schema = {
@@ -217,10 +380,16 @@ await jsonRepair('{ user_name: "Ada", user_age: "36" }', schema, {
217
380
  // { userName: 'Ada', userAge: 36 }
218
381
 
219
382
  await jsonRepair('{ userName: "Ada", reasoning: "let me think…" }', schema, {
220
- additionalProperties: 'remove',
383
+ additionalProperties: false,
221
384
  })
222
385
  // { userName: 'Ada' }
223
386
 
387
+ // one declaration covers every key the Schema does not name
388
+ await jsonRepair('{ userName: "Ada", score: "12" }', schema, {
389
+ additionalProperties: { type: 'number' },
390
+ })
391
+ // { userName: 'Ada', score: 12 }
392
+
224
393
  const querySchema = {
225
394
  type: 'object',
226
395
  properties: { query: { type: 'string' }, intent: { type: 'string' } },