@isdk/json-repair 0.1.1
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 +4 -0
- package/.prettierrc +8 -0
- package/.versionrc +36 -0
- package/CHANGELOG.md +11 -0
- package/LICENSE-MIT +22 -0
- package/README.cn.md +101 -0
- package/README.md +103 -0
- package/TODO +0 -0
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +181 -0
- package/dist/index.d.ts +181 -0
- package/dist/index.js +1 -0
- package/docs/README.md +107 -0
- package/docs/_media/README.cn.md +101 -0
- package/docs/classes/RepairParser.md +64 -0
- package/docs/classes/SchemaWalker.md +121 -0
- package/docs/functions/jsonRepair.md +48 -0
- package/docs/globals.md +24 -0
- package/docs/interfaces/RepairOptions.md +63 -0
- package/docs/type-aliases/JSONPath.md +14 -0
- package/eslint.config.mjs +31 -0
- package/package.json +69 -0
- package/setupVitest.mjs +15 -0
- package/tsconfig.json +19 -0
- package/tsconfig.spec.json +19 -0
- package/tsup.config.ts +34 -0
- package/typedoc.config.cjs +7 -0
- package/vite.config.mjs +16 -0
package/.prettierignore
ADDED
package/.prettierrc
ADDED
package/.versionrc
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"types": [
|
|
3
|
+
{
|
|
4
|
+
"type": "feat",
|
|
5
|
+
"section": "Features"
|
|
6
|
+
},
|
|
7
|
+
{
|
|
8
|
+
"type": "fix",
|
|
9
|
+
"section": "Bug Fixes"
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"type": "chore",
|
|
13
|
+
"hidden": true
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
"type": "docs",
|
|
17
|
+
"hidden": true
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"type": "style",
|
|
21
|
+
"hidden": true
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
"type": "refactor",
|
|
25
|
+
"section": "Refactor"
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"type": "perf",
|
|
29
|
+
"section": "Performance"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"type": "test",
|
|
33
|
+
"hidden": true
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
}
|
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
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.1.1 (2026-01-30)
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
### Features
|
|
9
|
+
|
|
10
|
+
* initial implementation of schema-guided json-repair with fuzzy matching and semantic coercion ([0b5c61d](https://github.com/isdk/json-repair.js/commit/0b5c61d4f059ddcdc6b47498f3bb4cfbb905409d))
|
|
11
|
+
* support JSON repair with missing or empty schema ([285873c](https://github.com/isdk/json-repair.js/commit/285873c5a6c2afa891c3cbea3296f13e2b11a4d0))
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Copyright (c) 2026 Riceball LEE
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person
|
|
4
|
+
obtaining a copy of this software and associated documentation
|
|
5
|
+
files (the "Software"), to deal in the Software without
|
|
6
|
+
restriction, including without limitation the rights to use,
|
|
7
|
+
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
8
|
+
copies of the Software, and to permit persons to whom the
|
|
9
|
+
Software is furnished to do so, subject to the following
|
|
10
|
+
conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be
|
|
13
|
+
included in all copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
16
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
17
|
+
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
18
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
19
|
+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
20
|
+
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
21
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
22
|
+
OTHER DEALINGS IN THE SOFTWARE.
|
package/README.cn.md
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# @isdk/json-repair
|
|
2
|
+
|
|
3
|
+
> 【[English](./README.md)|中文】
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
一个强大的、基于 Schema 引导的 JSON 修复库,专为修复大语言模型 (LLM) 生成的“破碎” JSON 而设计。
|
|
7
|
+
|
|
8
|
+
[](https://opensource.org/licenses/MIT)
|
|
9
|
+
[](https://www.npmjs.com/package/@isdk/json-repair)
|
|
10
|
+
|
|
11
|
+
## 🚀 为什么选择这个库?
|
|
12
|
+
|
|
13
|
+
LLM 生成的 JSON 经常包含语法错误或语义噪声。常见问题包括:
|
|
14
|
+
|
|
15
|
+
- 键或值缺少引号。
|
|
16
|
+
- 字符串内部引号未转义(例如 `"a"b"`)。
|
|
17
|
+
- 缺少逗号或结尾花括号。
|
|
18
|
+
- 值中混合了自然语言(例如 `"age": "大约 30 岁"`)。
|
|
19
|
+
- 隐式结构(例如数组中的对象缺少花括号)。
|
|
20
|
+
|
|
21
|
+
传统的 `json-repair` 库仅在语法层面打补丁。**@isdk/json-repair** 利用 **JSON Schema** 作为导航图,智能地解析、修复并将数据强制转换为符合规范的结构化对象。
|
|
22
|
+
|
|
23
|
+
## ✨ 核心特性
|
|
24
|
+
|
|
25
|
+
- **Schema 引导修复**:利用 Schema 解决歧义(例如通过判断冒号后面是否跟着 Schema 定义的 Key 来决定它是定界符还是字符串内容)。
|
|
26
|
+
- **贪婪字符串捕获**:智能捕获未加引号或破碎的字符串,直到遇到下一个合法的 Schema 键名。
|
|
27
|
+
- **“奇偶判定法”**:完美解决嵌套引号歧义(例如准确区分 `"A" OR "B"` 和 `"a"b"`)。
|
|
28
|
+
- **语义强制转换 (Coercion)**:
|
|
29
|
+
- **枚举模糊匹配**:如果 Schema 定义了枚举,能将 `"Processing!"` 自动匹配为 `"processing"`。
|
|
30
|
+
- **噪声数字提取**:能从 `"约 1,200.50 元"` 中提取出 `1200.5`。
|
|
31
|
+
- **布尔值变体**:识别 `yes/no`、`on/off`、`1/0`、`确定/取消`、`是/否` 为布尔值。
|
|
32
|
+
- **隐式结构支持**:自动修复对象或数组中缺失的花括号。
|
|
33
|
+
- **高性能**:支持复用 `SchemaWalker` 实例,适用于高吞吐量的批处理场景。
|
|
34
|
+
|
|
35
|
+
## 📦 安装
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## 🛠 用法
|
|
42
|
+
|
|
43
|
+
### 1. Schema 引导修复 (推荐)
|
|
44
|
+
|
|
45
|
+
这是最强大的使用方式。提供 Schema 可以开启语义强制转换、贪婪捕获和更精准的歧义消除等高级特性。
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
import { jsonRepair } from '@isdk/json-repair';
|
|
49
|
+
|
|
50
|
+
const schema = {
|
|
51
|
+
type: 'object',
|
|
52
|
+
properties: {
|
|
53
|
+
query: { type: 'string' },
|
|
54
|
+
status: { enum: ['success', 'error'] }
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const brokenJson = '{ query: "python" OR "js", status: 成功 }';
|
|
59
|
+
|
|
60
|
+
const result = await jsonRepair(brokenJson, schema);
|
|
61
|
+
console.log(result);
|
|
62
|
+
// 输出: { query: '"python" OR "js"', status: 'success' }
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 2. 简单用法 (不使用 Schema)
|
|
66
|
+
|
|
67
|
+
对于基础的语法修复,你可以不提供 Schema:
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
import { jsonRepair } from '@isdk/json-repair';
|
|
71
|
+
|
|
72
|
+
const result = await jsonRepair('{ name: 张三, age: 30 }');
|
|
73
|
+
console.log(result); // { name: '张三', age: 30 }
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 高级技巧:复用 SchemaWalker (批处理)
|
|
77
|
+
|
|
78
|
+
如果你需要使用相同的 Schema 处理大量数据,预解析 Schema 可以显著提升性能:
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import { jsonRepair, SchemaWalker } from '@isdk/json-repair';
|
|
82
|
+
|
|
83
|
+
const walker = await SchemaWalker.create(mySchema);
|
|
84
|
+
|
|
85
|
+
for (const item of brokenItems) {
|
|
86
|
+
const result = await jsonRepair(item, walker);
|
|
87
|
+
// ...
|
|
88
|
+
}
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## ⚠️ 注意事项与歧义说明
|
|
92
|
+
|
|
93
|
+
- **“奇偶判定法”逻辑**:当字符串被引号包裹且内部包含引号时,我们会计算内部引号的数量。
|
|
94
|
+
- 奇数个 (如 `"a"b"`):认为外层是定界符 -> 结果 `a"b`。
|
|
95
|
+
- 偶数个 (如 `"A" OR "B"`):认为外层是内容的一部分 -> 结果 `"A" OR "B"`。
|
|
96
|
+
- **局限性**:极少数极端模式如 `"a"b"c"` 可能仍存在歧义。
|
|
97
|
+
- **Markdown 代码块**:本库专注于 JSON 内容修复。如果 LLM 的输出包含 ```json ...``` 标记,请在传入前自行剥离。
|
|
98
|
+
|
|
99
|
+
## 📄 开源协议
|
|
100
|
+
|
|
101
|
+
MIT © Riceball LEE
|
package/README.md
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# @isdk/json-repair
|
|
2
|
+
|
|
3
|
+
> 【English|[中文](./README.cn.md)】
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
A powerful, schema-guided JSON repair library specifically designed to fix "broken" JSON generated by LLMs (Large Language Models).
|
|
7
|
+
|
|
8
|
+
[](https://opensource.org/licenses/MIT)
|
|
9
|
+
[](https://www.npmjs.com/package/@isdk/json-repair)
|
|
10
|
+
|
|
11
|
+
## 🚀 Why this library?
|
|
12
|
+
|
|
13
|
+
LLMs often output JSON that is syntactically invalid or semantically "noisy". Common issues include:
|
|
14
|
+
|
|
15
|
+
- Missing quotes around keys or values.
|
|
16
|
+
- Unescaped quotes inside strings (e.g., `"a"b"`).
|
|
17
|
+
- Missing commas or closing braces.
|
|
18
|
+
- Natural language mixed into values (e.g., `"age": "about 30 years old"`).
|
|
19
|
+
- Implicit structures (e.g., an array of objects without curly braces).
|
|
20
|
+
|
|
21
|
+
Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses your **JSON Schema** as a map to intelligently navigate, repair, and coerce the output into valid, structured data.
|
|
22
|
+
|
|
23
|
+
## ✨ Key Features
|
|
24
|
+
|
|
25
|
+
- **Schema-Guided Repair**: Uses your Schema to resolve ambiguities (e.g., knowing if a colon marks a new key or is part of a string).
|
|
26
|
+
- **Greedy String Capture**: Intelligently captures unquoted or broken strings until the next valid Schema key.
|
|
27
|
+
- **The "Parity Rule"**: Solves nested quote ambiguity (e.g., correctly distinguishing between `"A" OR "B"` and `"a"b"`).
|
|
28
|
+
- **Semantic Coercion**:
|
|
29
|
+
- **Fuzzy Enum Matching**: Matches "Processing!" to `"processing"` if defined in Schema enums.
|
|
30
|
+
- **Noisy Number Extraction**: Extracts `1200.5` from `"Approx. 1,200.50 USD"`.
|
|
31
|
+
- **Boolean Variants**: Recognizes `yes/no`, `on/off`, `1/0`, `确定/取消` as booleans.
|
|
32
|
+
- **Implicit Structure Support**: Automatically repairs missing braces in objects and arrays.
|
|
33
|
+
- **Performance**: Support for reusing `SchemaWalker` instances for high-throughput batch processing.
|
|
34
|
+
|
|
35
|
+
## 📦 Installation
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm install @isdk/json-repair @apidevtools/json-schema-ref-parser
|
|
39
|
+
# or
|
|
40
|
+
pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## 🛠 Usage
|
|
44
|
+
|
|
45
|
+
### 1. Schema-Guided Repair (Recommended)
|
|
46
|
+
|
|
47
|
+
This is the most powerful way to use the library. Providing a schema enables advanced features like semantic coercion, greedy capture, and accurate disambiguation.
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
import { jsonRepair } from '@isdk/json-repair';
|
|
51
|
+
|
|
52
|
+
const schema = {
|
|
53
|
+
type: 'object',
|
|
54
|
+
properties: {
|
|
55
|
+
query: { type: 'string' },
|
|
56
|
+
status: { enum: ['success', 'error'] }
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const brokenJson = '{ query: "python" OR "js", status: Success! }';
|
|
61
|
+
|
|
62
|
+
const result = await jsonRepair(brokenJson, schema);
|
|
63
|
+
console.log(result);
|
|
64
|
+
// Output: { query: '"python" OR "js"', status: 'success' }
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 2. Simple Usage (Without Schema)
|
|
68
|
+
|
|
69
|
+
For basic syntax repair where schema guidance isn't required:
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
import { jsonRepair } from '@isdk/json-repair';
|
|
73
|
+
|
|
74
|
+
const result = await jsonRepair('{ name: John, age: 30 }');
|
|
75
|
+
console.log(result); // { name: 'John', age: 30 }
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### Advanced: Reusing SchemaWalker (Batch Processing)
|
|
79
|
+
|
|
80
|
+
For better performance when processing many items with the same schema:
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
import { jsonRepair, SchemaWalker } from '@isdk/json-repair';
|
|
84
|
+
|
|
85
|
+
const walker = await SchemaWalker.create(mySchema);
|
|
86
|
+
|
|
87
|
+
for (const item of brokenItems) {
|
|
88
|
+
const result = await jsonRepair(item, walker);
|
|
89
|
+
// ...
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## ⚠️ Known Limitations & Disambiguation
|
|
94
|
+
|
|
95
|
+
- **The "Parity Rule"**: When a string is wrapped in quotes and contains internal quotes, we count the internal ones.
|
|
96
|
+
- Odd count (e.g., `"a"b"`): We assume the outer quotes are delimiters -> `a"b`.
|
|
97
|
+
- Even count (e.g., `"A" OR "B"`): We assume the outer quotes are part of the expression -> `"A" OR "B"`.
|
|
98
|
+
- **Limitation**: Highly unusual patterns like `"a"b"c"` might remain ambiguous.
|
|
99
|
+
- **Markdown Blocks**: This library focuses on the JSON content. Please strip ```json ...``` markers before passing the string if your LLM includes them.
|
|
100
|
+
|
|
101
|
+
## 📄 License
|
|
102
|
+
|
|
103
|
+
MIT © Riceball LEE
|
package/TODO
ADDED
|
File without changes
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +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=this.pos;for(;this.pos<this.input.length&&!this.isAtDelimiter();)t+=this.next();this.pos===s&&this.pos<this.input.length&&!this.isAtDelimiter()&&(t+=this.next());let i=t.trim();if(i.length>=2){const t=i[0],s=i[i.length-1];if(('"'===t||"'"===t)&&t===s){const s=i.slice(1,-1);let h=0;for(let i=0;i<s.length;i++)s[i]!==t||0!==i&&"\\"===s[i-1]||h++;if(h%2==1||0===h)return s}}return i}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)}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for the JSON repair process.
|
|
3
|
+
*/
|
|
4
|
+
interface RepairOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Fuzzy matching for keys.
|
|
7
|
+
*
|
|
8
|
+
* - `false` (default): Strict matching against the Schema defined keys.
|
|
9
|
+
* - `true`: Allows case-insensitive matching and conversion between snake_case and camelCase.
|
|
10
|
+
* - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic to find a matching property name.
|
|
11
|
+
*/
|
|
12
|
+
keyMatching?: boolean | ((key: string, properties: string[]) => string | undefined);
|
|
13
|
+
/**
|
|
14
|
+
* Strategy for greedy string capture when standard JSON parsing fails.
|
|
15
|
+
*
|
|
16
|
+
* - `'conservative'`: Stops at any text matching the `"key":` pattern.
|
|
17
|
+
* - `'aggressive'` (default): Only stops if the key exists in the Schema and its following value type matches the expectations.
|
|
18
|
+
*/
|
|
19
|
+
stringCaptureStrategy?: 'conservative' | 'aggressive';
|
|
20
|
+
/**
|
|
21
|
+
* Whether to attempt type coercion based on the Schema.
|
|
22
|
+
*
|
|
23
|
+
* If `true`, the parser will try to convert values to the expected type (e.g., "123" to 123 for numbers, "yes" to true for booleans).
|
|
24
|
+
*/
|
|
25
|
+
coerceTypes?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Defines how to handle properties not defined in the Schema.
|
|
28
|
+
*
|
|
29
|
+
* - `'keep'` (default): Keeps these extra properties in the output.
|
|
30
|
+
* - `'remove'`: Automatically removes properties not found in the Schema.
|
|
31
|
+
*/
|
|
32
|
+
additionalProperties?: 'keep' | 'remove';
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Represents the current path in a JSON structure.
|
|
36
|
+
* A list of strings (keys) and numbers (indices).
|
|
37
|
+
*/
|
|
38
|
+
type JSONPath = (string | number)[];
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Navigates through a JSON Schema based on a JSON Path.
|
|
42
|
+
* Handles $ref resolution and provides type information for specific paths.
|
|
43
|
+
*/
|
|
44
|
+
declare class SchemaWalker {
|
|
45
|
+
private dereferencedSchema;
|
|
46
|
+
private constructor();
|
|
47
|
+
/**
|
|
48
|
+
* Static factory method to create a SchemaWalker instance.
|
|
49
|
+
* Asynchronously dereferences the provided JSON Schema.
|
|
50
|
+
*
|
|
51
|
+
* @param schema - The JSON Schema object to walk.
|
|
52
|
+
* @returns A promise that resolves to a SchemaWalker instance.
|
|
53
|
+
*/
|
|
54
|
+
static create(schema: any): Promise<SchemaWalker>;
|
|
55
|
+
/**
|
|
56
|
+
* Retrieves the sub-schema for a given JSON path.
|
|
57
|
+
*
|
|
58
|
+
* @param path - The path to navigate to.
|
|
59
|
+
* @returns The sub-schema at the specified path, or undefined if not found.
|
|
60
|
+
*/
|
|
61
|
+
getSchemaForPath(path: JSONPath): any;
|
|
62
|
+
/**
|
|
63
|
+
* Determines if a property key is valid for the given path according to the Schema.
|
|
64
|
+
*
|
|
65
|
+
* @param path - The current parent path.
|
|
66
|
+
* @param key - The property key to check.
|
|
67
|
+
* @returns True if the property is defined in the Schema or allowed by additionalProperties.
|
|
68
|
+
*/
|
|
69
|
+
isValidProperty(path: JSONPath, key: string): boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Gets the expected types for a specific property at a given path.
|
|
72
|
+
*
|
|
73
|
+
* @param path - The current parent path.
|
|
74
|
+
* @param key - The property key.
|
|
75
|
+
* @returns An array of expected type strings (e.g., ["string", "number"]).
|
|
76
|
+
*/
|
|
77
|
+
getExpectedTypes(path: JSONPath, key: string): string[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A state-machine based parser that repairs and extracts structured data from broken JSON strings.
|
|
82
|
+
* It uses a JSON Schema to guide the parsing process, especially for handling ambiguous or missing syntax.
|
|
83
|
+
*/
|
|
84
|
+
declare class RepairParser {
|
|
85
|
+
private input;
|
|
86
|
+
private pos;
|
|
87
|
+
private pathStack;
|
|
88
|
+
private walker;
|
|
89
|
+
private options;
|
|
90
|
+
/**
|
|
91
|
+
* Creates a new RepairParser instance.
|
|
92
|
+
*
|
|
93
|
+
* @param walker - An initialized SchemaWalker instance for Schema guidance.
|
|
94
|
+
* @param options - Configuration options for the repair process.
|
|
95
|
+
*/
|
|
96
|
+
constructor(walker: SchemaWalker, options?: RepairOptions);
|
|
97
|
+
/**
|
|
98
|
+
* Parses the input string and returns the repaired JavaScript object.
|
|
99
|
+
*
|
|
100
|
+
* @param input - The potentially broken JSON string.
|
|
101
|
+
* @returns The parsed and repaired object.
|
|
102
|
+
*/
|
|
103
|
+
parse(input: string): any;
|
|
104
|
+
/**
|
|
105
|
+
* Consumes a single value from the input.
|
|
106
|
+
* Uses Schema guidance to decide whether to use standard parsing or greedy capture.
|
|
107
|
+
*/
|
|
108
|
+
private consumeValue;
|
|
109
|
+
/**
|
|
110
|
+
* Parses a JSON object, handling both standard and implicit (no braces) structures.
|
|
111
|
+
*/
|
|
112
|
+
private consumeObject;
|
|
113
|
+
/**
|
|
114
|
+
* Parses a JSON array.
|
|
115
|
+
*/
|
|
116
|
+
private consumeArray;
|
|
117
|
+
/**
|
|
118
|
+
* Consumes a property key, handling both quoted and unquoted keys.
|
|
119
|
+
*/
|
|
120
|
+
private consumeKey;
|
|
121
|
+
/**
|
|
122
|
+
* Captures content greedily until it encounters a delimiter that marks the start of the next property or the end of a structure.
|
|
123
|
+
* Implements the "Parity Rule" for smart quote stripping.
|
|
124
|
+
*/
|
|
125
|
+
private consumeGreedyString;
|
|
126
|
+
/**
|
|
127
|
+
* Probes whether the current position marks a structural delimiter (end or next property).
|
|
128
|
+
*/
|
|
129
|
+
private isAtDelimiter;
|
|
130
|
+
/**
|
|
131
|
+
* Checks if the upcoming text looks like a property key defined in the Schema at the given path.
|
|
132
|
+
*/
|
|
133
|
+
private isLookingAtKey;
|
|
134
|
+
/**
|
|
135
|
+
* Performs type coercion and semantic repair based on the Schema.
|
|
136
|
+
* Handles fuzzy enum matching, noisy number extraction, and boolean variants.
|
|
137
|
+
*/
|
|
138
|
+
private coerceValue;
|
|
139
|
+
/**
|
|
140
|
+
* Consumes a standard JSON string.
|
|
141
|
+
*/
|
|
142
|
+
private consumeString;
|
|
143
|
+
/**
|
|
144
|
+
* Consumes a standard JSON number.
|
|
145
|
+
*/
|
|
146
|
+
private consumeNumber;
|
|
147
|
+
/**
|
|
148
|
+
* Consumes a standard JSON boolean.
|
|
149
|
+
*/
|
|
150
|
+
private consumeBoolean;
|
|
151
|
+
/**
|
|
152
|
+
* Consumes a standard JSON null.
|
|
153
|
+
*/
|
|
154
|
+
private consumeNull;
|
|
155
|
+
private peek;
|
|
156
|
+
private next;
|
|
157
|
+
private consumeChar;
|
|
158
|
+
private isWhitespace;
|
|
159
|
+
private isDigit;
|
|
160
|
+
private skipWhitespace;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Repairs and parses a JSON string generated by an LLM, guided by a JSON Schema.
|
|
165
|
+
* This is the main entry point for the library.
|
|
166
|
+
*
|
|
167
|
+
* @param input - The potentially broken JSON string to be repaired.
|
|
168
|
+
* @param schema - Either a plain JSON Schema object or a pre-initialized SchemaWalker instance for better performance in batch processing.
|
|
169
|
+
* @param options - Optional configuration to tune the repair process.
|
|
170
|
+
* @returns A promise that resolves to the repaired and parsed JavaScript object.
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```typescript
|
|
174
|
+
* const schema = { type: 'object', properties: { name: { type: 'string' } } };
|
|
175
|
+
* const result = await jsonRepair('{ name: John }', schema);
|
|
176
|
+
* console.log(result); // { name: 'John' }
|
|
177
|
+
* ```
|
|
178
|
+
*/
|
|
179
|
+
declare function jsonRepair(input: string, schema?: any | SchemaWalker, options?: RepairOptions): Promise<any>;
|
|
180
|
+
|
|
181
|
+
export { type JSONPath, type RepairOptions, RepairParser, SchemaWalker, jsonRepair };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for the JSON repair process.
|
|
3
|
+
*/
|
|
4
|
+
interface RepairOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Fuzzy matching for keys.
|
|
7
|
+
*
|
|
8
|
+
* - `false` (default): Strict matching against the Schema defined keys.
|
|
9
|
+
* - `true`: Allows case-insensitive matching and conversion between snake_case and camelCase.
|
|
10
|
+
* - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic to find a matching property name.
|
|
11
|
+
*/
|
|
12
|
+
keyMatching?: boolean | ((key: string, properties: string[]) => string | undefined);
|
|
13
|
+
/**
|
|
14
|
+
* Strategy for greedy string capture when standard JSON parsing fails.
|
|
15
|
+
*
|
|
16
|
+
* - `'conservative'`: Stops at any text matching the `"key":` pattern.
|
|
17
|
+
* - `'aggressive'` (default): Only stops if the key exists in the Schema and its following value type matches the expectations.
|
|
18
|
+
*/
|
|
19
|
+
stringCaptureStrategy?: 'conservative' | 'aggressive';
|
|
20
|
+
/**
|
|
21
|
+
* Whether to attempt type coercion based on the Schema.
|
|
22
|
+
*
|
|
23
|
+
* If `true`, the parser will try to convert values to the expected type (e.g., "123" to 123 for numbers, "yes" to true for booleans).
|
|
24
|
+
*/
|
|
25
|
+
coerceTypes?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Defines how to handle properties not defined in the Schema.
|
|
28
|
+
*
|
|
29
|
+
* - `'keep'` (default): Keeps these extra properties in the output.
|
|
30
|
+
* - `'remove'`: Automatically removes properties not found in the Schema.
|
|
31
|
+
*/
|
|
32
|
+
additionalProperties?: 'keep' | 'remove';
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Represents the current path in a JSON structure.
|
|
36
|
+
* A list of strings (keys) and numbers (indices).
|
|
37
|
+
*/
|
|
38
|
+
type JSONPath = (string | number)[];
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Navigates through a JSON Schema based on a JSON Path.
|
|
42
|
+
* Handles $ref resolution and provides type information for specific paths.
|
|
43
|
+
*/
|
|
44
|
+
declare class SchemaWalker {
|
|
45
|
+
private dereferencedSchema;
|
|
46
|
+
private constructor();
|
|
47
|
+
/**
|
|
48
|
+
* Static factory method to create a SchemaWalker instance.
|
|
49
|
+
* Asynchronously dereferences the provided JSON Schema.
|
|
50
|
+
*
|
|
51
|
+
* @param schema - The JSON Schema object to walk.
|
|
52
|
+
* @returns A promise that resolves to a SchemaWalker instance.
|
|
53
|
+
*/
|
|
54
|
+
static create(schema: any): Promise<SchemaWalker>;
|
|
55
|
+
/**
|
|
56
|
+
* Retrieves the sub-schema for a given JSON path.
|
|
57
|
+
*
|
|
58
|
+
* @param path - The path to navigate to.
|
|
59
|
+
* @returns The sub-schema at the specified path, or undefined if not found.
|
|
60
|
+
*/
|
|
61
|
+
getSchemaForPath(path: JSONPath): any;
|
|
62
|
+
/**
|
|
63
|
+
* Determines if a property key is valid for the given path according to the Schema.
|
|
64
|
+
*
|
|
65
|
+
* @param path - The current parent path.
|
|
66
|
+
* @param key - The property key to check.
|
|
67
|
+
* @returns True if the property is defined in the Schema or allowed by additionalProperties.
|
|
68
|
+
*/
|
|
69
|
+
isValidProperty(path: JSONPath, key: string): boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Gets the expected types for a specific property at a given path.
|
|
72
|
+
*
|
|
73
|
+
* @param path - The current parent path.
|
|
74
|
+
* @param key - The property key.
|
|
75
|
+
* @returns An array of expected type strings (e.g., ["string", "number"]).
|
|
76
|
+
*/
|
|
77
|
+
getExpectedTypes(path: JSONPath, key: string): string[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A state-machine based parser that repairs and extracts structured data from broken JSON strings.
|
|
82
|
+
* It uses a JSON Schema to guide the parsing process, especially for handling ambiguous or missing syntax.
|
|
83
|
+
*/
|
|
84
|
+
declare class RepairParser {
|
|
85
|
+
private input;
|
|
86
|
+
private pos;
|
|
87
|
+
private pathStack;
|
|
88
|
+
private walker;
|
|
89
|
+
private options;
|
|
90
|
+
/**
|
|
91
|
+
* Creates a new RepairParser instance.
|
|
92
|
+
*
|
|
93
|
+
* @param walker - An initialized SchemaWalker instance for Schema guidance.
|
|
94
|
+
* @param options - Configuration options for the repair process.
|
|
95
|
+
*/
|
|
96
|
+
constructor(walker: SchemaWalker, options?: RepairOptions);
|
|
97
|
+
/**
|
|
98
|
+
* Parses the input string and returns the repaired JavaScript object.
|
|
99
|
+
*
|
|
100
|
+
* @param input - The potentially broken JSON string.
|
|
101
|
+
* @returns The parsed and repaired object.
|
|
102
|
+
*/
|
|
103
|
+
parse(input: string): any;
|
|
104
|
+
/**
|
|
105
|
+
* Consumes a single value from the input.
|
|
106
|
+
* Uses Schema guidance to decide whether to use standard parsing or greedy capture.
|
|
107
|
+
*/
|
|
108
|
+
private consumeValue;
|
|
109
|
+
/**
|
|
110
|
+
* Parses a JSON object, handling both standard and implicit (no braces) structures.
|
|
111
|
+
*/
|
|
112
|
+
private consumeObject;
|
|
113
|
+
/**
|
|
114
|
+
* Parses a JSON array.
|
|
115
|
+
*/
|
|
116
|
+
private consumeArray;
|
|
117
|
+
/**
|
|
118
|
+
* Consumes a property key, handling both quoted and unquoted keys.
|
|
119
|
+
*/
|
|
120
|
+
private consumeKey;
|
|
121
|
+
/**
|
|
122
|
+
* Captures content greedily until it encounters a delimiter that marks the start of the next property or the end of a structure.
|
|
123
|
+
* Implements the "Parity Rule" for smart quote stripping.
|
|
124
|
+
*/
|
|
125
|
+
private consumeGreedyString;
|
|
126
|
+
/**
|
|
127
|
+
* Probes whether the current position marks a structural delimiter (end or next property).
|
|
128
|
+
*/
|
|
129
|
+
private isAtDelimiter;
|
|
130
|
+
/**
|
|
131
|
+
* Checks if the upcoming text looks like a property key defined in the Schema at the given path.
|
|
132
|
+
*/
|
|
133
|
+
private isLookingAtKey;
|
|
134
|
+
/**
|
|
135
|
+
* Performs type coercion and semantic repair based on the Schema.
|
|
136
|
+
* Handles fuzzy enum matching, noisy number extraction, and boolean variants.
|
|
137
|
+
*/
|
|
138
|
+
private coerceValue;
|
|
139
|
+
/**
|
|
140
|
+
* Consumes a standard JSON string.
|
|
141
|
+
*/
|
|
142
|
+
private consumeString;
|
|
143
|
+
/**
|
|
144
|
+
* Consumes a standard JSON number.
|
|
145
|
+
*/
|
|
146
|
+
private consumeNumber;
|
|
147
|
+
/**
|
|
148
|
+
* Consumes a standard JSON boolean.
|
|
149
|
+
*/
|
|
150
|
+
private consumeBoolean;
|
|
151
|
+
/**
|
|
152
|
+
* Consumes a standard JSON null.
|
|
153
|
+
*/
|
|
154
|
+
private consumeNull;
|
|
155
|
+
private peek;
|
|
156
|
+
private next;
|
|
157
|
+
private consumeChar;
|
|
158
|
+
private isWhitespace;
|
|
159
|
+
private isDigit;
|
|
160
|
+
private skipWhitespace;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Repairs and parses a JSON string generated by an LLM, guided by a JSON Schema.
|
|
165
|
+
* This is the main entry point for the library.
|
|
166
|
+
*
|
|
167
|
+
* @param input - The potentially broken JSON string to be repaired.
|
|
168
|
+
* @param schema - Either a plain JSON Schema object or a pre-initialized SchemaWalker instance for better performance in batch processing.
|
|
169
|
+
* @param options - Optional configuration to tune the repair process.
|
|
170
|
+
* @returns A promise that resolves to the repaired and parsed JavaScript object.
|
|
171
|
+
*
|
|
172
|
+
* @example
|
|
173
|
+
* ```typescript
|
|
174
|
+
* const schema = { type: 'object', properties: { name: { type: 'string' } } };
|
|
175
|
+
* const result = await jsonRepair('{ name: John }', schema);
|
|
176
|
+
* console.log(result); // { name: 'John' }
|
|
177
|
+
* ```
|
|
178
|
+
*/
|
|
179
|
+
declare function jsonRepair(input: string, schema?: any | SchemaWalker, options?: RepairOptions): Promise<any>;
|
|
180
|
+
|
|
181
|
+
export { type JSONPath, type RepairOptions, RepairParser, SchemaWalker, jsonRepair };
|