@isdk/json-repair 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.cn.md +245 -14
- package/README.md +293 -14
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +777 -23
- package/dist/index.d.ts +777 -23
- package/dist/index.js +1 -1
- package/docs/README.md +293 -14
- package/docs/_media/README.cn.md +245 -14
- package/docs/classes/RepairParser.md +71 -5
- package/docs/classes/SchemaWalker.md +126 -6
- package/docs/functions/compareScores.md +32 -0
- package/docs/functions/discardedText.md +42 -0
- package/docs/functions/expectsArrayRoot.md +23 -0
- package/docs/functions/findImplicitRecordRegion.md +32 -0
- package/docs/functions/jsonRepair.md +4 -3
- package/docs/functions/jsonRepairResult.md +50 -0
- package/docs/functions/locateJsonCandidates.md +33 -0
- package/docs/functions/looksLikeSchemaEcho.md +29 -0
- package/docs/functions/renderValidatorErrors.md +32 -0
- package/docs/functions/scoreCandidate.md +45 -0
- package/docs/functions/validateValue.md +38 -0
- package/docs/globals.md +19 -0
- package/docs/interfaces/CandidateScore.md +63 -0
- package/docs/interfaces/JsonCandidate.md +71 -0
- package/docs/interfaces/LocatedJson.md +48 -0
- package/docs/interfaces/RepairOptions.md +257 -19
- package/docs/interfaces/RepairResult.md +58 -0
- package/docs/interfaces/ValidationError.md +27 -0
- package/docs/type-aliases/CommentStyle.md +13 -0
- package/docs/type-aliases/EscapeMode.md +13 -0
- package/docs/type-aliases/JSONPath.md +1 -1
- package/docs/type-aliases/LiteralDialect.md +13 -0
- package/docs/type-aliases/RepairFlag.md +11 -0
- package/package.json +38 -12
- package/.prettierignore +0 -4
- package/.prettierrc +0 -8
- package/.versionrc +0 -36
- package/CHANGELOG.md +0 -18
- package/TODO +0 -0
- package/eslint.config.mjs +0 -31
- package/setupVitest.mjs +0 -15
- package/tsconfig.json +0 -19
- package/tsconfig.spec.json +0 -19
- package/tsup.config.ts +0 -34
- package/typedoc.config.cjs +0 -7
- package/vite.config.mjs +0 -16
package/dist/index.d.cts
CHANGED
|
@@ -3,39 +3,337 @@
|
|
|
3
3
|
*/
|
|
4
4
|
interface RepairOptions {
|
|
5
5
|
/**
|
|
6
|
-
* Fuzzy matching
|
|
6
|
+
* Fuzzy matching of property keys against the Schema's declared `properties`.
|
|
7
7
|
*
|
|
8
|
-
* - `false` (default):
|
|
9
|
-
* - `true`:
|
|
10
|
-
* -
|
|
8
|
+
* - `false` (default): Only an exactly declared key counts as a match.
|
|
9
|
+
* - `true`: Case-insensitive and separator-insensitive matching, so `user_name`,
|
|
10
|
+
* `userName`, `USER-NAME` and `user name` all resolve to the declared key.
|
|
11
|
+
* - `(key: string, properties: string[]) => string | undefined`: Custom mapping logic;
|
|
12
|
+
* it receives the incoming key and the declared names, and returns the name to use
|
|
13
|
+
* (or `undefined` to fall back to the incoming key).
|
|
14
|
+
*
|
|
15
|
+
* A match renames the key to the Schema's name in the output and makes nested Schema
|
|
16
|
+
* lookups (and therefore type coercion) work for it.
|
|
17
|
+
* It also decides where greedy capture stops: with `true` a separator or case variant of a
|
|
18
|
+
* declared key (`user_name:` for `userName`) ends the value in front of it.
|
|
19
|
+
* When you reuse a `SchemaWalker`, pass this option to `SchemaWalker.create()`.
|
|
11
20
|
*/
|
|
12
21
|
keyMatching?: boolean | ((key: string, properties: string[]) => string | undefined);
|
|
13
22
|
/**
|
|
14
|
-
* Strategy for greedy string capture when
|
|
23
|
+
* Strategy for greedy string capture when the strict JSON path failed for a value.
|
|
24
|
+
*
|
|
25
|
+
* - `'aggressive'` (default): When the Schema declares property names for the current
|
|
26
|
+
* level, the captured value only ends at one of those declared keys. Text that merely
|
|
27
|
+
* looks like `"some words":` stays inside the value.
|
|
28
|
+
* - `'conservative'`: Any text matching the `"key":` / `key:` pattern ends the value,
|
|
29
|
+
* which keeps the structure of the document at the cost of cutting values short.
|
|
15
30
|
*
|
|
16
|
-
* -
|
|
17
|
-
*
|
|
31
|
+
* A whitespace-containing key the Schema declares is a breakpoint in both strategies even
|
|
32
|
+
* when the document left it unquoted (`{ Capital: Berlin, Official language: Italian }`),
|
|
33
|
+
* because it can only be recognised from the declaration.
|
|
34
|
+
* Neither strategy affects values that were parsed by the strict JSON path; the
|
|
35
|
+
* boundary rules described in the README apply to those unchanged.
|
|
18
36
|
*/
|
|
19
37
|
stringCaptureStrategy?: 'conservative' | 'aggressive';
|
|
20
38
|
/**
|
|
21
|
-
* Whether to
|
|
39
|
+
* Whether to coerce values to the type the Schema declares. Enabled by default.
|
|
40
|
+
*
|
|
41
|
+
* - `true` (default): `"Approx. 1,200.50 USD"` becomes `1200.5`, `"yes"` becomes `true`,
|
|
42
|
+
* `"Processing!"` becomes the enum entry it fuzzy matches, `12` becomes `"12"` when the
|
|
43
|
+
* Schema says `type: 'string'`.
|
|
44
|
+
* - `false`: values are returned exactly as they were parsed.
|
|
45
|
+
*
|
|
46
|
+
* Coercion needs the Schema of the property the value belongs to; a level that declares
|
|
47
|
+
* no types is left alone.
|
|
22
48
|
*
|
|
23
|
-
*
|
|
49
|
+
* Coercing to a declared `string` reuses the text the document wrote, not the number it
|
|
50
|
+
* parsed to, so a leading zero survives: `{ id: 01234 }` becomes `"01234"`.
|
|
51
|
+
* `null` and structures (`{}` / `[]`) are never stringified - `"null"` and
|
|
52
|
+
* `"[object Object]"` are not what a `type: 'string'` declaration asks for.
|
|
53
|
+
*
|
|
54
|
+
* A coercion that keeps part of a value and gives up the text around it says so:
|
|
55
|
+
* `coerced-text-dropped`. A unit given up that way (`Approx. USD`) is the option doing its
|
|
56
|
+
* job; text long enough to read as a sentence is listed in {@link RepairResult.discarded}
|
|
57
|
+
* too, because greedy capture can run a value into prose the model wrote after it
|
|
58
|
+
* (`age: 30\n\nHope this helps!}` -> `30`) and the sentence would otherwise leave no trace.
|
|
24
59
|
*/
|
|
25
60
|
coerceTypes?: boolean;
|
|
26
61
|
/**
|
|
27
62
|
* Defines how to handle properties not defined in the Schema.
|
|
28
63
|
*
|
|
29
64
|
* - `'keep'` (default): Keeps these extra properties in the output.
|
|
30
|
-
* - `'remove'`:
|
|
65
|
+
* - `'remove'`: Drops them. Only applies at a level whose Schema declares `properties`;
|
|
66
|
+
* a free-form level has no "extra" keys and is left untouched.
|
|
67
|
+
*
|
|
68
|
+
* This option is independent from the JSON Schema keyword `additionalProperties: false`,
|
|
69
|
+
* which is respected on its own when validating incoming keys.
|
|
31
70
|
*/
|
|
32
71
|
additionalProperties?: 'keep' | 'remove';
|
|
72
|
+
/**
|
|
73
|
+
* Where a quoted value ends when the model left one of its quotes unescaped -
|
|
74
|
+
* `{"t": "The "Best" Paper", "y": 2020}`.
|
|
75
|
+
*
|
|
76
|
+
* - `'keep'` (default) - what the document spells, delimiters included:
|
|
77
|
+
* `t = '"The "Best" Paper"'`. Nothing is inferred, which is the rule the README section
|
|
78
|
+
* "How Property Boundaries Are Detected" describes.
|
|
79
|
+
* - `'declared'` - the first quote after which a member the Schema declares begins:
|
|
80
|
+
* `t = 'The "Best" Paper'`. The Schema named that member, so the boundary is known rather
|
|
81
|
+
* than guessed - and where the Schema names nothing at that level, nothing is inferred
|
|
82
|
+
* either.
|
|
83
|
+
* - `'lookahead'` - the same rule judged by the shape of the text alone, for documents with
|
|
84
|
+
* no Schema. It reads more, and guesses more.
|
|
85
|
+
*
|
|
86
|
+
* A document that `JSON.parse` accepts is never affected: the strict parse is tried first,
|
|
87
|
+
* and only a quoted value it could not close comes here. Emits `unescaped-quote-inferred`.
|
|
88
|
+
*/
|
|
89
|
+
unescapedQuotes?: 'keep' | 'declared' | 'lookahead';
|
|
90
|
+
/**
|
|
91
|
+
* Which comment styles are skipped, and only where a member is expected: between two
|
|
92
|
+
* fields, after `{` or `[`, before a closing bracket, and after a completed value.
|
|
93
|
+
*
|
|
94
|
+
* Strict JSON has no comments, so this is off by default - skipping one consumes
|
|
95
|
+
* characters, and only the caller knows which style its models write. Open the style you
|
|
96
|
+
* actually see.
|
|
97
|
+
*
|
|
98
|
+
* - `'line'` - `//` to the end of the line (JSONC, and most JavaScript-trained models).
|
|
99
|
+
* - `'block'` - `/* ... *\/`, and only when it is closed: an unterminated `/*` stays text.
|
|
100
|
+
* - `'hash'` - `#` to the end of the line (Python-trained models).
|
|
101
|
+
* - `true` - all three. `false` or `[]` - none, which is the default.
|
|
102
|
+
*
|
|
103
|
+
* A style is never recognised inside a string or inside a bare token, so
|
|
104
|
+
* `url: https://x.com/a`, `issue: #123` and `"#ff0000"` survive every setting. With the
|
|
105
|
+
* default, a comment written between two fields ends up inside one of them; turning the
|
|
106
|
+
* switch on is what prevents that. Emits `comment-skipped`.
|
|
107
|
+
*/
|
|
108
|
+
comments?: boolean | CommentStyle[];
|
|
109
|
+
/**
|
|
110
|
+
* Which bare tokens (tokens with no quotes around them) are read as a literal of another
|
|
111
|
+
* language.
|
|
112
|
+
*
|
|
113
|
+
* `ok: True` means `true`, not the word `True`: the token carries no quotes, so it is not a
|
|
114
|
+
* string in any JSON dialect either - reading it as a literal is reading the model, while
|
|
115
|
+
* turning it into `'True'` invents a value.
|
|
116
|
+
*
|
|
117
|
+
* - `'python'` - `True` -> `true`, `False` -> `false`, `None` -> `null`.
|
|
118
|
+
* - `'js'` - `undefined` -> `null`. `NaN` is left as the text it spells: no JSON number
|
|
119
|
+
* can carry it, so the reported errors point at the field instead of the parser inventing
|
|
120
|
+
* a value that cannot be serialised.
|
|
121
|
+
* - `true` - both dialects, which is the default. `false` or `[]` - neither: the token
|
|
122
|
+
* becomes the string it spells.
|
|
123
|
+
*
|
|
124
|
+
* A model trained on JavaScript does not write `None` and a Python-trained one rarely writes
|
|
125
|
+
* `undefined`, so the list is how you say which of them can occur. It never applies to a
|
|
126
|
+
* quoted `"True"` (always a string), never to a key, and never to a path whose Schema names
|
|
127
|
+
* a type - there {@link coerceTypes} decides, and it already reads `True` as `true`.
|
|
128
|
+
* Emits `non-json-literal`.
|
|
129
|
+
*/
|
|
130
|
+
literals?: boolean | LiteralDialect[];
|
|
131
|
+
/**
|
|
132
|
+
* How much the parser trusts the backslashes a document writes.
|
|
133
|
+
*
|
|
134
|
+
* The three settings read as one axis - how far the document's escapes are escapes:
|
|
135
|
+
*
|
|
136
|
+
* - `'json5'` (default): JSON's own escapes decode, the JSON5-style `\xNN` decodes to the
|
|
137
|
+
* character it names, and an escape of a character that needs none is unwrapped
|
|
138
|
+
* (`"\$10"` -> `$10`, `"C:\Users"` -> `C:Users`) the way JSON5 reads one.
|
|
139
|
+
* - `'json'`: only the escapes JSON defines decode. Anything else stays exactly as the
|
|
140
|
+
* document wrote it, backslash included (`"C:\Users"` -> `C:\Users`), so markdown and
|
|
141
|
+
* LaTeX punctuation keeps its backslashes and a path keeps its separators.
|
|
142
|
+
* - `'raw'`: nothing decodes - a backslash is content. `"C:\temp"` is a path, not a tab,
|
|
143
|
+
* and `"\frac{a}{b}"` is a LaTeX command, not a form feed. The setting is honest about
|
|
144
|
+
* what it costs: it applies to escapes JSON defines too, so `"a\nb"` stays two characters
|
|
145
|
+
* and a value can no longer carry a newline. Use it when the values are paths, regular
|
|
146
|
+
* expressions or markup rather than prose.
|
|
147
|
+
*
|
|
148
|
+
* A backslash is structural in every setting: it always keeps the character behind it inside
|
|
149
|
+
* the string, so a value is never cut where the model escaped something. An incomplete hex
|
|
150
|
+
* escape (`\xg`, `\uZZ`) decodes nothing in every setting and stays as written.
|
|
151
|
+
* Whichever is chosen, an escape strict JSON would reject is reported as `invalid-escape`.
|
|
152
|
+
*/
|
|
153
|
+
escapes?: EscapeMode;
|
|
154
|
+
/**
|
|
155
|
+
* Whether a key or separator the output was cut off at is dropped or kept.
|
|
156
|
+
*
|
|
157
|
+
* `{"a": 1, "b`: `true` (default) gives `{ a: 1 }`. `false` gives `{ a: '1, "b' }` - the
|
|
158
|
+
* fragment written into a field that was already correct, which is exactly what this option
|
|
159
|
+
* exists to prevent. Dropping is the default, and the dropped text is listed in
|
|
160
|
+
* {@link RepairResult.discarded} and flagged `dangling-dropped`, so nothing disappears
|
|
161
|
+
* without a trace. Only the fragment is dropped: the container closes and a record written
|
|
162
|
+
* after it is still read, so `{"a": 1, "b"} {"c": 2}` becomes `[{ a: 1 }, { c: 2 }]`. A
|
|
163
|
+
* broken key with a value after it is syntax to repair, not a fragment, and is left alone.
|
|
164
|
+
*/
|
|
165
|
+
dangling?: boolean;
|
|
166
|
+
/**
|
|
167
|
+
* Whether a record the Schema expects inside a list is read as one item: a single object
|
|
168
|
+
* under a root `array` becomes `[object]`, and sibling records written side by side
|
|
169
|
+
* (`{...} {...}`, or the same without braces) become the items of that list.
|
|
170
|
+
*
|
|
171
|
+
* Enabled by default - the structure was declared by the Schema, so it is not a guess.
|
|
172
|
+
* Set it to `false` to keep the value exactly as the document wrote it and let the
|
|
173
|
+
* reported `errors` say what is missing. The cost: the record is no longer looked up
|
|
174
|
+
* against `items`, so its own keys lose their Schema guide - coercion stops applying and
|
|
175
|
+
* a value can run into the next key. That is why the default is `true`.
|
|
176
|
+
*/
|
|
177
|
+
wrapArrays?: boolean;
|
|
178
|
+
/**
|
|
179
|
+
* Whether to look for the JSON inside the input text first.
|
|
180
|
+
*
|
|
181
|
+
* LLM output is text, not a document: the JSON often sits inside a Markdown fence and
|
|
182
|
+
* between sentences. With `true` (the default) the input is scanned for
|
|
183
|
+
* quote-aware, escape-aware, bracket-balanced JSON regions and the best one is repaired;
|
|
184
|
+
* prose and fences around it are dropped and reported. With `false` the whole string is
|
|
185
|
+
* parsed as if it were already a JSON document (the behaviour up to 0.1.x).
|
|
186
|
+
*
|
|
187
|
+
* Input that already parses as JSON is never touched either way.
|
|
188
|
+
*/
|
|
189
|
+
locate?: boolean;
|
|
190
|
+
/**
|
|
191
|
+
* How to choose when the input contains more than one JSON fragment.
|
|
192
|
+
*
|
|
193
|
+
* - `'best'` (default): rank the fragments by how well they fit the Schema - fewer
|
|
194
|
+
* validation errors, more `required` fields carrying real values, more declared fields,
|
|
195
|
+
* fewer Schema keywords in the answer - and take the winner. A tie is decided by position,
|
|
196
|
+
* last first, because a model usually drafts before it answers; the tie is then reported as
|
|
197
|
+
* `ambiguous-candidates` rather than hidden. An extra key the Schema never named is not held
|
|
198
|
+
* against a fragment ({@link CandidateScore.undeclaredKeys} reports it); only an answer built
|
|
199
|
+
* out of the Schema itself is.
|
|
200
|
+
* - `'last'` / `'first'`: take the position regardless of how well the fragment fits. The
|
|
201
|
+
* Schema errors of the chosen fragment are still reported.
|
|
202
|
+
* - `'throw'`: reject the input outright and list the candidates with their scores.
|
|
203
|
+
*
|
|
204
|
+
* Without a Schema the ranking has no information to work with, so it collapses to the
|
|
205
|
+
* position rule (the last fragment).
|
|
206
|
+
*/
|
|
207
|
+
onMultiple?: 'best' | 'last' | 'first' | 'throw';
|
|
208
|
+
/**
|
|
209
|
+
* What to do with text the repair dropped on the floor (prose, fences, losing fragments).
|
|
210
|
+
*
|
|
211
|
+
* - `'report'` (default): drop it, but list it in `RepairResult.discarded`.
|
|
212
|
+
* - `'throw'`: refuse the input - a caller that cannot afford to lose content should not
|
|
213
|
+
* accept a repair that discards any.
|
|
214
|
+
* - `'ignore'`: drop it silently.
|
|
215
|
+
*/
|
|
216
|
+
onDiscard?: 'report' | 'throw' | 'ignore';
|
|
33
217
|
}
|
|
34
218
|
/**
|
|
35
219
|
* Represents the current path in a JSON structure.
|
|
36
220
|
* A list of strings (keys) and numbers (indices).
|
|
37
221
|
*/
|
|
38
222
|
type JSONPath = (string | number)[];
|
|
223
|
+
/**
|
|
224
|
+
* A named observation about the input or about the choices the repair made.
|
|
225
|
+
* Flags exist so that a caller can see which failures it is paying for instead of
|
|
226
|
+
* guessing from the output - the failure taxonomy of LLM output is what tells an operator
|
|
227
|
+
* whether another model call is worth spending.
|
|
228
|
+
*
|
|
229
|
+
* - Input shape: `markdown-fence`, `prose-prefix`, `trailing-chatter`,
|
|
230
|
+
* `implicit-structure`, `truncated-candidate`
|
|
231
|
+
* - Decisions taken: `sibling-objects-merged`, `extra-fragments-dropped`,
|
|
232
|
+
* `duplicate-candidates`, `ambiguous-candidates`, `coerced-text-dropped` (a coercion gave up
|
|
233
|
+
* the text around the value it kept)
|
|
234
|
+
* - Content suspicions: `empty-required` (a `required` string field satisfied by `""` -
|
|
235
|
+
* schema-valid and information-free), `schema-echo-detected` (the model reproduced the
|
|
236
|
+
* Schema instead of filling it in)
|
|
237
|
+
* - Limits reached: `nesting-limited` (a document deeper than the parser reads, with the text
|
|
238
|
+
* it never reached listed in `discarded`)
|
|
239
|
+
*/
|
|
240
|
+
/** A comment style. See {@link RepairOptions.comments}. */
|
|
241
|
+
type CommentStyle = 'line' | 'block' | 'hash';
|
|
242
|
+
/** A language whose bare-token literals a model may write. See {@link RepairOptions.literals}. */
|
|
243
|
+
type LiteralDialect = 'js' | 'python';
|
|
244
|
+
/** How much a backslash is trusted as an escape. See {@link RepairOptions.escapes}. */
|
|
245
|
+
type EscapeMode = 'json5' | 'json' | 'raw';
|
|
246
|
+
type RepairFlag = 'markdown-fence' | 'prose-prefix' | 'trailing-chatter' | 'implicit-structure' | 'truncated-candidate' | 'sibling-objects-merged' | 'extra-fragments-dropped' | 'duplicate-candidates' | 'ambiguous-candidates' | 'empty-required' | 'schema-echo-detected'
|
|
247
|
+
/** A quoted value's closing quote was inferred (see `unescapedQuotes`). */
|
|
248
|
+
| 'unescaped-quote-inferred'
|
|
249
|
+
/** A comment was skipped between two members (see `comments`). */
|
|
250
|
+
| 'comment-skipped'
|
|
251
|
+
/**
|
|
252
|
+
* A comment in a style that was not asked for ended up inside a value. `comments` decides
|
|
253
|
+
* whether a comment is read, and {@link RepairOptions.comments} says what the default costs;
|
|
254
|
+
* this is that cost, named, so it can be seen without reading the value back.
|
|
255
|
+
*/
|
|
256
|
+
| 'comment-in-value'
|
|
257
|
+
/** A bare token was read as a literal of another language (see `literals`). */
|
|
258
|
+
| 'non-json-literal'
|
|
259
|
+
/**
|
|
260
|
+
* The document contains an escape strict JSON would reject (`"\$10"`, `"a\qb"`, `"\x41"`,
|
|
261
|
+
* `"\xg"). How it was read depends on {@link RepairOptions.escapes} - unwrapped, or left as
|
|
262
|
+
* written - but the caller is told either way, because the value lost or gained a backslash.
|
|
263
|
+
*/
|
|
264
|
+
| 'invalid-escape'
|
|
265
|
+
/** A key the output never finished was dropped; its text is in `discarded`. */
|
|
266
|
+
| 'dangling-dropped'
|
|
267
|
+
/** The parser stopped before the end of the region it was given. */
|
|
268
|
+
| 'unparsed-tail'
|
|
269
|
+
/**
|
|
270
|
+
* A coercion kept part of a value and gave up the text around it (`"Approx. 1,200.50 USD"`
|
|
271
|
+
* -> `1200.5` gives up `Approx. USD`). Giving a unit up is what
|
|
272
|
+
* {@link RepairOptions.coerceTypes} is for, so only text that reads as a sentence rather than
|
|
273
|
+
* a qualifier is listed in {@link RepairResult.discarded} as well - three words, or twenty
|
|
274
|
+
* characters with no space to count them by.
|
|
275
|
+
*/
|
|
276
|
+
| 'coerced-text-dropped'
|
|
277
|
+
/**
|
|
278
|
+
* The document is nested deeper than the parser reads (1,000 levels). The value came back as
|
|
279
|
+
* far as the parser went and {@link RepairResult.discarded} holds the text it never reached -
|
|
280
|
+
* the alternative was a stack overflow, which is not an outcome a caller can report on.
|
|
281
|
+
*/
|
|
282
|
+
| 'nesting-limited';
|
|
283
|
+
/**
|
|
284
|
+
* How well one fragment fits the Schema. Compared in this order:
|
|
285
|
+
* `errors` ascending, then `requiredCovered`, `declaredCovered` descending,
|
|
286
|
+
* then `schemaEchoKeys` ascending. A single extra key is not held against a fragment -
|
|
287
|
+
* `additionalProperties` is the caller's business, not a ranking signal - but a fragment
|
|
288
|
+
* built out of Schema keywords is.
|
|
289
|
+
*
|
|
290
|
+
* Coverage counts only fields that carry a usable value: `""` and a `null` the Schema does
|
|
291
|
+
* not allow are not "covered", which is what stops a placeholder-only fragment from beating
|
|
292
|
+
* a fragment with real data.
|
|
293
|
+
*/
|
|
294
|
+
interface CandidateScore {
|
|
295
|
+
errors: number;
|
|
296
|
+
requiredCovered: number;
|
|
297
|
+
declaredCovered: number;
|
|
298
|
+
/** Keys the Schema never declared. Reported, and used to rank only via `schemaEchoKeys`. */
|
|
299
|
+
undeclaredKeys: number;
|
|
300
|
+
/** How many of those undeclared keys are JSON Schema keywords - the echo signature. */
|
|
301
|
+
schemaEchoKeys: number;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* A JSON region located inside a larger piece of text, given as offsets into that text so
|
|
305
|
+
* the caller can line it up against what the model actually returned.
|
|
306
|
+
*/
|
|
307
|
+
interface LocatedJson {
|
|
308
|
+
start: number;
|
|
309
|
+
end: number;
|
|
310
|
+
text: string;
|
|
311
|
+
flags: RepairFlag[];
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* A JSON fragment found in the input text, with the score it earned against the Schema.
|
|
315
|
+
*/
|
|
316
|
+
interface JsonCandidate extends LocatedJson {
|
|
317
|
+
score: CandidateScore;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* A JSON Schema violation, located by path so it can be handed back to a model verbatim.
|
|
321
|
+
*/
|
|
322
|
+
interface ValidationError {
|
|
323
|
+
path: JSONPath;
|
|
324
|
+
message: string;
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Everything a repair produced: the value, what was noticed about the input, what still
|
|
328
|
+
* fails against the Schema, and what was discarded to get there.
|
|
329
|
+
*/
|
|
330
|
+
interface RepairResult<T = any> {
|
|
331
|
+
value: T;
|
|
332
|
+
flags: RepairFlag[];
|
|
333
|
+
errors: ValidationError[];
|
|
334
|
+
candidates: JsonCandidate[];
|
|
335
|
+
discarded: string[];
|
|
336
|
+
}
|
|
39
337
|
|
|
40
338
|
/**
|
|
41
339
|
* Navigates through a JSON Schema based on a JSON Path.
|
|
@@ -43,15 +341,20 @@ type JSONPath = (string | number)[];
|
|
|
43
341
|
*/
|
|
44
342
|
declare class SchemaWalker {
|
|
45
343
|
private dereferencedSchema;
|
|
344
|
+
private options;
|
|
46
345
|
private constructor();
|
|
47
346
|
/**
|
|
48
347
|
* Static factory method to create a SchemaWalker instance.
|
|
49
348
|
* Asynchronously dereferences the provided JSON Schema.
|
|
50
349
|
*
|
|
350
|
+
* The Schema is dereferenced on a deep copy: `$RefParser.dereference()` replaces every
|
|
351
|
+
* `$ref` in place, which would otherwise rewrite the object the caller passed in.
|
|
352
|
+
*
|
|
51
353
|
* @param schema - The JSON Schema object to walk.
|
|
354
|
+
* @param options - Repair options that concern the Schema itself (`keyMatching`).
|
|
52
355
|
* @returns A promise that resolves to a SchemaWalker instance.
|
|
53
356
|
*/
|
|
54
|
-
static create(schema: any): Promise<SchemaWalker>;
|
|
357
|
+
static create(schema: any, options?: RepairOptions): Promise<SchemaWalker>;
|
|
55
358
|
/**
|
|
56
359
|
* Retrieves the sub-schema for a given JSON path.
|
|
57
360
|
*
|
|
@@ -67,6 +370,46 @@ declare class SchemaWalker {
|
|
|
67
370
|
* @returns True if the property is defined in the Schema or allowed by additionalProperties.
|
|
68
371
|
*/
|
|
69
372
|
isValidProperty(path: JSONPath, key: string): boolean;
|
|
373
|
+
/**
|
|
374
|
+
* Resolves an incoming property name to the name declared by the Schema at `path`.
|
|
375
|
+
*
|
|
376
|
+
* Without `keyMatching` this only accepts an exact declaration. With `keyMatching: true`
|
|
377
|
+
* the comparison ignores case and the separators used by the two common naming styles
|
|
378
|
+
* (`user_name` / `userName` / `USER NAME`). A function matcher decides itself and may
|
|
379
|
+
* return a name the Schema does not declare.
|
|
380
|
+
*
|
|
381
|
+
* Besides renaming, the result is what makes a key a breakpoint for greedy string capture:
|
|
382
|
+
* the parser calls this while deciding whether an upcoming `key:` ends the value in front of it.
|
|
383
|
+
*
|
|
384
|
+
* @param path - The current parent path.
|
|
385
|
+
* @param key - The property key found in the broken document.
|
|
386
|
+
* @returns The canonical Schema property name, or `null` when nothing matches.
|
|
387
|
+
*/
|
|
388
|
+
matchProperty(path: JSONPath, key: string): string | null;
|
|
389
|
+
/**
|
|
390
|
+
* The property names the Schema declares at `path` (empty when the level is free-form).
|
|
391
|
+
*/
|
|
392
|
+
declaredPropertyNames(path: JSONPath): string[];
|
|
393
|
+
/**
|
|
394
|
+
* Folding used for fuzzy key matching: case-insensitive and separator-insensitive, so
|
|
395
|
+
* snake_case, kebab-case, camelCase and spaced keys collide.
|
|
396
|
+
*/
|
|
397
|
+
private static normalizeName;
|
|
398
|
+
/**
|
|
399
|
+
* Whether a property name is explicitly declared in the Schema at the given path.
|
|
400
|
+
*
|
|
401
|
+
* @param path - The current parent path.
|
|
402
|
+
* @param key - The property key to check.
|
|
403
|
+
* @returns True only when `key` appears in the Schema `properties` of that path.
|
|
404
|
+
*/
|
|
405
|
+
isDeclaredProperty(path: JSONPath, key: string): boolean;
|
|
406
|
+
/**
|
|
407
|
+
* Whether the Schema at the given path declares any property names at all.
|
|
408
|
+
* Used to decide whether key matching can be strict or has to stay lenient.
|
|
409
|
+
*
|
|
410
|
+
* @param path - The current parent path.
|
|
411
|
+
*/
|
|
412
|
+
hasDeclaredProperties(path: JSONPath): boolean;
|
|
70
413
|
/**
|
|
71
414
|
* Gets the expected types for a specific property at a given path.
|
|
72
415
|
*
|
|
@@ -87,6 +430,15 @@ declare class RepairParser {
|
|
|
87
430
|
private pathStack;
|
|
88
431
|
private walker;
|
|
89
432
|
private options;
|
|
433
|
+
private readFlags;
|
|
434
|
+
/**
|
|
435
|
+
* Text the parser deliberately dropped - a key the output never finished, dropped as a
|
|
436
|
+
* fragment rather than merged into the field before it. Reported to the caller, because text
|
|
437
|
+
* never goes away silently.
|
|
438
|
+
*/
|
|
439
|
+
private dropped;
|
|
440
|
+
private readonly commentStyles;
|
|
441
|
+
private readonly literalDialects;
|
|
90
442
|
/**
|
|
91
443
|
* Creates a new RepairParser instance.
|
|
92
444
|
*
|
|
@@ -94,6 +446,18 @@ declare class RepairParser {
|
|
|
94
446
|
* @param options - Configuration options for the repair process.
|
|
95
447
|
*/
|
|
96
448
|
constructor(walker: SchemaWalker, options?: RepairOptions);
|
|
449
|
+
/**
|
|
450
|
+
* Where the last {@link parse} call stopped, as an offset into the trimmed string the
|
|
451
|
+
* parser worked on. Whatever follows it is not part of the document - the text a caller
|
|
452
|
+
* needs when it wants to know what a repair left behind.
|
|
453
|
+
*/
|
|
454
|
+
get consumed(): number;
|
|
455
|
+
/** The text the last {@link parse} call dropped as an unfinished fragment. */
|
|
456
|
+
get droppedText(): readonly string[];
|
|
457
|
+
/** How the last {@link parse} call read the document (see {@link RepairFlag}). */
|
|
458
|
+
get flags(): ReadonlySet<RepairFlag>;
|
|
459
|
+
/** The text after the parsed document, as the parser saw it (see {@link consumed}). */
|
|
460
|
+
get remainder(): string;
|
|
97
461
|
/**
|
|
98
462
|
* Parses the input string and returns the repaired JavaScript object.
|
|
99
463
|
*
|
|
@@ -106,33 +470,198 @@ declare class RepairParser {
|
|
|
106
470
|
* Uses Schema guidance to decide whether to use standard parsing or greedy capture.
|
|
107
471
|
*/
|
|
108
472
|
private consumeValue;
|
|
473
|
+
/** Whether the Schema's own listed values include `value`. */
|
|
474
|
+
private static allows;
|
|
475
|
+
/** Whether the Schema says what kind of value belongs at this path. */
|
|
476
|
+
private static guidesScalar;
|
|
477
|
+
/**
|
|
478
|
+
* The literal a bare token stands for in one of the dialects `RepairOptions.literals`
|
|
479
|
+
* allows, or `undefined` when the token is ordinary text. Exact match only: `None-ish` and
|
|
480
|
+
* `True story` are text, and a token that carries any of it cannot be a literal.
|
|
481
|
+
*/
|
|
482
|
+
private dialectLiteral;
|
|
483
|
+
private static readonly PYTHON_LITERALS;
|
|
484
|
+
private static readonly JS_LITERALS;
|
|
485
|
+
/**
|
|
486
|
+
* A value that begins with a `"` the model never closed -
|
|
487
|
+
* `{"t": "The "Best" Paper", "y": 2020}`. Each later quote is a candidate for where the
|
|
488
|
+
* value meant to end, and it is one only if a member follows it. With `'declared'` that
|
|
489
|
+
* member also has to be one the Schema names at this level, which is the difference between
|
|
490
|
+
* knowing the boundary and guessing it.
|
|
491
|
+
*
|
|
492
|
+
* @returns the content of the value, or `undefined` when no candidate is confirmed (in
|
|
493
|
+
* which case greedy capture reads it, as it always did).
|
|
494
|
+
*/
|
|
495
|
+
private consumeUnterminatedString;
|
|
496
|
+
/**
|
|
497
|
+
* Whether the quote at `quoteAt` ends the value: a member separator, a closing bracket or
|
|
498
|
+
* the end of the document has to follow it - and under `'declared'`, the member has to be a
|
|
499
|
+
* key the Schema declares.
|
|
500
|
+
*/
|
|
501
|
+
private closesValueAt;
|
|
502
|
+
/**
|
|
503
|
+
* Skips whitespace and, where a member is expected, the comments
|
|
504
|
+
* {@link RepairOptions.comments} allows. A comment is only ever recognised at a member
|
|
505
|
+
* position - never after a `:` and never inside a bare token - which is what keeps
|
|
506
|
+
* `issue: #123` and `url: https://x.com/a` intact at every setting.
|
|
507
|
+
*/
|
|
508
|
+
private skipMemberGap;
|
|
509
|
+
/** Consumes one comment at the current position, when an allowed style matches one. */
|
|
510
|
+
private skipOneComment;
|
|
511
|
+
/**
|
|
512
|
+
* Characters a comment can follow at a member gap: the start of a container, a separator, or
|
|
513
|
+
* whitespace. Anything else - the `:` of `issue: #123`, the `:` of `https://x` - is a value
|
|
514
|
+
* position, where the text belongs to the model and a comment is never read.
|
|
515
|
+
*/
|
|
516
|
+
private static readonly COMMENT_GAP;
|
|
517
|
+
/**
|
|
518
|
+
* Whether the text a capture took in hides a comment in a style the caller did not ask for.
|
|
519
|
+
*
|
|
520
|
+
* Quoted runs are skipped (so `"#ff0000"` is a color), a marker glued to a token is skipped
|
|
521
|
+
* (so `https://x.com/a` is a URL), and a marker that starts the capture is skipped (so
|
|
522
|
+
* `issue: #123` is an issue number) - the three positions where the parser never reads a
|
|
523
|
+
* comment, at any setting.
|
|
524
|
+
*/
|
|
525
|
+
private swallowedComment;
|
|
526
|
+
/**
|
|
527
|
+
* Where the next token begins, looking past whitespace and (where a member gap is allowed)
|
|
528
|
+
* past the comments that were asked for. Does not move the parser.
|
|
529
|
+
*/
|
|
530
|
+
private nextMemberPos;
|
|
531
|
+
/** Consumes to (not including) the next newline, or to the end of the input. */
|
|
532
|
+
private skipToLineEnd;
|
|
533
|
+
/**
|
|
534
|
+
* Attempts a strict JSON scalar parse (string / number / boolean / null) at the current
|
|
535
|
+
* position and rewinds when the token is not followed by a boundary.
|
|
536
|
+
*
|
|
537
|
+
* The boundary test runs in `'structural'` mode: a cleanly parsed value is trusted, so
|
|
538
|
+
* anything that looks like the next key is treated as structure and the successful parse
|
|
539
|
+
* is never discarded in favour of greedy capture. This is what guarantees that valid JSON
|
|
540
|
+
* always parses exactly like `JSON.parse`.
|
|
541
|
+
*/
|
|
542
|
+
private tryConsumeStrictValue;
|
|
543
|
+
/**
|
|
544
|
+
* How deep a document the parser reads. The host stack overflows somewhere around 2,500
|
|
545
|
+
* levels of this recursion; 1,000 leaves room for the validator and the scorer, which walk
|
|
546
|
+
* the same structure, and is far past any document a model writes.
|
|
547
|
+
*/
|
|
548
|
+
private static readonly MAX_NESTING;
|
|
549
|
+
/**
|
|
550
|
+
* Whether the Schema describes an object at the current path.
|
|
551
|
+
*
|
|
552
|
+
* `SchemaWalker` navigates on `type === 'object' || properties`, so implicit-object
|
|
553
|
+
* detection has to use the same rule: a level that declares `properties` (or a
|
|
554
|
+
* `type: ['object', ...]` union) is an object even when it never spells out `type`.
|
|
555
|
+
*/
|
|
556
|
+
private static declaresObject;
|
|
109
557
|
/**
|
|
110
558
|
* Parses a JSON object, handling both standard and implicit (no braces) structures.
|
|
111
559
|
*/
|
|
112
560
|
private consumeObject;
|
|
561
|
+
/**
|
|
562
|
+
* Whether a property belongs in the output, according to `RepairOptions.additionalProperties`.
|
|
563
|
+
*
|
|
564
|
+
* `'remove'` only drops keys at a level whose Schema declares property names: a level
|
|
565
|
+
* that is free-form (`type: 'object'` without `properties`, or no Schema at all) has no
|
|
566
|
+
* notion of an "extra" key, so dropping everything there would be destructive.
|
|
567
|
+
*/
|
|
568
|
+
private isKeptProperty;
|
|
569
|
+
/**
|
|
570
|
+
* Assigns an own enumerable property without going through setters.
|
|
571
|
+
*
|
|
572
|
+
* `obj[key] = value` with a key such as `__proto__` rewrites the prototype of the result
|
|
573
|
+
* instead of storing a value (`JSON.parse` keeps it as a plain data property), which both
|
|
574
|
+
* loses the key and leaks inherited properties into the repaired document.
|
|
575
|
+
*/
|
|
576
|
+
private static setOwn;
|
|
577
|
+
/**
|
|
578
|
+
* Whether the Schema describes an array at the current path.
|
|
579
|
+
*
|
|
580
|
+
* `items` alone counts: `SchemaWalker` navigates children on `type === 'array' || items`,
|
|
581
|
+
* so an implicit list has to be recognised under the same rule.
|
|
582
|
+
*/
|
|
583
|
+
private static declaresArray;
|
|
113
584
|
/**
|
|
114
585
|
* Parses a JSON array.
|
|
586
|
+
*
|
|
587
|
+
* @param implicit - True when the document has no opening bracket and the list is implied
|
|
588
|
+
* by the Schema: successive records are read as items until the input runs out.
|
|
115
589
|
*/
|
|
116
590
|
private consumeArray;
|
|
591
|
+
/**
|
|
592
|
+
* Whether the Schema expects records as items and the text right here begins one. Used to
|
|
593
|
+
* decide whether a list continues after its bracket closed.
|
|
594
|
+
*
|
|
595
|
+
* Deliberately narrow: a bare key continues the list only when the items Schema declares
|
|
596
|
+
* it, so the next property of the enclosing object (`[{...}] "title": "x"`) is not
|
|
597
|
+
* mistaken for another item.
|
|
598
|
+
*/
|
|
599
|
+
private startsAnotherRecord;
|
|
117
600
|
/**
|
|
118
601
|
* Consumes a property key, handling both quoted and unquoted keys.
|
|
602
|
+
*
|
|
603
|
+
* A quoted key keeps its exact content, including whitespace and punctuation
|
|
604
|
+
* (`"Official language"`); a bare key stops at quote characters so that a malformed
|
|
605
|
+
* document can never produce keys such as `language"`.
|
|
606
|
+
*
|
|
607
|
+
* A bare key that the Schema declares verbatim at `path` wins over the token scan, so a
|
|
608
|
+
* multi-word declaration (`Official language`) is read as one key even when the document
|
|
609
|
+
* left it unquoted (see {@link RepairParser.matchDeclaredKey}).
|
|
610
|
+
*
|
|
611
|
+
* @param path - The parent path the key belongs to; `pathStack` (the key is pushed later).
|
|
612
|
+
* @returns the key, or `null` when no key is present at all (an empty quoted key `""`
|
|
613
|
+
* is a valid key and returns the empty string).
|
|
119
614
|
*/
|
|
120
615
|
private consumeKey;
|
|
121
616
|
/**
|
|
122
|
-
* Captures content greedily until it encounters a delimiter that marks the start of the
|
|
123
|
-
*
|
|
617
|
+
* Captures content greedily until it encounters a delimiter that marks the start of the
|
|
618
|
+
* next property or the end of a structure. This is the fallback used when the strict JSON
|
|
619
|
+
* path failed, so the boundary test runs in `'greedy'` mode: when the Schema declares
|
|
620
|
+
* property names for this level, capture stops only at a declared key (see
|
|
621
|
+
* {@link RepairParser.isBoundaryAhead}).
|
|
622
|
+
*
|
|
623
|
+
* It also tracks balanced delimiters (parentheses, brackets, braces) and quotes, so that
|
|
624
|
+
* structural markers inside DSL-like strings (e.g. `@weather(location="SH, CN")`) stay
|
|
625
|
+
* part of the captured value, and implements the "Parity Rule" for quote stripping.
|
|
124
626
|
*/
|
|
627
|
+
private consumeGreedyString;
|
|
125
628
|
/**
|
|
126
|
-
*
|
|
629
|
+
* Characters that make the text before a candidate key part of a longer word.
|
|
630
|
+
*/
|
|
631
|
+
private static readonly WORD_CHAR;
|
|
632
|
+
/**
|
|
633
|
+
* Compiled "declared key literally here" patterns, shared across instances.
|
|
634
|
+
* Keyed by `fuzzy` + name because the `i` flag depends on `keyMatching`, and bounded: the names
|
|
635
|
+
* come from the Schema in play, and a long-lived process sees many of them.
|
|
636
|
+
*/
|
|
637
|
+
private static readonly declaredKeyPatterns;
|
|
638
|
+
/**
|
|
639
|
+
* Memo of the last path the multi-word declarations were collected for.
|
|
640
|
+
* Greedy capture probes every character of a value while the path stays the same, so this
|
|
641
|
+
* avoids re-walking the Schema (and re-keying a Map) thousands of times per document.
|
|
642
|
+
*/
|
|
643
|
+
private cachedPath;
|
|
644
|
+
private cachedDeclaredKeys;
|
|
645
|
+
/**
|
|
646
|
+
* The property names declared at `path` that contain whitespace, with a pattern that matches
|
|
647
|
+
* them literally: the name escaped, internal whitespace runs relaxed to `\s+`, and a `:`
|
|
648
|
+
* required after it. Single-word names are deliberately excluded - the generic key-shaped
|
|
649
|
+
* regex of {@link RepairParser.matchKey} already covers them.
|
|
650
|
+
*/
|
|
651
|
+
private declaredMultiWordKeys;
|
|
652
|
+
/**
|
|
653
|
+
* Matches a Schema-declared property name that contains whitespace at `startPos`, literally
|
|
654
|
+
* (case as declared, unless `keyMatching` folds case).
|
|
127
655
|
*
|
|
128
|
-
*
|
|
129
|
-
*
|
|
130
|
-
*
|
|
656
|
+
* The generic key scanner cannot help here: its bare-key branch excludes whitespace, so an
|
|
657
|
+
* unquoted `Official language:` in the document is never seen as one key. Declaring the name
|
|
658
|
+
* in the Schema supplies the missing information, and this method turns it into both a
|
|
659
|
+
* breakpoint for greedy capture and a readable key. A candidate glued to a longer word
|
|
660
|
+
* (`de-factoOfficial language:`) is rejected, so the breakpoint stays anchored on real keys.
|
|
131
661
|
*
|
|
132
|
-
*
|
|
133
|
-
* consuming the rest of the JSON.
|
|
662
|
+
* @returns the declared name and the amount of text it covers, or `null`.
|
|
134
663
|
*/
|
|
135
|
-
private
|
|
664
|
+
private matchDeclaredKey;
|
|
136
665
|
/**
|
|
137
666
|
* Probes whether the current position marks a structural delimiter (end or next property).
|
|
138
667
|
*/
|
|
@@ -141,15 +670,128 @@ declare class RepairParser {
|
|
|
141
670
|
* Checks if the upcoming text looks like a property key defined in the Schema at the given path.
|
|
142
671
|
*/
|
|
143
672
|
private isLookingAtKey;
|
|
673
|
+
/**
|
|
674
|
+
* Matches a property key at `startPos`, including quoted keys that contain
|
|
675
|
+
* whitespace/commas/colons (`"Official language":`), and returns the decoded key.
|
|
676
|
+
*/
|
|
677
|
+
private matchKey;
|
|
678
|
+
/**
|
|
679
|
+
* Whether the text here is a key that never got its colon or value: `{"a": 1, "b`.
|
|
680
|
+
* Closing brackets may follow the name, because a model can close the container and still
|
|
681
|
+
* leave the key hanging - and what follows the brackets may be the next record, since two
|
|
682
|
+
* records joined into one document are read by the same parser. Off with
|
|
683
|
+
* {@link RepairOptions.dangling}.
|
|
684
|
+
*/
|
|
685
|
+
private static readonly DANGLING_TAIL;
|
|
686
|
+
private danglingTail;
|
|
687
|
+
/** Whether the text here is a key the output never finished. */
|
|
688
|
+
private isDanglingTail;
|
|
689
|
+
/** Whether `raw` is a string literal that closed itself (ran to input end: it did not). */
|
|
690
|
+
private static closesString;
|
|
691
|
+
/** A token followed by a colon and then a path separator - a scheme or a path, not a key. */
|
|
692
|
+
private static readonly PATH_NOT_KEY;
|
|
693
|
+
/**
|
|
694
|
+
* Is a property boundary (a key followed by ':') ahead of `startPos`?
|
|
695
|
+
*
|
|
696
|
+
* - 'structural': trust any key-shaped token. Used right after a value was parsed by the
|
|
697
|
+
* strict JSON path, so a successful parse is never thrown away.
|
|
698
|
+
* - 'greedy': when the Schema declares property names at this level, stop only at a
|
|
699
|
+
* declared key; otherwise text that merely looks like `"foo bar":` would cut the value.
|
|
700
|
+
*
|
|
701
|
+
* A whitespace-containing name declared by the Schema is always a breakpoint, quoted or not,
|
|
702
|
+
* because it can only be recognised literally (see {@link RepairParser.matchDeclaredKey});
|
|
703
|
+
* in greedy mode other keys count as breakpoints through `keyMatching`, so a declared key
|
|
704
|
+
* written as `user_name` still breaks a value when the Schema declares `userName`.
|
|
705
|
+
*/
|
|
706
|
+
private isBoundaryAhead;
|
|
144
707
|
/**
|
|
145
708
|
* Performs type coercion and semantic repair based on the Schema.
|
|
146
709
|
* Handles fuzzy enum matching, noisy number extraction, and boolean variants.
|
|
710
|
+
*
|
|
711
|
+
* @param raw - The exact text the strict JSON path consumed for `val`, when it came from
|
|
712
|
+
* there. Coercing to `string` uses it so that `{ zip: 01234 }` yields `'01234'`.
|
|
147
713
|
*/
|
|
148
714
|
private coerceValue;
|
|
715
|
+
/**
|
|
716
|
+
* Reporting the text a number coercion gave up to keep the number in it.
|
|
717
|
+
*
|
|
718
|
+
* Giving up the unit is what makes `"约 1,200.50 元"` read as `1200.5`, and a unit is not a
|
|
719
|
+
* loss. The same path is also where a sentence goes missing: greedy capture runs a value into
|
|
720
|
+
* whatever follows it, so `age: 30\n\nHope this helps!}` hands the value `30\n\nHope this
|
|
721
|
+
* helps!` and the coercion throws the sentence away with the rest - out of the value, out of
|
|
722
|
+
* `flags` and out of `discarded`, which is how a repair that lost content reads as a perfect
|
|
723
|
+
* parse (`errors: [] flags: [] discarded: []`).
|
|
724
|
+
*
|
|
725
|
+
* Both are flagged `coerced-text-dropped`. Only text that reads as a sentence rather than as
|
|
726
|
+
* a qualifier is listed in `discarded`: that is what keeps `onDiscard: 'throw'` meaning "no
|
|
727
|
+
* content went missing" rather than "the document held no units", which no caller writing
|
|
728
|
+
* noisy numbers could use.
|
|
729
|
+
*
|
|
730
|
+
* @param written - the whole text this value was read from, digit-group separators relaxed.
|
|
731
|
+
* @param taken - the numeric match the value keeps inside it.
|
|
732
|
+
*/
|
|
733
|
+
private reportNumberCoercion;
|
|
734
|
+
/**
|
|
735
|
+
* Text around a numeric token that is structure rather than content: whitespace, and the
|
|
736
|
+
* member separator the parser crossed on its way into the value.
|
|
737
|
+
*/
|
|
738
|
+
private static readonly COERCED_EDGE;
|
|
739
|
+
/**
|
|
740
|
+
* How a value is spelled when comparing it to an `enum` entry: lower case, separators gone,
|
|
741
|
+
* so `Processing!` matches `'processing'` and `"user-name"` matches `userName`. `null` means
|
|
742
|
+
* there is no spelling to compare - a structured entry, `null`, a boolean, or text that says
|
|
743
|
+
* nothing once its punctuation is dropped. Only an exact match counts for those, and the
|
|
744
|
+
* Schema decides through the reported errors.
|
|
745
|
+
*/
|
|
746
|
+
private static enumSpelling;
|
|
747
|
+
/**
|
|
748
|
+
* The single-character escapes JSON defines.
|
|
749
|
+
*/
|
|
750
|
+
private static readonly ESCAPE_MAP;
|
|
751
|
+
/**
|
|
752
|
+
* Reads one escape sequence, backslash included.
|
|
753
|
+
*
|
|
754
|
+
* A valid JSON escape decodes exactly as `JSON.parse` decodes it, so a document that parses
|
|
755
|
+
* cleanly never loses what it wrote. `\uXXXX` is decoded one code unit at a time, which makes
|
|
756
|
+
* a surrogate pair come out as the astral character without extra handling - and leaves an
|
|
757
|
+
* unpaired surrogate where `JSON.parse` leaves it.
|
|
758
|
+
*
|
|
759
|
+
* Past JSON, {@link RepairOptions.escapes} decides how far the trust in a backslash reaches:
|
|
760
|
+
* - `'json5'` (default) reads `\xNN` as the character it names, and unwraps an escape of a
|
|
761
|
+
* character that never needs one (`"\$10"` -> `$10`), the way JSON5 does. Dropping the
|
|
762
|
+
* backslash of `\xNN` instead would leave the letters of the escape in the value
|
|
763
|
+
* (`"a\xa0b"` -> `axa0b`); dropping the one of `\U` is what turns a Windows path into
|
|
764
|
+
* `C:Usersme`. Both raise `invalid-escape`.
|
|
765
|
+
* - `'json'` leaves everything JSON does not define as the document wrote it, backslash
|
|
766
|
+
* included.
|
|
767
|
+
* - `'raw'` leaves every escape alone, so a backslash is content: paths, regular expressions
|
|
768
|
+
* and LaTeX survive whole, and `"a\nb"` is two characters rather than a newline.
|
|
769
|
+
*
|
|
770
|
+
* The backslash itself is structural in all three: it always keeps the character behind it
|
|
771
|
+
* inside the string, so the mode cannot change where a value ends. An incomplete hex escape
|
|
772
|
+
* decodes nothing and is left as written - `readHex` did not consume its digits.
|
|
773
|
+
*
|
|
774
|
+
* Decoding stops there: a decoded or literal NBSP, a zero-width character, a smart quote all
|
|
775
|
+
* stay in the value. Rewriting those would change the model's content, not repair its syntax.
|
|
776
|
+
*/
|
|
777
|
+
private consumeEscape;
|
|
778
|
+
/**
|
|
779
|
+
* Reads `count` hexadecimal digits, consuming them only when all `count` are digits, so an
|
|
780
|
+
* incomplete escape leaves the rest of the text to the caller.
|
|
781
|
+
*/
|
|
782
|
+
private readHex;
|
|
149
783
|
/**
|
|
150
784
|
* Consumes a standard JSON string.
|
|
151
785
|
*/
|
|
152
786
|
private consumeString;
|
|
787
|
+
/**
|
|
788
|
+
* Matches a JSON number literal at the current position.
|
|
789
|
+
*
|
|
790
|
+
* Scientific notation (`1e5`, `-2E2`) and a leading `+` are accepted; the match always
|
|
791
|
+
* stops at the end of a well-formed literal so that leftovers such as `1.2.3` remain
|
|
792
|
+
* available for greedy capture instead of being silently truncated.
|
|
793
|
+
*/
|
|
794
|
+
private static readonly NUMBER_PATTERN;
|
|
153
795
|
/**
|
|
154
796
|
* Consumes a standard JSON number.
|
|
155
797
|
*/
|
|
@@ -171,10 +813,11 @@ declare class RepairParser {
|
|
|
171
813
|
}
|
|
172
814
|
|
|
173
815
|
/**
|
|
174
|
-
* Repairs and parses a
|
|
816
|
+
* Repairs and parses a string generated by an LLM, guided by a JSON Schema.
|
|
175
817
|
* This is the main entry point for the library.
|
|
176
818
|
*
|
|
177
|
-
* @param input - The
|
|
819
|
+
* @param input - The text the model returned: broken JSON, or JSON wrapped in a Markdown
|
|
820
|
+
* fence and prose. See {@link RepairOptions.locate}.
|
|
178
821
|
* @param schema - Either a plain JSON Schema object or a pre-initialized SchemaWalker instance for better performance in batch processing.
|
|
179
822
|
* @param options - Optional configuration to tune the repair process.
|
|
180
823
|
* @returns A promise that resolves to the repaired and parsed JavaScript object.
|
|
@@ -187,5 +830,116 @@ declare class RepairParser {
|
|
|
187
830
|
* ```
|
|
188
831
|
*/
|
|
189
832
|
declare function jsonRepair(input: string, schema?: any | SchemaWalker, options?: RepairOptions): Promise<any>;
|
|
833
|
+
/**
|
|
834
|
+
* The same repair, plus what it noticed and what it had to give up.
|
|
835
|
+
*
|
|
836
|
+
* A repaired value that validates can still be the wrong answer, and a repair that had to
|
|
837
|
+
* choose between fragments or throw prose away has made decisions the caller should be able
|
|
838
|
+
* to see. `flags`, `errors`, `candidates` and `discarded` are what a caller needs to decide
|
|
839
|
+
* whether to accept the value, hand the `errors` back to the model for another try, or give
|
|
840
|
+
* up and ask a bigger model.
|
|
841
|
+
*
|
|
842
|
+
* @example
|
|
843
|
+
* ```typescript
|
|
844
|
+
* const { value, errors, flags } = await jsonRepairResult('```json\n{ name: Ada }\n```', schema)
|
|
845
|
+
* if (errors.length) await retryWith(renderValidatorErrors(errors))
|
|
846
|
+
* ```
|
|
847
|
+
*/
|
|
848
|
+
declare function jsonRepairResult<T = any>(input: string, schema?: any | SchemaWalker, options?: RepairOptions): Promise<RepairResult<T>>;
|
|
849
|
+
|
|
850
|
+
/** Whether the Schema expects an array at the root of the document. */
|
|
851
|
+
declare function expectsArrayRoot(walker: SchemaWalker): boolean;
|
|
852
|
+
/**
|
|
853
|
+
* @param text - The text to scan, normally already trimmed by the caller.
|
|
854
|
+
* @param walker - The Schema in play. It decides three things: whether adjacent sibling
|
|
855
|
+
* records may be read as one array, where a record written without braces starts (a key only
|
|
856
|
+
* the Schema can name), and nothing at all when no Schema is given.
|
|
857
|
+
* @returns The regions in document order.
|
|
858
|
+
*/
|
|
859
|
+
declare function locateJsonCandidates(text: string, walker?: SchemaWalker): LocatedJson[];
|
|
860
|
+
/**
|
|
861
|
+
* Where a record that has no braces at all starts, when prose sits in front of it:
|
|
862
|
+
* `Here you go:\nname: Noah, age: 30`. The only thing that can tell `name` is a key rather
|
|
863
|
+
* than part of a sentence is the Schema declaring it, so the Schema supplies the offset.
|
|
864
|
+
*
|
|
865
|
+
* @returns A region running from the first declared key to the end of the text, or
|
|
866
|
+
* `undefined` when the text names none of them.
|
|
867
|
+
*/
|
|
868
|
+
declare function findImplicitRecordRegion(text: string, walker: SchemaWalker): LocatedJson | undefined;
|
|
869
|
+
/**
|
|
870
|
+
* What the repair threw away around a chosen region: the prose between and around the JSON
|
|
871
|
+
* regions (with offsets, so the caller can tell prefix from trailing chatter), and the
|
|
872
|
+
* regions it did not pick. Reported separately from the flags because a caller that cannot
|
|
873
|
+
* afford to lose content needs the text itself, not just a hint that something went.
|
|
874
|
+
*/
|
|
875
|
+
declare function discardedText(text: string, chosen: LocatedJson, others: LocatedJson[]): {
|
|
876
|
+
prose: {
|
|
877
|
+
text: string;
|
|
878
|
+
start: number;
|
|
879
|
+
}[];
|
|
880
|
+
fragments: string[];
|
|
881
|
+
};
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* A small JSON Schema validator, kept inside this package on purpose: the repair already
|
|
885
|
+
* knows the Schema through `SchemaWalker`, and the two things a caller needs after a repair
|
|
886
|
+
* are "does this still fail?" (to decide whether another model call is worth it) and "where
|
|
887
|
+
* does it fail?" (to tell the model). Pulling in a full validator would duplicate the
|
|
888
|
+
* walking this library already does.
|
|
889
|
+
*
|
|
890
|
+
* The keywords covered are the ones that describe a shape an LLM can get wrong: `type`
|
|
891
|
+
* (including `integer` and unions), `required`, `properties`, `additionalProperties: false`,
|
|
892
|
+
* `items`, `enum`, `const`, `pattern`, `format` for dates and times, numeric bounds, string
|
|
893
|
+
* length and array length. Unknown keywords are ignored, and so is everything below a Schema
|
|
894
|
+
* that says nothing - notably `anyOf` / `oneOf` / `allOf` are not evaluated, so a Schema built
|
|
895
|
+
* out of them reports no errors and the fragment ranking falls back to coverage alone.
|
|
896
|
+
*/
|
|
897
|
+
declare function validateValue(value: any, walker: SchemaWalker): ValidationError[];
|
|
898
|
+
/**
|
|
899
|
+
* Renders validation errors the way a repair prompt needs them: one `path: message` line
|
|
900
|
+
* each, short enough that a 360M-parameter model still follows it. Paths point at the field,
|
|
901
|
+
* so the model has something concrete to fix rather than a document to re-read.
|
|
902
|
+
*
|
|
903
|
+
* @param limit - How many lines to emit. More than a handful of simultaneous complaints is
|
|
904
|
+
* wasted on a small model; it fixes the first few and breaks the rest.
|
|
905
|
+
*/
|
|
906
|
+
declare function renderValidatorErrors(errors: ValidationError[], limit?: number): string;
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* How well a value fits the Schema, measured rather than felt.
|
|
910
|
+
*
|
|
911
|
+
* Counting declared keys is not the same as counting keys a model happened to write. Two
|
|
912
|
+
* real failure modes make that difference decisive:
|
|
913
|
+
*
|
|
914
|
+
* - A model that copies the Schema into its answer (`type`, `properties`, `required`, ...)
|
|
915
|
+
* produces the fragment with the *most* keys and the least data.
|
|
916
|
+
* - A model that answers with `"name": ""` satisfies `type: string` exactly and says nothing.
|
|
917
|
+
*
|
|
918
|
+
* So coverage counts only fields carrying a usable value, and keys the Schema never declared
|
|
919
|
+
* are counted against the fragment.
|
|
920
|
+
*/
|
|
921
|
+
declare function scoreCandidate(value: any, walker: SchemaWalker): {
|
|
922
|
+
score: CandidateScore;
|
|
923
|
+
flags: RepairFlag[];
|
|
924
|
+
};
|
|
925
|
+
/**
|
|
926
|
+
* Whether the model reproduced the Schema instead of filling it in.
|
|
927
|
+
*
|
|
928
|
+
* Given the fragment's text, Schema keywords are counted where they are written - the usual
|
|
929
|
+
* place to look, because an echo is often swallowed by greedy capture on the way to the real
|
|
930
|
+
* keys. Given a repaired value, its own keys are counted: a weaker signal (a document with
|
|
931
|
+
* one real `items` field is not an echo), which is why one keyword is never enough here
|
|
932
|
+
* either way. Anything else - a number, a string that is not text - is not an echo.
|
|
933
|
+
*/
|
|
934
|
+
declare function looksLikeSchemaEcho(fragment: unknown): boolean;
|
|
935
|
+
/**
|
|
936
|
+
* Compare two scores the way {@link RepairOptions.onMultiple} promises: fewer errors first, then
|
|
937
|
+
* more `required` fields with real values, then more declared fields, then fewer keys that are
|
|
938
|
+
* JSON Schema keywords - the signature of an answer built out of the Schema itself. An undeclared
|
|
939
|
+
* key that is not a keyword is reported but not held against a fragment.
|
|
940
|
+
*
|
|
941
|
+
* @returns a negative number when `a` should win, positive when `b` should.
|
|
942
|
+
*/
|
|
943
|
+
declare function compareScores(a: CandidateScore, b: CandidateScore): number;
|
|
190
944
|
|
|
191
|
-
export { type JSONPath, type RepairOptions, RepairParser, SchemaWalker, jsonRepair };
|
|
945
|
+
export { type CandidateScore, type CommentStyle, type EscapeMode, type JSONPath, type JsonCandidate, type LiteralDialect, type LocatedJson, type RepairFlag, type RepairOptions, RepairParser, type RepairResult, SchemaWalker, type ValidationError, compareScores, discardedText, expectsArrayRoot, findImplicitRecordRegion, jsonRepair, jsonRepairResult, locateJsonCandidates, looksLikeSchemaEcho, renderValidatorErrors, scoreCandidate, validateValue };
|