@isdk/json-repair 0.2.0 → 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 +90 -0
- package/README.cn.md +24 -9
- package/README.md +40 -12
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +269 -49
- package/dist/index.d.ts +269 -49
- package/dist/index.js +1 -1
- package/package.json +6 -5
- package/docs/README.md +0 -387
- package/docs/_media/README.cn.md +0 -333
- package/docs/classes/RepairParser.md +0 -130
- package/docs/classes/SchemaWalker.md +0 -241
- package/docs/functions/compareScores.md +0 -32
- package/docs/functions/discardedText.md +0 -42
- package/docs/functions/expectsArrayRoot.md +0 -23
- package/docs/functions/findImplicitRecordRegion.md +0 -32
- package/docs/functions/jsonRepair.md +0 -49
- package/docs/functions/jsonRepairResult.md +0 -50
- package/docs/functions/locateJsonCandidates.md +0 -33
- package/docs/functions/looksLikeSchemaEcho.md +0 -29
- package/docs/functions/renderValidatorErrors.md +0 -32
- package/docs/functions/scoreCandidate.md +0 -45
- package/docs/functions/validateValue.md +0 -38
- package/docs/globals.md +0 -43
- package/docs/interfaces/CandidateScore.md +0 -63
- package/docs/interfaces/JsonCandidate.md +0 -71
- package/docs/interfaces/LocatedJson.md +0 -48
- package/docs/interfaces/RepairOptions.md +0 -301
- package/docs/interfaces/RepairResult.md +0 -58
- package/docs/interfaces/ValidationError.md +0 -27
- package/docs/type-aliases/CommentStyle.md +0 -13
- package/docs/type-aliases/EscapeMode.md +0 -13
- package/docs/type-aliases/JSONPath.md +0 -14
- package/docs/type-aliases/LiteralDialect.md +0 -13
- package/docs/type-aliases/RepairFlag.md +0 -11
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
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
|
+
|
|
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)
|
|
62
|
+
|
|
63
|
+
### Features
|
|
64
|
+
|
|
65
|
+
* wire up keyMatching, additionalProperties and stringCaptureStrategy ([3aea142](https://github.com/isdk/json-repair.js/commit/3aea14276d07fc71ad86f4d26d768f071b1ee21c))
|
|
66
|
+
|
|
67
|
+
### Bug Fixes
|
|
68
|
+
|
|
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))
|
|
76
|
+
|
|
77
|
+
## [0.1.2](https://github.com/isdk/json-repair.js/compare/v0.1.1...v0.1.2) (2026-01-30)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
### Features
|
|
81
|
+
|
|
82
|
+
* support balanced delimiter tracking in greedy capture ([51ba9c9](https://github.com/isdk/json-repair.js/commit/51ba9c939ae687b9da4b8574f2af0af0f31a3c0e))
|
|
83
|
+
|
|
84
|
+
## 0.1.1 (2026-01-30)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
### Features
|
|
88
|
+
|
|
89
|
+
* initial implementation of schema-guided json-repair with fuzzy matching and semantic coercion ([0b5c61d](https://github.com/isdk/json-repair.js/commit/0b5c61d4f059ddcdc6b47498f3bb4cfbb905409d))
|
|
90
|
+
* support JSON repair with missing or empty schema ([285873c](https://github.com/isdk/json-repair.js/commit/285873c5a6c2afa891c3cbea3296f13e2b11a4d0))
|
package/README.cn.md
CHANGED
|
@@ -36,15 +36,18 @@ LLM 生成的 JSON 经常包含语法错误或语义噪声。常见问题包括
|
|
|
36
36
|
- **转义保真的字符串**:解析器读到的字符串,解码结果与 `JSON.parse` 完全一致(`\n`、`\t`、`\/`、`\uXXXX`、代理对);JSON5 风格的 `\xNN` 解码为它所指的字元;对不需要转义的字元做的多余转义会被拆包(`"\$10"` → `"$10"`);凡是严格 JSON 会拒绝的转义,都会报 `invalid-escape`。当反斜杠是内容而不是转义时,用 `escapes` 声明。
|
|
37
37
|
- **稳当的属性边界**:带引号的键名可以含空格与标点(`"Official language": "Italian"`);Schema 声明过的多词键名,即使文档里没加引号也能被识别;能完整解析的值不会被重新切分,因此合法 JSON 的产物与 `JSON.parse` 完全一致。
|
|
38
38
|
- **模糊键名匹配**:`user_name`、`userName`、`USER NAME` 都会归位到 Schema 声明的属性名,输出里用的就是声明的名字。
|
|
39
|
+
- **读懂 Schema 组合关键字**:`$ref` 与 `allOf` / `anyOf` / `oneOf` 会先被折叠到它们所描述的层级,再去遍历;所以写在分支里的类型和属性,照样触发强制转换、照样参与校验 —— `{ anyOf: [{ type: 'string' }] }` 会把 `12` 变成 `"12"`。
|
|
39
40
|
- **原型安全的输出**:`__proto__`、`constructor` 这类键名存为自身的普通属性,与 `JSON.parse` 的处理一致。
|
|
40
41
|
- **高性能**:支持复用 `SchemaWalker` 实例,适用于高吞吐量的批处理场景。
|
|
41
42
|
|
|
42
43
|
## 📦 安装
|
|
43
44
|
|
|
44
45
|
```bash
|
|
45
|
-
pnpm add @isdk/json-repair
|
|
46
|
+
pnpm add @isdk/json-repair
|
|
46
47
|
```
|
|
47
48
|
|
|
49
|
+
`@apidevtools/json-schema-ref-parser` 会随之安装 —— 它是本包的 `$ref` 解析依赖,不是 peer 依赖,自己再钉一次只会多一份副本。
|
|
50
|
+
|
|
48
51
|
## 🛠 用法
|
|
49
52
|
|
|
50
53
|
### 1. Schema 引导修复 (推荐)
|
|
@@ -126,13 +129,15 @@ for (const item of brokenItems) {
|
|
|
126
129
|
|
|
127
130
|
````typescript
|
|
128
131
|
await jsonRepair('```json\n{ name: Ada }\n```', schema)
|
|
129
|
-
// { name: 'Ada' }
|
|
132
|
+
// { name: 'Ada' } flags: ['markdown-fence', 'prose-prefix', 'trailing-chatter']
|
|
133
|
+
// discarded: ['```json', '```'] —— 围栏本身也算作文本
|
|
130
134
|
|
|
131
135
|
await jsonRepair('```json\n{ name: Ada }\n```\nHope this helps!', schema)
|
|
132
|
-
//
|
|
136
|
+
// 值与 flags 同上;那句话只是追加到 discarded 里 closing fence 的后面:
|
|
137
|
+
// discarded: ['```json', '```\nHope this helps!']
|
|
133
138
|
|
|
134
139
|
await jsonRepair('Here you go:\nname: Ada', schema)
|
|
135
|
-
// { name: 'Ada' }
|
|
140
|
+
// { name: 'Ada' } flags: ['implicit-structure', 'prose-prefix']
|
|
136
141
|
````
|
|
137
142
|
|
|
138
143
|
- 定位扫描感知引号与括号配平,所以 `{ "code": "```json\n{}\n```" }` 的内容完好无损——
|
|
@@ -188,7 +193,7 @@ renderValidatorErrors(errors, 6)
|
|
|
188
193
|
|
|
189
194
|
重试也看不见占位符。`"name": ""` 满足 schema,让模型去修一个它并不存在的错误,它只会再写一遍,
|
|
190
195
|
所以修复过程自己会点名:`empty-required`(必填字符串留空)、`schema-echo-detected`(把 schema 原样抄回来当答案,抄得完全合法也会点名)、
|
|
191
|
-
`ambiguous-candidates`(两个片段同样合规)、`coerced-text-dropped`(强制转换保留了值的一部分,舍掉了它周围的文本)。修复过程做过的每个决定都在 `flags` 里(完整列表见 API
|
|
196
|
+
`ambiguous-candidates`(两个片段同样合规)、`coerced-text-dropped`(强制转换保留了值的一部分,舍掉了它周围的文本)。修复过程做过的每个决定都在 `flags` 里(完整列表见 [API 文档](https://github.com/isdk/json-repair.js/blob/main/docs/type-aliases/RepairFlag.md) 里的 `RepairFlag`),
|
|
192
197
|
因此接受、重试还是换更大的模型,是依据证据决定,而不是因为“它解析成功了”。
|
|
193
198
|
|
|
194
199
|
## 🧭 属性边界是如何判定的
|
|
@@ -225,6 +230,10 @@ renderValidatorErrors(errors, 6)
|
|
|
225
230
|
|
|
226
231
|
反方向同样成立:Schema 声明 `type: 'string'` 时 `12` 会被转成 `"12"`;并且文本取自文档原文而非解析后的数字,所以前导零不会丢失(`{ id: 01234 }` → `"01234"`)。`null` 与对象/数组不会被转成字符串。
|
|
227
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
|
+
|
|
228
237
|
### 转义是如何读取的
|
|
229
238
|
|
|
230
239
|
转义是解码,不是猜测:
|
|
@@ -280,14 +289,14 @@ renderValidatorErrors(errors, 6)
|
|
|
280
289
|
| 选项 | 默认值 | 作用 |
|
|
281
290
|
| --- | --- | --- |
|
|
282
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`。 |
|
|
283
|
-
| `keyMatching` | `false` | 把输入键名解析成 Schema 声明的属性名。`true`
|
|
284
|
-
| `additionalProperties` | `
|
|
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` 优先于默认值;未声明任何属性名的自由层级不会被清空。 |
|
|
285
294
|
| `stringCaptureStrategy` | `'aggressive'` | `'conservative'`:贪婪捕获在任意“键形状 + `:`”处结束,而不再只在 Schema 声明的键名处结束。代价是值更容易被截断,好处是一个破碎的值不会吞掉后面的一大片内容。 |
|
|
286
295
|
| `locate` | `true` | 是否先在文本里定位 JSON(围栏、散文、多个片段)。`false` 则把整个字符串当成一个 JSON 文档——即 0.1.x 之前的行为。两种情况下,本来就能解析的输入都不会被重新定位。 |
|
|
287
296
|
| `onMultiple` | `'best'` | 文本里有多个片段时如何取舍:`'best'` 按对 schema 的契合度排序取胜者(打平时取最后一个,并以 `ambiguous-candidates` 上报);`'last'` / `'first'` 无视排序纯按位置;`'throw'` 直接拒绝输入,并附带各片段的评分。 |
|
|
288
297
|
| `onDiscard` | `'report'` | `'throw'`:只要修复过程中丢弃了散文、落选片段,或某个值吞下的一句话就直接失败;`'ignore'`:丢弃且不在 `RepairResult.discarded` 里列出。 |
|
|
289
298
|
| `wrapArrays` | `true` | schema 期待位于列表内部的记录是否按元素读取:数组 schema 下的 `{ name: Ada }` 会变成 `[{ name: 'Ada' }]`,并排书写的多条记录会成为该列表的元素。设为 `false` 则保留文档原样,代价是该记录的键不再按 `items` 解析(不再强制类型,值可能粘连)。 |
|
|
290
|
-
| `dangling` | `true` | 丢弃输出被截断时留下的键或分隔符(`{"a": 1, "b"` → `{ a: 1 }`),残片会列入 `discarded` 并带上 `dangling-dropped` 标记。设为 `false`
|
|
299
|
+
| `dangling` | `true` | 丢弃输出被截断时留下的键或分隔符(`{"a": 1, "b"` → `{ a: 1 }`),残片会列入 `discarded` 并带上 `dangling-dropped` 标记。设为 `false` 则把残片留在前面的字段里。丢弃不会中断解析:右花括号之后的那条记录仍会被读取,因此在声明了列表的 Schema 下,`{"a": 1, "b"} {"c": 2}` 会得到 `[{ a: 1 }, { c: 2 }]`;没有这条声明时两条记录是互相竞争的片段,失败的一方进入 `discarded` 而不是被合并进来。 |
|
|
291
300
|
| `literals` | `true` | 哪些未加引号的裸 token 按另一种语言的字面量读取:`'python'`(`True`/`False`/`None`)、`'js'`(`undefined`)、`true` 两者都读、`false` 或 `[]` 都不读。该路径上 schema 声明了类型时以 schema 为准;加引号的 `"True"` 永远是字符串。 |
|
|
292
301
|
| `comments` | `false` | 成员之间会跳过哪些注释风格:`'line'`(`//`)、`'block'`(`/* */`,且必须闭合)、`'hash'`(`#`)、`true` 三者全开。字符串内部与裸 token 内部永远不会被识别为注释,因此任何设置下 `https://x` 与 `#123` 都安全;在应当出现值的位置(`:` 之后)也不会识别注释——那里的文本属于模型,可能带注释形状并落入值中;一旦如此,修复会以 `comment-in-value` 点名。 |
|
|
293
302
|
| `unescapedQuotes` | `'keep'` | 模型漏写引号时,引号值在哪里结束:`'declared'` 以引号之后 schema 声明过的成员作为锚点,`'lookahead'` 仅凭文本形状判断,`'keep'` 不做任何推断。 |
|
|
@@ -309,10 +318,16 @@ await jsonRepair('{ user_name: "Ada", user_age: "36" }', schema, {
|
|
|
309
318
|
// { userName: 'Ada', userAge: 36 }
|
|
310
319
|
|
|
311
320
|
await jsonRepair('{ userName: "Ada", reasoning: "让我想想…" }', schema, {
|
|
312
|
-
additionalProperties:
|
|
321
|
+
additionalProperties: false,
|
|
313
322
|
})
|
|
314
323
|
// { userName: 'Ada' }
|
|
315
324
|
|
|
325
|
+
// 一处声明,覆盖 Schema 未点名的一切键
|
|
326
|
+
await jsonRepair('{ userName: "Ada", score: "12" }', schema, {
|
|
327
|
+
additionalProperties: { type: 'number' },
|
|
328
|
+
})
|
|
329
|
+
// { userName: 'Ada', score: 12 }
|
|
330
|
+
|
|
316
331
|
const querySchema = {
|
|
317
332
|
type: 'object',
|
|
318
333
|
properties: { query: { type: 'string' }, intent: { type: 'string' } },
|
package/README.md
CHANGED
|
@@ -36,6 +36,7 @@ Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses you
|
|
|
36
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.
|
|
37
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`.
|
|
38
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"`.
|
|
39
40
|
- **Prototype-Safe Output**: keys such as `__proto__` or `constructor` are stored as own data properties, exactly as `JSON.parse` leaves them.
|
|
40
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.
|
|
41
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.
|
|
@@ -45,11 +46,14 @@ Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses you
|
|
|
45
46
|
## 📦 Installation
|
|
46
47
|
|
|
47
48
|
```bash
|
|
48
|
-
npm install @isdk/json-repair
|
|
49
|
+
npm install @isdk/json-repair
|
|
49
50
|
# or
|
|
50
|
-
pnpm add @isdk/json-repair
|
|
51
|
+
pnpm add @isdk/json-repair
|
|
51
52
|
```
|
|
52
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
|
+
|
|
53
57
|
## 🛠 Usage
|
|
54
58
|
|
|
55
59
|
### 1. Schema-Guided Repair (Recommended)
|
|
@@ -131,13 +135,15 @@ sentences. `jsonRepair` finds the JSON first, then repairs it:
|
|
|
131
135
|
|
|
132
136
|
````typescript
|
|
133
137
|
await jsonRepair('```json\n{ name: Ada }\n```', schema)
|
|
134
|
-
// { name: 'Ada' }
|
|
138
|
+
// { name: 'Ada' } flags: ['markdown-fence', 'prose-prefix', 'trailing-chatter']
|
|
139
|
+
// discarded: ['```json', '```'] — the fence is text too
|
|
135
140
|
|
|
136
141
|
await jsonRepair('```json\n{ name: Ada }\n```\nHope this helps!', schema)
|
|
137
|
-
//
|
|
142
|
+
// the same value and the same flags; the sentence joins the closing fence in
|
|
143
|
+
// discarded: ['```json', '```\nHope this helps!']
|
|
138
144
|
|
|
139
145
|
await jsonRepair('Here you go:\nname: Ada', schema)
|
|
140
|
-
// { name: 'Ada' }
|
|
146
|
+
// { name: 'Ada' } flags: ['implicit-structure', 'prose-prefix']
|
|
141
147
|
````
|
|
142
148
|
|
|
143
149
|
- The scan is quote-aware and bracket-aware, so `{ "code": "```json\n{}\n```" }` keeps its
|
|
@@ -202,8 +208,8 @@ know — an answer that is well formed and wrong.
|
|
|
202
208
|
A retry cannot see a placeholder either. `"name": ""` satisfies the Schema, and a model asked to
|
|
203
209
|
fix an error it does not have writes the placeholder again, so the repair names it:
|
|
204
210
|
`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,
|
|
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,
|
|
207
213
|
retrying or escalating is a decision made on evidence, not on "it parsed".
|
|
208
214
|
|
|
209
215
|
## 🧭 How Property Boundaries Are Detected
|
|
@@ -271,6 +277,22 @@ A declared `type: 'string'` is honoured in the other direction too: `12` becomes
|
|
|
271
277
|
because the text comes from the document rather than the parsed number, a leading zero
|
|
272
278
|
survives (`{ id: 01234 }` → `"01234"`). `null` and structures are never stringified.
|
|
273
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
|
+
|
|
274
296
|
### How Escapes Are Read
|
|
275
297
|
|
|
276
298
|
Escapes are decoded, not guessed:
|
|
@@ -324,19 +346,19 @@ escape (`"\xg"`, `"\uZZ"`) decodes nothing in every setting and is left exactly
|
|
|
324
346
|
|
|
325
347
|
## ⚙️ Repair Options
|
|
326
348
|
|
|
327
|
-
`jsonRepair(input, schema, options)` takes a
|
|
349
|
+
`jsonRepair(input, schema, options)` takes a third argument of type `RepairOptions`:
|
|
328
350
|
|
|
329
351
|
| Option | Default | What it does |
|
|
330
352
|
| --- | --- | --- |
|
|
331
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. |
|
|
332
|
-
| `keyMatching` | `false` | Resolves incoming keys to the names the Schema declares. `true`
|
|
333
|
-
| `additionalProperties` | `
|
|
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. |
|
|
334
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. |
|
|
335
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. |
|
|
336
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. |
|
|
337
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`. |
|
|
338
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). |
|
|
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 }]`. |
|
|
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. |
|
|
340
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. |
|
|
341
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`. |
|
|
342
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. |
|
|
@@ -358,10 +380,16 @@ await jsonRepair('{ user_name: "Ada", user_age: "36" }', schema, {
|
|
|
358
380
|
// { userName: 'Ada', userAge: 36 }
|
|
359
381
|
|
|
360
382
|
await jsonRepair('{ userName: "Ada", reasoning: "let me think…" }', schema, {
|
|
361
|
-
additionalProperties:
|
|
383
|
+
additionalProperties: false,
|
|
362
384
|
})
|
|
363
385
|
// { userName: 'Ada' }
|
|
364
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
|
+
|
|
365
393
|
const querySchema = {
|
|
366
394
|
type: 'object',
|
|
367
395
|
properties: { query: { type: 'string' }, intent: { type: 'string' } },
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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)}
|
|
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,{KEY_SEPARATORS:()=>p,RepairParser:()=>$,SchemaWalker:()=>g,compareScores:()=>K,discardedText:()=>P,expectsArrayRoot:()=>j,findImplicitRecordRegion:()=>A,jsonRepair:()=>H,jsonRepairResult:()=>V,locateJsonCandidates:()=>w,looksLikeSchemaEcho:()=>M,renderValidatorErrors:()=>L,scoreCandidate:()=>R,validateValue:()=>I}),module.exports=(t=n,((t,n,o,h)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let c of i(n))r.call(t,c)||c===o||e(t,c,{get:()=>n[c],enumerable:!(h=s(n,c))||h.enumerable});return t})(e({},"__esModule",{value:!0}),t));var o=require("@apidevtools/json-schema-ref-parser"),h=require("lodash-es"),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}},a=2e3;function u(t,e,s=e){return void 0===t?[...s]:"boolean"==typeof t?t?[...e]:[]:[...t]}var f=["js","python"],l=["line","block","hash"],d=[],p=[" ","\t","\n","\r","_","-","."];var m=new Map;function y(t,e){let s=t;if(e.separators){const t=e.separators.join("");let i=m.get(t);i||(i=new RegExp(`[${e.separators.map(t=>t.replace(/[\\\]^-]/g,"\\$&")).join("")}]`,"g"),m.set(t,i)),s=s.replace(i,"")}return e.foldCase?s.toLowerCase():s}var g=class t{dereferencedSchema;options;resolvedKeyMatching;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(t.flatten(i),s)}static COMBINATORS=["allOf","anyOf","oneOf"];static SCHEMA_MAPS=["properties","patternProperties","$defs","definitions"];static SCHEMA_NODES=["items","additionalItems","additionalProperties","contains","not","propertyNames"];static SHARED_KEYWORDS=["type","properties","patternProperties","items","additionalItems","enum"];static flatten(e){return t.flattenNode(e,{nodes:new Map,merged:new Map})}static flattenMap(e,s){if(!e||"object"!=typeof e)return e;const i={};for(const[r,n]of Object.entries(e))i[r]=t.flattenNode(n,s);return i}static flattenNode(e,s){if(!e||"object"!=typeof e)return e;const i=s.nodes.get(e);if(i)return i;const r={};s.nodes.set(e,r);for(const[i,n]of Object.entries(e))t.COMBINATORS.includes(i)||(t.SCHEMA_MAPS.includes(i)?r[i]=t.flattenMap(n,s):t.SCHEMA_NODES.includes(i)?r[i]=Array.isArray(n)?n.map(e=>t.flattenNode(e,s)):t.flattenNode(n,s):r[i]=n);for(const i of t.COMBINATORS){const n=e[i];if(!Array.isArray(n))continue;const o="allOf"===i;for(const e of n){const i=t.flattenNode(e,s);i&&"object"==typeof i&&t.mergeInto(r,i,o,s)}}return r}static mergeInto(e,s,i,r){let n=r.merged.get(e);if(n||(n=new Set,r.merged.set(e,n)),!n.has(s)){n.add(s);for(const[n,o]of Object.entries(s))if(i||t.SHARED_KEYWORDS.includes(n))if("type"===n){const s=t.unique(e.type,o);e.type=1===s.length?s[0]:s}else if("enum"===n)e.enum=t.unique(e.enum,o);else if("required"===n)i&&(e.required=t.unique(e.required,o));else if("properties"===n||"patternProperties"===n){const s=e[n]??={};for(const[e,n]of Object.entries(o))s[e]?t.mergeInto(s[e],n,i,r):s[e]=n}else n in e||(e[n]=o)}}static unique(t,e){const s=Array.isArray(t)?t:void 0===t?[]:[t];for(const t of Array.isArray(e)?e:void 0===e?[]:[e])s.includes(t)||s.push(t);return s}getSchemaForPath(t){let e=this.dereferencedSchema;for(const s of t){if(!e)return;if("object"===e.type||e.properties||e.patternProperties)e=e.properties?.[s]??this.patternSchemaForNode(e,s)??this.valueSchemaOf(e);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}additionalPropertiesAt(t){return this.effectiveAdditionalProperties(this.getSchemaForPath(t))}effectiveAdditionalProperties(t){const e=t?.additionalProperties;return void 0!==e?e:this.options.additionalProperties??!0}valueSchemaOf(t){const e=this.effectiveAdditionalProperties(t);return"object"==typeof e&&null!==e?e:void 0}patternSchemaFor(t,e){return this.patternSchemaForNode(this.getSchemaForPath(t),e)}patternSchemaForNode(e,s){if("string"==typeof s)for(const[i,r]of t.patternEntries(e))if(t.patternOf(i)?.test(s))return r}matchesKeyPattern(e,s){const i=this.getSchemaForPath(e);return void 0!==this.patternSchemaForNode(i,s)||t.patternEntries(i).some(([e])=>null===t.patternOf(e))}hasKeyPatterns(e){return t.patternEntries(this.getSchemaForPath(e)).length>0}static patternEntries(t){const e=t?.patternProperties;return e&&"object"==typeof e?Object.entries(e):[]}static patterns=new c(a);static patternOf(e){return t.patterns.compute(e,t=>{try{return new RegExp(t)}catch{return null}})}isValidProperty(t,e){const s=this.getSchemaForPath(t);return!s||(0===Object.keys(s).length||(!s.type||"object"===s.type)&&this.allowsProperty(t,e))}allowsProperty(t,e){return null!==this.matchProperty(t,e)||(!!this.matchesKeyPattern(t,e)||(!1!==this.additionalPropertiesAt(t)||!(this.hasDeclaredProperties(t)||this.hasKeyPatterns(t))))}matchProperty(t,e){const s=this.declaredPropertyNames(t);if(s.includes(e))return e;const i=this.keyMatching;if(i.matcher){const t=i.matcher(e,s);return"string"==typeof t&&""!==t?t:null}if(0===s.length)return null;const r=y(e,i),n=i.foldCase||null!==i.separators;for(const[t,e]of Object.entries(i.aliases))if(s.includes(t)&&e.some(t=>y(t,i)===r))return t;return n?s.find(t=>y(t,i)===r)??null:null}get keyMatching(){return this.resolvedKeyMatching||(this.resolvedKeyMatching=function(t){if("function"==typeof t)return{foldCase:!1,separators:null,aliases:{},matcher:t};if(void 0===t||!1===t)return{foldCase:!1,separators:null,aliases:{},matcher:null};const e=!0===t?{}:t,s=u(e.forms,["case","separators"]);return{foldCase:s.includes("case"),separators:s.includes("separators")?e.separators??p:null,aliases:e.aliases??{},matcher:null}}(this.options.keyMatching)),this.resolvedKeyMatching}declaredPropertyNames(t){const e=this.getSchemaForPath(t)?.properties;return e?Object.keys(e):[]}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]??this.patternSchemaForNode(s,e)??this.valueSchemaOf(s);return i?Array.isArray(i.type)?i.type:i.type?[i.type]:[]:[]}},b=512,v=new RegExp(String.raw`^\s*(?:"((?:\\.|[^"\\]){0,${b}})"|'((?:\\.|[^'\\]){0,${b}})'|([^\s"',:{}\[\]]{1,${b}}))\s*:`),$=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=u(this.options.comments,l,d),this.literalDialects=u(this.options.literals,f,f)}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||!!t.patternProperties)}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.walker.allowsProperty(o,h)?t.setOwn(e,h,s):(this.dropped.push(this.input.slice(r,this.pos).trim()),this.readFlags.add("undeclared-keys-dropped")))}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}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(a);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=this.walker.keyMatching,i=this.walker.declaredPropertyNames(e),r=[...i,...Object.entries(s.aliases).filter(([t])=>i.includes(t)).flatMap(([,t])=>t)].filter(t=>/\s/.test(t.trim())).map(e=>{const i=`${s.foldCase?"i":""}:${e}`,r=t.declaredKeyPatterns.compute(i,()=>{const t=e.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");return new RegExp(`^${t}(?=\\s*:)`,s.foldCase?"i":"")});return{name:e,pattern:r}}).sort((t,e)=>e.name.length-t.name.length);return this.cachedPath=[...e],this.cachedDeclaredKeys=r,r}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(v);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,${b}}"?|'(?:\\.|[^'\\]){0,${b}}'?|[^\s"',:{}\[\]]{1,${b}})\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)||void 0!==this.walker.patternSchemaFor(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}consumeKeyword(e){const s=this.pos+e.length;if(this.input.slice(this.pos,s)!==e)return!1;const i=this.input[s];return(void 0===i||!t.WORD_CHAR.test(i))&&(this.pos=s,!0)}consumeBoolean(){return!!this.consumeKeyword("true")||(this.consumeKeyword("false"),!1)}consumeNull(){return this.consumeKeyword("null"),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++}},O=/(?:```|~~~)[ \t]*[A-Za-z0-9+_-]*\s*$/,S=/^\s*(?:```|~~~)/;function j(t){const e=t.getSchemaForPath([]);return!!e&&(Array.isArray(e.type)?e.type.includes("array"):"array"===e.type||!!e.items)}function w(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(k(t,i,o+1)),i=-1)):(0===s&&(i=o),s++):r=!0}s>0&&i>=0&&e.push(k(t,i,t.length,["truncated-candidate"]));return e}(t),i=e?A(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=>x(t,e))}const r=e&&j(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]=k(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=>x(t,e))}function A(t,e){const s=[...e.declaredPropertyNames([]),...j(e)?e.declaredPropertyNames([0]):[]];if(0===s.length)return;let i;for(const e of s){const s=E(e).exec(t),r=s?.indices?.[1]?.[0];void 0!==r&&(void 0===i||r<i)&&(i=r)}return void 0!==i?k(t,i,t.length,["implicit-structure"]):void 0}var N=new c(a);function E(t){return N.compute(t,()=>{return new RegExp(`(?:^|[{[,\\s])(${e=t,e.replace(/[.*+?^${}()|[\\]\\]/g,"\\$&")})\\s*:`,"id");var e})}function k(t,e,s,i=[]){return{start:e,end:s,text:t.slice(e,s),flags:i}}function x(t,e){const s=[...e.flags],i=t.slice(0,e.start),r=t.slice(e.end);return!O.test(i)||!S.test(r)&&r.trim()||s.unshift("markdown-fence"),{...e,flags:s}}function P(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 R(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 c=h.properties,a=new Set(Array.isArray(h.required)?h.required:[]);if(c)for(const e of Object.keys(c))Object.hasOwn(t,e)&&void 0!==t[e]&&(_(t[e],c[e])?(s.declaredCovered++,a.has(e)&&s.requiredCovered++):a.has(e)&&"string"==typeof t[e]&&""===t[e].trim()&&i.add("empty-required"));for(const i of Object.keys(t)){const h=e.declaredPropertyNames(o);!c&&!e.hasKeyPatterns(o)||h.includes(i)||void 0!==e.patternSchemaFor(o,i)||(s.undeclaredKeys++,D.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 M(t){return"string"==typeof t?(t.match(C)?.length??0)>=2:!(!t||"object"!=typeof t||Array.isArray(t))&&Object.keys(t).filter(t=>T.has(t)).length>=2}var C=/(?:^|[{,]\s*)["']?(?:\$schema|\$id|\$ref|\$defs|additionalProperties|properties|required|definitions|enum|anyOf|allOf|oneOf|items)["']?\s*:/g,T=new Set("$schema $id $ref $defs additionalProperties properties required definitions enum anyOf allOf oneOf items".split(" "));function _(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 K(t,e){return t.errors-e.errors||e.requiredCovered-t.requiredCovered||e.declaredCovered-t.declaredCovered||t.schemaEchoKeys-e.schemaEchoKeys}var D=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 I(t,e){const s=[];return q(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 q(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&&!J(t,e.const)&&i.push({path:s,message:`expected the constant ${JSON.stringify(e.const)}`});if(Array.isArray(e.enum)){e.enum.some(e=>J(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=G[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)=>q(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 r of function(t){return Object.keys(t)}(t))s.allowsProperty(e,r)||i.push({path:[...e,r],message:"property is not declared by the Schema"}),q(t[r],[...e,r],s,i)}}function J(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=F(t),i=F(e);return null!==s&&null!==i&&s===i}(t,e)}function F(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 G={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 H(t,e,s={}){return(await V(t,e,s)).value}async function V(t,e,s={}){const i=e instanceof g?e:await g.create(e,s),r=t.trim();if(!1===s.locate||function(t){try{return JSON.parse(t),!0}catch{return!1}}(r)){const t=W(r,i,s),e=[...t.dropped,...t.leftover?[t.leftover]:[]];z(e,s);const n=[...t.flags];return M(t.value)&&n.push("schema-echo-detected"),{value:t.value,flags:n,errors:I(t.value,i),candidates:[],discarded:"ignore"===s.onDiscard?[]:e}}const n=w(r,i);if(0===n.length){const t=new $(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)),z(o,s),{value:e,flags:[...n],errors:I(e,i),candidates:[],discarded:"ignore"===s.onDiscard?[]:o}}const o=n.map(t=>{const e=W(t.text,i,s),{score:r,flags:n}=R(e.value,i),o=I(e.value,i);return r.errors=o.length,M(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(B(s.value),s);for(const i of t)e.get(B(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)=>K(t.region.score,e.region.score)||e.region.start-t.region.start);return{ordered:i,duplicates:s}}(o,s.onMultiple??"best"),a=h[0],u=h.slice(1),f="best"===(s.onMultiple??"best")&&u.length>0&&0===K(a.region.score,u[0].region.score),{prose:l,fragments:d}=P(r,a.region,o.filter(t=>t!==a).map(t=>t.region)),p=new Set([...a.region.flags,...a.read]);l.some(t=>t.start<a.region.start)&&p.add("prose-prefix"),l.some(t=>t.start>=a.region.end)&&p.add("trailing-chatter"),u.length>0&&p.add("extra-fragments-dropped"),c.size>0&&p.add("duplicate-candidates"),f&&p.add("ambiguous-candidates");for(const t of o)for(const e of t.suspicion)p.add(e);const m=[...l.map(t=>t.text),...d,...a.leftover];return z(m,s),{value:a.value,flags:[...p],errors:a.errors,candidates:o.map(t=>t.region),discarded:"ignore"===s.onDiscard?[]:m}}function W(t,e,s){const i=new $(e,s);let r=i.parse(t);!1!==s.wrapArrays&&j(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 z(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 B(t){return JSON.stringify(t)??String(t)}
|