@isdk/json-repair 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.cn.md +126 -7
  2. package/README.md +148 -7
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +571 -4
  5. package/dist/index.d.ts +571 -4
  6. package/dist/index.js +1 -1
  7. package/docs/README.md +148 -7
  8. package/docs/_media/README.cn.md +126 -7
  9. package/docs/classes/RepairParser.md +69 -3
  10. package/docs/classes/SchemaWalker.md +9 -9
  11. package/docs/functions/compareScores.md +32 -0
  12. package/docs/functions/discardedText.md +42 -0
  13. package/docs/functions/expectsArrayRoot.md +23 -0
  14. package/docs/functions/findImplicitRecordRegion.md +32 -0
  15. package/docs/functions/jsonRepair.md +4 -3
  16. package/docs/functions/jsonRepairResult.md +50 -0
  17. package/docs/functions/locateJsonCandidates.md +33 -0
  18. package/docs/functions/looksLikeSchemaEcho.md +29 -0
  19. package/docs/functions/renderValidatorErrors.md +32 -0
  20. package/docs/functions/scoreCandidate.md +45 -0
  21. package/docs/functions/validateValue.md +38 -0
  22. package/docs/globals.md +19 -0
  23. package/docs/interfaces/CandidateScore.md +63 -0
  24. package/docs/interfaces/JsonCandidate.md +71 -0
  25. package/docs/interfaces/LocatedJson.md +48 -0
  26. package/docs/interfaces/RepairOptions.md +210 -5
  27. package/docs/interfaces/RepairResult.md +58 -0
  28. package/docs/interfaces/ValidationError.md +27 -0
  29. package/docs/type-aliases/CommentStyle.md +13 -0
  30. package/docs/type-aliases/EscapeMode.md +13 -0
  31. package/docs/type-aliases/JSONPath.md +1 -1
  32. package/docs/type-aliases/LiteralDialect.md +13 -0
  33. package/docs/type-aliases/RepairFlag.md +11 -0
  34. package/package.json +26 -4
  35. package/.prettierignore +0 -12
  36. package/.prettierrc +0 -8
  37. package/.versionrc +0 -36
  38. package/CHANGELOG.md +0 -34
  39. package/TODO +0 -0
  40. package/eslint.config.mjs +0 -65
  41. package/setupVitest.mjs +0 -15
  42. package/tsconfig.json +0 -20
  43. package/tsconfig.release.json +0 -21
  44. package/tsup.config.ts +0 -38
  45. package/typedoc.config.cjs +0 -9
  46. package/vite.config.mjs +0 -21
package/dist/index.d.ts CHANGED
@@ -50,6 +50,12 @@ interface RepairOptions {
50
50
  * parsed to, so a leading zero survives: `{ id: 01234 }` becomes `"01234"`.
51
51
  * `null` and structures (`{}` / `[]`) are never stringified - `"null"` and
52
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.
53
59
  */
54
60
  coerceTypes?: boolean;
55
61
  /**
@@ -63,12 +69,271 @@ interface RepairOptions {
63
69
  * which is respected on its own when validating incoming keys.
64
70
  */
65
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';
66
217
  }
67
218
  /**
68
219
  * Represents the current path in a JSON structure.
69
220
  * A list of strings (keys) and numbers (indices).
70
221
  */
71
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
+ }
72
337
 
73
338
  /**
74
339
  * Navigates through a JSON Schema based on a JSON Path.
@@ -165,6 +430,15 @@ declare class RepairParser {
165
430
  private pathStack;
166
431
  private walker;
167
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;
168
442
  /**
169
443
  * Creates a new RepairParser instance.
170
444
  *
@@ -172,6 +446,18 @@ declare class RepairParser {
172
446
  * @param options - Configuration options for the repair process.
173
447
  */
174
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;
175
461
  /**
176
462
  * Parses the input string and returns the repaired JavaScript object.
177
463
  *
@@ -184,6 +470,66 @@ declare class RepairParser {
184
470
  * Uses Schema guidance to decide whether to use standard parsing or greedy capture.
185
471
  */
186
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;
187
533
  /**
188
534
  * Attempts a strict JSON scalar parse (string / number / boolean / null) at the current
189
535
  * position and rewinds when the token is not followed by a boundary.
@@ -194,6 +540,12 @@ declare class RepairParser {
194
540
  * always parses exactly like `JSON.parse`.
195
541
  */
196
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;
197
549
  /**
198
550
  * Whether the Schema describes an object at the current path.
199
551
  *
@@ -222,10 +574,29 @@ declare class RepairParser {
222
574
  * loses the key and leaks inherited properties into the repaired document.
223
575
  */
224
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;
225
584
  /**
226
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.
227
589
  */
228
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;
229
600
  /**
230
601
  * Consumes a property key, handling both quoted and unquoted keys.
231
602
  *
@@ -260,7 +631,8 @@ declare class RepairParser {
260
631
  private static readonly WORD_CHAR;
261
632
  /**
262
633
  * Compiled "declared key literally here" patterns, shared across instances.
263
- * Keyed by `fuzzy` + name because the `i` flag depends on `keyMatching`.
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.
264
636
  */
265
637
  private static readonly declaredKeyPatterns;
266
638
  /**
@@ -303,6 +675,21 @@ declare class RepairParser {
303
675
  * whitespace/commas/colons (`"Official language":`), and returns the decoded key.
304
676
  */
305
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;
306
693
  /**
307
694
  * Is a property boundary (a key followed by ':') ahead of `startPos`?
308
695
  *
@@ -325,6 +712,74 @@ declare class RepairParser {
325
712
  * there. Coercing to `string` uses it so that `{ zip: 01234 }` yields `'01234'`.
326
713
  */
327
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;
328
783
  /**
329
784
  * Consumes a standard JSON string.
330
785
  */
@@ -358,10 +813,11 @@ declare class RepairParser {
358
813
  }
359
814
 
360
815
  /**
361
- * Repairs and parses a JSON string generated by an LLM, guided by a JSON Schema.
816
+ * Repairs and parses a string generated by an LLM, guided by a JSON Schema.
362
817
  * This is the main entry point for the library.
363
818
  *
364
- * @param input - The potentially broken JSON string to be repaired.
819
+ * @param input - The text the model returned: broken JSON, or JSON wrapped in a Markdown
820
+ * fence and prose. See {@link RepairOptions.locate}.
365
821
  * @param schema - Either a plain JSON Schema object or a pre-initialized SchemaWalker instance for better performance in batch processing.
366
822
  * @param options - Optional configuration to tune the repair process.
367
823
  * @returns A promise that resolves to the repaired and parsed JavaScript object.
@@ -374,5 +830,116 @@ declare class RepairParser {
374
830
  * ```
375
831
  */
376
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;
377
944
 
378
- 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 };