@isdk/json-repair 0.1.2 → 0.1.3

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/.prettierignore CHANGED
@@ -2,3 +2,11 @@ node_modules
2
2
  dist
3
3
  web
4
4
  docs
5
+ .cache
6
+
7
+ # 由 commit-and-tag-version 生成
8
+ CHANGELOG.md
9
+
10
+ # 本地编辑器配置 / 包管理器配置
11
+ .vscode
12
+ .npmrc
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines.
4
4
 
5
+ ## [0.1.3](https://github.com///compare/v0.1.2...v0.1.3) (2026-11-30)
6
+
7
+ ### Features
8
+
9
+ * wire up keyMatching, additionalProperties and stringCaptureStrategy ([3aea142](https://github.com///commit/3aea14276d07fc71ad86f4d26d768f071b1ee21c))
10
+
11
+ ### Bug Fixes
12
+
13
+ * honour Schema-declared types that the parser used to ignore ([bd99943](https://github.com///commit/bd999430e5a6ec831a040451c76463ff7791a09a))
14
+ * keep clean parses and recognize quoted keys containing whitespace ([fbe4973](https://github.com///commit/fbe49736f3862b38354f93edf3dee294dbc2ed1e))
15
+ * never touch the prototype chain and dereference a copy of the Schema ([681d40f](https://github.com///commit/681d40f72400a92a50431dd5576db64ef7f1073c))
16
+ * parse scientific notation and stop a number at the end of the literal ([49ac3f4](https://github.com///commit/49ac3f403ff4bd148e118dd8fa506af1f3eec264))
17
+ * recognise Schema-declared multi-word keys in unquoted documents ([59c6d36](https://github.com///commit/59c6d36037a5cf1865954685d9201a03bb3231c6))
18
+ * take the first numeric token when coercing a noisy number ([d3b5f1b](https://github.com///commit/d3b5f1be9194cc880aea62ac3cdbb40d14ed2d29))
19
+ * use hasOwnProperty.call for the duplicate-key check ([e575794](https://github.com///commit/e575794cf3a652c9a872ea13f965453a797ddef5))
20
+
5
21
  ## [0.1.2](https://github.com/isdk/json-repair.js/compare/v0.1.1...v0.1.2) (2026-01-30)
6
22
 
7
23
 
package/README.cn.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # @isdk/json-repair
2
2
 
3
3
  > 【[English](./README.md)|中文】
4
+
4
5
  ---
5
6
 
6
7
  一个强大的、基于 Schema 引导的 JSON 修复库,专为修复大语言模型 (LLM) 生成的“破碎” JSON 而设计。
@@ -30,7 +31,11 @@ LLM 生成的 JSON 经常包含语法错误或语义噪声。常见问题包括
30
31
  - **枚举模糊匹配**:如果 Schema 定义了枚举,能将 `"Processing!"` 自动匹配为 `"processing"`。
31
32
  - **噪声数字提取**:能从 `"约 1,200.50 元"` 中提取出 `1200.5`。
32
33
  - **布尔值变体**:识别 `yes/no`、`on/off`、`1/0`、`确定/取消`、`是/否` 为布尔值。
34
+ - **声明为 string 的值保持文本**:`{ Population: 12 }` 在 `{ type: 'string' }` 下得到 `"12"`;数字取自文档原文,所以 `{ id: 01234 }` 得到 `"01234"`。
33
35
  - **隐式结构支持**:自动修复对象或数组中缺失的花括号。
36
+ - **稳当的属性边界**:带引号的键名可以含空格与标点(`"Official language": "Italian"`);Schema 声明过的多词键名,即使文档里没加引号也能被识别;能完整解析的值不会被重新切分,因此合法 JSON 的产物与 `JSON.parse` 完全一致。
37
+ - **模糊键名匹配**:`user_name`、`userName`、`USER NAME` 都会归位到 Schema 声明的属性名,输出里用的就是声明的名字。
38
+ - **原型安全的输出**:`__proto__`、`constructor` 这类键名存为自身的普通属性,与 `JSON.parse` 的处理一致。
34
39
  - **高性能**:支持复用 `SchemaWalker` 实例,适用于高吞吐量的批处理场景。
35
40
 
36
41
  ## 📦 安装
@@ -46,21 +51,38 @@ pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
46
51
  这是最强大的使用方式。提供 Schema 可以开启语义强制转换、贪婪捕获和更精准的歧义消除等高级特性。
47
52
 
48
53
  ```typescript
49
- import { jsonRepair } from '@isdk/json-repair';
54
+ import { jsonRepair } from '@isdk/json-repair'
50
55
 
51
56
  const schema = {
52
57
  type: 'object',
53
58
  properties: {
54
59
  query: { type: 'string' },
55
- status: { enum: ['success', 'error'] }
56
- }
57
- };
60
+ status: { enum: ['success', 'error'] },
61
+ },
62
+ }
58
63
 
59
- const brokenJson = '{ query: "python" OR "js", status: Success! }';
64
+ const brokenJson = '{ query: "python" OR "js", status: Success! }'
60
65
 
61
- const result = await jsonRepair(brokenJson, schema);
62
- console.log(result);
66
+ const result = await jsonRepair(brokenJson, schema)
67
+ console.log(result)
63
68
  // 输出: { query: '"python" OR "js"', status: 'success' }
69
+
70
+ // Schema 声明过的多词键名,即使文档里没加引号也能被识别。
71
+ const countrySchema = {
72
+ type: 'object',
73
+ properties: {
74
+ Capital: { type: 'string' },
75
+ 'Official language': { type: 'string' },
76
+ },
77
+ }
78
+
79
+ console.log(
80
+ await jsonRepair(
81
+ '{ Capital: Berlin, Official language: Italian }',
82
+ countrySchema
83
+ )
84
+ )
85
+ // 输出: { Capital: 'Berlin', 'Official language': 'Italian' }
64
86
  ```
65
87
 
66
88
  ### 2. 简单用法 (不使用 Schema)
@@ -68,10 +90,16 @@ console.log(result);
68
90
  对于基础的语法修复,你可以不提供 Schema:
69
91
 
70
92
  ```typescript
71
- import { jsonRepair } from '@isdk/json-repair';
93
+ import { jsonRepair } from '@isdk/json-repair'
72
94
 
73
- const result = await jsonRepair('{ name: 张三, age: 30 }');
74
- console.log(result); // { name: '张三', age: 30 }
95
+ const result = await jsonRepair('{ name: 张三, age: 30 }')
96
+ console.log(result) // { name: '张三', age: 30 }
97
+
98
+ // 带引号的键名可以包含空格与标点;合法 JSON 会被原样保留。
99
+ const country = await jsonRepair(
100
+ '{ "Capital": "Berlin", "Official language": "Italian" }'
101
+ )
102
+ console.log(country) // { Capital: 'Berlin', 'Official language': 'Italian' }
75
103
  ```
76
104
 
77
105
  ### 高级技巧:复用 SchemaWalker (批处理)
@@ -79,23 +107,107 @@ console.log(result); // { name: '张三', age: 30 }
79
107
  如果你需要使用相同的 Schema 处理大量数据,预解析 Schema 可以显著提升性能:
80
108
 
81
109
  ```typescript
82
- import { jsonRepair, SchemaWalker } from '@isdk/json-repair';
110
+ import { jsonRepair, SchemaWalker } from '@isdk/json-repair'
83
111
 
84
- const walker = await SchemaWalker.create(mySchema);
112
+ // 与 Schema 本身相关的选项(`keyMatching`)属于 walker。
113
+ const walker = await SchemaWalker.create(mySchema, { keyMatching: true })
85
114
 
86
115
  for (const item of brokenItems) {
87
- const result = await jsonRepair(item, walker);
116
+ const result = await jsonRepair(item, walker)
88
117
  // ...
89
118
  }
90
119
  ```
91
120
 
121
+ ## 🧭 属性边界是如何判定的
122
+
123
+ 在修复一个值的过程中,解析器必须在每个位置上判断接下来的 `"foo":` 是**下一个属性**的起点,还是**当前值**的一部分。它分为两种模式:
124
+
125
+ 1. **结构模式 (Structural mode)** —— 适用于刚刚由严格 JSON 路径解析成功的值(成对的 `"string"`、格式合法的数字、`true`/`false`/`null`)。
126
+ 此时任何“键形状 + `:`”都被视为下一个属性,**包括含空格或标点的引号键名**(如 `"Official language":`、`"a, b":`、`"a: b":`)。
127
+ 一次成功的严格解析**永远不会被丢弃**,这正是“合法 JSON 的产物与 `JSON.parse` 一致”这条不变量的来源。
128
+ 2. **贪婪模式 (Greedy mode)** —— 适用于无法严格解析的值(无引号文本、内部引号未转义、`"A" OR "B"` 表达式、`@func(a="x, y")` 这类 DSL 片段)。
129
+ - 如果 Schema 在当前层级声明了属性名,则**只在已声明的键名处断开**。仅仅是“看起来像键”的文本会留在值里:
130
+ `{ "query": he said "hello there": loudly, "intent": "x" }` 会得到 `query = 'he said "hello there": loudly'`。
131
+ - 如果当前层级没有任何声明的属性名(无 Schema、只有 `type: "object"` 没有 `properties`、或只写了 `additionalProperties`),则退回到“第一个键形状的 token 即结束值”。
132
+ - **已声明**的键名还会被按字面量搜索,因此即使文档里没加引号、且键名内部含空格,它依然是断点(也是键)。通用键扫描器看不出裸的 `Official language:` 是一个键,而 Schema 能告诉你:
133
+ `{ Capital: Berlin, Official language: Italian }` 会得到 `{ Capital: 'Berlin', 'Official language': 'Italian' }`。开启 `keyMatching` 后,已声明键名的分隔符与大小写变体(`user_name` 对应 `userName`)同样会结束一个值。
134
+
135
+ 将 `stringCaptureStrategy: 'conservative'` 可以让贪婪模式不管 Schema 声明与否,都在任意“键形状 + `:`”处结束(参见[修复选项](#-修复选项))。
136
+
137
+ ### 如何理解这套启发式
138
+
139
+ 歧义的本质是信息缺失,而不是魔法:`{ "note": see "foo bar": baz here, "b": 2 }` 在没有 Schema 时无法判定,因为两种解读都说得通。解析器遵循的原则是:
140
+
141
+ - **能干净解析**的值会被信任;它后面的东西被当作结构。
142
+ - **本身已破碎**的值,只要 Schema 能给出真正的锚点,就尽量作为文本保留。
143
+ - Schema **声明过**的键名会被按字面量匹配,所以多词键名在文档里不加引号也能被识别;而 Schema 未声明的多词文本永远不会被当成键。
144
+ - 因此,**为当前层级声明 `properties` 是引导修复效果最显著的手段** —— 已声明的键名是贪婪捕获的断点,已声明的 `type`/`enum` 才能开启语义强制转换。
145
+ - 只要 Schema 在该层级声明了 `properties`(或 `type: 'object'`),该层级就被当作对象;因此省略 `type: 'object'` 也不会让无花括号的文档退化成标量。
146
+ - 如果值里可能合法地出现 `word:` 或 `"phrase":`,要么让模型输出正确转义的 JSON(严格解析直接胜出),要么在 Schema 里声明该层级的属性。
147
+ - 如果某个值在“看起来像键”的地方被截断,通常是你的 Schema 在该层级缺少 `properties` —— 补上后重试。
148
+
149
+ 数字字面量支持科学计数法(`1e5`、`-2E2`),也容忍 LLM 常见的 `+5`、`.5`、`5.`。而 `1.2.3` 这种不完整的字面量会先作为字符串保留,再按 Schema 做强制转换。
150
+
151
+ 反方向同样成立:Schema 声明 `type: 'string'` 时 `12` 会被转成 `"12"`;并且文本取自文档原文而非解析后的数字,所以前导零不会丢失(`{ id: 01234 }` → `"01234"`)。`null` 与对象/数组不会被转成字符串。
152
+
92
153
  ## ⚠️ 注意事项与歧义说明
93
154
 
94
155
  - **“奇偶判定法”逻辑**:当字符串被引号包裹且内部包含引号时,我们会计算内部引号的数量。
95
156
  - 奇数个 (如 `"a"b"`):认为外层是定界符 -> 结果 `a"b`。
96
157
  - 偶数个 (如 `"A" OR "B"`):认为外层是内容的一部分 -> 结果 `"A" OR "B"`。
97
158
  - **局限性**:极少数极端模式如 `"a"b"c"` 可能仍存在歧义。
98
- - **Markdown 代码块**:本库专注于 JSON 内容修复。如果 LLM 的输出包含 ```json ...``` 标记,请在传入前自行剥离。
159
+ - **破碎值内部“看起来像键”的文本(无 Schema 引导时)**:当前层级没有声明任何属性名时,第一个键形状的 token 就会结束该值。
160
+ 因此无 Schema 的 `{ "note": see "foo bar": baz here, "b": 2 }` 会被读成 `{ note: 'see', 'foo bar': 'baz here', b: 2 }`。
161
+ 声明该层级的 `properties` 后,贪婪捕获只在真正的键名处断开,才能还原成 `{ note: 'see "foo bar": baz here', b: 2 }`(参见[如何理解这套启发式](#如何理解这套启发式))。
162
+ - **未加引号的多词键名必须有声明。** `{ Capital: Berlin, Official language: Italian }` 能拆成两个属性,是因为 Schema 声明了 `Official language`。若文档里的带空格键名 _没有_ 声明,它就不是键:`{ Capital: Berlin, Official Lang: Italian }` 在默认的 `'aggressive'` 策略下会把整段都留在 `Capital` 里;改用 `'conservative'` 则会在空格处断开(`{ Capital: 'Berlin, Official', Lang: 'Italian' }`)。
163
+ - **值里重复出现已声明的键名时会被截断。** 声明过的键就是断点,所以 `{ summary: the Official language: Italian is wrong, Official language: Italian }` 会读成 `summary = 'the'`。如果值确实可能重复某个已声明的键名,就让模型给键加引号,或者换一个不会碰撞的属性名。
164
+ - **Markdown 代码块**:本库专注于 JSON 内容修复。如果 LLM 的输出包含 `json ...` 标记,请在传入前自行剥离。
165
+
166
+ ## ⚙️ 修复选项
167
+
168
+ `jsonRepair(input, schema, options)` 的第三个参数就是 `RepairOptions`:
169
+
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 声明的键名处结束。代价是值更容易被截断,好处是一个破碎的值不会吞掉后面的一大片内容。 |
176
+
177
+ ```typescript
178
+ const schema = {
179
+ type: 'object',
180
+ properties: {
181
+ userName: { type: 'string' },
182
+ userAge: { type: 'number' },
183
+ },
184
+ }
185
+
186
+ await jsonRepair('{ user_name: "Ada", user_age: "36" }', schema, {
187
+ keyMatching: true,
188
+ coerceTypes: true,
189
+ })
190
+ // { userName: 'Ada', userAge: 36 }
191
+
192
+ await jsonRepair('{ userName: "Ada", reasoning: "让我想想…" }', schema, {
193
+ additionalProperties: 'remove',
194
+ })
195
+ // { userName: 'Ada' }
196
+
197
+ const querySchema = {
198
+ type: 'object',
199
+ properties: { query: { type: 'string' }, intent: { type: 'string' } },
200
+ }
201
+
202
+ await jsonRepair(
203
+ '{ "query": he said "hello there": loudly, "intent": "x" }',
204
+ querySchema,
205
+ { stringCaptureStrategy: 'conservative' }
206
+ )
207
+ // { query: 'he said', 'hello there': 'loudly', intent: 'x' }
208
+ ```
209
+
210
+ 复用 walker 时,`keyMatching` 取自 `SchemaWalker.create()` 的选项;其余选项在每次 `jsonRepair()` 调用时读取。
99
211
 
100
212
  ## 📄 开源协议
101
213
 
package/README.md CHANGED
@@ -1,6 +1,7 @@
1
1
  # @isdk/json-repair
2
2
 
3
3
  > 【English|[中文](./README.cn.md)】
4
+
4
5
  ---
5
6
 
6
7
  A powerful, schema-guided JSON repair library specifically designed to fix "broken" JSON generated by LLMs (Large Language Models).
@@ -30,7 +31,11 @@ Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses you
30
31
  - **Fuzzy Enum Matching**: Matches "Processing!" to `"processing"` if defined in Schema enums.
31
32
  - **Noisy Number Extraction**: Extracts `1200.5` from `"Approx. 1,200.50 USD"`.
32
33
  - **Boolean Variants**: Recognizes `yes/no`, `on/off`, `1/0`, `确定/取消` as booleans.
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"`.
33
35
  - **Implicit Structure Support**: Automatically repairs missing braces in objects and arrays.
36
+ - **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
+ - **Fuzzy Key Matching**: `user_name`, `userName` and `USER NAME` resolve to the property your Schema declares, and the output carries the declared name.
38
+ - **Prototype-Safe Output**: keys such as `__proto__` or `constructor` are stored as own data properties, exactly as `JSON.parse` leaves them.
34
39
  - **Performance**: Support for reusing `SchemaWalker` instances for high-throughput batch processing.
35
40
 
36
41
  ## 📦 Installation
@@ -48,21 +53,38 @@ pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
48
53
  This is the most powerful way to use the library. Providing a schema enables advanced features like semantic coercion, greedy capture, and accurate disambiguation.
49
54
 
50
55
  ```typescript
51
- import { jsonRepair } from '@isdk/json-repair';
56
+ import { jsonRepair } from '@isdk/json-repair'
52
57
 
53
58
  const schema = {
54
59
  type: 'object',
55
60
  properties: {
56
61
  query: { type: 'string' },
57
- status: { enum: ['success', 'error'] }
58
- }
59
- };
62
+ status: { enum: ['success', 'error'] },
63
+ },
64
+ }
60
65
 
61
- const brokenJson = '{ query: "python" OR "js", status: Success! }';
66
+ const brokenJson = '{ query: "python" OR "js", status: Success! }'
62
67
 
63
- const result = await jsonRepair(brokenJson, schema);
64
- console.log(result);
68
+ const result = await jsonRepair(brokenJson, schema)
69
+ console.log(result)
65
70
  // Output: { query: '"python" OR "js"', status: 'success' }
71
+
72
+ // A multi-word key the Schema declares is found even when the document leaves it unquoted.
73
+ const countrySchema = {
74
+ type: 'object',
75
+ properties: {
76
+ Capital: { type: 'string' },
77
+ 'Official language': { type: 'string' },
78
+ },
79
+ }
80
+
81
+ console.log(
82
+ await jsonRepair(
83
+ '{ Capital: Berlin, Official language: Italian }',
84
+ countrySchema
85
+ )
86
+ )
87
+ // Output: { Capital: 'Berlin', 'Official language': 'Italian' }
66
88
  ```
67
89
 
68
90
  ### 2. Simple Usage (Without Schema)
@@ -70,10 +92,16 @@ console.log(result);
70
92
  For basic syntax repair where schema guidance isn't required:
71
93
 
72
94
  ```typescript
73
- import { jsonRepair } from '@isdk/json-repair';
95
+ import { jsonRepair } from '@isdk/json-repair'
74
96
 
75
- const result = await jsonRepair('{ name: John, age: 30 }');
76
- console.log(result); // { name: 'John', age: 30 }
97
+ const result = await jsonRepair('{ name: John, age: 30 }')
98
+ console.log(result) // { name: 'John', age: 30 }
99
+
100
+ // Quoted keys may contain spaces and punctuation; valid JSON round-trips untouched.
101
+ const country = await jsonRepair(
102
+ '{ "Capital": "Berlin", "Official language": "Italian" }'
103
+ )
104
+ console.log(country) // { Capital: 'Berlin', 'Official language': 'Italian' }
77
105
  ```
78
106
 
79
107
  ### Advanced: Reusing SchemaWalker (Batch Processing)
@@ -81,23 +109,133 @@ console.log(result); // { name: 'John', age: 30 }
81
109
  For better performance when processing many items with the same schema:
82
110
 
83
111
  ```typescript
84
- import { jsonRepair, SchemaWalker } from '@isdk/json-repair';
112
+ import { jsonRepair, SchemaWalker } from '@isdk/json-repair'
85
113
 
86
- const walker = await SchemaWalker.create(mySchema);
114
+ // Options that concern the Schema itself (`keyMatching`) belong to the walker.
115
+ const walker = await SchemaWalker.create(mySchema, { keyMatching: true })
87
116
 
88
117
  for (const item of brokenItems) {
89
- const result = await jsonRepair(item, walker);
118
+ const result = await jsonRepair(item, walker)
90
119
  // ...
91
120
  }
92
121
  ```
93
122
 
123
+ ## 🧭 How Property Boundaries Are Detected
124
+
125
+ While repairing a value, the parser must decide at every position whether an upcoming
126
+ `"foo":` starts the **next property** or is just part of the **current value**. It uses two modes:
127
+
128
+ 1. **Structural mode** — applies right after a value was parsed by the strict JSON path
129
+ (a balanced `"string"`, a well-formed number, `true`/`false`/`null`).
130
+ Any key-shaped token followed by `:` counts as the next property, _including quoted keys
131
+ that contain whitespace or punctuation_ (`"Official language":`, `"a, b":`, `"a: b":`).
132
+ A successful strict parse is **never** discarded, which is why valid JSON always yields
133
+ exactly what `JSON.parse` would return.
134
+ 2. **Greedy mode** — applies when the value could not be parsed strictly (unquoted text,
135
+ unescaped inner quotes, `"A" OR "B"` expressions, DSL snippets such as `@func(a="x, y")`).
136
+ - If the Schema declares property names for the current level, capture stops **only at a
137
+ declared key**. Text that merely looks like a key stays inside the value:
138
+ `{ "query": he said "hello there": loudly, "intent": "x" }` keeps
139
+ `query = 'he said "hello there": loudly'`.
140
+ - If the Schema declares no property names for that level (no schema, `type: "object"`
141
+ without `properties`, or only `additionalProperties`), the parser falls back to
142
+ “the first key-shaped token ends the value”.
143
+ - A **declared** name is additionally searched for literally, so it is a breakpoint (and a key)
144
+ even when the document left it unquoted and it contains whitespace. The generic key scanner
145
+ cannot see a bare `Official language:` as one key — the Schema can:
146
+ `{ Capital: Berlin, Official language: Italian }` yields
147
+ `{ Capital: 'Berlin', 'Official language': 'Italian' }`. Under `keyMatching`, separator and
148
+ case variants of a declared key (`user_name` for `userName`) end a value too.
149
+
150
+ Set `stringCaptureStrategy: 'conservative'` to make greedy mode stop at _any_ key-shaped
151
+ token, whatever the Schema declares (see [Repair Options](#-repair-options)).
152
+
153
+ ### Thinking about the heuristic
154
+
155
+ Ambiguity is missing information, not magic: `{ "note": see "foo bar": baz here, "b": 2 }`
156
+ cannot be decided without a schema, because both readings are plausible. The principles the
157
+ parser follows are:
158
+
159
+ - A **cleanly parsed** value is trusted; whatever follows it is assumed to be structure.
160
+ - A **messy** value is preserved as text whenever the Schema can name the real anchors.
161
+ - A name the Schema **declares** is matched literally, so a multi-word key does not need quotes in the document to be recognised; a multi-word name the Schema does not declare is never treated as a key.
162
+ - Consequently, **declaring the `properties` of the current level is the single most effective
163
+ way to steer the repair** — declared keys act as breakpoints for greedy capture, and
164
+ declared `type`/`enum` enable semantic coercion.
165
+ - A level counts as an object when the Schema declares `properties` or `type: 'object'`, so
166
+ omitting `type: 'object'` does not degrade a brace-less document into a scalar value.
167
+ - If a value may legitimately contain `word:` or `"phrase":`, prefer having the model emit
168
+ properly escaped JSON (then the strict parse wins outright), or declare that level's
169
+ properties in the Schema.
170
+ - If a value looks truncated right at something key-shaped, that level is probably missing
171
+ `properties` in your Schema — add them and re-run.
172
+
173
+ Numeric literals support scientific notation (`1e5`, `-2E2`) as well as the lax LLM forms
174
+ `+5`, `.5` and `5.`. A partial literal such as `1.2.3` is kept as a string and then coerced
175
+ according to the Schema.
176
+
177
+ A declared `type: 'string'` is honoured in the other direction too: `12` becomes `"12"`, and
178
+ because the text comes from the document rather than the parsed number, a leading zero
179
+ survives (`{ id: 01234 }` → `"01234"`). `null` and structures are never stringified.
180
+
94
181
  ## ⚠️ Known Limitations & Disambiguation
95
182
 
96
183
  - **The "Parity Rule"**: When a string is wrapped in quotes and contains internal quotes, we count the internal ones.
97
184
  - Odd count (e.g., `"a"b"`): We assume the outer quotes are delimiters -> `a"b`.
98
185
  - Even count (e.g., `"A" OR "B"`): We assume the outer quotes are part of the expression -> `"A" OR "B"`.
99
186
  - **Limitation**: Highly unusual patterns like `"a"b"c"` might remain ambiguous.
100
- - **Markdown Blocks**: This library focuses on the JSON content. Please strip ```json ...``` markers before passing the string if your LLM includes them.
187
+ - **Key-shaped text inside a broken value (no schema guidance)**: when the Schema declares no property names for the current level, the first key-shaped token ends the value.
188
+ `{ "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
+ - **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
+ - **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.
192
+
193
+ ## ⚙️ Repair Options
194
+
195
+ `jsonRepair(input, schema, options)` takes a fourth argument of type `RepairOptions`:
196
+
197
+ | Option | Default | What it does |
198
+ | ----------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
199
+ | `coerceTypes` | `true` | Converts a value to the type the Schema declares: `"Approx. 1,200.50 USD"` → `1200.5`, `"yes"` → `true`, `"Processing!"` → `"processing"` when the enum says so, `12` → `"12"` under `type: 'string'` (the digits come from the document, so `{ id: 01234 }` → `"01234"`). `null` and structures are never stringified. |
200
+ | `keyMatching` | `false` | Resolves incoming keys to the names the Schema declares. `true` ignores case and separators, so `user_name`, `userName` and `USER NAME` all match `userName`; a function `(key, properties) => string \| undefined` decides itself (`undefined` keeps the key as it is). A match renames the key in the output, which also re-enables coercion for that subtree. With `true` it also decides where greedy capture stops: `user_name:` ends a value when the Schema declares `userName`. |
201
+ | `additionalProperties` | `'keep'` | `'remove'` drops keys the Schema does not declare. Applied only at levels that do declare `properties` — a free-form level has no “extra” keys and is left untouched. Independent of the JSON Schema keyword `additionalProperties: false`, which is honoured on its own. |
202
+ | `stringCaptureStrategy` | `'aggressive'` | `'conservative'` ends greedy capture at any key-shaped token instead of only at declared Schema keys: less risk of one broken value swallowing the rest of the document, at the cost of cutting values short. |
203
+
204
+ ```typescript
205
+ const schema = {
206
+ type: 'object',
207
+ properties: {
208
+ userName: { type: 'string' },
209
+ userAge: { type: 'number' },
210
+ },
211
+ }
212
+
213
+ await jsonRepair('{ user_name: "Ada", user_age: "36" }', schema, {
214
+ keyMatching: true,
215
+ coerceTypes: true,
216
+ })
217
+ // { userName: 'Ada', userAge: 36 }
218
+
219
+ await jsonRepair('{ userName: "Ada", reasoning: "let me think…" }', schema, {
220
+ additionalProperties: 'remove',
221
+ })
222
+ // { userName: 'Ada' }
223
+
224
+ const querySchema = {
225
+ type: 'object',
226
+ properties: { query: { type: 'string' }, intent: { type: 'string' } },
227
+ }
228
+
229
+ await jsonRepair(
230
+ '{ "query": he said "hello there": loudly, "intent": "x" }',
231
+ querySchema,
232
+ { stringCaptureStrategy: 'conservative' }
233
+ )
234
+ // { query: 'he said', 'hello there': 'loudly', intent: 'x' }
235
+ ```
236
+
237
+ `keyMatching` is read from the options passed to `SchemaWalker.create()` when you reuse a
238
+ walker; the other options are read on every `jsonRepair()` call.
101
239
 
102
240
  ## 📄 License
103
241
 
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var t,s=Object.create,i=Object.defineProperty,h=Object.getOwnPropertyDescriptor,e=Object.getOwnPropertyNames,r=Object.getPrototypeOf,n=Object.prototype.hasOwnProperty,o=(t,s,r,o)=>{if(s&&"object"==typeof s||"function"==typeof s)for(let c of e(s))n.call(t,c)||c===r||i(t,c,{get:()=>s[c],enumerable:!(o=h(s,c))||o.enumerable});return t},c={};((t,s)=>{for(var h in s)i(t,h,{get:s[h],enumerable:!0})})(c,{RepairParser:()=>a,SchemaWalker:()=>f,jsonRepair:()=>l}),module.exports=(t=c,o(i({},"__esModule",{value:!0}),t));var u=((t,h,e)=>(e=null!=t?s(r(t)):{},o(!h&&t&&t.__esModule?e:i(e,"default",{value:t,enumerable:!0}),t)))(require("@apidevtools/json-schema-ref-parser"),1),f=class t{dereferencedSchema;constructor(t){this.dereferencedSchema=t}static async create(s){if(!s)return new t({});const i=new u.default,h=await i.dereference(s);return new t(h)}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&&!!i.properties[s]||!1!==i.additionalProperties))}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),h=i?.properties?.[s];return h?Array.isArray(h.type)?h.type:h.type?[h.type]:[]:[]}},a=class{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.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const t=this.peek(),s=this.walker.getSchemaForPath(this.pathStack),i=s?.type;if("{"===t||"object"===i&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===t)return this.consumeArray();const h=this.pos;let e,r=!1;if('"'===t||"'"===t)try{e=this.consumeString();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if(this.isDigit(t)||"-"===t)try{e=this.consumeNumber();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}else if("t"===t||"f"===t||"n"===t)try{e="n"===t?this.consumeNull():this.consumeBoolean();this.pos;this.skipWhitespace(),this.isAtDelimiter()||this.pos>=this.input.length?r=!0:this.pos=h}catch(t){this.pos=h}if(r)return this.options.coerceTypes&&s?this.coerceValue(e,s):e;this.pos=h;const n=this.consumeGreedyString();return this.options.coerceTypes&&s?this.coerceValue(n,s):n}consumeObject(){const t={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const i=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const h=this.consumeKey();if(!h)break;if(!s&&t.hasOwnProperty(h)){this.pos=i;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==i||void 0!==s&&""!==s)&&(t[h]=s)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||s&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!s)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===i)break}return s&&"}"===this.peek()&&this.consumeChar("}"),t}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 h=this.consumeValue();this.pos!==i&&(t.push(h),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(){if(this.skipWhitespace(),this.pos>=this.input.length)return"";if('"'===this.peek()||"'"===this.peek())return this.consumeString();let t="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek();)t+=this.next();return t}consumeGreedyString(){let t="";const s=[];let i=!1,h="";for(;this.pos<this.input.length;){const e=this.peek();if(0===s.length&&this.isAtDelimiter())break;if(i){if(e===h){let t=0,s=this.pos-1;for(;s>=0&&"\\"===this.input[s];)t++,s--;t%2==0&&(i=!1)}}else if('"'===e||"'"===e)i=!0,h=e;else if("("===e||"["===e||"{"===e)s.push(e);else if(")"===e||"]"===e||"}"===e){const t=s[s.length-1];(")"===e&&"("===t||"]"===e&&"["===t||"}"===e&&"{"===t)&&s.pop()}t+=this.next()}let e=t.trim();if(e.length>=2){const t=e[0],s=e[e.length-1];if(('"'===t||"'"===t)&&t===s){const s=e.slice(1,-1);let i=0;for(let h=0;h<s.length;h++)s[h]!==t||0!==h&&"\\"===s[h-1]||i++;if(i%2==1||0===i)return s}}return e}isAtDelimiter(){if(this.pos>=this.input.length)return!0;const t=this.peek();if("}"===t||"]"===t)return!0;const s="number"==typeof this.pathStack[this.pathStack.length-1];if(","===t){if(s)return!0;const t=this.input.slice(this.pos+1);return!!/^\s*[}\]]/.test(t)||this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)}if(this.isLookingAtKey(this.pathStack.slice(0,-1)))return!0;if(this.isWhitespace(t)){const t=this.pos;this.skipWhitespace();const s=this.peek(),i="}"===s||"]"===s||","===s||this.isLookingAtKey(this.pathStack.slice(0,-1));return this.pos=t,i}return!1}isLookingAtKey(t,s=this.pos){const i=this.input.slice(s).match(/^\s*["']?([^"'\s:]+)["']?\s*:/);if(i){const s=i[1];return this.walker.isValidProperty(t,s)}return!1}coerceValue(t,s){const i=Array.isArray(s.type)?s.type:s.type?[s.type]:[],h=String(t).trim();if(s.enum){const t=h.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 e=null===t?"null":typeof t;if(i.length>0&&i.includes(e))return t;if(i.includes("number")||i.includes("integer")){let t=h.replace(/([^0-9.\-])/g,t=>","===t||","===t?"":" ").trim().split(/\s+/)[0];const s=parseFloat(t);if(!isNaN(s))return i.includes("integer")?Math.round(s):s}if(i.includes("boolean")){const t=h.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 i.includes("null")&&"null"===h.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}consumeNumber(){let t="";for(;this.pos<this.input.length&&/[0-9.\-]/.test(this.peek());)t+=this.next();return parseFloat(t)}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 l(t,s,i={}){const h=s instanceof f?s:await f.create(s);return new a(h,i).parse(t)}
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)}