json-stream-lite 1.3.2 → 1.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -0
- package/dist/byte-buffer.d.ts +1 -0
- package/dist/byte-buffer.js +15 -2
- package/dist/parser.d.ts +146 -0
- package/dist/parser.js +479 -3
- package/dist/stringify.d.ts +26 -0
- package/dist/stringify.js +156 -45
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -209,10 +209,63 @@ for (const chunk of jsonStreamStringify(data, null, 0, {
|
|
|
209
209
|
}
|
|
210
210
|
```
|
|
211
211
|
|
|
212
|
+
## RFC 8259 Conformance Notes
|
|
213
|
+
|
|
214
|
+
json-stream-lite reads and writes JSON as defined by [RFC 8259](https://www.rfc-editor.org/rfc/rfc8259). Like `JSON.parse`, it accepts any value at the top level (not only objects and arrays) and treats only space, tab, line feed and carriage return as whitespace. To stream without validating every byte, the parser is lenient in some places. The writer follows `JSON.stringify` with a few differences.
|
|
215
|
+
|
|
216
|
+
### Parser leniencies
|
|
217
|
+
|
|
218
|
+
- **Comments and trailing commas**: JSONC comments (`//` and `/* */`) are accepted around values and before a closing bracket, and so is a trailing comma after the last item or member (`[1, 2,]`). The same parser reads JSON and JSONC, including the stringifier's `jsonc: true` output.
|
|
219
|
+
- **Byte order mark**: a UTF-8 BOM at the very start of the input is ignored, as RFC 8259 section 8.1 allows.
|
|
220
|
+
- **Separators**: commas and colons are not validated. Missing, leading or repeated commas (`[1 2]`, `[,1]`, `[1,,2]`) and a missing colon (`{"a" 1}`) are accepted.
|
|
221
|
+
- **Trailing content**: only the first value is read. Anything after it is not checked (`{} x` reads `{}`, and `truex` reads `true`).
|
|
222
|
+
- **Numbers**: the number grammar is not enforced. Leading zeros (`01`) and a trailing decimal point (`1.`) are accepted, and malformed numbers such as `-` or `1e` read as `NaN`. Numbers are JavaScript numbers, so integers beyond 2^53 lose precision and exponents that overflow become `Infinity`, as with `JSON.parse`.
|
|
223
|
+
- **Strings**: unescaped control characters (such as a raw tab or newline) are accepted. Unknown escapes (`\x`) are dropped, and a `\u` escape is not checked for valid hex digits. Invalid UTF-8 and lone surrogate escapes (`\ud800`) are replaced with U+FFFD.
|
|
224
|
+
- **Duplicate keys**: the last member with a given name wins, as with `JSON.parse`. RFC 8259 leaves the behaviour undefined.
|
|
225
|
+
- **Nesting**: parsing is recursive. Thousands of levels of nesting work, but extremely deep input (around 10,000 levels) throws a `RangeError`, as `JSON.parse` does.
|
|
226
|
+
|
|
227
|
+
### Writer defaults
|
|
228
|
+
|
|
229
|
+
- **Escaping**: `"`, `\\` and control characters are escaped (using `\n`, `\t` and so on where available, otherwise `\u00XX`). `/` and non-ASCII characters, including U+2028 and U+2029, are written as-is.
|
|
230
|
+
- **Lone surrogates**: unpaired surrogates in strings are written as-is, and `jsonStreamStringifyBytes` encodes them as U+FFFD. `JSON.stringify` escapes them (`\ud800`) instead.
|
|
231
|
+
- **Values with no JSON representation**: as with `JSON.stringify`, `NaN` and `±Infinity` are written as `null`. `undefined`, functions and symbols are left out of objects and written as `null` in arrays, and at the top level produce no output. A BigInt throws a `TypeError` unless `toJSON` or the replacer converts it.
|
|
232
|
+
- **Replacer**: as with `JSON.stringify`, a function is called with each key and value (with the containing object as `this`) after `toJSON`, and an array lists the object properties to write.
|
|
233
|
+
- **`toJSON` and `toString`**: a `toJSON()` method is used when present. Otherwise an object with its own `toString()` (anything but the default `Object` and `Array` ones) is written as that string, for example class instances and boxed numbers (`new Number(5)` gives `"5"`). `JSON.stringify` would write their properties or the number.
|
|
234
|
+
- **Indentation**: `indent` is a number of spaces. Strings such as `'\t'` are not supported.
|
|
235
|
+
- **JSONC**: `jsonc: true` adds a trailing comma after the last item of every object and array, which is not valid JSON, and `comments` writes comments when indenting.
|
|
236
|
+
- **Circular references**: these are not detected and overflow the stack (`RangeError`). `JSON.stringify` throws a `TypeError`.
|
|
237
|
+
|
|
212
238
|
## API Reference
|
|
213
239
|
|
|
214
240
|
See [docs](https://jacobshirley.github.io/json-stream-lite/v1).
|
|
215
241
|
|
|
242
|
+
### JSON Lines (JSONL / NDJSON)
|
|
243
|
+
|
|
244
|
+
```typescript
|
|
245
|
+
import { JsonLines } from 'json-stream-lite'
|
|
246
|
+
|
|
247
|
+
// Parse lazily, one value per line (blank lines are skipped)
|
|
248
|
+
for (const line of new JsonLines('{"a":1}\n{"a":2}\n')) {
|
|
249
|
+
console.log(line.readValue())
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// Async streaming from any byte/string stream
|
|
253
|
+
const response = await fetch('https://api.example.com/data.jsonl')
|
|
254
|
+
for await (const line of new JsonLines(response.body!)) {
|
|
255
|
+
console.log(await line.readValueAsync())
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Stringify: one compact value per line, newline-terminated
|
|
259
|
+
// (values with no JSON representation, e.g. undefined, are written as null)
|
|
260
|
+
for (const chunk of JsonLines.stringify([{ a: 1 }, { a: 2 }])) {
|
|
261
|
+
process.stdout.write(chunk)
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
By default the parser is lenient: blank lines are ignored and several values may share a line. Set `lines.strict = true` on a `JsonLines` instance to reject both, as the [JSON Lines](https://jsonlines.org/) format requires.
|
|
266
|
+
|
|
267
|
+
Also available: `JsonLines.stringifyBytes`, `JsonLines.stringifyAsync` (accepts sync or async iterables) and `JsonLines.stringifyBytesAsync`, plus the equivalent standalone functions `jsonLinesStringify`, `jsonLinesStringifyBytes`, `jsonLinesStringifyAsync` and `jsonLinesStringifyBytesAsync`.
|
|
268
|
+
|
|
216
269
|
## Advanced Usage
|
|
217
270
|
|
|
218
271
|
### Processing Large Files
|
package/dist/byte-buffer.d.ts
CHANGED
|
@@ -108,6 +108,7 @@ export declare class ByteBuffer {
|
|
|
108
108
|
/**
|
|
109
109
|
* Override to customize when to compact the buffer
|
|
110
110
|
* By default, compacts when more than maxBufferSize bytes have been consumed
|
|
111
|
+
* and the consumed part is at least half the buffer
|
|
111
112
|
*
|
|
112
113
|
* @returns boolean indicating whether to compact the buffer
|
|
113
114
|
*/
|
package/dist/byte-buffer.js
CHANGED
|
@@ -102,8 +102,16 @@ export class ByteBuffer {
|
|
|
102
102
|
if (!this.asyncIterator) {
|
|
103
103
|
this.asyncIterator = this.asyncIterable[Symbol.asyncIterator]();
|
|
104
104
|
}
|
|
105
|
+
// Everything from bufferIndex on is parsed again after this read; when
|
|
106
|
+
// readAsync() retries a whole document that is all of it. Reading at
|
|
107
|
+
// least that many new bytes grows the buffer geometrically, so a large
|
|
108
|
+
// document is re-parsed O(log n) times instead of once per chunk.
|
|
109
|
+
const pending = this.length - this.bufferIndex;
|
|
110
|
+
const target = this.allowBufferToBeExceeded
|
|
111
|
+
? Math.max(this.maxBufferSize, this.length + pending)
|
|
112
|
+
: this.maxBufferSize;
|
|
105
113
|
let processed = false;
|
|
106
|
-
while (this.length <
|
|
114
|
+
while (this.length < target || !processed) {
|
|
107
115
|
processed = true;
|
|
108
116
|
const next = await this.asyncIterator.next();
|
|
109
117
|
if (next.done) {
|
|
@@ -275,11 +283,16 @@ export class ByteBuffer {
|
|
|
275
283
|
/**
|
|
276
284
|
* Override to customize when to compact the buffer
|
|
277
285
|
* By default, compacts when more than maxBufferSize bytes have been consumed
|
|
286
|
+
* and the consumed part is at least half the buffer
|
|
278
287
|
*
|
|
279
288
|
* @returns boolean indicating whether to compact the buffer
|
|
280
289
|
*/
|
|
281
290
|
canCompact() {
|
|
282
|
-
|
|
291
|
+
// Compacting copies everything not yet consumed, so only do it once
|
|
292
|
+
// the consumed part is at least as large: otherwise a large buffered
|
|
293
|
+
// input is copied again every maxBufferSize bytes (quadratic).
|
|
294
|
+
return (this.bufferIndex > this.maxBufferSize &&
|
|
295
|
+
this.bufferIndex * 2 >= this.buffer.length);
|
|
283
296
|
}
|
|
284
297
|
/**
|
|
285
298
|
* Attempts to execute a function, resetting buffer position on failure.
|
package/dist/parser.d.ts
CHANGED
|
@@ -102,6 +102,18 @@ export declare abstract class JsonEntity<T> {
|
|
|
102
102
|
* Skips whitespace characters (and comments when JSONC is enabled) in the buffer.
|
|
103
103
|
*/
|
|
104
104
|
protected skipWhitespace(): void;
|
|
105
|
+
/**
|
|
106
|
+
* If only whitespace and comments stand between the current position and
|
|
107
|
+
* `close` (a closing bracket), consumes up to and including `close`.
|
|
108
|
+
* Otherwise consumes nothing, so comments before a value stay available
|
|
109
|
+
* through its `preComments`.
|
|
110
|
+
*
|
|
111
|
+
* This lets a collection end after a trailing comma (JSONC) or a comment.
|
|
112
|
+
*
|
|
113
|
+
* @param close - The closing bracket byte
|
|
114
|
+
* @returns True if the closing bracket was consumed
|
|
115
|
+
*/
|
|
116
|
+
protected consumeClosing(close: number): boolean;
|
|
105
117
|
/**
|
|
106
118
|
* Reads and parses the entity, consuming it in the process.
|
|
107
119
|
*
|
|
@@ -124,6 +136,16 @@ export declare abstract class JsonEntity<T> {
|
|
|
124
136
|
* Asynchronously consumes the entity by reading it if not already consumed.
|
|
125
137
|
*/
|
|
126
138
|
consumeAsync(): Promise<void>;
|
|
139
|
+
/**
|
|
140
|
+
* Advances a restartable item generator (such as `items()` or
|
|
141
|
+
* `members()`), reading more input until the next item has started.
|
|
142
|
+
*
|
|
143
|
+
* @param generator - The generator to advance
|
|
144
|
+
* @param restart - Creates a fresh generator after a failed attempt; the
|
|
145
|
+
* buffer has been rewound to the same item boundary
|
|
146
|
+
* @returns The generator's next result
|
|
147
|
+
*/
|
|
148
|
+
protected nextAsync<I>(generator: Generator<I>, restart: () => Generator<I>): Promise<IteratorResult<I>>;
|
|
127
149
|
/**
|
|
128
150
|
* Attempts to parse by executing a callback, reverting buffer state on failure.
|
|
129
151
|
*
|
|
@@ -195,6 +217,12 @@ export declare class JsonString<T extends string = string> extends JsonEntity<T>
|
|
|
195
217
|
* @yields Uint8Array chunks containing the unescaped string bytes
|
|
196
218
|
*/
|
|
197
219
|
streamBytes(chunkSize?: number): Generator<Uint8Array>;
|
|
220
|
+
/**
|
|
221
|
+
* If `charCode` is a high surrogate and the next six bytes are a `\uXXXX`
|
|
222
|
+
* escape for a low surrogate, returns that low surrogate without
|
|
223
|
+
* consuming anything.
|
|
224
|
+
*/
|
|
225
|
+
private peekLowSurrogateEscape;
|
|
198
226
|
/**
|
|
199
227
|
* Async generator that yields the string content as raw byte chunks from a stream.
|
|
200
228
|
* Handles escape sequences by converting them to their actual byte values.
|
|
@@ -204,6 +232,16 @@ export declare class JsonString<T extends string = string> extends JsonEntity<T>
|
|
|
204
232
|
* @yields Uint8Array chunks containing the unescaped string bytes
|
|
205
233
|
*/
|
|
206
234
|
streamBytesAsync(chunkSize?: number): AsyncGenerator<Uint8Array>;
|
|
235
|
+
/**
|
|
236
|
+
* Asynchronously reads the string from a stream.
|
|
237
|
+
*
|
|
238
|
+
* Reads through {@link streamBytesAsync}, which resumes mid-string when
|
|
239
|
+
* more input is needed, so a long string split across many chunks is
|
|
240
|
+
* not re-parsed from its opening quote on every refill.
|
|
241
|
+
*
|
|
242
|
+
* @returns A promise that resolves to the parsed string value
|
|
243
|
+
*/
|
|
244
|
+
readAsync(): Promise<T>;
|
|
207
245
|
/**
|
|
208
246
|
* Generator that yields the string content as chunks of strings.
|
|
209
247
|
*
|
|
@@ -367,6 +405,16 @@ export declare class JsonObject<T extends object = any> extends JsonEntity<T> {
|
|
|
367
405
|
* @yields Object containing the key and value entities for each member
|
|
368
406
|
*/
|
|
369
407
|
membersAsync(): AsyncGenerator<JsonObjectMember<T>>;
|
|
408
|
+
/**
|
|
409
|
+
* Asynchronously reads the whole object from a stream.
|
|
410
|
+
*
|
|
411
|
+
* Reads member by member through {@link membersAsync}, so when more
|
|
412
|
+
* input is needed only the current member is parsed again, not the
|
|
413
|
+
* whole object.
|
|
414
|
+
*
|
|
415
|
+
* @returns A promise that resolves to the parsed object
|
|
416
|
+
*/
|
|
417
|
+
readAsync(): Promise<T>;
|
|
370
418
|
/**
|
|
371
419
|
* Returns an iterator for object members.
|
|
372
420
|
* Enables use of for...of loops on JsonObject.
|
|
@@ -405,6 +453,15 @@ export declare class JsonArray<T = any> extends JsonEntity<T[]> {
|
|
|
405
453
|
* @yields Each item entity in the array
|
|
406
454
|
*/
|
|
407
455
|
itemsAsync(): AsyncGenerator<JsonValue<T>>;
|
|
456
|
+
/**
|
|
457
|
+
* Asynchronously reads the whole array from a stream.
|
|
458
|
+
*
|
|
459
|
+
* Reads item by item through {@link itemsAsync}, so when more input is
|
|
460
|
+
* needed only the current item is parsed again, not the whole array.
|
|
461
|
+
*
|
|
462
|
+
* @returns A promise that resolves to the parsed array
|
|
463
|
+
*/
|
|
464
|
+
readAsync(): Promise<T[]>;
|
|
408
465
|
/**
|
|
409
466
|
* Returns an iterator for array items.
|
|
410
467
|
* Enables use of for...of loops on JsonArray.
|
|
@@ -422,6 +479,95 @@ export declare class JsonArray<T = any> extends JsonEntity<T[]> {
|
|
|
422
479
|
*/
|
|
423
480
|
protected parse(): T[];
|
|
424
481
|
}
|
|
482
|
+
/**
|
|
483
|
+
* Represents a JSON Lines (JSONL / NDJSON) document: a sequence of JSON values
|
|
484
|
+
* separated by newlines. Provides streaming access to each line's value.
|
|
485
|
+
*
|
|
486
|
+
* @typeParam T - The expected type of each line's value
|
|
487
|
+
*/
|
|
488
|
+
export declare class JsonLines<T = any> extends JsonEntity<T[]> {
|
|
489
|
+
private valuesRead;
|
|
490
|
+
/**
|
|
491
|
+
* When false (default), blank lines are silently ignored and several
|
|
492
|
+
* values may share a line. When true, the input must follow the JSON Lines
|
|
493
|
+
* format exactly: one value per line, no blank lines, and nothing after the
|
|
494
|
+
* final line terminator. Violations throw an Error.
|
|
495
|
+
*/
|
|
496
|
+
strict: boolean;
|
|
497
|
+
/**
|
|
498
|
+
* Generator that yields one JsonValue per line. Blank lines are skipped
|
|
499
|
+
* unless `strict` is set.
|
|
500
|
+
*
|
|
501
|
+
* @yields Each value entity in the document
|
|
502
|
+
*/
|
|
503
|
+
items(): Generator<JsonValue<T>>;
|
|
504
|
+
/**
|
|
505
|
+
* Async generator that yields one JsonValue per line from a stream.
|
|
506
|
+
*
|
|
507
|
+
* @yields Each value entity in the document
|
|
508
|
+
*/
|
|
509
|
+
itemsAsync(): AsyncGenerator<JsonValue<T>>;
|
|
510
|
+
/**
|
|
511
|
+
* Enables use of for...of loops on JsonLines.
|
|
512
|
+
*/
|
|
513
|
+
[Symbol.iterator](): Generator<JsonValue<T, string>, any, any>;
|
|
514
|
+
/**
|
|
515
|
+
* Enables use of for await...of loops on JsonLines.
|
|
516
|
+
*/
|
|
517
|
+
[Symbol.asyncIterator](): AsyncGenerator<JsonValue<T, string>, any, any>;
|
|
518
|
+
/**
|
|
519
|
+
* Parses the entire document into an array of values.
|
|
520
|
+
*
|
|
521
|
+
* @returns The parsed values, one per line
|
|
522
|
+
*/
|
|
523
|
+
protected parse(): T[];
|
|
524
|
+
/**
|
|
525
|
+
* Serializes values as JSON Lines (JSONL / NDJSON) using json-stream-lite.
|
|
526
|
+
* See `jsonLinesStringify` for more details.
|
|
527
|
+
* @param indent - Ignored: JSON Lines output is never indented
|
|
528
|
+
* @returns A generator yielding JSON Lines string chunks
|
|
529
|
+
*/
|
|
530
|
+
static stringify(values: Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<string>;
|
|
531
|
+
/**
|
|
532
|
+
* Serializes values as JSON Lines as Uint8Array byte chunks using json-stream-lite.
|
|
533
|
+
* See `jsonLinesStringifyBytes` for more details.
|
|
534
|
+
* @param indent - Ignored: JSON Lines output is never indented
|
|
535
|
+
* @returns A generator yielding JSON Lines byte chunks
|
|
536
|
+
*/
|
|
537
|
+
static stringifyBytes(values: Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<Uint8Array>;
|
|
538
|
+
/**
|
|
539
|
+
* Asynchronously serializes values as JSON Lines using json-stream-lite.
|
|
540
|
+
* See `jsonLinesStringifyAsync` for more details.
|
|
541
|
+
* @param indent - Ignored: JSON Lines output is never indented
|
|
542
|
+
* @returns An async generator yielding JSON Lines string chunks
|
|
543
|
+
* */
|
|
544
|
+
static stringifyAsync(values: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<string>;
|
|
545
|
+
/**
|
|
546
|
+
* Asynchronously serializes values as JSON Lines as Uint8Array byte chunks using json-stream-lite.
|
|
547
|
+
* See `jsonLinesStringifyBytesAsync` for more details.
|
|
548
|
+
* @param indent - Ignored: JSON Lines output is never indented
|
|
549
|
+
* @returns An async generator yielding JSON Lines byte chunks
|
|
550
|
+
* */
|
|
551
|
+
static stringifyBytesAsync(values: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<Uint8Array>;
|
|
552
|
+
/**
|
|
553
|
+
* Asynchronously reads the entire document into an array of values.
|
|
554
|
+
*
|
|
555
|
+
* Reads line by line: a value that is fully buffered is read
|
|
556
|
+
* synchronously, one that is not is read incrementally, so a refill
|
|
557
|
+
* re-parses at most the unfinished value and the buffer stays near
|
|
558
|
+
* `maxBufferSize`. Retrying the whole document instead would re-run the
|
|
559
|
+
* strict-mode checks with a stale line count.
|
|
560
|
+
*
|
|
561
|
+
* @returns The parsed values, one per line
|
|
562
|
+
*/
|
|
563
|
+
readAsync(): Promise<T[]>;
|
|
564
|
+
/**
|
|
565
|
+
* Reads the entire document into an array of values.
|
|
566
|
+
*
|
|
567
|
+
* @returns The parsed values, one per line
|
|
568
|
+
*/
|
|
569
|
+
read(): T[];
|
|
570
|
+
}
|
|
425
571
|
/**
|
|
426
572
|
* Parser that flattens nested JSON structures into key-value pairs.
|
|
427
573
|
* Useful for extracting specific values from complex JSON without parsing the entire structure.
|
package/dist/parser.js
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
import { ByteBuffer } from './byte-buffer.js';
|
|
2
|
-
import { jsonStreamStringify, jsonStreamStringifyAsync, jsonStreamStringifyBytes, jsonStreamStringifyBytesAsync, } from './stringify.js';
|
|
2
|
+
import { jsonStreamStringify, jsonStreamStringifyAsync, jsonStreamStringifyBytes, jsonStreamStringifyBytesAsync, jsonLinesStringify, jsonLinesStringifyAsync, jsonLinesStringifyBytes, jsonLinesStringifyBytesAsync, } from './stringify.js';
|
|
3
3
|
import { bytesToNumber, bytesToString } from './utils.js';
|
|
4
|
+
/**
|
|
5
|
+
* Sets an own, enumerable property. Plain assignment would treat a member
|
|
6
|
+
* named `__proto__` as the prototype setter instead of creating a property.
|
|
7
|
+
*/
|
|
8
|
+
function setOwnProperty(obj, key, value) {
|
|
9
|
+
if (key === '__proto__') {
|
|
10
|
+
Object.defineProperty(obj, key, {
|
|
11
|
+
value,
|
|
12
|
+
writable: true,
|
|
13
|
+
enumerable: true,
|
|
14
|
+
configurable: true,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
;
|
|
19
|
+
obj[key] = value;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Chunk size used when JsonString.readAsync() streams a string. When more
|
|
24
|
+
* input is needed, at most this much of the string is parsed again.
|
|
25
|
+
*/
|
|
26
|
+
const ASYNC_READ_CHUNK_SIZE = 16 * 1024;
|
|
27
|
+
/** Marks the end of a container's items in the async read loops below. */
|
|
28
|
+
const END = Symbol('end');
|
|
4
29
|
/**
|
|
5
30
|
* Map of character names to their byte values for JSON parsing.
|
|
6
31
|
* Contains commonly used characters in JSON syntax.
|
|
@@ -267,6 +292,58 @@ export class JsonEntity {
|
|
|
267
292
|
this.buffer.next();
|
|
268
293
|
}
|
|
269
294
|
}
|
|
295
|
+
/**
|
|
296
|
+
* If only whitespace and comments stand between the current position and
|
|
297
|
+
* `close` (a closing bracket), consumes up to and including `close`.
|
|
298
|
+
* Otherwise consumes nothing, so comments before a value stay available
|
|
299
|
+
* through its `preComments`.
|
|
300
|
+
*
|
|
301
|
+
* This lets a collection end after a trailing comma (JSONC) or a comment.
|
|
302
|
+
*
|
|
303
|
+
* @param close - The closing bracket byte
|
|
304
|
+
* @returns True if the closing bracket was consumed
|
|
305
|
+
*/
|
|
306
|
+
consumeClosing(close) {
|
|
307
|
+
let offset = 0;
|
|
308
|
+
while (true) {
|
|
309
|
+
const byte = this.buffer.peek(offset);
|
|
310
|
+
if (isWhitespace(byte)) {
|
|
311
|
+
offset++;
|
|
312
|
+
continue;
|
|
313
|
+
}
|
|
314
|
+
if (byte === BYTE_MAP.slash) {
|
|
315
|
+
const next = this.buffer.peek(offset + 1);
|
|
316
|
+
if (next === BYTE_MAP.slash) {
|
|
317
|
+
// Line comment: runs to the end of the line
|
|
318
|
+
offset += 2;
|
|
319
|
+
let b = this.buffer.peek(offset);
|
|
320
|
+
while (b !== null && b !== BYTE_MAP.lineFeed) {
|
|
321
|
+
b = this.buffer.peek(++offset);
|
|
322
|
+
}
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
if (next === BYTE_MAP.asterisk) {
|
|
326
|
+
// Block comment: runs to the closing */
|
|
327
|
+
offset += 2;
|
|
328
|
+
while (!(this.buffer.peek(offset) === BYTE_MAP.asterisk &&
|
|
329
|
+
this.buffer.peek(offset + 1) === BYTE_MAP.slash)) {
|
|
330
|
+
if (this.buffer.peek(offset) === null)
|
|
331
|
+
return false;
|
|
332
|
+
offset++;
|
|
333
|
+
}
|
|
334
|
+
offset += 2;
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (byte !== close) {
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
for (let i = 0; i <= offset; i++) {
|
|
342
|
+
this.buffer.next();
|
|
343
|
+
}
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
270
347
|
/**
|
|
271
348
|
* Reads and parses the entity, consuming it in the process.
|
|
272
349
|
*
|
|
@@ -320,6 +397,29 @@ export class JsonEntity {
|
|
|
320
397
|
await this.readAsync();
|
|
321
398
|
}
|
|
322
399
|
}
|
|
400
|
+
/**
|
|
401
|
+
* Advances a restartable item generator (such as `items()` or
|
|
402
|
+
* `members()`), reading more input until the next item has started.
|
|
403
|
+
*
|
|
404
|
+
* @param generator - The generator to advance
|
|
405
|
+
* @param restart - Creates a fresh generator after a failed attempt; the
|
|
406
|
+
* buffer has been rewound to the same item boundary
|
|
407
|
+
* @returns The generator's next result
|
|
408
|
+
*/
|
|
409
|
+
async nextAsync(generator, restart) {
|
|
410
|
+
while (true) {
|
|
411
|
+
const next = this.tryParse(() => generator.next());
|
|
412
|
+
if (next !== undefined) {
|
|
413
|
+
return next;
|
|
414
|
+
}
|
|
415
|
+
if (this.buffer.atEof()) {
|
|
416
|
+
// Let the synchronous parser raise the usual error
|
|
417
|
+
return restart().next();
|
|
418
|
+
}
|
|
419
|
+
await this.buffer.readStreamAsync();
|
|
420
|
+
generator = restart();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
323
423
|
/**
|
|
324
424
|
* Attempts to parse by executing a callback, reverting buffer state on failure.
|
|
325
425
|
*
|
|
@@ -506,6 +606,10 @@ export class JsonString extends JsonEntity {
|
|
|
506
606
|
bytes.push(BYTE_MAP.tab); // tab
|
|
507
607
|
this.buffer.next(); // consume escaped character
|
|
508
608
|
break;
|
|
609
|
+
case BYTE_MAP.slash:
|
|
610
|
+
bytes.push(BYTE_MAP.slash); // solidus
|
|
611
|
+
this.buffer.next(); // consume escaped character
|
|
612
|
+
break;
|
|
509
613
|
case BYTE_MAP.u:
|
|
510
614
|
// Unicode escape sequence \uXXXX
|
|
511
615
|
this.buffer.next(); // consume 'u'
|
|
@@ -523,8 +627,18 @@ export class JsonString extends JsonEntity {
|
|
|
523
627
|
bytes.push(charCode);
|
|
524
628
|
}
|
|
525
629
|
else {
|
|
630
|
+
// A high surrogate followed by a \u low
|
|
631
|
+
// surrogate escape is one character outside
|
|
632
|
+
// the BMP (e.g. "\ud83d\ude00"); decoding
|
|
633
|
+
// the halves separately gives two U+FFFD.
|
|
634
|
+
const low = this.peekLowSurrogateEscape(charCode);
|
|
635
|
+
let char = String.fromCharCode(charCode);
|
|
636
|
+
if (low !== undefined) {
|
|
637
|
+
for (let i = 0; i < 6; i++)
|
|
638
|
+
this.buffer.next();
|
|
639
|
+
char = String.fromCharCode(charCode, low);
|
|
640
|
+
}
|
|
526
641
|
// UTF-8 encode the character
|
|
527
|
-
const char = String.fromCharCode(charCode);
|
|
528
642
|
const encoded = new TextEncoder().encode(char);
|
|
529
643
|
bytes.push(...encoded);
|
|
530
644
|
}
|
|
@@ -557,6 +671,30 @@ export class JsonString extends JsonEntity {
|
|
|
557
671
|
yield result;
|
|
558
672
|
}
|
|
559
673
|
}
|
|
674
|
+
/**
|
|
675
|
+
* If `charCode` is a high surrogate and the next six bytes are a `\uXXXX`
|
|
676
|
+
* escape for a low surrogate, returns that low surrogate without
|
|
677
|
+
* consuming anything.
|
|
678
|
+
*/
|
|
679
|
+
peekLowSurrogateEscape(charCode) {
|
|
680
|
+
if (charCode < 0xd800 || charCode > 0xdbff)
|
|
681
|
+
return undefined;
|
|
682
|
+
if (this.buffer.peek() !== BYTE_MAP.backslash ||
|
|
683
|
+
this.buffer.peek(1) !== BYTE_MAP.u) {
|
|
684
|
+
return undefined;
|
|
685
|
+
}
|
|
686
|
+
let hex = '';
|
|
687
|
+
for (let i = 2; i < 6; i++) {
|
|
688
|
+
const byte = this.buffer.peek(i);
|
|
689
|
+
if (byte === null)
|
|
690
|
+
return undefined;
|
|
691
|
+
hex += String.fromCharCode(byte);
|
|
692
|
+
}
|
|
693
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex))
|
|
694
|
+
return undefined;
|
|
695
|
+
const low = parseInt(hex, 16);
|
|
696
|
+
return low >= 0xdc00 && low <= 0xdfff ? low : undefined;
|
|
697
|
+
}
|
|
560
698
|
/**
|
|
561
699
|
* Async generator that yields the string content as raw byte chunks from a stream.
|
|
562
700
|
* Handles escape sequences by converting them to their actual byte values.
|
|
@@ -582,6 +720,45 @@ export class JsonString extends JsonEntity {
|
|
|
582
720
|
}
|
|
583
721
|
}
|
|
584
722
|
}
|
|
723
|
+
/**
|
|
724
|
+
* Asynchronously reads the string from a stream.
|
|
725
|
+
*
|
|
726
|
+
* Reads through {@link streamBytesAsync}, which resumes mid-string when
|
|
727
|
+
* more input is needed, so a long string split across many chunks is
|
|
728
|
+
* not re-parsed from its opening quote on every refill.
|
|
729
|
+
*
|
|
730
|
+
* @returns A promise that resolves to the parsed string value
|
|
731
|
+
*/
|
|
732
|
+
async readAsync() {
|
|
733
|
+
if (this.consumed) {
|
|
734
|
+
throw new Error('JSON entity has already been consumed.');
|
|
735
|
+
}
|
|
736
|
+
// Fast path: the whole string is already buffered
|
|
737
|
+
const whole = this.tryParse(() => this.read());
|
|
738
|
+
if (whole !== undefined) {
|
|
739
|
+
return whole;
|
|
740
|
+
}
|
|
741
|
+
for await (const _ of this.preCommentsAsync) {
|
|
742
|
+
}
|
|
743
|
+
const chunks = [];
|
|
744
|
+
let length = 0;
|
|
745
|
+
for await (const chunk of this.streamBytesAsync(ASYNC_READ_CHUNK_SIZE)) {
|
|
746
|
+
chunks.push(chunk);
|
|
747
|
+
length += chunk.length;
|
|
748
|
+
}
|
|
749
|
+
if (!this.consumed) {
|
|
750
|
+
// The input ended before the string started: let the synchronous
|
|
751
|
+
// parser raise the usual error.
|
|
752
|
+
return this.read();
|
|
753
|
+
}
|
|
754
|
+
const bytes = new Uint8Array(length);
|
|
755
|
+
let offset = 0;
|
|
756
|
+
for (const chunk of chunks) {
|
|
757
|
+
bytes.set(chunk, offset);
|
|
758
|
+
offset += chunk.length;
|
|
759
|
+
}
|
|
760
|
+
return bytesToString(bytes);
|
|
761
|
+
}
|
|
585
762
|
/**
|
|
586
763
|
* Generator that yields the string content as chunks of strings.
|
|
587
764
|
*
|
|
@@ -864,6 +1041,11 @@ export class JsonObject extends JsonEntity {
|
|
|
864
1041
|
this.buffer.next(); // consume ,
|
|
865
1042
|
this.skipWhitespace();
|
|
866
1043
|
}
|
|
1044
|
+
// A trailing comma (JSONC) or a comment before the closing brace
|
|
1045
|
+
if (this.consumeClosing(BYTE_MAP.rightBrace)) {
|
|
1046
|
+
this.consumed = true;
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
867
1049
|
if (this.buffer.peek() === null) {
|
|
868
1050
|
throw new Error('Unterminated object in JSON input.');
|
|
869
1051
|
}
|
|
@@ -907,6 +1089,55 @@ export class JsonObject extends JsonEntity {
|
|
|
907
1089
|
await this.buffer.readStreamAsync();
|
|
908
1090
|
}
|
|
909
1091
|
}
|
|
1092
|
+
/**
|
|
1093
|
+
* Asynchronously reads the whole object from a stream.
|
|
1094
|
+
*
|
|
1095
|
+
* Reads member by member through {@link membersAsync}, so when more
|
|
1096
|
+
* input is needed only the current member is parsed again, not the
|
|
1097
|
+
* whole object.
|
|
1098
|
+
*
|
|
1099
|
+
* @returns A promise that resolves to the parsed object
|
|
1100
|
+
*/
|
|
1101
|
+
async readAsync() {
|
|
1102
|
+
if (this.consumed) {
|
|
1103
|
+
throw new Error('JSON entity has already been consumed.');
|
|
1104
|
+
}
|
|
1105
|
+
for await (const _ of this.preCommentsAsync) {
|
|
1106
|
+
}
|
|
1107
|
+
const obj = {};
|
|
1108
|
+
let members = this.members();
|
|
1109
|
+
while (true) {
|
|
1110
|
+
// Fast path: read a whole member synchronously if it is buffered
|
|
1111
|
+
const member = this.tryParse(() => {
|
|
1112
|
+
const next = members.next();
|
|
1113
|
+
if (next.done)
|
|
1114
|
+
return END;
|
|
1115
|
+
return {
|
|
1116
|
+
key: next.value.key.read(),
|
|
1117
|
+
value: next.value.value.readValue(),
|
|
1118
|
+
};
|
|
1119
|
+
});
|
|
1120
|
+
if (member === END)
|
|
1121
|
+
break;
|
|
1122
|
+
if (member !== undefined) {
|
|
1123
|
+
setOwnProperty(obj, member.key, member.value);
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
// Not buffered yet: restart at this member and read it
|
|
1127
|
+
// incrementally, so only the unfinished part waits for input.
|
|
1128
|
+
members = this.members();
|
|
1129
|
+
const next = await this.nextAsync(members, () => {
|
|
1130
|
+
members = this.members();
|
|
1131
|
+
return members;
|
|
1132
|
+
});
|
|
1133
|
+
if (next.done)
|
|
1134
|
+
break;
|
|
1135
|
+
const keyString = await next.value.key.readAsync();
|
|
1136
|
+
setOwnProperty(obj, keyString, await next.value.value.readValueAsync());
|
|
1137
|
+
}
|
|
1138
|
+
this.consumed = true;
|
|
1139
|
+
return obj;
|
|
1140
|
+
}
|
|
910
1141
|
/**
|
|
911
1142
|
* Returns an iterator for object members.
|
|
912
1143
|
* Enables use of for...of loops on JsonObject.
|
|
@@ -930,7 +1161,7 @@ export class JsonObject extends JsonEntity {
|
|
|
930
1161
|
const obj = {};
|
|
931
1162
|
for (const { key, value } of this.members()) {
|
|
932
1163
|
const keyString = key.read();
|
|
933
|
-
obj
|
|
1164
|
+
setOwnProperty(obj, keyString, value.readValue());
|
|
934
1165
|
}
|
|
935
1166
|
return obj;
|
|
936
1167
|
}
|
|
@@ -964,6 +1195,11 @@ export class JsonArray extends JsonEntity {
|
|
|
964
1195
|
this.buffer.next(); // consume ,
|
|
965
1196
|
this.skipWhitespace();
|
|
966
1197
|
}
|
|
1198
|
+
// A trailing comma (JSONC) or a comment before the closing bracket
|
|
1199
|
+
if (this.consumeClosing(BYTE_MAP.rightSquare)) {
|
|
1200
|
+
this.consumed = true;
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
967
1203
|
const valueObject = new JsonValue(this.buffer);
|
|
968
1204
|
yield valueObject;
|
|
969
1205
|
valueObject.consume();
|
|
@@ -996,6 +1232,48 @@ export class JsonArray extends JsonEntity {
|
|
|
996
1232
|
await this.buffer.readStreamAsync();
|
|
997
1233
|
}
|
|
998
1234
|
}
|
|
1235
|
+
/**
|
|
1236
|
+
* Asynchronously reads the whole array from a stream.
|
|
1237
|
+
*
|
|
1238
|
+
* Reads item by item through {@link itemsAsync}, so when more input is
|
|
1239
|
+
* needed only the current item is parsed again, not the whole array.
|
|
1240
|
+
*
|
|
1241
|
+
* @returns A promise that resolves to the parsed array
|
|
1242
|
+
*/
|
|
1243
|
+
async readAsync() {
|
|
1244
|
+
if (this.consumed) {
|
|
1245
|
+
throw new Error('JSON entity has already been consumed.');
|
|
1246
|
+
}
|
|
1247
|
+
for await (const _ of this.preCommentsAsync) {
|
|
1248
|
+
}
|
|
1249
|
+
const values = [];
|
|
1250
|
+
let items = this.items();
|
|
1251
|
+
while (true) {
|
|
1252
|
+
// Fast path: read a whole item synchronously if it is buffered
|
|
1253
|
+
const item = this.tryParse(() => {
|
|
1254
|
+
const next = items.next();
|
|
1255
|
+
return next.done ? END : { value: next.value.readValue() };
|
|
1256
|
+
});
|
|
1257
|
+
if (item === END)
|
|
1258
|
+
break;
|
|
1259
|
+
if (item !== undefined) {
|
|
1260
|
+
values.push(item.value);
|
|
1261
|
+
continue;
|
|
1262
|
+
}
|
|
1263
|
+
// Not buffered yet: restart at this item and read it
|
|
1264
|
+
// incrementally, so only the unfinished part waits for input.
|
|
1265
|
+
items = this.items();
|
|
1266
|
+
const next = await this.nextAsync(items, () => {
|
|
1267
|
+
items = this.items();
|
|
1268
|
+
return items;
|
|
1269
|
+
});
|
|
1270
|
+
if (next.done)
|
|
1271
|
+
break;
|
|
1272
|
+
values.push((await next.value.readValueAsync()));
|
|
1273
|
+
}
|
|
1274
|
+
this.consumed = true;
|
|
1275
|
+
return values;
|
|
1276
|
+
}
|
|
999
1277
|
/**
|
|
1000
1278
|
* Returns an iterator for array items.
|
|
1001
1279
|
* Enables use of for...of loops on JsonArray.
|
|
@@ -1023,6 +1301,204 @@ export class JsonArray extends JsonEntity {
|
|
|
1023
1301
|
return values;
|
|
1024
1302
|
}
|
|
1025
1303
|
}
|
|
1304
|
+
/**
|
|
1305
|
+
* Represents a JSON Lines (JSONL / NDJSON) document: a sequence of JSON values
|
|
1306
|
+
* separated by newlines. Provides streaming access to each line's value.
|
|
1307
|
+
*
|
|
1308
|
+
* @typeParam T - The expected type of each line's value
|
|
1309
|
+
*/
|
|
1310
|
+
export class JsonLines extends JsonEntity {
|
|
1311
|
+
valuesRead = 0;
|
|
1312
|
+
/**
|
|
1313
|
+
* When false (default), blank lines are silently ignored and several
|
|
1314
|
+
* values may share a line. When true, the input must follow the JSON Lines
|
|
1315
|
+
* format exactly: one value per line, no blank lines, and nothing after the
|
|
1316
|
+
* final line terminator. Violations throw an Error.
|
|
1317
|
+
*/
|
|
1318
|
+
strict = false;
|
|
1319
|
+
/**
|
|
1320
|
+
* Generator that yields one JsonValue per line. Blank lines are skipped
|
|
1321
|
+
* unless `strict` is set.
|
|
1322
|
+
*
|
|
1323
|
+
* @yields Each value entity in the document
|
|
1324
|
+
*/
|
|
1325
|
+
*items() {
|
|
1326
|
+
while (true) {
|
|
1327
|
+
let newlines = 0;
|
|
1328
|
+
while (isWhitespace(this.buffer.peek())) {
|
|
1329
|
+
if (this.buffer.next() === BYTE_MAP.lineFeed)
|
|
1330
|
+
newlines++;
|
|
1331
|
+
}
|
|
1332
|
+
const atEnd = this.buffer.peek() === null;
|
|
1333
|
+
if (this.strict) {
|
|
1334
|
+
// Exactly one terminator between values, none before the
|
|
1335
|
+
// first, and at most one after the last.
|
|
1336
|
+
const expected = this.valuesRead === 0 ? 0 : 1;
|
|
1337
|
+
if (newlines > expected) {
|
|
1338
|
+
throw new Error(`Blank line in JSON Lines input after value ${this.valuesRead}.`);
|
|
1339
|
+
}
|
|
1340
|
+
if (!atEnd && newlines < expected) {
|
|
1341
|
+
throw new Error(`Multiple values on one line in JSON Lines input after value ${this.valuesRead}.`);
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
if (atEnd) {
|
|
1345
|
+
this.consumed = true;
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
const valueObject = new JsonValue(this.buffer);
|
|
1349
|
+
yield valueObject;
|
|
1350
|
+
valueObject.consume();
|
|
1351
|
+
this.valuesRead++;
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
/**
|
|
1355
|
+
* Async generator that yields one JsonValue per line from a stream.
|
|
1356
|
+
*
|
|
1357
|
+
* @yields Each value entity in the document
|
|
1358
|
+
*/
|
|
1359
|
+
async *itemsAsync() {
|
|
1360
|
+
while (!this.buffer.atEof()) {
|
|
1361
|
+
const itemGen = this.items();
|
|
1362
|
+
while (true) {
|
|
1363
|
+
const current = this.tryParse(() => itemGen.next());
|
|
1364
|
+
if (current === undefined) {
|
|
1365
|
+
break; // Need more data
|
|
1366
|
+
}
|
|
1367
|
+
if (current.done) {
|
|
1368
|
+
return; // No more lines
|
|
1369
|
+
}
|
|
1370
|
+
yield current.value;
|
|
1371
|
+
await current.value.consumeAsync();
|
|
1372
|
+
}
|
|
1373
|
+
await this.buffer.readStreamAsync();
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
/**
|
|
1377
|
+
* Enables use of for...of loops on JsonLines.
|
|
1378
|
+
*/
|
|
1379
|
+
[Symbol.iterator]() {
|
|
1380
|
+
return this.items();
|
|
1381
|
+
}
|
|
1382
|
+
/**
|
|
1383
|
+
* Enables use of for await...of loops on JsonLines.
|
|
1384
|
+
*/
|
|
1385
|
+
[Symbol.asyncIterator]() {
|
|
1386
|
+
return this.itemsAsync();
|
|
1387
|
+
}
|
|
1388
|
+
/**
|
|
1389
|
+
* Parses the entire document into an array of values.
|
|
1390
|
+
*
|
|
1391
|
+
* @returns The parsed values, one per line
|
|
1392
|
+
*/
|
|
1393
|
+
parse() {
|
|
1394
|
+
const values = [];
|
|
1395
|
+
for (const value of this) {
|
|
1396
|
+
values.push(value.readValue());
|
|
1397
|
+
}
|
|
1398
|
+
return values;
|
|
1399
|
+
}
|
|
1400
|
+
/**
|
|
1401
|
+
* Serializes values as JSON Lines (JSONL / NDJSON) using json-stream-lite.
|
|
1402
|
+
* See `jsonLinesStringify` for more details.
|
|
1403
|
+
* @param indent - Ignored: JSON Lines output is never indented
|
|
1404
|
+
* @returns A generator yielding JSON Lines string chunks
|
|
1405
|
+
*/
|
|
1406
|
+
static stringify(values, replacer, indent = 0, options) {
|
|
1407
|
+
return jsonLinesStringify(values, replacer, options);
|
|
1408
|
+
}
|
|
1409
|
+
/**
|
|
1410
|
+
* Serializes values as JSON Lines as Uint8Array byte chunks using json-stream-lite.
|
|
1411
|
+
* See `jsonLinesStringifyBytes` for more details.
|
|
1412
|
+
* @param indent - Ignored: JSON Lines output is never indented
|
|
1413
|
+
* @returns A generator yielding JSON Lines byte chunks
|
|
1414
|
+
*/
|
|
1415
|
+
static stringifyBytes(values, replacer, indent = 0, options) {
|
|
1416
|
+
return jsonLinesStringifyBytes(values, replacer, options);
|
|
1417
|
+
}
|
|
1418
|
+
/**
|
|
1419
|
+
* Asynchronously serializes values as JSON Lines using json-stream-lite.
|
|
1420
|
+
* See `jsonLinesStringifyAsync` for more details.
|
|
1421
|
+
* @param indent - Ignored: JSON Lines output is never indented
|
|
1422
|
+
* @returns An async generator yielding JSON Lines string chunks
|
|
1423
|
+
* */
|
|
1424
|
+
static stringifyAsync(values, replacer, indent = 0, options) {
|
|
1425
|
+
return jsonLinesStringifyAsync(values, replacer, options);
|
|
1426
|
+
}
|
|
1427
|
+
/**
|
|
1428
|
+
* Asynchronously serializes values as JSON Lines as Uint8Array byte chunks using json-stream-lite.
|
|
1429
|
+
* See `jsonLinesStringifyBytesAsync` for more details.
|
|
1430
|
+
* @param indent - Ignored: JSON Lines output is never indented
|
|
1431
|
+
* @returns An async generator yielding JSON Lines byte chunks
|
|
1432
|
+
* */
|
|
1433
|
+
static stringifyBytesAsync(values, replacer, indent = 0, options) {
|
|
1434
|
+
return jsonLinesStringifyBytesAsync(values, replacer, options);
|
|
1435
|
+
}
|
|
1436
|
+
/**
|
|
1437
|
+
* Asynchronously reads the entire document into an array of values.
|
|
1438
|
+
*
|
|
1439
|
+
* Reads line by line: a value that is fully buffered is read
|
|
1440
|
+
* synchronously, one that is not is read incrementally, so a refill
|
|
1441
|
+
* re-parses at most the unfinished value and the buffer stays near
|
|
1442
|
+
* `maxBufferSize`. Retrying the whole document instead would re-run the
|
|
1443
|
+
* strict-mode checks with a stale line count.
|
|
1444
|
+
*
|
|
1445
|
+
* @returns The parsed values, one per line
|
|
1446
|
+
*/
|
|
1447
|
+
async readAsync() {
|
|
1448
|
+
if (this.consumed) {
|
|
1449
|
+
throw new Error('JSON entity has already been consumed.');
|
|
1450
|
+
}
|
|
1451
|
+
// Unlike JsonArray, leading whitespace is left to items(): skipping
|
|
1452
|
+
// it here would hide a blank first line from strict mode.
|
|
1453
|
+
const values = [];
|
|
1454
|
+
let items = this.items();
|
|
1455
|
+
while (true) {
|
|
1456
|
+
// Fast path: read a whole value synchronously if it is buffered
|
|
1457
|
+
const item = this.tryParse(() => {
|
|
1458
|
+
const next = items.next();
|
|
1459
|
+
return next.done ? END : { value: next.value.readValue() };
|
|
1460
|
+
});
|
|
1461
|
+
if (item === END)
|
|
1462
|
+
break;
|
|
1463
|
+
if (item !== undefined) {
|
|
1464
|
+
values.push(item.value);
|
|
1465
|
+
continue;
|
|
1466
|
+
}
|
|
1467
|
+
// Not buffered yet: restart at this value and read it
|
|
1468
|
+
// incrementally, so only the unfinished part waits for input.
|
|
1469
|
+
items = this.items();
|
|
1470
|
+
const next = await this.nextAsync(items, () => {
|
|
1471
|
+
items = this.items();
|
|
1472
|
+
return items;
|
|
1473
|
+
});
|
|
1474
|
+
if (next.done)
|
|
1475
|
+
break;
|
|
1476
|
+
values.push((await next.value.readValueAsync()));
|
|
1477
|
+
}
|
|
1478
|
+
this.consumed = true;
|
|
1479
|
+
return values;
|
|
1480
|
+
}
|
|
1481
|
+
/**
|
|
1482
|
+
* Reads the entire document into an array of values.
|
|
1483
|
+
*
|
|
1484
|
+
* @returns The parsed values, one per line
|
|
1485
|
+
*/
|
|
1486
|
+
read() {
|
|
1487
|
+
if (this.strict && this.valuesRead === 0) {
|
|
1488
|
+
// The base read() skips leading whitespace, which would hide a
|
|
1489
|
+
// blank first line from items().
|
|
1490
|
+
let ahead = 0;
|
|
1491
|
+
let byte = this.buffer.peek(ahead);
|
|
1492
|
+
while (isWhitespace(byte)) {
|
|
1493
|
+
if (byte === BYTE_MAP.lineFeed) {
|
|
1494
|
+
throw new Error('Blank line in JSON Lines input after value 0.');
|
|
1495
|
+
}
|
|
1496
|
+
byte = this.buffer.peek(++ahead);
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
return super.read();
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1026
1502
|
/**
|
|
1027
1503
|
* Parser that flattens nested JSON structures into key-value pairs.
|
|
1028
1504
|
* Useful for extracting specific values from complex JSON without parsing the entire structure.
|
package/dist/stringify.d.ts
CHANGED
|
@@ -56,3 +56,29 @@ export declare function jsonStreamStringify(value: unknown, replacer?: any, inde
|
|
|
56
56
|
export declare function jsonStreamStringifyBytes(value: unknown, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<Uint8Array>;
|
|
57
57
|
export declare function jsonStreamStringifyAsync(value: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<string>;
|
|
58
58
|
export declare function jsonStreamStringifyBytesAsync(value: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): AsyncGenerator<Uint8Array>;
|
|
59
|
+
/**
|
|
60
|
+
* Serializes values as JSON Lines (JSONL / NDJSON): one compact JSON value per
|
|
61
|
+
* line, each terminated by a newline. Values with no JSON representation
|
|
62
|
+
* (undefined, functions) are written as `null`. The `jsonc` option is ignored.
|
|
63
|
+
*
|
|
64
|
+
* @param values - The values to serialize, one per line
|
|
65
|
+
* @param replacer - Optional replacer function or array
|
|
66
|
+
* @param options - Additional stringification options
|
|
67
|
+
* @returns Generator yielding string chunks
|
|
68
|
+
*/
|
|
69
|
+
export declare function jsonLinesStringify(values: Iterable<unknown>, replacer?: any, options?: JsonStreamStringifyOptions): Generator<string>;
|
|
70
|
+
/**
|
|
71
|
+
* Serializes values as JSON Lines, yielding Uint8Array chunks.
|
|
72
|
+
* See {@link jsonLinesStringify}.
|
|
73
|
+
*/
|
|
74
|
+
export declare function jsonLinesStringifyBytes(values: Iterable<unknown>, replacer?: any, options?: JsonStreamStringifyOptions): Generator<Uint8Array>;
|
|
75
|
+
/**
|
|
76
|
+
* Asynchronously serializes values (sync or async iterable) as JSON Lines.
|
|
77
|
+
* See {@link jsonLinesStringify}.
|
|
78
|
+
*/
|
|
79
|
+
export declare function jsonLinesStringifyAsync(values: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, options?: JsonStreamStringifyOptions): AsyncGenerator<string>;
|
|
80
|
+
/**
|
|
81
|
+
* Asynchronously serializes values as JSON Lines, yielding Uint8Array chunks.
|
|
82
|
+
* See {@link jsonLinesStringify}.
|
|
83
|
+
*/
|
|
84
|
+
export declare function jsonLinesStringifyBytesAsync(values: AsyncIterable<unknown> | Iterable<unknown>, replacer?: any, options?: JsonStreamStringifyOptions): AsyncGenerator<Uint8Array>;
|
package/dist/stringify.js
CHANGED
|
@@ -58,24 +58,66 @@ function* formatString(str, chunkSize = 1024) {
|
|
|
58
58
|
i += chunkSize;
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
|
+
function createContext(replacer, options) {
|
|
62
|
+
if (typeof replacer === 'function') {
|
|
63
|
+
return {
|
|
64
|
+
replacerFn: replacer,
|
|
65
|
+
options,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
if (Array.isArray(replacer)) {
|
|
69
|
+
// Strings and numbers (or their wrapper objects) name properties
|
|
70
|
+
const propertyList = [];
|
|
71
|
+
for (const item of replacer) {
|
|
72
|
+
if (typeof item === 'string' ||
|
|
73
|
+
typeof item === 'number' ||
|
|
74
|
+
item instanceof String ||
|
|
75
|
+
item instanceof Number) {
|
|
76
|
+
const key = String(item);
|
|
77
|
+
if (!propertyList.includes(key))
|
|
78
|
+
propertyList.push(key);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return { propertyList, options };
|
|
82
|
+
}
|
|
83
|
+
return { options };
|
|
84
|
+
}
|
|
61
85
|
/**
|
|
62
|
-
*
|
|
63
|
-
*
|
|
86
|
+
* Whether a value has no JSON representation (undefined, functions and
|
|
87
|
+
* symbols). Such values are left out of objects and written as `null` in
|
|
88
|
+
* arrays.
|
|
64
89
|
*
|
|
65
90
|
* @param value - The value to check
|
|
66
|
-
* @returns True if the value
|
|
91
|
+
* @returns True if the value has no JSON representation
|
|
67
92
|
*/
|
|
68
|
-
function
|
|
69
|
-
return
|
|
93
|
+
function hasNoJsonValue(value) {
|
|
94
|
+
return (value === undefined ||
|
|
95
|
+
typeof value === 'function' ||
|
|
96
|
+
typeof value === 'symbol');
|
|
70
97
|
}
|
|
71
98
|
/**
|
|
72
|
-
*
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
*
|
|
99
|
+
* Works out the value to write for `holder[key]`, in the same order as
|
|
100
|
+
* `JSON.stringify`: `toJSON(key)` first, then the replacer function (called
|
|
101
|
+
* with `holder` as `this`). An object with its own `toString()` is then
|
|
102
|
+
* written as that string.
|
|
76
103
|
*/
|
|
77
|
-
function
|
|
78
|
-
|
|
104
|
+
function resolveValue(holder, key, value, context) {
|
|
105
|
+
if ((typeof value === 'object' && value !== null) ||
|
|
106
|
+
typeof value === 'bigint') {
|
|
107
|
+
const toJSON = value.toJSON;
|
|
108
|
+
if (typeof toJSON === 'function') {
|
|
109
|
+
value = toJSON.call(value, key);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (context.replacerFn) {
|
|
113
|
+
value = context.replacerFn.call(holder, key, value);
|
|
114
|
+
}
|
|
115
|
+
if (value &&
|
|
116
|
+
typeof value === 'object' &&
|
|
117
|
+
hasCustomToStringFunction(value)) {
|
|
118
|
+
value = value.toString();
|
|
119
|
+
}
|
|
120
|
+
return value;
|
|
79
121
|
}
|
|
80
122
|
/**
|
|
81
123
|
* Type guard to check if an object has a custom toString method.
|
|
@@ -110,30 +152,19 @@ function* emitComments(path, options, indentStr) {
|
|
|
110
152
|
}
|
|
111
153
|
}
|
|
112
154
|
/**
|
|
113
|
-
* Internal recursive function that stringifies
|
|
114
|
-
*
|
|
155
|
+
* Internal recursive function that stringifies an already resolved value
|
|
156
|
+
* (see {@link resolveValue}) with depth tracking.
|
|
115
157
|
*
|
|
116
158
|
* @param value - The value to stringify
|
|
117
|
-
* @param
|
|
159
|
+
* @param context - Replacer and options
|
|
118
160
|
* @param indent - Number of spaces for indentation (0 for compact)
|
|
119
161
|
* @param currentDepth - Current nesting depth for indentation
|
|
120
162
|
* @param start - Indicates if this is the start of the stringification
|
|
121
|
-
* @param options - Stringification options
|
|
122
163
|
* @param currentPath - Current dot-notation path for comment matching
|
|
123
164
|
* @yields String chunks representing the JSON output
|
|
124
165
|
*/
|
|
125
|
-
function*
|
|
126
|
-
|
|
127
|
-
value = replacer('', value);
|
|
128
|
-
}
|
|
129
|
-
if (value && typeof value === 'object') {
|
|
130
|
-
if (hasCustomToJsonFunction(value)) {
|
|
131
|
-
value = value.toJSON();
|
|
132
|
-
}
|
|
133
|
-
else if (hasCustomToStringFunction(value)) {
|
|
134
|
-
value = value.toString();
|
|
135
|
-
}
|
|
136
|
-
}
|
|
166
|
+
function* stringifyValue(value, context, indent = 0, currentDepth = 0, start = true, currentPath = '') {
|
|
167
|
+
const options = context.options;
|
|
137
168
|
// If this is the first call and indenting, add initial indentation
|
|
138
169
|
if (start && indent > 0 && currentDepth > 0) {
|
|
139
170
|
yield ' '.repeat(indent * currentDepth);
|
|
@@ -150,6 +181,10 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
|
|
|
150
181
|
else if (typeof value === 'string') {
|
|
151
182
|
yield* formatString(value, options?.stringChunkSize);
|
|
152
183
|
}
|
|
184
|
+
else if (typeof value === 'bigint') {
|
|
185
|
+
// As JSON.stringify: JSON has no BigInt type
|
|
186
|
+
throw new TypeError('Do not know how to serialize a BigInt');
|
|
187
|
+
}
|
|
153
188
|
else if (Array.isArray(value)) {
|
|
154
189
|
const len = value.length;
|
|
155
190
|
const valueIndent = indent * (currentDepth + 1);
|
|
@@ -157,7 +192,7 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
|
|
|
157
192
|
const isJsonc = options?.jsonc === true;
|
|
158
193
|
yield '[';
|
|
159
194
|
for (let i = 0; i < len; i++) {
|
|
160
|
-
const next = value[i];
|
|
195
|
+
const next = resolveValue(value, String(i), value[i], context);
|
|
161
196
|
const isLast = i === len - 1;
|
|
162
197
|
if (i > 0) {
|
|
163
198
|
yield ',';
|
|
@@ -168,14 +203,14 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
|
|
|
168
203
|
yield* emitComments(itemPath, options, valueIndentStr);
|
|
169
204
|
yield valueIndentStr;
|
|
170
205
|
}
|
|
171
|
-
if (
|
|
206
|
+
if (hasNoJsonValue(next)) {
|
|
172
207
|
yield 'null';
|
|
173
208
|
if (isLast && isJsonc)
|
|
174
209
|
yield ',';
|
|
175
210
|
continue;
|
|
176
211
|
}
|
|
177
212
|
const itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;
|
|
178
|
-
yield*
|
|
213
|
+
yield* stringifyValue(next, context, indent > 0 ? indent : 0, currentDepth + 1, false, itemPath);
|
|
179
214
|
if (isLast && isJsonc)
|
|
180
215
|
yield ',';
|
|
181
216
|
}
|
|
@@ -185,20 +220,18 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
|
|
|
185
220
|
yield ']';
|
|
186
221
|
}
|
|
187
222
|
else if (typeof value === 'object') {
|
|
188
|
-
const
|
|
189
|
-
const
|
|
223
|
+
const object = value;
|
|
224
|
+
const keys = context.propertyList ?? Object.keys(object);
|
|
190
225
|
const valueIndent = indent * (currentDepth + 1);
|
|
191
226
|
const valueIndentStr = indent > 0 ? ' '.repeat(valueIndent) : '';
|
|
192
227
|
const isJsonc = options?.jsonc === true;
|
|
193
228
|
let count = 0;
|
|
194
|
-
// Count non-ignored keys for trailing comma logic
|
|
195
|
-
const validKeys = keys.filter((k) => !shouldIgnore(value[k]));
|
|
196
|
-
const totalValid = validKeys.length;
|
|
197
229
|
yield '{';
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
230
|
+
// Members are resolved one at a time, in order, so a replacer is
|
|
231
|
+
// called depth-first as with JSON.stringify.
|
|
232
|
+
for (const key of keys) {
|
|
233
|
+
const next = resolveValue(object, key, object[key], context);
|
|
234
|
+
if (hasNoJsonValue(next)) {
|
|
202
235
|
continue;
|
|
203
236
|
}
|
|
204
237
|
if (count > 0) {
|
|
@@ -212,12 +245,13 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
|
|
|
212
245
|
}
|
|
213
246
|
yield* formatString(key, options?.stringChunkSize);
|
|
214
247
|
yield `:${indent > 0 ? ' ' : ''}`;
|
|
215
|
-
yield*
|
|
248
|
+
yield* stringifyValue(next, context, indent > 0 ? indent : 0, currentDepth + 1, false, memberPath);
|
|
216
249
|
count++;
|
|
217
|
-
if (count === totalValid && isJsonc)
|
|
218
|
-
yield ',';
|
|
219
250
|
}
|
|
220
|
-
|
|
251
|
+
// JSONC: trailing comma after the last member that was written
|
|
252
|
+
if (count > 0 && isJsonc)
|
|
253
|
+
yield ',';
|
|
254
|
+
if (indent > 0 && count > 0) {
|
|
221
255
|
yield '\n' + ' '.repeat(indent * currentDepth);
|
|
222
256
|
}
|
|
223
257
|
yield '}';
|
|
@@ -242,7 +276,16 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
|
|
|
242
276
|
* ```
|
|
243
277
|
*/
|
|
244
278
|
export function jsonStreamStringify(value, replacer, indent = 0, options) {
|
|
245
|
-
return
|
|
279
|
+
return jsonStreamStringifyRoot(value, replacer, indent, options);
|
|
280
|
+
}
|
|
281
|
+
function* jsonStreamStringifyRoot(value, replacer, indent, options) {
|
|
282
|
+
const context = createContext(replacer, options);
|
|
283
|
+
// As JSON.stringify, the root is resolved with key '' on a wrapper object
|
|
284
|
+
const resolved = resolveValue({ '': value }, '', value, context);
|
|
285
|
+
// A root with no JSON representation (e.g. undefined) produces no output
|
|
286
|
+
if (hasNoJsonValue(resolved))
|
|
287
|
+
return;
|
|
288
|
+
yield* stringifyValue(resolved, context, indent, 0, true);
|
|
246
289
|
}
|
|
247
290
|
/**
|
|
248
291
|
* Converts a JavaScript value to JSON format, yielding Uint8Array byte chunks.
|
|
@@ -269,12 +312,23 @@ export function* jsonStreamStringifyBytes(value, replacer, indent = 0, options)
|
|
|
269
312
|
}
|
|
270
313
|
}
|
|
271
314
|
export async function* jsonStreamStringifyAsync(value, replacer, indent = 0, options) {
|
|
315
|
+
const context = createContext(replacer, options);
|
|
272
316
|
yield '[';
|
|
273
317
|
if (indent > 0)
|
|
274
318
|
yield '\n';
|
|
275
319
|
let isFirst = true;
|
|
320
|
+
let index = 0;
|
|
276
321
|
for await (const item of value) {
|
|
277
|
-
|
|
322
|
+
// Each item is resolved as an array element, with its index as key.
|
|
323
|
+
// There is no array to pass as the replacer's `this`.
|
|
324
|
+
const resolved = resolveValue(undefined, String(index++), item, context);
|
|
325
|
+
const stringGenerator = hasNoJsonValue(resolved)
|
|
326
|
+
? (function* () {
|
|
327
|
+
if (indent > 0)
|
|
328
|
+
yield ' '.repeat(indent);
|
|
329
|
+
yield 'null';
|
|
330
|
+
})()
|
|
331
|
+
: stringifyValue(resolved, context, indent, 1, true);
|
|
278
332
|
if (!isFirst) {
|
|
279
333
|
yield ',';
|
|
280
334
|
if (indent > 0)
|
|
@@ -296,3 +350,60 @@ export async function* jsonStreamStringifyBytesAsync(value, replacer, indent = 0
|
|
|
296
350
|
yield stringToBytes(chunk);
|
|
297
351
|
}
|
|
298
352
|
}
|
|
353
|
+
/**
|
|
354
|
+
* Serializes a single JSON Lines record. Values with no JSON representation
|
|
355
|
+
* (undefined, functions) are written as `null` so every input value produces
|
|
356
|
+
* exactly one line.
|
|
357
|
+
*/
|
|
358
|
+
function* jsonLinesStringifyLine(value, replacer, options) {
|
|
359
|
+
let empty = true;
|
|
360
|
+
// Every line must be a plain JSON value, so JSONC output is never used.
|
|
361
|
+
const lineOptions = options?.jsonc ? { ...options, jsonc: false } : options;
|
|
362
|
+
for (const chunk of jsonStreamStringify(value, replacer, 0, lineOptions)) {
|
|
363
|
+
empty = false;
|
|
364
|
+
yield chunk;
|
|
365
|
+
}
|
|
366
|
+
yield empty ? 'null\n' : '\n';
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Serializes values as JSON Lines (JSONL / NDJSON): one compact JSON value per
|
|
370
|
+
* line, each terminated by a newline. Values with no JSON representation
|
|
371
|
+
* (undefined, functions) are written as `null`. The `jsonc` option is ignored.
|
|
372
|
+
*
|
|
373
|
+
* @param values - The values to serialize, one per line
|
|
374
|
+
* @param replacer - Optional replacer function or array
|
|
375
|
+
* @param options - Additional stringification options
|
|
376
|
+
* @returns Generator yielding string chunks
|
|
377
|
+
*/
|
|
378
|
+
export function* jsonLinesStringify(values, replacer, options) {
|
|
379
|
+
for (const value of values) {
|
|
380
|
+
yield* jsonLinesStringifyLine(value, replacer, options);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Serializes values as JSON Lines, yielding Uint8Array chunks.
|
|
385
|
+
* See {@link jsonLinesStringify}.
|
|
386
|
+
*/
|
|
387
|
+
export function* jsonLinesStringifyBytes(values, replacer, options) {
|
|
388
|
+
for (const chunk of jsonLinesStringify(values, replacer, options)) {
|
|
389
|
+
yield stringToBytes(chunk);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Asynchronously serializes values (sync or async iterable) as JSON Lines.
|
|
394
|
+
* See {@link jsonLinesStringify}.
|
|
395
|
+
*/
|
|
396
|
+
export async function* jsonLinesStringifyAsync(values, replacer, options) {
|
|
397
|
+
for await (const value of values) {
|
|
398
|
+
yield* jsonLinesStringifyLine(value, replacer, options);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Asynchronously serializes values as JSON Lines, yielding Uint8Array chunks.
|
|
403
|
+
* See {@link jsonLinesStringify}.
|
|
404
|
+
*/
|
|
405
|
+
export async function* jsonLinesStringifyBytesAsync(values, replacer, options) {
|
|
406
|
+
for await (const chunk of jsonLinesStringifyAsync(values, replacer, options)) {
|
|
407
|
+
yield stringToBytes(chunk);
|
|
408
|
+
}
|
|
409
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "json-stream-lite",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.3",
|
|
4
4
|
"description": "A lightweight, memory-efficient, zero-dependency streaming JSON parser and stringifier for JavaScript and TypeScript. It works in both Node.js and browser environments.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"@vitest/browser": "^5.0.0",
|
|
54
54
|
"@vitest/browser-playwright": "^5.0.0",
|
|
55
55
|
"@vitest/coverage-v8": "^5.0.0",
|
|
56
|
-
"playwright": "^1.
|
|
56
|
+
"playwright": "^1.65.1",
|
|
57
57
|
"typescript": "^6.0.2",
|
|
58
58
|
"vitest": "^5.0.0"
|
|
59
59
|
},
|