@isdk/json-repair 0.1.3 → 0.2.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.
Files changed (46) hide show
  1. package/README.cn.md +126 -7
  2. package/README.md +148 -7
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +571 -4
  5. package/dist/index.d.ts +571 -4
  6. package/dist/index.js +1 -1
  7. package/docs/README.md +148 -7
  8. package/docs/_media/README.cn.md +126 -7
  9. package/docs/classes/RepairParser.md +69 -3
  10. package/docs/classes/SchemaWalker.md +9 -9
  11. package/docs/functions/compareScores.md +32 -0
  12. package/docs/functions/discardedText.md +42 -0
  13. package/docs/functions/expectsArrayRoot.md +23 -0
  14. package/docs/functions/findImplicitRecordRegion.md +32 -0
  15. package/docs/functions/jsonRepair.md +4 -3
  16. package/docs/functions/jsonRepairResult.md +50 -0
  17. package/docs/functions/locateJsonCandidates.md +33 -0
  18. package/docs/functions/looksLikeSchemaEcho.md +29 -0
  19. package/docs/functions/renderValidatorErrors.md +32 -0
  20. package/docs/functions/scoreCandidate.md +45 -0
  21. package/docs/functions/validateValue.md +38 -0
  22. package/docs/globals.md +19 -0
  23. package/docs/interfaces/CandidateScore.md +63 -0
  24. package/docs/interfaces/JsonCandidate.md +71 -0
  25. package/docs/interfaces/LocatedJson.md +48 -0
  26. package/docs/interfaces/RepairOptions.md +210 -5
  27. package/docs/interfaces/RepairResult.md +58 -0
  28. package/docs/interfaces/ValidationError.md +27 -0
  29. package/docs/type-aliases/CommentStyle.md +13 -0
  30. package/docs/type-aliases/EscapeMode.md +13 -0
  31. package/docs/type-aliases/JSONPath.md +1 -1
  32. package/docs/type-aliases/LiteralDialect.md +13 -0
  33. package/docs/type-aliases/RepairFlag.md +11 -0
  34. package/package.json +26 -4
  35. package/.prettierignore +0 -12
  36. package/.prettierrc +0 -8
  37. package/.versionrc +0 -36
  38. package/CHANGELOG.md +0 -34
  39. package/TODO +0 -0
  40. package/eslint.config.mjs +0 -65
  41. package/setupVitest.mjs +0 -15
  42. package/tsconfig.json +0 -20
  43. package/tsconfig.release.json +0 -21
  44. package/tsup.config.ts +0 -38
  45. package/typedoc.config.cjs +0 -9
  46. package/vite.config.mjs +0 -21
package/README.cn.md CHANGED
@@ -33,6 +33,7 @@ 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 声明的属性名,输出里用的就是声明的名字。
38
39
  - **原型安全的输出**:`__proto__`、`constructor` 这类键名存为自身的普通属性,与 `JSON.parse` 的处理一致。
@@ -118,6 +119,78 @@ for (const item of brokenItems) {
118
119
  }
119
120
  ```
120
121
 
122
+ ## 🧭 先定位 JSON 从哪里开始
123
+
124
+ 模型的回复是文本,不是文档:JSON 外面套着围栏,前后还裹着句子。`jsonRepair` 先定位 JSON,
125
+ 再修它:
126
+
127
+ ````typescript
128
+ await jsonRepair('```json\n{ name: Ada }\n```', schema)
129
+ // { name: 'Ada' } flags: ['markdown-fence']
130
+
131
+ await jsonRepair('```json\n{ name: Ada }\n```\nHope this helps!', schema)
132
+ // { name: 'Ada' } flags: ['markdown-fence', 'prose-prefix', 'trailing-chatter']
133
+
134
+ await jsonRepair('Here you go:\nname: Ada', schema)
135
+ // { name: 'Ada' } flags: ['prose-prefix', 'implicit-structure']
136
+ ````
137
+
138
+ - 定位扫描感知引号与括号配平,所以 `{ "code": "```json\n{}\n```" }` 的内容完好无损——
139
+ 而一个剥离围栏的正则会把 `{}` 交给你。
140
+ - 已经能解析的输入永远不会被重新定位,这正是「合法 JSON 与 `JSON.parse` 结果完全一致」的前提。
141
+ - 定位阶段丢掉的内容——包裹散文、围栏、落选片段——都会列在 `discarded` 里;`onDiscard: 'throw'` 会让任何有丢弃的修复直接失败,
142
+ 供丢不起内容的调用方使用。强制转换在值内部舍掉的文本则由 flag 报告,规则见[注意事项与歧义说明](#-注意事项与歧义说明)。
143
+
144
+ ### 多个 JSON 片段
145
+
146
+ 回复里常常有好几个 JSON 片段:草稿加最终答案、诱饵,或者 schema 期待数组时并排放着的若干条记录。
147
+ 选哪一个由 schema 决定,所以这是度量而不是猜测。片段按下列顺序比较:
148
+
149
+ | 先比 | 再比 |
150
+ | --- | --- |
151
+ | schema 违规更少(`errors`) | `required` 字段里带真实值的更多(`""` 等于没有) |
152
+ | 声明字段里带真实值的更多 | 答案里复刻的 JSON Schema 关键字更少(`schemaEchoKeys`) |
153
+
154
+ 打平时按位置裁决——**最后**一个优先,因为模型通常先推理再作答——并且以
155
+ `ambiguous-candidates` 上报,而不是悄悄替你做决定。`onMultiple` 可以改成 `'first'`、`'last'`
156
+ 或 `'throw'`。没有 schema 时排序没有信息可用,于是退化为位置规则;如果这点对你的日志很重要,
157
+ 请自己标注。
158
+
159
+ 在 `array` schema 下并排摆放的记录(`{"name": "Noah"} {"name": "Ada"}`,或者连花括号都没有的
160
+ 同样记录)会被读成「一个文档、两个元素」(`sibling-objects-merged`)——结构是声明过的,
161
+ 这同样不是猜测。
162
+
163
+ ### 审查修复结果:合法不等于正确
164
+
165
+ 一个值可以完全满足 schema 却什么也没说:`"name": ""`、占位的电话号码、默认选中的第一个枚举项。
166
+ 所以 `jsonRepairResult()` 在返回值之外,还把注意到的事情一起交给你:
167
+
168
+ ```typescript
169
+ import { jsonRepairResult, renderValidatorErrors } from '@isdk/json-repair'
170
+
171
+ const { value, errors, flags, candidates, discarded } = await jsonRepairResult(
172
+ reply,
173
+ schema
174
+ )
175
+
176
+ flags
177
+ // ['markdown-fence', 'prose-prefix', 'empty-required']
178
+ errors
179
+ // [{ path: ['email'], message: 'missing required property' }]
180
+
181
+ renderValidatorErrors(errors, 6)
182
+ // - email: missing required property
183
+ ```
184
+
185
+ `errors` 正是重试提示词需要的东西,`renderValidatorErrors` 把它压到小模型还跟得上的几行。
186
+ 先修复,后重试:语法、类型、结构都由确定性代码解决,成本为零;第二次模型调用只该花在代码无从得知的地方——
187
+ 一个格式正确但内容错误的答案。
188
+
189
+ 重试也看不见占位符。`"name": ""` 满足 schema,让模型去修一个它并不存在的错误,它只会再写一遍,
190
+ 所以修复过程自己会点名:`empty-required`(必填字符串留空)、`schema-echo-detected`(把 schema 原样抄回来当答案,抄得完全合法也会点名)、
191
+ `ambiguous-candidates`(两个片段同样合规)、`coerced-text-dropped`(强制转换保留了值的一部分,舍掉了它周围的文本)。修复过程做过的每个决定都在 `flags` 里(完整列表见 API 文档的 `RepairFlag`),
192
+ 因此接受、重试还是换更大的模型,是依据证据决定,而不是因为“它解析成功了”。
193
+
121
194
  ## 🧭 属性边界是如何判定的
122
195
 
123
196
  在修复一个值的过程中,解析器必须在每个位置上判断接下来的 `"foo":` 是**下一个属性**的起点,还是**当前值**的一部分。它分为两种模式:
@@ -146,10 +219,43 @@ for (const item of brokenItems) {
146
219
  - 如果值里可能合法地出现 `word:` 或 `"phrase":`,要么让模型输出正确转义的 JSON(严格解析直接胜出),要么在 Schema 里声明该层级的属性。
147
220
  - 如果某个值在“看起来像键”的地方被截断,通常是你的 Schema 在该层级缺少 `properties` —— 补上后重试。
148
221
 
222
+ 另一类歧义是模型写了一半的引号:`{"t": "The "Best" Paper", "y": 2020}`。默认 `unescapedQuotes: 'keep'`,值会保留文档里写的引号。`'declared'` 在“引号之后紧跟 schema 声明过的成员”的位置结束该值——被声明的成员就是锚点,边界于是是被读出来的,而不是猜出来的。`'lookahead'` 只凭文本形状套用同一规则,适用于没有 schema 的文档。
223
+
149
224
  数字字面量支持科学计数法(`1e5`、`-2E2`),也容忍 LLM 常见的 `+5`、`.5`、`5.`。而 `1.2.3` 这种不完整的字面量会先作为字符串保留,再按 Schema 做强制转换。
150
225
 
151
226
  反方向同样成立:Schema 声明 `type: 'string'` 时 `12` 会被转成 `"12"`;并且文本取自文档原文而非解析后的数字,所以前导零不会丢失(`{ id: 01234 }` → `"01234"`)。`null` 与对象/数组不会被转成字符串。
152
227
 
228
+ ### 转义是如何读取的
229
+
230
+ 转义是解码,不是猜测:
231
+
232
+ | 文档里写的 | 值里的内容 |
233
+ | --- | --- |
234
+ | `"a\nb"`、`"\t"`、`"\/"` | 控制字元、`/` —— 与 `JSON.parse` 的结果完全一致 |
235
+ | `"café"`、`"\ud83d\ude00"` | `é`、`😀`;落单的代理项也留在 `JSON.parse` 会在的位置 |
236
+ | `"\xa0"`(JSON5 风格的十六进制转义) | 字元 U+00A0 |
237
+ | `"\$10"`、`"a\qb"`(给不需要转义的字元加了转义) | `$10`、`aqb` |
238
+ | `note: first line\nsecond`(被捕获的无引号值) | 按原文保留,反斜杠也在 —— 贪婪捕获不做解码 |
239
+
240
+ 解码到此为止。文档里写下的 NBSP、零宽空格、弯引号都原样留在值里:改写它们是在改动模型的内容,而不是在修复它的语法。
241
+
242
+ 凡是严格 JSON 会拒绝的转义,无论怎么处理,都会报 `invalid-escape`:值少了一个或多了一个反斜杠,
243
+ 调用方有权知道。`escapes` 决定反斜杠在多大程度上被当成转义:
244
+
245
+ | `escapes` | `"\$10"` | `"C:\Users"` | `"C:\temp"` | `"\x41"` | `"a\nb"` |
246
+ | --- | --- | --- | --- | --- | --- |
247
+ | `'json5'`(默认) | `$10` | `C:Users` | `C:`、制表符、`emp` | `A` | 换行 |
248
+ | `'json'` | `\$10` | `C:\Users` | `C:`、制表符、`emp` | `\x41` | 换行 |
249
+ | `'raw'` | `\$10` | `C:\Users` | `C:\temp` | `\x41` | `\n` —— 两个字元 |
250
+
251
+ `'json'` 只修复它确定的语法,JSON 没有定义的转义一律按原文保留——这正是 markdown 与 LaTeX 训练出来的
252
+ 模型习惯写的写法。`'raw'` 把每个反斜杠都当作内容,适用于值本身就是 Windows 路径、正则表达式或 LaTeX
253
+ 的文档(`"C:\temp"` 是路径不是制表符,`"\frac{a}{b}"` 是命令不是换页符),代价也写得很清楚:值里不
254
+ 再可能出现换行。
255
+
256
+ 任何设置下反斜杠都仍然是结构性的——它始终是下一个字元留在字符串里的理由——所以这个选择不会改变值
257
+ 在哪里结束。写坏了的十六进制转义(`"\xg"`、`"\uZZ"`)在任何设置下都不做解码,原样保留。
258
+
153
259
  ## ⚠️ 注意事项与歧义说明
154
260
 
155
261
  - **“奇偶判定法”逻辑**:当字符串被引号包裹且内部包含引号时,我们会计算内部引号的数量。
@@ -161,18 +267,31 @@ for (const item of brokenItems) {
161
267
  声明该层级的 `properties` 后,贪婪捕获只在真正的键名处断开,才能还原成 `{ note: 'see "foo bar": baz here', b: 2 }`(参见[如何理解这套启发式](#如何理解这套启发式))。
162
268
  - **未加引号的多词键名必须有声明。** `{ Capital: Berlin, Official language: Italian }` 能拆成两个属性,是因为 Schema 声明了 `Official language`。若文档里的带空格键名 _没有_ 声明,它就不是键:`{ Capital: Berlin, Official Lang: Italian }` 在默认的 `'aggressive'` 策略下会把整段都留在 `Capital` 里;改用 `'conservative'` 则会在空格处断开(`{ Capital: 'Berlin, Official', Lang: 'Italian' }`)。
163
269
  - **值里重复出现已声明的键名时会被截断。** 声明过的键就是断点,所以 `{ summary: the Official language: Italian is wrong, Official language: Italian }` 会读成 `summary = 'the'`。如果值确实可能重复某个已声明的键名,就让模型给键加引号,或者换一个不会碰撞的属性名。
164
- - **Markdown 代码块**:本库专注于 JSON 内容修复。如果 LLM 的输出包含 `json ...` 标记,请在传入前自行剥离。
270
+ - **当作路径分隔符的反斜杠无法被认出来。** `{ "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` 都会告诉你文档里有这种转义。
271
+ - **没有花括号的记录,其后的散文会被保留**:`Here you go:\nname: Ada\nHope this helps!` 会得到 `name = 'Ada\nHope this helps!'`。没有花括号的值只能在 schema 点名下一个键的地方切断——后面跟 `city:` 能切,后面是一句话则无从判断它是散文。
272
+ - **转成数字时,值在数字结束处被切断**:`{ "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!` 进)。
273
+ - **围栏与散文是被定位、被丢弃的**:JSON 外面的包裹文本会被丢掉,并列入 `RepairResult.discarded`。设为 `locate: false` 时,整个字符串被当成一个 JSON 文档——不做定位,定位这一步就不丢任何东西(强制转换舍掉一句话时仍会报告)。
274
+ - **嵌套超过 1000 层会停止解析。** 写到几千层的 `{"a": {"a": …` 是模型陷入循环,而不是值得读的文档;继续递归只会以栈溢出收场。解析器会闭合已经读到的部分,标记 `nesting-limited`,并把没读到的内容列在 `discarded` 里。
165
275
 
166
276
  ## ⚙️ 修复选项
167
277
 
168
278
  `jsonRepair(input, schema, options)` 的第三个参数就是 `RepairOptions`:
169
279
 
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 声明的键名处结束。代价是值更容易被截断,好处是一个破碎的值不会吞掉后面的一大片内容。 |
280
+ | 选项 | 默认值 | 作用 |
281
+ | --- | --- | --- |
282
+ | `coerceTypes` | `true` | 按 Schema 声明的类型做强制转换:`"约 1,200.50 元"` → `1200.5`、`"yes"` → `true`、枚举内的 `"Processing!"` → `"processing"`、`type: 'string'` 下的 `12` → `"12"`(数字取自文档原文,故 `{ id: 01234 }` → `"01234"`)。`null` 与对象/数组不会被转成字符串。强制转换舍掉值周围的文本时会标 `coerced-text-dropped`;那段文本读起来是一句话而非单位时,还会列入 `discarded`。 |
283
+ | `keyMatching` | `false` | 把输入键名解析成 Schema 声明的属性名。`true` 忽略大小写和分隔符,`user_name`、`userName`、`USER NAME` 均匹配 `userName`;也可以传 `(key, properties) => string \| undefined` 自定义映射(返回 `undefined` 则保留原键名)。命中后输出里的键名会被改写,该子树的类型转换也随之生效。开启 `true` 时它同时决定贪婪捕获在哪里断开:Schema 声明了 `userName`,那么 `user_name:` 就会结束一个值。 |
284
+ | `additionalProperties` | `'keep'` | `'remove'` 丢弃 Schema 未声明的键,且只在确实声明了 `properties` 的层级生效 —— 自由结构没有“多余键”的概念,保持原样。它与 JSON Schema 关键字 `additionalProperties: false` 互不影响,后者单独生效。 |
285
+ | `stringCaptureStrategy` | `'aggressive'` | `'conservative'`:贪婪捕获在任意“键形状 + `:`”处结束,而不再只在 Schema 声明的键名处结束。代价是值更容易被截断,好处是一个破碎的值不会吞掉后面的一大片内容。 |
286
+ | `locate` | `true` | 是否先在文本里定位 JSON(围栏、散文、多个片段)。`false` 则把整个字符串当成一个 JSON 文档——即 0.1.x 之前的行为。两种情况下,本来就能解析的输入都不会被重新定位。 |
287
+ | `onMultiple` | `'best'` | 文本里有多个片段时如何取舍:`'best'` 按对 schema 的契合度排序取胜者(打平时取最后一个,并以 `ambiguous-candidates` 上报);`'last'` / `'first'` 无视排序纯按位置;`'throw'` 直接拒绝输入,并附带各片段的评分。 |
288
+ | `onDiscard` | `'report'` | `'throw'`:只要修复过程中丢弃了散文、落选片段,或某个值吞下的一句话就直接失败;`'ignore'`:丢弃且不在 `RepairResult.discarded` 里列出。 |
289
+ | `wrapArrays` | `true` | schema 期待位于列表内部的记录是否按元素读取:数组 schema 下的 `{ name: Ada }` 会变成 `[{ name: 'Ada' }]`,并排书写的多条记录会成为该列表的元素。设为 `false` 则保留文档原样,代价是该记录的键不再按 `items` 解析(不再强制类型,值可能粘连)。 |
290
+ | `dangling` | `true` | 丢弃输出被截断时留下的键或分隔符(`{"a": 1, "b"` → `{ a: 1 }`),残片会列入 `discarded` 并带上 `dangling-dropped` 标记。设为 `false` 则把残片留在前面的字段里。丢弃不会中断解析:右花括号之后的那条记录仍会被读取,因此 `{"a": 1, "b"} {"c": 2}` 会得到 `[{ a: 1 }, { c: 2 }]`。 |
291
+ | `literals` | `true` | 哪些未加引号的裸 token 按另一种语言的字面量读取:`'python'`(`True`/`False`/`None`)、`'js'`(`undefined`)、`true` 两者都读、`false` 或 `[]` 都不读。该路径上 schema 声明了类型时以 schema 为准;加引号的 `"True"` 永远是字符串。 |
292
+ | `comments` | `false` | 成员之间会跳过哪些注释风格:`'line'`(`//`)、`'block'`(`/* */`,且必须闭合)、`'hash'`(`#`)、`true` 三者全开。字符串内部与裸 token 内部永远不会被识别为注释,因此任何设置下 `https://x` 与 `#123` 都安全;在应当出现值的位置(`:` 之后)也不会识别注释——那里的文本属于模型,可能带注释形状并落入值中;一旦如此,修复会以 `comment-in-value` 点名。 |
293
+ | `unescapedQuotes` | `'keep'` | 模型漏写引号时,引号值在哪里结束:`'declared'` 以引号之后 schema 声明过的成员作为锚点,`'lookahead'` 仅凭文本形状判断,`'keep'` 不做任何推断。 |
294
+ | `escapes` | `'json5'` | 反斜杠在多大程度上被当成转义:`'json5'` 解码 JSON 自己的转义加 `\xNN`,其余拆包(`"\$10"` → `$10`);`'json'` 把 JSON 没有定义的转义按原文保留(`"C:\Users"` → `C:\Users`);`'raw'` 完全不解码,路径、正则、LaTeX 得以完整保留,`"\n"` 则是两个字元。任何设置下反斜杠都仍是结构性的;严格 JSON 拒绝的转义都会报 `invalid-escape`。 |
176
295
 
177
296
  ```typescript
178
297
  const schema = {
package/README.md CHANGED
@@ -33,9 +33,13 @@ 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.
38
39
  - **Prototype-Safe Output**: keys such as `__proto__` or `constructor` are stored as own data properties, exactly as `JSON.parse` leaves them.
40
+ - **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.
41
+ - **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.
42
+ - **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
43
  - **Performance**: Support for reusing `SchemaWalker` instances for high-throughput batch processing.
40
44
 
41
45
  ## 📦 Installation
@@ -120,6 +124,88 @@ for (const item of brokenItems) {
120
124
  }
121
125
  ```
122
126
 
127
+ ## 🧭 Where the JSON Starts
128
+
129
+ A model's reply is text, not a document. It wraps the JSON in a fence, and dresses it up in
130
+ sentences. `jsonRepair` finds the JSON first, then repairs it:
131
+
132
+ ````typescript
133
+ await jsonRepair('```json\n{ name: Ada }\n```', schema)
134
+ // { name: 'Ada' } flags: ['markdown-fence']
135
+
136
+ await jsonRepair('```json\n{ name: Ada }\n```\nHope this helps!', schema)
137
+ // { name: 'Ada' } flags: ['markdown-fence', 'prose-prefix', 'trailing-chatter']
138
+
139
+ await jsonRepair('Here you go:\nname: Ada', schema)
140
+ // { name: 'Ada' } flags: ['prose-prefix', 'implicit-structure']
141
+ ````
142
+
143
+ - The scan is quote-aware and bracket-aware, so `{ "code": "```json\n{}\n```" }` keeps its
144
+ content intact. A regular expression that strips fences would hand you `{}` instead.
145
+ - Input that already parses as JSON is never relocated, which is what keeps valid JSON
146
+ round-tripping exactly like `JSON.parse`.
147
+ - Everything the locating step threw away — wrapper prose, fences, losing fragments — is
148
+ listed in `discarded`. `onDiscard: 'throw'` refuses a repair that discards anything, for
149
+ callers that cannot afford to lose content. What a coercion gives up from inside a value is
150
+ reported by a flag, and follows the rule described under
151
+ [Known Limitations](#-known-limitations--disambiguation).
152
+
153
+ ### More than one fragment
154
+
155
+ A reply often holds several JSON fragments: a draft and a final answer, a decoy, or records laid
156
+ out side by side where the Schema expects an array. The Schema says which one to keep, so it is a
157
+ measurement rather than a guess. Fragments are ranked by:
158
+
159
+ | Compared first | Then |
160
+ | --- | --- |
161
+ | fewer Schema violations (`errors`) | more `required` fields carrying a real value (`""` carries nothing) |
162
+ | more declared fields carrying a real value | fewer JSON Schema keywords reproduced into the answer (`schemaEchoKeys`) |
163
+
164
+ A tie is decided by position — the **last** fragment first, because a model normally drafts
165
+ before it answers — and is reported as `ambiguous-candidates` instead of being hidden.
166
+ `onMultiple` changes the policy to `'first'`, `'last'`, or `'throw'`. Without a Schema the
167
+ ranking has no information to work with, so it collapses to the position rule; say so in your
168
+ own logs if that matters to you.
169
+
170
+ Records sitting side by side under an `array` Schema — `{"name": "Noah"} {"name": "Ada"}`, or the
171
+ same records without any braces — are read as one document holding two items
172
+ (`sibling-objects-merged`). The structure was declared, so that is not a guess either.
173
+
174
+ ### Auditing the repair: valid is not correct
175
+
176
+ A value can satisfy the Schema and still say nothing: `"name": ""`, a placeholder phone number,
177
+ the first enum entry picked by default. `jsonRepairResult()` returns what it noticed along with
178
+ the value:
179
+
180
+ ```typescript
181
+ import { jsonRepairResult, renderValidatorErrors } from '@isdk/json-repair'
182
+
183
+ const { value, errors, flags, candidates, discarded } = await jsonRepairResult(
184
+ reply,
185
+ schema
186
+ )
187
+
188
+ flags
189
+ // ['markdown-fence', 'prose-prefix', 'empty-required']
190
+ errors
191
+ // [{ path: ['email'], message: 'missing required property' }]
192
+
193
+ renderValidatorErrors(errors, 6)
194
+ // - email: missing required property
195
+ ```
196
+
197
+ `errors` is what a retry prompt needs, and `renderValidatorErrors` keeps it to the few lines a
198
+ small model actually follows. Repair first, then retry: syntax, type and structure are settled
199
+ deterministically and cost nothing, so a second model call is spent only on what no code can
200
+ know — an answer that is well formed and wrong.
201
+
202
+ A retry cannot see a placeholder either. `"name": ""` satisfies the Schema, and a model asked to
203
+ fix an error it does not have writes the placeholder again, so the repair names it:
204
+ `empty-required` (a required string left empty), `schema-echo-detected` (the Schema copied back as the answer, even when the copy
205
+ 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). Every decision the
206
+ repair made is in `flags` — the full list is `RepairFlag` in the API docs — so accepting,
207
+ retrying or escalating is a decision made on evidence, not on "it parsed".
208
+
123
209
  ## 🧭 How Property Boundaries Are Detected
124
210
 
125
211
  While repairing a value, the parser must decide at every position whether an upcoming
@@ -170,6 +256,13 @@ parser follows are:
170
256
  - If a value looks truncated right at something key-shaped, that level is probably missing
171
257
  `properties` in your Schema — add them and re-run.
172
258
 
259
+ A value that stops at a quote the model never closed is the other ambiguous case:
260
+ `{"t": "The "Best" Paper", "y": 2020}`. By default (`unescapedQuotes: 'keep'`) it keeps the
261
+ delimiters the document spelled. `'declared'` ends it at the first quote after which a member
262
+ the Schema declares begins — the declared member is the anchor, so the boundary is read rather
263
+ than guessed. `'lookahead'` applies the same rule to the text alone, for documents with no
264
+ Schema.
265
+
173
266
  Numeric literals support scientific notation (`1e5`, `-2E2`) as well as the lax LLM forms
174
267
  `+5`, `.5` and `5.`. A partial literal such as `1.2.3` is kept as a string and then coerced
175
268
  according to the Schema.
@@ -178,6 +271,41 @@ A declared `type: 'string'` is honoured in the other direction too: `12` becomes
178
271
  because the text comes from the document rather than the parsed number, a leading zero
179
272
  survives (`{ id: 01234 }` → `"01234"`). `null` and structures are never stringified.
180
273
 
274
+ ### How Escapes Are Read
275
+
276
+ Escapes are decoded, not guessed:
277
+
278
+ | The document writes | The value contains |
279
+ | --- | --- |
280
+ | `"a\nb"`, `"\t"`, `"\/"` | the control character, `/` — exactly what `JSON.parse` yields |
281
+ | `"café"`, `"\ud83d\ude00"` | `é`, `😀`; an unpaired surrogate stays where `JSON.parse` puts it |
282
+ | `"\xa0"` (the JSON5-style hex escape) | the character U+00A0 |
283
+ | `"\$10"`, `"a\qb"` (an escape of a character that needs none) | `$10`, `aqb` |
284
+ | `note: first line\nsecond` (a captured, unquoted value) | the text as written, backslash included — greedy capture does not decode |
285
+
286
+ Decoding stops at decoding. An NBSP, a zero-width space or a smart quote that the document
287
+ wrote stays in the value: rewriting those would change the model's content, not its syntax.
288
+
289
+ An escape strict JSON would reject is always reported as `invalid-escape`, whatever is done
290
+ with it: a value gained or lost a backslash, and the caller is owed that information.
291
+ `escapes` decides how far a backslash is trusted:
292
+
293
+ | `escapes` | `"\$10"` | `"C:\Users"` | `"C:\temp"` | `"\x41"` | `"a\nb"` |
294
+ | --- | --- | --- | --- | --- | --- |
295
+ | `'json5'` (default) | `$10` | `C:Users` | `C:`, tab, `emp` | `A` | a newline |
296
+ | `'json'` | `\$10` | `C:\Users` | `C:`, tab, `emp` | `\x41` | a newline |
297
+ | `'raw'` | `\$10` | `C:\Users` | `C:\temp` | `\x41` | `\n` — two characters |
298
+
299
+ `'json'` repairs only the syntax it is sure of and leaves every escape JSON does not define as
300
+ the document wrote it, which is what markdown- and LaTeX-trained models write. `'raw'` treats
301
+ every backslash as content, which is what a document of Windows paths, regular expressions or
302
+ LaTeX wants (`"C:\temp"` is a path, not a tab; `"\frac{a}{b}"` is a command, not a form feed)
303
+ at the price it names: no value can carry a newline any more.
304
+
305
+ A backslash stays structural at every setting — it is always the reason the character behind it
306
+ remains inside the string — so the choice cannot change where a value ends. An incomplete hex
307
+ escape (`"\xg"`, `"\uZZ"`) decodes nothing in every setting and is left exactly as written.
308
+
181
309
  ## ⚠️ Known Limitations & Disambiguation
182
310
 
183
311
  - **The "Parity Rule"**: When a string is wrapped in quotes and contains internal quotes, we count the internal ones.
@@ -188,18 +316,31 @@ survives (`{ id: 01234 }` → `"01234"`). `null` and structures are never string
188
316
  `{ "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
317
  - **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
318
  - **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.
319
+ - **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.
320
+ - **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.
321
+ - **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.
322
+ - **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).
323
+ - **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
324
 
193
325
  ## ⚙️ Repair Options
194
326
 
195
327
  `jsonRepair(input, schema, options)` takes a fourth argument of type `RepairOptions`:
196
328
 
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. |
329
+ | Option | Default | What it does |
330
+ | --- | --- | --- |
331
+ | `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. |
332
+ | `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`. |
333
+ | `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. |
334
+ | `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. |
335
+ | `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. |
336
+ | `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. |
337
+ | `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`. |
338
+ | `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). |
339
+ | `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 `{"a": 1, "b"} {"c": 2}` becomes `[{ a: 1 }, { c: 2 }]`. |
340
+ | `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. |
341
+ | `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`. |
342
+ | `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. |
343
+ | `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
344
 
204
345
  ```typescript
205
346
  const schema = {
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var t,s=Object.create,i=Object.defineProperty,e=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,h=Object.getPrototypeOf,n=Object.prototype.hasOwnProperty,o=(t,s,h,o)=>{if(s&&"object"==typeof s||"function"==typeof s)for(let u of r(s))n.call(t,u)||u===h||i(t,u,{get:()=>s[u],enumerable:!(o=e(s,u))||o.enumerable});return t},u={};((t,s)=>{for(var e in s)i(t,e,{get:s[e],enumerable:!0})})(u,{RepairParser:()=>f,SchemaWalker:()=>a,jsonRepair:()=>d}),module.exports=(t=u,o(i({},"__esModule",{value:!0}),t));var c=((t,e,r)=>(r=null!=t?s(h(t)):{},o(!e&&t&&t.__esModule?r:i(r,"default",{value:t,enumerable:!0}),t)))(require("@apidevtools/json-schema-ref-parser"),1),l=require("lodash-es"),a=class t{dereferencedSchema;options;constructor(t,s={}){this.dereferencedSchema=t,this.options=s}static async create(s,i={}){if(!s)return new t({},i);const e=new c.default,r=await e.dereference((0,l.cloneDeep)(s));return new t(r,i)}getSchemaForPath(t){let s=this.dereferencedSchema;for(const i of t){if(!s)return;if("object"===s.type||s.properties)s=s.properties?.[i]||s.additionalProperties;else{if("array"!==s.type&&!s.items)return 0===Object.keys(s).length?{}:void 0;s=Array.isArray(s.items)?s.items[i]||s.additionalItems:s.items}}return s}isValidProperty(t,s){const i=this.getSchemaForPath(t);return!i||(0===Object.keys(i).length||(!i.type||"object"===i.type)&&(i.properties&&null!==this.matchProperty(t,s)||!1!==i.additionalProperties))}matchProperty(s,i){const e=this.declaredPropertyNames(s);if(e.includes(i))return i;const r=this.options.keyMatching;if(!r||0===e.length)return null;if("function"==typeof r){const t=r(i,e);return"string"==typeof t&&""!==t?t:null}const h=t.normalizeName(i);return e.find(s=>t.normalizeName(s)===h)??null}declaredPropertyNames(t){const s=this.getSchemaForPath(t)?.properties;return s?Object.keys(s):[]}static normalizeName(t){return t.replace(/[\s_\-.]/g,"").toLowerCase()}isDeclaredProperty(t,s){const i=this.getSchemaForPath(t);return!!i?.properties&&Object.prototype.hasOwnProperty.call(i.properties,s)}hasDeclaredProperties(t){const s=this.getSchemaForPath(t);return!!s?.properties&&Object.keys(s.properties).length>0}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),e=i?.properties?.[s];return e?Array.isArray(e.type)?e.type:e.type?[e.type]:[]:[]}},f=class t{input="";pos=0;pathStack=[];walker;options;constructor(t,s={}){this.walker=t,this.options={coerceTypes:!0,...s}}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.cachedPath=null,this.cachedDeclaredKeys=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const s=this.peek(),i=this.walker.getSchemaForPath(this.pathStack);if("{"===s||t.declaresObject(i)&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===s)return this.consumeArray();const e=this.pos,r=this.tryConsumeStrictValue(s);if(r.ok)return this.options.coerceTypes&&i?this.coerceValue(r.value,i,r.raw):r.value;this.pos=e;const h=this.consumeGreedyString();return this.options.coerceTypes&&i?this.coerceValue(h,i):h}tryConsumeStrictValue(t){const s=this.pos;let i=null;if('"'===t||"'"===t?i=()=>this.consumeString():this.isDigit(t)||"-"===t||"+"===t?i=()=>this.consumeNumber():"t"!==t&&"f"!==t&&"n"!==t||(i=()=>"n"===t?this.consumeNull():this.consumeBoolean()),!i)return{ok:!1,value:void 0};try{const t=i(),e=this.input.slice(s,this.pos);if(this.skipWhitespace(),this.isAtDelimiter("structural")||this.pos>=this.input.length)return{ok:!0,value:t,raw:e}}catch(t){}return this.pos=s,{ok:!1,value:void 0}}static declaresObject(t){return!!t&&(Array.isArray(t.type)?t.type.includes("object"):"object"===t.type||!!t.properties)}consumeObject(){const s={},i="{"===this.peek();for(i&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const e=this.pos;if(!i&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const r=this.consumeKey(this.pathStack);if(null===r)break;const h=[...this.pathStack],n=this.walker.matchProperty(h,r)??r;if(!i&&Object.prototype.hasOwnProperty.call(s,n)){this.pos=e;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(n);try{const i=this.consumeValue();(this.pos!==e||void 0!==i&&""!==i)&&this.isKeptProperty(h,n)&&t.setOwn(s,n,i)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||i&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!i)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===e)break}return i&&"}"===this.peek()&&this.consumeChar("}"),s}isKeptProperty(t,s){return"remove"!==this.options.additionalProperties||(!this.walker.hasDeclaredProperties(t)||this.walker.isDeclaredProperty(t,s))}static setOwn(t,s,i){Object.defineProperty(t,s,{value:i,enumerable:!0,writable:!0,configurable:!0})}consumeArray(){const t=[];this.consumeChar("["),this.skipWhitespace();let s=0;for(;this.pos<this.input.length&&"]"!==this.peek()&&"}"!==this.peek();){const i=this.pos;this.pathStack.push(s);try{const e=this.consumeValue();this.pos!==i&&(t.push(e),s++)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()&&(this.consumeChar(","),this.skipWhitespace()),this.pos===i)break}return"]"===this.peek()&&this.consumeChar("]"),t}consumeKey(t=this.pathStack){if(this.skipWhitespace(),this.pos>=this.input.length)return null;if('"'===this.peek()||"'"===this.peek())return this.consumeString();const s=this.matchDeclaredKey(this.pos,t);if(s)return this.pos+=s.length,s.key;let i="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek()&&'"'!==this.peek()&&"'"!==this.peek();)i+=this.next();return i}consumeGreedyString(){let t="";const s=[];let i=!1,e="";for(;this.pos<this.input.length;){const r=this.peek();if(0===s.length&&this.isAtDelimiter("greedy"))break;if(i){if(r===e){let t=0,s=this.pos-1;for(;s>=0&&"\\"===this.input[s];)t++,s--;t%2==0&&(i=!1)}}else if('"'===r||"'"===r)i=!0,e=r;else if("("===r||"["===r||"{"===r)s.push(r);else if(")"===r||"]"===r||"}"===r){const t=s[s.length-1];(")"===r&&"("===t||"]"===r&&"["===t||"}"===r&&"{"===t)&&s.pop()}t+=this.next()}let r=t.trim();if(r.length>=2){const t=r[0],s=r[r.length-1];if(('"'===t||"'"===t)&&t===s){const s=r.slice(1,-1);let i=0;for(let e=0;e<s.length;e++)s[e]!==t||0!==e&&"\\"===s[e-1]||i++;if(i%2==1||0===i)return s}}return r}static WORD_CHAR=/[\p{L}\p{N}_]/u;static declaredKeyPatterns=new Map;cachedPath=null;cachedDeclaredKeys=[];declaredMultiWordKeys(s){if(this.cachedPath&&this.cachedPath.length===s.length&&this.cachedPath.every((t,i)=>t===s[i]))return this.cachedDeclaredKeys;const i=!0===this.options.keyMatching,e=this.walker.declaredPropertyNames(s).filter(t=>/\s/.test(t.trim())).map(s=>{const e=`${i?"i":""}:${s}`;let r=t.declaredKeyPatterns.get(e);if(!r){const h=s.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");r=new RegExp(`^${h}(?=\\s*:)`,i?"i":""),t.declaredKeyPatterns.set(e,r)}return{name:s,pattern:r}}).sort((t,s)=>s.name.length-t.name.length);return this.cachedPath=[...s],this.cachedDeclaredKeys=e,e}matchDeclaredKey(s,i=this.pathStack){let e=s;for(;e<this.input.length&&this.isWhitespace(this.input[e]);)e++;if(e>0&&t.WORD_CHAR.test(this.input[e-1]))return null;const r=this.declaredMultiWordKeys(i);if(0===r.length)return null;const h=this.input.slice(e);let n=null;for(const{name:t,pattern:s}of r){const i=h.match(s);i&&(!n||i[0].length>n.length)&&(n={key:t,length:i[0].length})}return n}isAtDelimiter(t="greedy"){if(this.pos>=this.input.length)return!0;const s=this.peek();if("}"===s||"]"===s)return!0;const i="number"==typeof this.pathStack[this.pathStack.length-1];if(","===s){if(i)return!0;const s=this.input.slice(this.pos+1);return!!/^\s*[}\]]/.test(s)||(!!/^\s*$/.test(s)||this.isBoundaryAhead(this.pos+1,t))}if(this.isBoundaryAhead(this.pos,t))return!0;if(this.isWhitespace(s)){const s=this.pos;this.skipWhitespace();const i=this.peek(),e="}"===i||"]"===i||","===i||this.isBoundaryAhead(this.pos,t);return this.pos=s,e}return!1}isLookingAtKey(t,s=this.pos){if(null!==this.matchDeclaredKey(s,t))return!0;const i=this.matchKey(s);return null!==i&&this.walker.isValidProperty(t,i)}matchKey(t=this.pos){const s=this.input.slice(t).match(/^\s*(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'|([^\s"',:{}\[\]]+))\s*:/);if(!s)return null;const i=void 0!==s[1]||void 0!==s[2];let e=s[1]??s[2]??s[3];return i&&(e=e.replace(/\\(["'\\])/g,"$1")),e}isBoundaryAhead(t,s){const i=this.pathStack.slice(0,-1);if(null!==this.matchDeclaredKey(t,i))return!0;const e=this.matchKey(t);return null!==e&&("structural"===s||("conservative"===this.options.stringCaptureStrategy||(this.walker.hasDeclaredProperties(i)?null!==this.walker.matchProperty(i,e):this.walker.isValidProperty(i,e))))}coerceValue(t,s,i){const e=Array.isArray(s.type)?s.type:s.type?[s.type]:[],r=String(t).trim();if(s.enum){const t=r.toLowerCase().replace(/[^a-z0-9]/g,"");for(const i of s.enum){if(t===String(i).toLowerCase().replace(/[^a-z0-9]/g,""))return i}}const h=null===t?"null":typeof t;if(e.length>0&&e.includes(h))return t;if(e.includes("string"))return null===t||"object"==typeof t||"string"==typeof t?t:void 0!==i?i.trim():String(t);if(e.includes("number")||e.includes("integer")){const t=r.replace(/(?<=\d)[,,](?=\d)/g,"").match(/-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?/),s=t?parseFloat(t[0]):NaN;if(!isNaN(s))return e.includes("integer")?Math.round(s):s}if(e.includes("boolean")){const t=r.toLowerCase(),s=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(s.includes(t))return!1}return e.includes("null")&&"null"===r.toLowerCase()?null:t}consumeString(){const t=this.next();let s="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?(this.next(),this.pos<this.input.length&&(s+=this.next())):s+=this.next();return this.peek()===t&&this.next(),s}static NUMBER_PATTERN=/^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?/;consumeNumber(){const s=this.input.slice(this.pos).match(t.NUMBER_PATTERN);return s?(this.pos+=s[0].length,parseFloat(s[0])):NaN}consumeBoolean(){const t=this.input.slice(this.pos);return t.startsWith("true")?(this.pos+=4,!0):!!t.startsWith("false")&&(this.pos+=5,!1)}consumeNull(){return this.pos+=4,null}peek(){return this.input[this.pos]}next(){return this.input[this.pos++]}consumeChar(t){this.peek()===t&&this.next()}isWhitespace(t){return/\s/.test(t)}isDigit(t){return/[0-9]/.test(t)}skipWhitespace(){for(;this.pos<this.input.length&&this.isWhitespace(this.peek());)this.pos++}};async function d(t,s,i={}){const e=s instanceof a?s:await a.create(s,i);return new f(e,i).parse(t)}
1
+ "use strict";var t,e=Object.defineProperty,s=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,r=Object.prototype.hasOwnProperty,n={};((t,s)=>{for(var i in s)e(t,i,{get:s[i],enumerable:!0})})(n,{RepairParser:()=>g,SchemaWalker:()=>u,compareScores:()=>T,discardedText:()=>N,expectsArrayRoot:()=>v,findImplicitRecordRegion:()=>S,jsonRepair:()=>K,jsonRepairResult:()=>q,locateJsonCandidates:()=>$,looksLikeSchemaEcho:()=>x,renderValidatorErrors:()=>L,scoreCandidate:()=>k,validateValue:()=>C}),module.exports=(t=n,((t,n,o,h)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let u of i(n))r.call(t,u)||u===o||e(t,u,{get:()=>n[u],enumerable:!(h=s(n,u))||h.enumerable});return t})(e({},"__esModule",{value:!0}),t));var o=require("@apidevtools/json-schema-ref-parser"),h=require("lodash-es"),u=class t{dereferencedSchema;options;constructor(t,e={}){this.dereferencedSchema=t,this.options=e}static async create(e,s={}){if(!e)return new t({},s);const i=await(0,o.dereference)((0,h.cloneDeep)(e));return new t(i,s)}getSchemaForPath(t){let e=this.dereferencedSchema;for(const s of t){if(!e)return;if("object"===e.type||e.properties)e=e.properties?.[s]||e.additionalProperties;else{if("array"!==e.type&&!e.items)return 0===Object.keys(e).length?{}:void 0;e=Array.isArray(e.items)?e.items[s]||e.additionalItems:e.items}}return e}isValidProperty(t,e){const s=this.getSchemaForPath(t);return!s||(0===Object.keys(s).length||(!s.type||"object"===s.type)&&(s.properties&&null!==this.matchProperty(t,e)||!1!==s.additionalProperties))}matchProperty(e,s){const i=this.declaredPropertyNames(e);if(i.includes(s))return s;const r=this.options.keyMatching;if(!r||0===i.length)return null;if("function"==typeof r){const t=r(s,i);return"string"==typeof t&&""!==t?t:null}const n=t.normalizeName(s);return i.find(e=>t.normalizeName(e)===n)??null}declaredPropertyNames(t){const e=this.getSchemaForPath(t)?.properties;return e?Object.keys(e):[]}static normalizeName(t){return t.replace(/[\s_\-.]/g,"").toLowerCase()}isDeclaredProperty(t,e){const s=this.getSchemaForPath(t);return!!s?.properties&&Object.prototype.hasOwnProperty.call(s.properties,e)}hasDeclaredProperties(t){const e=this.getSchemaForPath(t);return!!e?.properties&&Object.keys(e.properties).length>0}getExpectedTypes(t,e){const s=this.getSchemaForPath(t),i=s?.properties?.[e];return i?Array.isArray(i.type)?i.type:i.type?[i.type]:[]:[]}},c=class{constructor(t){this.max=t}max;entries=new Map;compute(t,e){const s=this.entries.get(t);if(void 0!==s)return s;const i=e(t);return this.entries.set(t,i),this.entries.size>this.max&&this.entries.delete(this.entries.keys().next().value),i}get size(){return this.entries.size}};function a(t,e,s=e){return void 0===t?[...s]:"boolean"==typeof t?t?[...e]:[]:[...t]}var l=["js","python"],f=["line","block","hash"],d=[],p=512,m=new RegExp(String.raw`^\s*(?:"((?:\\.|[^"\\]){0,${p}})"|'((?:\\.|[^'\\]){0,${p}})'|([^\s"',:{}\[\]]{1,${p}}))\s*:`),g=class t{input="";pos=0;pathStack=[];walker;options;readFlags=new Set;dropped=[];commentStyles;literalDialects;constructor(t,e={}){this.walker=t,this.options={coerceTypes:!0,...e},this.commentStyles=a(this.options.comments,f,d),this.literalDialects=a(this.options.literals,l,l)}get consumed(){return this.pos}get droppedText(){return this.dropped}get flags(){return this.readFlags}get remainder(){return this.input.slice(this.pos)}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.cachedPath=null,this.cachedDeclaredKeys=[],this.readFlags.clear(),this.dropped=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const e=this.peek(),s=this.walker.getSchemaForPath(this.pathStack);if(this.pathStack.length>=t.MAX_NESTING&&("["===e||"{"===e||!1!==this.options.wrapArrays&&t.declaresArray(s)&&this.isLookingAtKey([...this.pathStack,0])||t.declaresObject(s)&&this.isLookingAtKey(this.pathStack)))return void this.readFlags.add("nesting-limited");if("["===e)return this.consumeArray();if(!1!==this.options.wrapArrays&&t.declaresArray(s)&&("{"===e||this.isLookingAtKey([...this.pathStack,0])))return this.consumeArray(!0);if("{"===e||t.declaresObject(s)&&this.isLookingAtKey(this.pathStack))return this.consumeObject();const i=this.pos,r=this.tryConsumeStrictValue(e);if(r.ok)return this.options.coerceTypes&&s?this.coerceValue(r.value,s,r.raw):r.value;this.pos=i;const n=this.consumeUnterminatedString()??this.consumeGreedyString();this.swallowedComment(this.input.slice(i,this.pos))&&this.readFlags.add("comment-in-value");let o=t.guidesScalar(s)?void 0:this.dialectLiteral(n);if(!o&&s){const e=this.dialectLiteral(n);e&&t.allows(s,e.value)&&(o=e)}return o?(this.readFlags.add("non-json-literal"),o.value):this.options.coerceTypes&&s?this.coerceValue(n,s):n}static allows(t,e){return t.enum?t.enum.some(t=>t===e):"const"in t&&t.const===e}static guidesScalar(t){return!!t&&(void 0!==t.type||void 0!==t.enum||void 0!==t.const)}dialectLiteral(e){return this.literalDialects.includes("python")&&t.PYTHON_LITERALS.has(e)?{value:t.PYTHON_LITERALS.get(e)}:this.literalDialects.includes("js")&&t.JS_LITERALS.has(e)?{value:t.JS_LITERALS.get(e)}:void 0}static PYTHON_LITERALS=new Map([["True",!0],["False",!1],["None",null]]);static JS_LITERALS=new Map([["undefined",null]]);consumeUnterminatedString(){const t=this.options.unescapedQuotes??"keep";if("keep"===t||'"'!==this.peek())return;const e="declared"===t;for(let t=this.pos+1;t<this.input.length;t++){if("\\"===this.input[t]){t++;continue}if('"'!==this.input[t]||!this.closesValueAt(t,e))continue;this.next();let s="";for(;this.pos<t;)s+="\\"===this.peek()&&this.pos+1<t?this.consumeEscape():this.next();return this.next(),this.readFlags.add("unescaped-quote-inferred"),s}}closesValueAt(t,e){const s=this.pos;this.pos=t+1;const i=this.isAtDelimiter("structural");if(this.pos=s,!i)return!1;if(!e)return!0;const r=this.nextMemberPos(t+1);if(r>=this.input.length)return!0;if("}"===this.input[r]||"]"===this.input[r])return!0;const n=this.pathStack.slice(0,-1),o=this.matchKey(r+(","===this.input[r]?1:0));return null!==o&&null!==this.walker.matchProperty(n,o)}skipMemberGap(){if(this.skipWhitespace(),0===this.commentStyles.length)return;let t=!1;for(;this.skipOneComment();)t=!0,this.skipWhitespace();t&&this.readFlags.add("comment-skipped")}skipOneComment(){const t=this.input.slice(this.pos,this.pos+2);if("/*"===t&&this.commentStyles.includes("block")){const t=this.input.indexOf("*/",this.pos+2);return-1!==t&&(this.pos=t+2,!0)}return("//"===t&&this.commentStyles.includes("line")||!("#"!==t[0]||!this.commentStyles.includes("hash")))&&this.skipToLineEnd()}static COMMENT_GAP=/[\s{[,]/;swallowedComment(e){let s=null,i=!1;for(let r=0;r<e.length;r++){const n=e[r];if(s){i?i=!1:"\\"===n?i=!0:n===s&&(s=null);continue}if('"'===n||"'"===n){s=n;continue}if(0===r||!t.COMMENT_GAP.test(e[r-1]))continue;const o="#"===n?"hash":"/"===n&&"/"===e[r+1]?"line":"/"===n&&"*"===e[r+1]?"block":null;if(null!==o&&!this.commentStyles.includes(o))return!0}return!1}nextMemberPos(t){const e=this.pos;this.pos=t,this.skipMemberGap();const s=this.pos;return this.pos=e,s}skipToLineEnd(){const t=this.input.indexOf("\n",this.pos);return this.pos=-1===t?this.input.length:t,!0}tryConsumeStrictValue(e){const s=this.pos;let i=null;if('"'===e||"'"===e?i=()=>this.consumeString():this.isDigit(e)||"-"===e||"+"===e?i=()=>this.consumeNumber():"t"!==e&&"f"!==e&&"n"!==e||(i=()=>"n"===e?this.consumeNull():this.consumeBoolean()),!i)return{ok:!1,value:void 0};try{const r=i(),n=this.input.slice(s,this.pos);this.skipMemberGap();const o='"'!==e&&"'"!==e||t.closesString(n);if(this.isAtDelimiter("structural",o)||this.pos>=this.input.length)return{ok:!0,value:r,raw:n}}catch(t){}return this.pos=s,{ok:!1,value:void 0}}static MAX_NESTING=1e3;static declaresObject(t){return!!t&&(Array.isArray(t.type)?t.type.includes("object"):"object"===t.type||!!t.properties)}consumeObject(){const e={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipMemberGap();this.pos<this.input.length&&"}"!==this.peek();){this.skipMemberGap();const i=this.danglingTail();if(i){this.dropped.push(i.text),this.readFlags.add("dangling-dropped"),this.pos=i.end;break}const r=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const n=this.consumeKey(this.pathStack);if(null===n)break;const o=[...this.pathStack],h=this.walker.matchProperty(o,n)??n;if(!s&&Object.prototype.hasOwnProperty.call(e,h)){this.pos=r;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==r||void 0!==s&&""!==s)&&this.isKeptProperty(o,h)&&t.setOwn(e,h,s)}finally{this.pathStack.pop()}if(this.skipMemberGap(),","===this.peek()){const t=this.nextMemberPos(this.pos+1);if(this.isLookingAtKey(this.pathStack,t)||s&&"}"===this.input[t])this.consumeChar(","),this.skipMemberGap();else{if(!s)break;this.consumeChar(","),this.skipMemberGap()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===r)break}return s&&"}"===this.peek()&&this.consumeChar("}"),e}isKeptProperty(t,e){return"remove"!==this.options.additionalProperties||(!this.walker.hasDeclaredProperties(t)||this.walker.isDeclaredProperty(t,e))}static setOwn(t,e,s){Object.defineProperty(t,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}static declaresArray(t){return!!t&&(Array.isArray(t.type)?t.type.includes("array"):"array"===t.type||!!t.items)}consumeArray(t=!1){const e=[];t||this.consumeChar("["),this.skipMemberGap();let s=0;for(;this.pos<this.input.length;){if(this.skipMemberGap(),"]"===this.peek()){if(this.consumeChar("]"),this.skipWhitespace(),!this.startsAnotherRecord())break;continue}if("}"===this.peek())break;const t=this.pos;this.pathStack.push(s);try{const i=this.consumeValue();this.pos!==t&&(e.push(i),s++)}finally{this.pathStack.pop()}if(this.skipMemberGap(),","===this.peek()&&(this.consumeChar(","),this.skipMemberGap()),this.pos===t)break}return e}startsAnotherRecord(){const t=[...this.pathStack,0],e=this.walker.getSchemaForPath(t);if(!e)return!1;if("object"!==e.type&&!e.properties)return!1;if("{"===this.peek())return!0;if(this.matchDeclaredKey(this.pos,t))return!0;const s=this.matchKey(this.pos);return null!==s&&null!==this.walker.matchProperty(t,s)}consumeKey(t=this.pathStack){if(this.skipWhitespace(),this.pos>=this.input.length)return null;if('"'===this.peek()||"'"===this.peek())return this.consumeString();if("{"===this.peek()||"["===this.peek())return null;const e=this.matchDeclaredKey(this.pos,t);if(e)return this.pos+=e.length,e.key;let s="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek()&&'"'!==this.peek()&&"'"!==this.peek();)s+=this.next();return s}consumeGreedyString(){let t="";const e=[];let s=!1,i="";for(;this.pos<this.input.length;){const r=this.peek();if(0===e.length&&this.isAtDelimiter("greedy",!s))break;if(s){if(r===i){let t=0,e=this.pos-1;for(;e>=0&&"\\"===this.input[e];)t++,e--;t%2==0&&(s=!1)}}else if('"'===r||"'"===r)s=!0,i=r;else if("("===r||"["===r||"{"===r)e.push(r);else if(")"===r||"]"===r||"}"===r){const t=e[e.length-1];(")"===r&&"("===t||"]"===r&&"["===t||"}"===r&&"{"===t)&&e.pop()}t+=this.next()}let r=t.trim();if(r.length>=2){const t=r[0],e=r[r.length-1];if(('"'===t||"'"===t)&&t===e){const e=r.slice(1,-1);let s=0;for(let i=0;i<e.length;i++)e[i]!==t||0!==i&&"\\"===e[i-1]||s++;if(s%2==1||0===s)return e}}return r}static WORD_CHAR=/[\p{L}\p{N}_]/u;static declaredKeyPatterns=new c(2e3);cachedPath=null;cachedDeclaredKeys=[];declaredMultiWordKeys(e){if(this.cachedPath&&this.cachedPath.length===e.length&&this.cachedPath.every((t,s)=>t===e[s]))return this.cachedDeclaredKeys;const s=!0===this.options.keyMatching,i=this.walker.declaredPropertyNames(e).filter(t=>/\s/.test(t.trim())).map(e=>{const i=`${s?"i":""}:${e}`,r=t.declaredKeyPatterns.compute(i,()=>{const t=e.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");return new RegExp(`^${t}(?=\\s*:)`,s?"i":"")});return{name:e,pattern:r}}).sort((t,e)=>e.name.length-t.name.length);return this.cachedPath=[...e],this.cachedDeclaredKeys=i,i}matchDeclaredKey(e,s=this.pathStack){let i=e;for(;i<this.input.length&&this.isWhitespace(this.input[i]);)i++;if(i>0&&t.WORD_CHAR.test(this.input[i-1]))return null;const r=this.declaredMultiWordKeys(s);if(0===r.length)return null;const n=this.input.slice(i);let o=null;for(const{name:t,pattern:e}of r){const s=n.match(e);s&&(!o||s[0].length>o.length)&&(o={key:t,length:s[0].length})}return o}isAtDelimiter(t="greedy",e=!0){if(this.pos>=this.input.length)return!0;const s=this.peek();if("}"===s||"]"===s)return!0;const i="number"==typeof this.pathStack[this.pathStack.length-1];if(","===s){if(i)return!0;const s=this.nextMemberPos(this.pos+1),r=this.input.slice(s);return!!/^[}\]]/.test(r)||(""===r.trimEnd()||(!(!e||!this.isDanglingTail(s))||this.isBoundaryAhead(s,t)))}if(this.isBoundaryAhead(this.pos,t))return!0;if(this.isWhitespace(s)){const e=this.pos;this.skipMemberGap();const s=this.peek(),i="}"===s||"]"===s||","===s||this.isBoundaryAhead(this.pos,t);return this.pos=e,i}return!1}isLookingAtKey(t,e=this.pos){if(null!==this.matchDeclaredKey(e,t))return!0;const s=this.matchKey(e);return null!==s&&this.walker.isValidProperty(t,s)}matchKey(e=this.pos){if(e>0&&t.WORD_CHAR.test(this.input[e-1]))return null;const s=this.input.slice(e).match(m);if(!s)return null;const i=void 0!==s[1]||void 0!==s[2];let r=s[1]??s[2]??s[3];return i&&(r=r.replace(/\\(["'\\])/g,"$1")),r}static DANGLING_TAIL=new RegExp(String.raw`^\s*("(?:\\.|[^"\\]){0,${p}}"?|'(?:\\.|[^'\\]){0,${p}}'?|[^\s"',:{}\[\]]{1,${p}})\s*[}\]]*\s*(?:\{|\[|$)`);danglingTail(e=this.pos){if(!1===this.options.dangling)return;const s=this.input.slice(e),i=t.DANGLING_TAIL.exec(s);if(!i)return;const r=i[1];return'"'!==r[0]&&"'"!==r[0]&&/^[\d.+-]+$/.test(r)?void 0:{text:r,end:e+i.index+r.length}}isDanglingTail(t=this.pos){return void 0!==this.danglingTail(t)}static closesString(t){const e=t[0];if(t.length<2||t[t.length-1]!==e)return!1;let s=0;for(let e=t.length-2;e>=0&&"\\"===t[e];e--)s++;return s%2==0}static PATH_NOT_KEY=/^\s*[^\s"',:{}\[\]]+:[/\\]/;isBoundaryAhead(e,s){const i=this.pathStack.slice(0,-1);if(null!==this.matchDeclaredKey(e,i))return!0;const r=this.matchKey(e);return null!==r&&(!t.PATH_NOT_KEY.test(this.input.slice(e))&&("structural"===s||("conservative"===this.options.stringCaptureStrategy||(this.walker.hasDeclaredProperties(i)?null!==this.walker.matchProperty(i,r):this.walker.isValidProperty(i,r)))))}coerceValue(e,s,i){const r=Array.isArray(s.type)?s.type:s.type?[s.type]:[],n=String(e).trim();if(s.enum){const i=t.enumSpelling(e);if(null!==i)for(const e of s.enum)if(t.enumSpelling(e)===i)return e}const o=null===e?"null":typeof e;if(r.length>0&&r.includes(o))return e;if(r.includes("string"))return null===e||"object"==typeof e||"string"==typeof e?e:void 0!==i?i.trim():String(e);if(r.includes("number")||r.includes("integer")){const t=n.replace(/(?<=\d)[,,](?=\d)/g,""),e=t.match(/-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?/),s=e?parseFloat(e[0]):NaN;if(!isNaN(s))return e&&this.reportNumberCoercion(t,e),r.includes("integer")?Math.round(s):s}if(r.includes("boolean")){const t=n.toLowerCase(),e=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(e.includes(t))return!1}return r.includes("null")&&"null"===n.toLowerCase()?null:e}reportNumberCoercion(e,s){const i=s.index??0,r=(e.slice(0,i)+e.slice(i+s[0].length)).replace(t.COERCED_EDGE,"");""!==r&&(this.readFlags.add("coerced-text-dropped"),(r.split(/\s+/).length>=3||r.length>=20)&&this.dropped.push(r))}static COERCED_EDGE=/^[\s,]+|[\s,]+$/g;static enumSpelling(t){if("string"!=typeof t&&"number"!=typeof t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]/g,"");return""===e?null:e}static ESCAPE_MAP={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};consumeEscape(){const e=this.options.escapes??"json5";if(this.next(),this.pos>=this.input.length)return"\\";const s=this.next(),i=t.ESCAPE_MAP[s],r="raw"===e||void 0!==i?0:"u"===s?4:"x"===s&&"json5"===e?2:0,n=r>0?this.readHex(r):null;return void 0!==i||null!==n&&"u"===s||this.readFlags.add("invalid-escape"),"raw"===e?`\\${s}`:void 0!==i?i:null!==n?String.fromCharCode(n):0===r&&"json5"===e?s:`\\${s}`}readHex(t){let e=0;for(let s=0;s<t;s++){const t=parseInt(this.input[this.pos+s],16);if(Number.isNaN(t))return null;e=16*e+t}return this.pos+=t,e}consumeString(){const t=this.next();let e="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?e+=this.consumeEscape():e+=this.next();return this.peek()===t&&this.next(),e}static NUMBER_PATTERN=/^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?/;consumeNumber(){const e=this.input.slice(this.pos).match(t.NUMBER_PATTERN);return e?(this.pos+=e[0].length,parseFloat(e[0])):NaN}consumeBoolean(){const t=this.input.slice(this.pos);return t.startsWith("true")?(this.pos+=4,!0):!!t.startsWith("false")&&(this.pos+=5,!1)}consumeNull(){return this.pos+=4,null}peek(){return this.input[this.pos]}next(){return this.input[this.pos++]}consumeChar(t){this.peek()===t&&this.next()}isWhitespace(t){return/\s/.test(t)}isDigit(t){return/[0-9]/.test(t)}skipWhitespace(){for(;this.pos<this.input.length&&this.isWhitespace(this.peek());)this.pos++}},y=/(?:```|~~~)[ \t]*[A-Za-z0-9+_-]*\s*$/,b=/^\s*(?:```|~~~)/;function v(t){const e=t.getSchemaForPath([]);return!!e&&(Array.isArray(e.type)?e.type.includes("array"):"array"===e.type||!!e.items)}function $(t,e){const s=function(t){const e=[];let s=0,i=-1,r=!1,n=!1;for(let o=0;o<t.length;o++){const h=t[o];r?n?n=!1:"\\"===h?n=!0:('"'===h||"\n"===h)&&(r=!1):'"'!==h?"{"!==h&&"["!==h?("}"===h||"]"===h)&&s>0&&(s--,0===s&&(e.push(j(t,i,o+1)),i=-1)):(0===s&&(i=o),s++):r=!0}s>0&&i>=0&&e.push(j(t,i,t.length,["truncated-candidate"]));return e}(t),i=e?S(t,e):void 0;if(i&&(0===s.length||i.start<s[0].start)){const e=s.filter(t=>t.end>i.end||t.start<i.start);return[i,...e].map(e=>A(t,e))}const r=e&&v(e)&&function(t){const e=t.getSchemaForPath([0]);return!(!e||"object"!==e.type&&!e.properties)}(e)?function(t,e){const s=[];for(const i of e){const e=s[s.length-1];e&&/^[\s,]*$/.test(t.slice(e.end,i.start))?s[s.length-1]=j(t,e.start,i.end,[...e.flags.filter(t=>"truncated-candidate"!==t),...i.flags,"sibling-objects-merged"]):s.push(i)}return s}(t,s):s;return r.map(e=>A(t,e))}function S(t,e){const s=[...e.declaredPropertyNames([]),...v(e)?e.declaredPropertyNames([0]):[]];if(0===s.length)return;let i;for(const e of s){const s=O(e).exec(t),r=s?.indices?.[1]?.[0];void 0!==r&&(void 0===i||r<i)&&(i=r)}return void 0!==i?j(t,i,t.length,["implicit-structure"]):void 0}var w=new c(2e3);function O(t){return w.compute(t,()=>{return new RegExp(`(?:^|[{[,\\s])(${e=t,e.replace(/[.*+?^${}()|[\\]\\]/g,"\\$&")})\\s*:`,"id");var e})}function j(t,e,s,i=[]){return{start:e,end:s,text:t.slice(e,s),flags:i}}function A(t,e){const s=[...e.flags],i=t.slice(0,e.start),r=t.slice(e.end);return!y.test(i)||!b.test(r)&&r.trim()||s.unshift("markdown-fence"),{...e,flags:s}}function N(t,e,s){const i=s.map(t=>t.text),r=[e,...s].sort((t,e)=>t.start-e.start),n=[];let o=0;for(const e of r){const s=t.slice(o,e.start).trim();s&&n.push({text:s,start:o}),o=Math.max(o,e.end)}const h=t.slice(o).trim();return h&&n.push({text:h,start:o}),{prose:n,fragments:i}}function k(t,e){const s={errors:0,requiredCovered:0,declaredCovered:0,undeclaredKeys:0,schemaEchoKeys:0},i=new Set;let r=0;const n=(t,o)=>{const h=e.getSchemaForPath(o);if(h){if(null!==t&&"object"==typeof t&&!Array.isArray(t)){const e=h.properties,u=new Set(Array.isArray(h.required)?h.required:[]);if(e)for(const r of Object.keys(e))Object.hasOwn(t,r)&&void 0!==t[r]&&(P(t[r],e[r])?(s.declaredCovered++,u.has(r)&&s.requiredCovered++):u.has(r)&&"string"==typeof t[r]&&""===t[r].trim()&&i.add("empty-required"));for(const i of Object.keys(t))e&&!(i in e)&&(s.undeclaredKeys++,_.has(i)&&(s.schemaEchoKeys++,r++)),n(t[i],[...o,i]);return}Array.isArray(t)&&t.forEach((e,s)=>n(t[s],[...o,s]))}};return n(t,[]),r>=2&&i.add("schema-echo-detected"),{score:s,flags:[...i]}}function x(t){return"string"==typeof t?(t.match(E)?.length??0)>=2:!(!t||"object"!=typeof t||Array.isArray(t))&&Object.keys(t).filter(t=>R.has(t)).length>=2}var E=/(?:^|[{,]\s*)["']?(?:\$schema|\$id|\$ref|\$defs|additionalProperties|properties|required|definitions|enum|anyOf|allOf|oneOf|items)["']?\s*:/g,R=new Set("$schema $id $ref $defs additionalProperties properties required definitions enum anyOf allOf oneOf items".split(" "));function P(t,e){if(void 0===t)return!1;if(null===t){return(Array.isArray(e?.type)?e.type:e?.type?[e.type]:[]).includes("null")}return"string"!=typeof t||""!==t.trim()}function T(t,e){return t.errors-e.errors||e.requiredCovered-t.requiredCovered||e.declaredCovered-t.declaredCovered||t.schemaEchoKeys-e.schemaEchoKeys}var _=new Set(["type","properties","required","additionalProperties","items","enum","allOf","anyOf","oneOf","not","format","pattern","minimum","maximum","minLength","maxLength","minItems","maxItems","definitions","$defs","$schema","$id","$ref","title","description","default"]);function C(t,e){const s=[];return M(t,[],e,s),s}function L(t,e=6){return t.slice(0,e).map(t=>{return`- ${e=t.path,0===e.length?"<root>":e.join(".")}: ${t.message}`;var e}).join("\n")}function M(t,e,s,i){const r=s.getSchemaForPath(e);if(r&&0!==Object.keys(r).length)if(function(t,e,s,i){const r=function(t){return null===t?"null":Array.isArray(t)?"array":void 0===t?"undefined":typeof t}(t);if(void 0!==e.type){const n=Array.isArray(e.type)?e.type:[e.type];n.some(e=>function(t,e,s){return e===s||"integer"===e&&("number"===s&&Number.isInteger(t))}(t,e,r))||i.push({path:s,message:`expected ${n.join(" or ")}, got ${r}`})}"const"in e&&!D(t,e.const)&&i.push({path:s,message:`expected the constant ${JSON.stringify(e.const)}`});if(Array.isArray(e.enum)){e.enum.some(e=>D(t,e))||i.push({path:s,message:`expected one of ${e.enum.map(t=>JSON.stringify(t)).join(", ")}, got ${JSON.stringify(t)}`})}"string"==typeof t&&("string"!=typeof e.pattern||function(t,e){try{return new RegExp(e).test(t)}catch{return!0}}(t,e.pattern)||i.push({path:s,message:`does not match pattern ${e.pattern}`}),"string"!=typeof e.format||function(t,e){const s=I[e];return!s||s.test(t)}(t,e.format)||i.push({path:s,message:`does not match format ${e.format}`}),"number"==typeof e.minLength&&t.length<e.minLength&&i.push({path:s,message:`shorter than minLength ${e.minLength}`}),"number"==typeof e.maxLength&&t.length>e.maxLength&&i.push({path:s,message:`longer than maxLength ${e.maxLength}`}));"number"==typeof t&&("number"==typeof e.minimum&&t<e.minimum&&i.push({path:s,message:`below minimum ${e.minimum}`}),"number"==typeof e.maximum&&t>e.maximum&&i.push({path:s,message:`above maximum ${e.maximum}`}),!0===e.exclusiveMinimum&&"number"==typeof e.minimum&&t===e.minimum&&i.push({path:s,message:`must be above minimum ${e.minimum}`}),!0===e.exclusiveMaximum&&"number"==typeof e.maximum&&t===e.maximum&&i.push({path:s,message:`must be below maximum ${e.maximum}`}));Array.isArray(t)&&("number"==typeof e.minItems&&t.length<e.minItems&&i.push({path:s,message:`fewer than minItems ${e.minItems}`}),"number"==typeof e.maxItems&&t.length>e.maxItems&&i.push({path:s,message:`more than maxItems ${e.maxItems}`}))}(t,r,e,i),Array.isArray(t))r.items&&t.forEach((r,n)=>M(t[n],[...e,n],s,i));else if(null!==t&&"object"==typeof t){const n=Array.isArray(r.required)?r.required:[];for(const s of n)Object.hasOwn(t,s)&&void 0!==t[s]||i.push({path:[...e,s],message:"missing required property"});for(const n of function(t){return Object.keys(t)}(t)){!r.properties||n in r.properties||!1!==r.additionalProperties||i.push({path:[...e,n],message:"property is not declared by the Schema"}),M(t[n],[...e,n],s,i)}}}function D(t,e){return function(t,e){if(t===e)return!0;if(null===t||null===e)return!1;if("object"!=typeof t||"object"!=typeof e)return!1;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}(t,e)||function(t,e){const s=J(t),i=J(e);return null!==s&&null!==i&&s===i}(t,e)}function J(t){if("number"==typeof t)return Number.isFinite(t)?String(t):null;if("string"!=typeof t)return null;const e=t.trim();if(!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e))return null;const s=Number(e);return Number.isFinite(s)?String(s):null}var I={date:/^\d{4}-\d{2}-\d{2}$/,"date-time":/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/,email:/^[^@\s]+@[^@\s]+\.[^@\s]+$/,uri:/^[a-z][a-z0-9+.-]*:\S*/i,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i};async function K(t,e,s={}){return(await q(t,e,s)).value}async function q(t,e,s={}){const i=e instanceof u?e:await u.create(e,s),r=t.trim();if(!1===s.locate||function(t){try{return JSON.parse(t),!0}catch{return!1}}(r)){const t=G(r,i,s),e=[...t.dropped,...t.leftover?[t.leftover]:[]];V(e,s);const n=[...t.flags];return x(t.value)&&n.push("schema-echo-detected"),{value:t.value,flags:n,errors:C(t.value,i),candidates:[],discarded:"ignore"===s.onDiscard?[]:e}}const n=$(r,i);if(0===n.length){const t=new g(i,s),e=t.parse(r),n=new Set(t.flags),o=[];null!==e&&"object"==typeof e&&n.add("implicit-structure");const h=t.remainder.trim();return h&&(n.add("trailing-chatter"),o.push(h)),V(o,s),{value:e,flags:[...n],errors:C(e,i),candidates:[],discarded:"ignore"===s.onDiscard?[]:o}}const o=n.map(t=>{const e=G(t.text,i,s),{score:r,flags:n}=k(e.value,i),o=C(e.value,i);return r.errors=o.length,x(t.text)&&n.push("schema-echo-detected"),{region:{...t,score:r},value:e.value,errors:o,read:e.flags,leftover:[...e.dropped,...e.leftover?[e.leftover]:[]],suspicion:n}}),{ordered:h,duplicates:c}=function(t,e){const s=new Set;if(t.length>1){const e=new Map;for(const s of t)e.set(z(s.value),s);for(const i of t)e.get(z(i.value))!==i&&s.add(i.region);t=t.filter(t=>!s.has(t.region))}if(t.length>1&&"throw"===e)throw new Error(`Found ${t.length} JSON candidates where one was expected: ${t.map((t,e)=>`#${e+1} ${JSON.stringify(t.region.text.slice(0,60))} {errors: ${t.region.score.errors}, requiredCovered: ${t.region.score.requiredCovered}}`).join("; ")}`);if("last"===e)return{ordered:[...t].sort((t,e)=>e.region.start-t.region.start),duplicates:s};if("first"===e)return{ordered:[...t].sort((t,e)=>t.region.start-e.region.start),duplicates:s};const i=[...t].sort((t,e)=>T(t.region.score,e.region.score)||e.region.start-t.region.start);return{ordered:i,duplicates:s}}(o,s.onMultiple??"best"),a=h[0],l=h.slice(1),f="best"===(s.onMultiple??"best")&&l.length>0&&0===T(a.region.score,l[0].region.score),{prose:d,fragments:p}=N(r,a.region,o.filter(t=>t!==a).map(t=>t.region)),m=new Set([...a.region.flags,...a.read]);d.some(t=>t.start<a.region.start)&&m.add("prose-prefix"),d.some(t=>t.start>=a.region.end)&&m.add("trailing-chatter"),l.length>0&&m.add("extra-fragments-dropped"),c.size>0&&m.add("duplicate-candidates"),f&&m.add("ambiguous-candidates");for(const t of o)for(const e of t.suspicion)m.add(e);const y=[...d.map(t=>t.text),...p,...a.leftover];return V(y,s),{value:a.value,flags:[...m],errors:a.errors,candidates:o.map(t=>t.region),discarded:"ignore"===s.onDiscard?[]:y}}function G(t,e,s){const i=new g(e,s);let r=i.parse(t);!1!==s.wrapArrays&&v(e)&&void 0!==r&&!Array.isArray(r)&&(r=[r]);const n=i.remainder.trim(),o=[...i.flags];return n&&!o.includes("dangling-dropped")&&o.push("unparsed-tail"),{value:r,flags:o,dropped:[...i.droppedText],leftover:n}}function V(t,e){if("throw"===e.onDiscard&&0!==t.length)throw new Error(`Repair discarded ${t.length} piece(s) of the input: ${JSON.stringify(t)}`)}function z(t){return JSON.stringify(t)??String(t)}