json-stream-lite 1.0.11 → 1.0.12
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/dist/byte-buffer.d.ts +38 -0
- package/dist/byte-buffer.js +44 -0
- package/dist/generators.d.ts +31 -0
- package/dist/generators.js +31 -0
- package/dist/parser.d.ts +250 -0
- package/dist/parser.js +265 -0
- package/dist/stringify.d.ts +40 -0
- package/dist/stringify.js +78 -0
- package/dist/types.d.ts +15 -0
- package/dist/utils.d.ts +18 -0
- package/dist/utils.js +18 -0
- package/package.json +1 -1
package/dist/byte-buffer.d.ts
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
1
|
import type { ByteStream, JsonStreamInput } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Error thrown when the buffer is empty and more input is needed.
|
|
4
|
+
*/
|
|
2
5
|
export declare class NoMoreTokensError extends Error {
|
|
3
6
|
}
|
|
7
|
+
/**
|
|
8
|
+
* Error thrown when the end of file has been reached and no more items are available.
|
|
9
|
+
*/
|
|
4
10
|
export declare class EofReachedError extends Error {
|
|
5
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* A buffer for managing byte-level input with support for async streams.
|
|
14
|
+
* Provides lookahead, consumption tracking, and buffer compaction capabilities.
|
|
15
|
+
*/
|
|
6
16
|
export declare class ByteBuffer {
|
|
7
17
|
/** Maximum size of the buffer before compaction */
|
|
8
18
|
maxBufferSize: number;
|
|
@@ -20,8 +30,22 @@ export declare class ByteBuffer {
|
|
|
20
30
|
protected buffer: number[];
|
|
21
31
|
/** Optional async iterable input source */
|
|
22
32
|
protected asyncIterable?: ByteStream;
|
|
33
|
+
/**
|
|
34
|
+
* Creates a new ByteBuffer instance.
|
|
35
|
+
*
|
|
36
|
+
* @param asyncIterable - Optional async iterable source for streaming input
|
|
37
|
+
*/
|
|
23
38
|
constructor(asyncIterable?: ByteStream);
|
|
39
|
+
/**
|
|
40
|
+
* Reads data from the async stream into the buffer.
|
|
41
|
+
* Reads up to maxBufferSize bytes at a time.
|
|
42
|
+
*/
|
|
24
43
|
readStream(): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Gets the current length of the buffer.
|
|
46
|
+
*
|
|
47
|
+
* @returns The number of bytes in the buffer
|
|
48
|
+
*/
|
|
25
49
|
get length(): number;
|
|
26
50
|
/**
|
|
27
51
|
* Feeds input items into the parser buffer.
|
|
@@ -71,6 +95,20 @@ export declare class ByteBuffer {
|
|
|
71
95
|
* @returns boolean indicating whether to compact the buffer
|
|
72
96
|
*/
|
|
73
97
|
canCompact(): boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Attempts to execute a function, resetting buffer position on failure.
|
|
100
|
+
* Useful for speculative parsing attempts that may need to be retried.
|
|
101
|
+
*
|
|
102
|
+
* @typeParam T - The return type of the try function
|
|
103
|
+
* @param tryFn - Function to attempt execution
|
|
104
|
+
* @param onFail - Optional callback invoked on failure
|
|
105
|
+
* @returns The result of tryFn if successful, undefined if NoMoreTokensError thrown
|
|
106
|
+
*/
|
|
74
107
|
resetOnFail<T>(tryFn: () => T, onFail?: (e: Error) => void): T | undefined;
|
|
108
|
+
/**
|
|
109
|
+
* Returns a string representation of the buffer state for debugging.
|
|
110
|
+
*
|
|
111
|
+
* @returns A formatted string showing buffer contents and state
|
|
112
|
+
*/
|
|
75
113
|
toString(): string;
|
|
76
114
|
}
|
package/dist/byte-buffer.js
CHANGED
|
@@ -1,10 +1,26 @@
|
|
|
1
1
|
import { bytesToString } from './utils.js';
|
|
2
|
+
/**
|
|
3
|
+
* Shared TextEncoder instance for converting strings to UTF-8 bytes.
|
|
4
|
+
*/
|
|
2
5
|
const textEncoder = new TextEncoder();
|
|
6
|
+
/**
|
|
7
|
+
* Default maximum buffer size before compaction
|
|
8
|
+
*/
|
|
3
9
|
const DEFAULT_MAX_BUFFER_SIZE = 1024 * 100; // 100 KB
|
|
10
|
+
/**
|
|
11
|
+
* Error thrown when the buffer is empty and more input is needed.
|
|
12
|
+
*/
|
|
4
13
|
export class NoMoreTokensError extends Error {
|
|
5
14
|
}
|
|
15
|
+
/**
|
|
16
|
+
* Error thrown when the end of file has been reached and no more items are available.
|
|
17
|
+
*/
|
|
6
18
|
export class EofReachedError extends Error {
|
|
7
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* A buffer for managing byte-level input with support for async streams.
|
|
22
|
+
* Provides lookahead, consumption tracking, and buffer compaction capabilities.
|
|
23
|
+
*/
|
|
8
24
|
export class ByteBuffer {
|
|
9
25
|
/** Maximum size of the buffer before compaction */
|
|
10
26
|
maxBufferSize = DEFAULT_MAX_BUFFER_SIZE;
|
|
@@ -22,9 +38,18 @@ export class ByteBuffer {
|
|
|
22
38
|
buffer = [];
|
|
23
39
|
/** Optional async iterable input source */
|
|
24
40
|
asyncIterable;
|
|
41
|
+
/**
|
|
42
|
+
* Creates a new ByteBuffer instance.
|
|
43
|
+
*
|
|
44
|
+
* @param asyncIterable - Optional async iterable source for streaming input
|
|
45
|
+
*/
|
|
25
46
|
constructor(asyncIterable) {
|
|
26
47
|
this.asyncIterable = asyncIterable;
|
|
27
48
|
}
|
|
49
|
+
/**
|
|
50
|
+
* Reads data from the async stream into the buffer.
|
|
51
|
+
* Reads up to maxBufferSize bytes at a time.
|
|
52
|
+
*/
|
|
28
53
|
async readStream() {
|
|
29
54
|
if (!this.asyncIterable) {
|
|
30
55
|
return;
|
|
@@ -41,6 +66,11 @@ export class ByteBuffer {
|
|
|
41
66
|
i++;
|
|
42
67
|
}
|
|
43
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* Gets the current length of the buffer.
|
|
71
|
+
*
|
|
72
|
+
* @returns The number of bytes in the buffer
|
|
73
|
+
*/
|
|
44
74
|
get length() {
|
|
45
75
|
return this.buffer.length;
|
|
46
76
|
}
|
|
@@ -148,6 +178,15 @@ export class ByteBuffer {
|
|
|
148
178
|
canCompact() {
|
|
149
179
|
return this.bufferIndex > this.maxBufferSize;
|
|
150
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Attempts to execute a function, resetting buffer position on failure.
|
|
183
|
+
* Useful for speculative parsing attempts that may need to be retried.
|
|
184
|
+
*
|
|
185
|
+
* @typeParam T - The return type of the try function
|
|
186
|
+
* @param tryFn - Function to attempt execution
|
|
187
|
+
* @param onFail - Optional callback invoked on failure
|
|
188
|
+
* @returns The result of tryFn if successful, undefined if NoMoreTokensError thrown
|
|
189
|
+
*/
|
|
151
190
|
resetOnFail(tryFn, onFail) {
|
|
152
191
|
const bufferIndex = this.bufferIndex;
|
|
153
192
|
try {
|
|
@@ -168,6 +207,11 @@ export class ByteBuffer {
|
|
|
168
207
|
}
|
|
169
208
|
return undefined;
|
|
170
209
|
}
|
|
210
|
+
/**
|
|
211
|
+
* Returns a string representation of the buffer state for debugging.
|
|
212
|
+
*
|
|
213
|
+
* @returns A formatted string showing buffer contents and state
|
|
214
|
+
*/
|
|
171
215
|
toString() {
|
|
172
216
|
return [
|
|
173
217
|
'ByteBuffer {',
|
package/dist/generators.d.ts
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
1
|
import { JsonKeyValuePair } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Parses JSON input and yields key-value pairs for all primitive values.
|
|
4
|
+
* Flattens nested structures using dot notation and array indices.
|
|
5
|
+
*
|
|
6
|
+
* @param bytes - The JSON input as bytes or string
|
|
7
|
+
* @yields Key-value pairs as [key, value] tuples
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* const json = '{"user": {"name": "John", "age": 30}}';
|
|
12
|
+
* for (const [key, value] of jsonKeyValueParser(json)) {
|
|
13
|
+
* console.log(`${key}: ${value}`);
|
|
14
|
+
* // Output: "user.name: John", "user.age: 30"
|
|
15
|
+
* }
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
2
18
|
export declare function jsonKeyValueParser(bytes: Iterable<number> | string): Generator<JsonKeyValuePair>;
|
|
19
|
+
/**
|
|
20
|
+
* Asynchronously parses JSON input from various sources and yields key-value pairs.
|
|
21
|
+
* Supports streaming from async iterables and ReadableStreams for memory-efficient parsing.
|
|
22
|
+
*
|
|
23
|
+
* @param bytes - The JSON input as bytes, string, or stream
|
|
24
|
+
* @yields Key-value pairs as [key, value] tuples
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```typescript
|
|
28
|
+
* const stream = fs.createReadStream('large.json');
|
|
29
|
+
* for await (const [key, value] of jsonKeyValueParserAsync(stream)) {
|
|
30
|
+
* console.log(`${key}: ${value}`);
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
3
34
|
export declare function jsonKeyValueParserAsync(bytes: Iterable<number> | AsyncIterable<number> | string | ReadableStream<number> | ReadableStream<Uint8Array> | ReadableStream<string>): AsyncGenerator<JsonKeyValuePair>;
|
package/dist/generators.js
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
import { JsonKeyValueParser } from './parser.js';
|
|
2
2
|
import { stringToBytes } from './utils.js';
|
|
3
|
+
/**
|
|
4
|
+
* Parses JSON input and yields key-value pairs for all primitive values.
|
|
5
|
+
* Flattens nested structures using dot notation and array indices.
|
|
6
|
+
*
|
|
7
|
+
* @param bytes - The JSON input as bytes or string
|
|
8
|
+
* @yields Key-value pairs as [key, value] tuples
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* const json = '{"user": {"name": "John", "age": 30}}';
|
|
13
|
+
* for (const [key, value] of jsonKeyValueParser(json)) {
|
|
14
|
+
* console.log(`${key}: ${value}`);
|
|
15
|
+
* // Output: "user.name: John", "user.age: 30"
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
3
19
|
export function* jsonKeyValueParser(bytes) {
|
|
4
20
|
if (typeof bytes === 'string') {
|
|
5
21
|
bytes = stringToBytes(bytes);
|
|
@@ -10,6 +26,21 @@ export function* jsonKeyValueParser(bytes) {
|
|
|
10
26
|
}
|
|
11
27
|
yield* parser.parse();
|
|
12
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Asynchronously parses JSON input from various sources and yields key-value pairs.
|
|
31
|
+
* Supports streaming from async iterables and ReadableStreams for memory-efficient parsing.
|
|
32
|
+
*
|
|
33
|
+
* @param bytes - The JSON input as bytes, string, or stream
|
|
34
|
+
* @yields Key-value pairs as [key, value] tuples
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* const stream = fs.createReadStream('large.json');
|
|
39
|
+
* for await (const [key, value] of jsonKeyValueParserAsync(stream)) {
|
|
40
|
+
* console.log(`${key}: ${value}`);
|
|
41
|
+
* }
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
13
44
|
export async function* jsonKeyValueParserAsync(bytes) {
|
|
14
45
|
if (typeof bytes === 'string') {
|
|
15
46
|
bytes = stringToBytes(bytes);
|
package/dist/parser.d.ts
CHANGED
|
@@ -1,79 +1,329 @@
|
|
|
1
1
|
import { ByteBuffer } from './byte-buffer.js';
|
|
2
2
|
import { ByteStream, JsonKeyValuePair, JsonStreamInput } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Abstract base class for all JSON entities.
|
|
5
|
+
* Provides common functionality for parsing, reading, and consuming JSON values.
|
|
6
|
+
*
|
|
7
|
+
* @typeParam T - The type of value this entity represents
|
|
8
|
+
*/
|
|
3
9
|
export declare abstract class JsonEntity<T> {
|
|
4
10
|
consumed: boolean;
|
|
5
11
|
protected buffer: ByteBuffer;
|
|
12
|
+
/**
|
|
13
|
+
* Creates a new JSON entity.
|
|
14
|
+
*
|
|
15
|
+
* @param buffer - Optional ByteBuffer or ByteStream to read from
|
|
16
|
+
*/
|
|
6
17
|
constructor(buffer?: ByteBuffer | ByteStream);
|
|
18
|
+
/**
|
|
19
|
+
* Gets the type name of this entity.
|
|
20
|
+
*
|
|
21
|
+
* @returns The constructor name of this entity
|
|
22
|
+
*/
|
|
7
23
|
get entityType(): string;
|
|
24
|
+
/**
|
|
25
|
+
* Sets the maximum buffer size before compaction occurs.
|
|
26
|
+
*
|
|
27
|
+
* @param size - The maximum buffer size in bytes
|
|
28
|
+
*/
|
|
8
29
|
set maxBufferSize(size: number);
|
|
30
|
+
/**
|
|
31
|
+
* Gets the current length of the buffer.
|
|
32
|
+
*
|
|
33
|
+
* @returns The number of bytes in the buffer
|
|
34
|
+
*/
|
|
9
35
|
get bufferLength(): number;
|
|
36
|
+
/**
|
|
37
|
+
* Feeds input data into the buffer.
|
|
38
|
+
*
|
|
39
|
+
* @param input - One or more strings, numbers, arrays of numbers, or Uint8Arrays to add to the buffer
|
|
40
|
+
*/
|
|
10
41
|
feed(...input: JsonStreamInput[]): void;
|
|
42
|
+
/**
|
|
43
|
+
* Abstract method that subclasses must implement to parse their specific type.
|
|
44
|
+
*
|
|
45
|
+
* @returns The parsed value of type T
|
|
46
|
+
*/
|
|
11
47
|
protected abstract parse(): T;
|
|
48
|
+
/**
|
|
49
|
+
* Skips whitespace characters in the buffer.
|
|
50
|
+
*/
|
|
12
51
|
protected skipWhitespace(): void;
|
|
52
|
+
/**
|
|
53
|
+
* Reads and parses the entity, consuming it in the process.
|
|
54
|
+
*
|
|
55
|
+
* @returns The parsed value
|
|
56
|
+
* @throws Error if the entity has already been consumed
|
|
57
|
+
*/
|
|
13
58
|
read(): T;
|
|
59
|
+
/**
|
|
60
|
+
* Asynchronously reads and parses the entity from a stream.
|
|
61
|
+
*
|
|
62
|
+
* @returns A promise that resolves to the parsed value
|
|
63
|
+
* @throws Error if the entity has already been consumed
|
|
64
|
+
*/
|
|
14
65
|
readAsync(): Promise<T>;
|
|
66
|
+
/**
|
|
67
|
+
* Consumes the entity by reading it if not already consumed.
|
|
68
|
+
*/
|
|
15
69
|
consume(): void;
|
|
70
|
+
/**
|
|
71
|
+
* Asynchronously consumes the entity by reading it if not already consumed.
|
|
72
|
+
*/
|
|
16
73
|
consumeAsync(): Promise<void>;
|
|
74
|
+
/**
|
|
75
|
+
* Attempts to parse by executing a callback, reverting buffer state on failure.
|
|
76
|
+
*
|
|
77
|
+
* @typeParam T - The return type of the callback
|
|
78
|
+
* @param cb - The callback function to execute
|
|
79
|
+
* @returns The result of the callback, or undefined if parsing needs more data
|
|
80
|
+
* @throws Error if the entity has already been consumed
|
|
81
|
+
*/
|
|
17
82
|
tryParse<T = this>(cb: (entity: this) => T): T | undefined;
|
|
18
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* Represents a JSON string value.
|
|
86
|
+
* Parses and stores string data from the buffer.
|
|
87
|
+
*
|
|
88
|
+
* @typeParam T - The specific string type (defaults to string)
|
|
89
|
+
*/
|
|
19
90
|
export declare class JsonString<T extends string = string> extends JsonEntity<T> {
|
|
91
|
+
/**
|
|
92
|
+
* Parses a JSON string from the buffer.
|
|
93
|
+
*
|
|
94
|
+
* @returns The parsed string value
|
|
95
|
+
*/
|
|
20
96
|
protected parse(): T;
|
|
21
97
|
}
|
|
98
|
+
/**
|
|
99
|
+
* Represents a JSON number value.
|
|
100
|
+
* Parses numeric data including integers, floats, and scientific notation.
|
|
101
|
+
*
|
|
102
|
+
* @typeParam T - The specific number type (defaults to number)
|
|
103
|
+
*/
|
|
22
104
|
export declare class JsonNumber<T extends number = number> extends JsonEntity<T> {
|
|
105
|
+
/**
|
|
106
|
+
* Parses a JSON number from the buffer.
|
|
107
|
+
*
|
|
108
|
+
* @returns The parsed number value
|
|
109
|
+
*/
|
|
23
110
|
protected parse(): T;
|
|
24
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* Represents a JSON boolean value (true or false).
|
|
114
|
+
*
|
|
115
|
+
* @typeParam T - The specific boolean type (defaults to boolean)
|
|
116
|
+
*/
|
|
25
117
|
export declare class JsonBoolean<T extends boolean = boolean> extends JsonEntity<T> {
|
|
118
|
+
/**
|
|
119
|
+
* Parses a JSON boolean from the buffer.
|
|
120
|
+
*
|
|
121
|
+
* @returns The parsed boolean value (true or false)
|
|
122
|
+
*/
|
|
26
123
|
protected parse(): T;
|
|
27
124
|
}
|
|
125
|
+
/**
|
|
126
|
+
* Represents a JSON null value.
|
|
127
|
+
*/
|
|
28
128
|
export declare class JsonNull extends JsonEntity<null> {
|
|
129
|
+
/**
|
|
130
|
+
* Parses a JSON null from the buffer.
|
|
131
|
+
*
|
|
132
|
+
* @returns null
|
|
133
|
+
*/
|
|
29
134
|
protected parse(): null;
|
|
30
135
|
}
|
|
136
|
+
/**
|
|
137
|
+
* Union type representing all JSON primitive entity types.
|
|
138
|
+
*/
|
|
31
139
|
export type JsonPrimitiveType = JsonString | JsonNumber | JsonBoolean | JsonNull;
|
|
140
|
+
/**
|
|
141
|
+
* Union type representing any JSON value entity type (primitive, object, or array).
|
|
142
|
+
*
|
|
143
|
+
* @typeParam T - The expected type of the value
|
|
144
|
+
*/
|
|
32
145
|
export type JsonValueType<T = unknown> = JsonPrimitiveType | JsonObject<T> | JsonArray<T>;
|
|
146
|
+
/**
|
|
147
|
+
* Represents any JSON value (primitive, object, or array).
|
|
148
|
+
* Provides lazy evaluation and type detection for JSON values.
|
|
149
|
+
*
|
|
150
|
+
* @typeParam T - The expected type of the value
|
|
151
|
+
* @typeParam K - The key type for object properties (defaults to string)
|
|
152
|
+
*/
|
|
33
153
|
export declare class JsonValue<T extends unknown = unknown, K extends string = string> extends JsonEntity<JsonValueType<T>> {
|
|
34
154
|
private key?;
|
|
35
155
|
private value?;
|
|
156
|
+
/**
|
|
157
|
+
* Creates a new JsonValue entity.
|
|
158
|
+
*
|
|
159
|
+
* @param buffer - Optional ByteBuffer or ByteStream to read from
|
|
160
|
+
* @param key - Optional key associated with this value (for object members)
|
|
161
|
+
*/
|
|
36
162
|
constructor(buffer?: ByteBuffer | ByteStream, key?: JsonString<K>);
|
|
163
|
+
/**
|
|
164
|
+
* Parses the value, determining its type and creating the appropriate entity.
|
|
165
|
+
*
|
|
166
|
+
* @returns The parsed JSON entity (primitive, object, or array)
|
|
167
|
+
*/
|
|
37
168
|
protected parse(): JsonValueType<T>;
|
|
169
|
+
/**
|
|
170
|
+
* Reads the value entity without reading its contents.
|
|
171
|
+
* Allows for lazy evaluation of the actual value.
|
|
172
|
+
*
|
|
173
|
+
* @returns The JSON entity representing this value
|
|
174
|
+
*/
|
|
38
175
|
read(): JsonValueType<T>;
|
|
176
|
+
/**
|
|
177
|
+
* Reads and fully evaluates the value.
|
|
178
|
+
*
|
|
179
|
+
* @returns The actual JavaScript value (string, number, boolean, null, object, or array)
|
|
180
|
+
*/
|
|
39
181
|
readValue(): unknown;
|
|
182
|
+
/**
|
|
183
|
+
* Asynchronously reads and fully evaluates the value.
|
|
184
|
+
*
|
|
185
|
+
* @returns A promise that resolves to the actual JavaScript value
|
|
186
|
+
*/
|
|
40
187
|
readValueAsync(): Promise<unknown>;
|
|
188
|
+
/**
|
|
189
|
+
* Asynchronously reads the value entity from a stream.
|
|
190
|
+
*
|
|
191
|
+
* @returns A promise that resolves to the JSON entity representing this value
|
|
192
|
+
*/
|
|
41
193
|
readAsync(): Promise<JsonValueType<T>>;
|
|
194
|
+
/**
|
|
195
|
+
* Consumes the value, ensuring it is fully read.
|
|
196
|
+
*/
|
|
42
197
|
consume(): void;
|
|
198
|
+
/**
|
|
199
|
+
* Asynchronously consumes the value, ensuring it is fully read.
|
|
200
|
+
*/
|
|
43
201
|
consumeAsync(): Promise<void>;
|
|
44
202
|
}
|
|
203
|
+
/**
|
|
204
|
+
* Represents a JSON object.
|
|
205
|
+
* Provides streaming access to object members (key-value pairs).
|
|
206
|
+
*
|
|
207
|
+
* @typeParam T - The expected type of the object
|
|
208
|
+
*/
|
|
45
209
|
export declare class JsonObject<T = unknown> extends JsonEntity<T> {
|
|
210
|
+
/**
|
|
211
|
+
* Generator that yields object members as key-value pairs.
|
|
212
|
+
* Allows for streaming/incremental processing of large objects.
|
|
213
|
+
*
|
|
214
|
+
* @yields Object containing the key and value entities for each member
|
|
215
|
+
*/
|
|
46
216
|
members(): Generator<{
|
|
47
217
|
key: JsonString<Extract<keyof T, string>>;
|
|
48
218
|
value: JsonValue<T>;
|
|
49
219
|
}>;
|
|
220
|
+
/**
|
|
221
|
+
* Async generator that yields object members from a stream.
|
|
222
|
+
* Allows for asynchronous streaming/incremental processing.
|
|
223
|
+
*
|
|
224
|
+
* @yields Object containing the key and value entities for each member
|
|
225
|
+
*/
|
|
50
226
|
membersAsync(): AsyncGenerator<{
|
|
51
227
|
key: JsonString<Extract<keyof T, string>>;
|
|
52
228
|
value: JsonValue<T>;
|
|
53
229
|
}>;
|
|
230
|
+
/**
|
|
231
|
+
* Returns an iterator for object members.
|
|
232
|
+
* Enables use of for...of loops on JsonObject.
|
|
233
|
+
*/
|
|
54
234
|
[Symbol.iterator](): Generator<{
|
|
55
235
|
key: JsonString<Extract<keyof T, string>>;
|
|
56
236
|
value: JsonValue<T>;
|
|
57
237
|
}, any, any>;
|
|
238
|
+
/**
|
|
239
|
+
* Returns an async iterator for object members.
|
|
240
|
+
* Enables use of for await...of loops on JsonObject.
|
|
241
|
+
*/
|
|
58
242
|
[Symbol.asyncIterator](): AsyncGenerator<{
|
|
59
243
|
key: JsonString<Extract<keyof T, string>>;
|
|
60
244
|
value: JsonValue<T>;
|
|
61
245
|
}, any, any>;
|
|
246
|
+
/**
|
|
247
|
+
* Parses the entire object into a JavaScript object.
|
|
248
|
+
*
|
|
249
|
+
* @returns The parsed object
|
|
250
|
+
*/
|
|
62
251
|
protected parse(): T;
|
|
63
252
|
}
|
|
253
|
+
/**
|
|
254
|
+
* Represents a JSON array.
|
|
255
|
+
* Provides streaming access to array items.
|
|
256
|
+
*
|
|
257
|
+
* @typeParam T - The expected type of array elements
|
|
258
|
+
*/
|
|
64
259
|
export declare class JsonArray<T = unknown> extends JsonEntity<T[]> {
|
|
260
|
+
/**
|
|
261
|
+
* Generator that yields array items.
|
|
262
|
+
* Allows for streaming/incremental processing of large arrays.
|
|
263
|
+
*
|
|
264
|
+
* @yields Each item entity in the array
|
|
265
|
+
*/
|
|
65
266
|
items(): Generator<JsonValueType<T>>;
|
|
267
|
+
/**
|
|
268
|
+
* Async generator that yields array items from a stream.
|
|
269
|
+
* Allows for asynchronous streaming/incremental processing.
|
|
270
|
+
*
|
|
271
|
+
* @yields Each item entity in the array
|
|
272
|
+
*/
|
|
66
273
|
itemsAsync(): AsyncGenerator<JsonValueType<T>>;
|
|
274
|
+
/**
|
|
275
|
+
* Returns an iterator for array items.
|
|
276
|
+
* Enables use of for...of loops on JsonArray.
|
|
277
|
+
*/
|
|
67
278
|
[Symbol.iterator](): Generator<JsonValueType<T>, any, any>;
|
|
279
|
+
/**
|
|
280
|
+
* Returns an async iterator for array items.
|
|
281
|
+
* Enables use of for await...of loops on JsonArray.
|
|
282
|
+
*/
|
|
68
283
|
[Symbol.asyncIterator](): AsyncGenerator<JsonValueType<T>, any, any>;
|
|
284
|
+
/**
|
|
285
|
+
* Parses the entire array into a JavaScript array.
|
|
286
|
+
*
|
|
287
|
+
* @returns The parsed array
|
|
288
|
+
*/
|
|
69
289
|
protected parse(): T[];
|
|
70
290
|
}
|
|
291
|
+
/**
|
|
292
|
+
* Parser that flattens nested JSON structures into key-value pairs.
|
|
293
|
+
* Useful for extracting specific values from complex JSON without parsing the entire structure.
|
|
294
|
+
*/
|
|
71
295
|
export declare class JsonKeyValueParser extends JsonEntity<Generator<JsonKeyValuePair>> {
|
|
72
296
|
private container;
|
|
73
297
|
private parentKey?;
|
|
298
|
+
/**
|
|
299
|
+
* Creates a new key-value parser.
|
|
300
|
+
*
|
|
301
|
+
* @param buffer - Optional ByteBuffer or ByteStream to read from
|
|
302
|
+
* @param container - The JSON container to parse (object, array, or value)
|
|
303
|
+
* @param parentKey - The parent key for nested structures (used for dot notation)
|
|
304
|
+
*/
|
|
74
305
|
constructor(buffer?: ByteBuffer | ByteStream, container?: JsonObject | JsonArray | JsonValue, parentKey?: string);
|
|
306
|
+
/**
|
|
307
|
+
* Generator that yields key-value pairs from the JSON structure.
|
|
308
|
+
* Flattens nested objects and arrays using dot notation and array indices.
|
|
309
|
+
*
|
|
310
|
+
* @yields Key-value pairs as [key, value] tuples
|
|
311
|
+
*/
|
|
75
312
|
parse(): Generator<JsonKeyValuePair>;
|
|
313
|
+
/**
|
|
314
|
+
* Async generator that yields key-value pairs from a stream.
|
|
315
|
+
*
|
|
316
|
+
* @yields Key-value pairs as [key, value] tuples
|
|
317
|
+
*/
|
|
76
318
|
parseAsync(): AsyncGenerator<JsonKeyValuePair>;
|
|
319
|
+
/**
|
|
320
|
+
* Returns an iterator for key-value pairs.
|
|
321
|
+
* Enables use of for...of loops on JsonKeyValueParser.
|
|
322
|
+
*/
|
|
77
323
|
[Symbol.iterator](): Generator<JsonKeyValuePair, any, any>;
|
|
324
|
+
/**
|
|
325
|
+
* Returns an async iterator for key-value pairs.
|
|
326
|
+
* Enables use of for await...of loops on JsonKeyValueParser.
|
|
327
|
+
*/
|
|
78
328
|
[Symbol.asyncIterator](): AsyncGenerator<JsonKeyValuePair, any, any>;
|
|
79
329
|
}
|
package/dist/parser.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { ByteBuffer } from './byte-buffer.js';
|
|
2
2
|
import { bytesToNumber, bytesToString } from './utils.js';
|
|
3
|
+
/**
|
|
4
|
+
* Map of character names to their byte values for JSON parsing.
|
|
5
|
+
* Contains commonly used characters in JSON syntax.
|
|
6
|
+
*/
|
|
3
7
|
const BYTE_MAP = {
|
|
4
8
|
quotes: 34,
|
|
5
9
|
a: 97,
|
|
@@ -28,19 +32,43 @@ const BYTE_MAP = {
|
|
|
28
32
|
comma: 44,
|
|
29
33
|
colon: 58,
|
|
30
34
|
};
|
|
35
|
+
/**
|
|
36
|
+
* Checks if a byte represents a whitespace character.
|
|
37
|
+
*
|
|
38
|
+
* @param byte - The byte to check
|
|
39
|
+
* @returns True if the byte is a space, tab, carriage return, or line feed
|
|
40
|
+
*/
|
|
31
41
|
const isWhitespace = (byte) => {
|
|
32
42
|
return (byte === BYTE_MAP.space ||
|
|
33
43
|
byte === BYTE_MAP.tab ||
|
|
34
44
|
byte === BYTE_MAP.carriageReturn ||
|
|
35
45
|
byte === BYTE_MAP.lineFeed);
|
|
36
46
|
};
|
|
47
|
+
/**
|
|
48
|
+
* Checks if a byte represents a digit (0-9).
|
|
49
|
+
*
|
|
50
|
+
* @param byte - The byte to check
|
|
51
|
+
* @returns True if the byte is a digit
|
|
52
|
+
*/
|
|
37
53
|
const isDigit = (byte) => {
|
|
38
54
|
return byte !== null && byte >= BYTE_MAP.zero && byte <= BYTE_MAP.nine;
|
|
39
55
|
};
|
|
56
|
+
/**
|
|
57
|
+
* Checks if a byte can start a JSON number (digit or minus sign).
|
|
58
|
+
*
|
|
59
|
+
* @param byte - The byte to check
|
|
60
|
+
* @returns True if the byte can start a number
|
|
61
|
+
*/
|
|
40
62
|
const isNumberStart = (byte) => {
|
|
41
63
|
return (byte === BYTE_MAP.minus ||
|
|
42
64
|
(byte !== null && byte >= BYTE_MAP.zero && byte <= BYTE_MAP.nine));
|
|
43
65
|
};
|
|
66
|
+
/**
|
|
67
|
+
* Checks if a byte is part of a numeric value (digit, dot, e, E, minus, or plus).
|
|
68
|
+
*
|
|
69
|
+
* @param byte - The byte to check
|
|
70
|
+
* @returns True if the byte is part of a numeric representation
|
|
71
|
+
*/
|
|
44
72
|
const isNumeric = (byte) => {
|
|
45
73
|
return (isDigit(byte) ||
|
|
46
74
|
byte === BYTE_MAP.dot || // .
|
|
@@ -50,32 +78,72 @@ const isNumeric = (byte) => {
|
|
|
50
78
|
byte === BYTE_MAP.plus // +
|
|
51
79
|
);
|
|
52
80
|
};
|
|
81
|
+
/**
|
|
82
|
+
* Abstract base class for all JSON entities.
|
|
83
|
+
* Provides common functionality for parsing, reading, and consuming JSON values.
|
|
84
|
+
*
|
|
85
|
+
* @typeParam T - The type of value this entity represents
|
|
86
|
+
*/
|
|
53
87
|
export class JsonEntity {
|
|
54
88
|
consumed = false;
|
|
55
89
|
buffer;
|
|
90
|
+
/**
|
|
91
|
+
* Creates a new JSON entity.
|
|
92
|
+
*
|
|
93
|
+
* @param buffer - Optional ByteBuffer or ByteStream to read from
|
|
94
|
+
*/
|
|
56
95
|
constructor(buffer) {
|
|
57
96
|
this.buffer =
|
|
58
97
|
buffer instanceof ByteBuffer ? buffer : new ByteBuffer(buffer);
|
|
59
98
|
}
|
|
99
|
+
/**
|
|
100
|
+
* Gets the type name of this entity.
|
|
101
|
+
*
|
|
102
|
+
* @returns The constructor name of this entity
|
|
103
|
+
*/
|
|
60
104
|
get entityType() {
|
|
61
105
|
return this.constructor.name;
|
|
62
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Sets the maximum buffer size before compaction occurs.
|
|
109
|
+
*
|
|
110
|
+
* @param size - The maximum buffer size in bytes
|
|
111
|
+
*/
|
|
63
112
|
set maxBufferSize(size) {
|
|
64
113
|
this.buffer.maxBufferSize = size;
|
|
65
114
|
}
|
|
115
|
+
/**
|
|
116
|
+
* Gets the current length of the buffer.
|
|
117
|
+
*
|
|
118
|
+
* @returns The number of bytes in the buffer
|
|
119
|
+
*/
|
|
66
120
|
get bufferLength() {
|
|
67
121
|
return this.buffer.length;
|
|
68
122
|
}
|
|
123
|
+
/**
|
|
124
|
+
* Feeds input data into the buffer.
|
|
125
|
+
*
|
|
126
|
+
* @param input - One or more strings, numbers, arrays of numbers, or Uint8Arrays to add to the buffer
|
|
127
|
+
*/
|
|
69
128
|
feed(...input) {
|
|
70
129
|
for (const item of input) {
|
|
71
130
|
this.buffer.feed(item);
|
|
72
131
|
}
|
|
73
132
|
}
|
|
133
|
+
/**
|
|
134
|
+
* Skips whitespace characters in the buffer.
|
|
135
|
+
*/
|
|
74
136
|
skipWhitespace() {
|
|
75
137
|
while (isWhitespace(this.buffer.peek())) {
|
|
76
138
|
this.buffer.next();
|
|
77
139
|
}
|
|
78
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* Reads and parses the entity, consuming it in the process.
|
|
143
|
+
*
|
|
144
|
+
* @returns The parsed value
|
|
145
|
+
* @throws Error if the entity has already been consumed
|
|
146
|
+
*/
|
|
79
147
|
read() {
|
|
80
148
|
if (this.consumed) {
|
|
81
149
|
throw new Error('JSON entity has already been consumed.');
|
|
@@ -86,6 +154,12 @@ export class JsonEntity {
|
|
|
86
154
|
this.buffer.compact();
|
|
87
155
|
return read;
|
|
88
156
|
}
|
|
157
|
+
/**
|
|
158
|
+
* Asynchronously reads and parses the entity from a stream.
|
|
159
|
+
*
|
|
160
|
+
* @returns A promise that resolves to the parsed value
|
|
161
|
+
* @throws Error if the entity has already been consumed
|
|
162
|
+
*/
|
|
89
163
|
async readAsync() {
|
|
90
164
|
if (this.consumed) {
|
|
91
165
|
throw new Error('JSON entity has already been consumed.');
|
|
@@ -99,16 +173,30 @@ export class JsonEntity {
|
|
|
99
173
|
}
|
|
100
174
|
return this.read();
|
|
101
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Consumes the entity by reading it if not already consumed.
|
|
178
|
+
*/
|
|
102
179
|
consume() {
|
|
103
180
|
if (!this.consumed) {
|
|
104
181
|
this.read();
|
|
105
182
|
}
|
|
106
183
|
}
|
|
184
|
+
/**
|
|
185
|
+
* Asynchronously consumes the entity by reading it if not already consumed.
|
|
186
|
+
*/
|
|
107
187
|
async consumeAsync() {
|
|
108
188
|
if (!this.consumed) {
|
|
109
189
|
await this.readAsync();
|
|
110
190
|
}
|
|
111
191
|
}
|
|
192
|
+
/**
|
|
193
|
+
* Attempts to parse by executing a callback, reverting buffer state on failure.
|
|
194
|
+
*
|
|
195
|
+
* @typeParam T - The return type of the callback
|
|
196
|
+
* @param cb - The callback function to execute
|
|
197
|
+
* @returns The result of the callback, or undefined if parsing needs more data
|
|
198
|
+
* @throws Error if the entity has already been consumed
|
|
199
|
+
*/
|
|
112
200
|
tryParse(cb) {
|
|
113
201
|
if (this.consumed) {
|
|
114
202
|
throw new Error('JSON entity has already been consumed.');
|
|
@@ -123,7 +211,18 @@ export class JsonEntity {
|
|
|
123
211
|
});
|
|
124
212
|
}
|
|
125
213
|
}
|
|
214
|
+
/**
|
|
215
|
+
* Represents a JSON string value.
|
|
216
|
+
* Parses and stores string data from the buffer.
|
|
217
|
+
*
|
|
218
|
+
* @typeParam T - The specific string type (defaults to string)
|
|
219
|
+
*/
|
|
126
220
|
export class JsonString extends JsonEntity {
|
|
221
|
+
/**
|
|
222
|
+
* Parses a JSON string from the buffer.
|
|
223
|
+
*
|
|
224
|
+
* @returns The parsed string value
|
|
225
|
+
*/
|
|
127
226
|
parse() {
|
|
128
227
|
const bytes = [];
|
|
129
228
|
this.buffer.next(); // consume opening quotes
|
|
@@ -135,7 +234,18 @@ export class JsonString extends JsonEntity {
|
|
|
135
234
|
return result;
|
|
136
235
|
}
|
|
137
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* Represents a JSON number value.
|
|
239
|
+
* Parses numeric data including integers, floats, and scientific notation.
|
|
240
|
+
*
|
|
241
|
+
* @typeParam T - The specific number type (defaults to number)
|
|
242
|
+
*/
|
|
138
243
|
export class JsonNumber extends JsonEntity {
|
|
244
|
+
/**
|
|
245
|
+
* Parses a JSON number from the buffer.
|
|
246
|
+
*
|
|
247
|
+
* @returns The parsed number value
|
|
248
|
+
*/
|
|
139
249
|
parse() {
|
|
140
250
|
const numberBytes = [];
|
|
141
251
|
while (isNumeric(this.buffer.peek())) {
|
|
@@ -145,7 +255,17 @@ export class JsonNumber extends JsonEntity {
|
|
|
145
255
|
return result;
|
|
146
256
|
}
|
|
147
257
|
}
|
|
258
|
+
/**
|
|
259
|
+
* Represents a JSON boolean value (true or false).
|
|
260
|
+
*
|
|
261
|
+
* @typeParam T - The specific boolean type (defaults to boolean)
|
|
262
|
+
*/
|
|
148
263
|
export class JsonBoolean extends JsonEntity {
|
|
264
|
+
/**
|
|
265
|
+
* Parses a JSON boolean from the buffer.
|
|
266
|
+
*
|
|
267
|
+
* @returns The parsed boolean value (true or false)
|
|
268
|
+
*/
|
|
149
269
|
parse() {
|
|
150
270
|
const next = this.buffer.next();
|
|
151
271
|
if (next === BYTE_MAP.t) {
|
|
@@ -163,7 +283,15 @@ export class JsonBoolean extends JsonEntity {
|
|
|
163
283
|
}
|
|
164
284
|
}
|
|
165
285
|
}
|
|
286
|
+
/**
|
|
287
|
+
* Represents a JSON null value.
|
|
288
|
+
*/
|
|
166
289
|
export class JsonNull extends JsonEntity {
|
|
290
|
+
/**
|
|
291
|
+
* Parses a JSON null from the buffer.
|
|
292
|
+
*
|
|
293
|
+
* @returns null
|
|
294
|
+
*/
|
|
167
295
|
parse() {
|
|
168
296
|
this.buffer.expect(BYTE_MAP.n); // n
|
|
169
297
|
this.buffer.expect(BYTE_MAP.u); // u
|
|
@@ -172,13 +300,31 @@ export class JsonNull extends JsonEntity {
|
|
|
172
300
|
return null;
|
|
173
301
|
}
|
|
174
302
|
}
|
|
303
|
+
/**
|
|
304
|
+
* Represents any JSON value (primitive, object, or array).
|
|
305
|
+
* Provides lazy evaluation and type detection for JSON values.
|
|
306
|
+
*
|
|
307
|
+
* @typeParam T - The expected type of the value
|
|
308
|
+
* @typeParam K - The key type for object properties (defaults to string)
|
|
309
|
+
*/
|
|
175
310
|
export class JsonValue extends JsonEntity {
|
|
176
311
|
key;
|
|
177
312
|
value;
|
|
313
|
+
/**
|
|
314
|
+
* Creates a new JsonValue entity.
|
|
315
|
+
*
|
|
316
|
+
* @param buffer - Optional ByteBuffer or ByteStream to read from
|
|
317
|
+
* @param key - Optional key associated with this value (for object members)
|
|
318
|
+
*/
|
|
178
319
|
constructor(buffer, key) {
|
|
179
320
|
super(buffer);
|
|
180
321
|
this.key = key;
|
|
181
322
|
}
|
|
323
|
+
/**
|
|
324
|
+
* Parses the value, determining its type and creating the appropriate entity.
|
|
325
|
+
*
|
|
326
|
+
* @returns The parsed JSON entity (primitive, object, or array)
|
|
327
|
+
*/
|
|
182
328
|
parse() {
|
|
183
329
|
this.key?.consume();
|
|
184
330
|
this.skipWhitespace();
|
|
@@ -214,6 +360,12 @@ export class JsonValue extends JsonEntity {
|
|
|
214
360
|
String.fromCharCode(next ?? 0));
|
|
215
361
|
}
|
|
216
362
|
}
|
|
363
|
+
/**
|
|
364
|
+
* Reads the value entity without reading its contents.
|
|
365
|
+
* Allows for lazy evaluation of the actual value.
|
|
366
|
+
*
|
|
367
|
+
* @returns The JSON entity representing this value
|
|
368
|
+
*/
|
|
217
369
|
read() {
|
|
218
370
|
if (this.value) {
|
|
219
371
|
return this.value;
|
|
@@ -222,14 +374,29 @@ export class JsonValue extends JsonEntity {
|
|
|
222
374
|
this.consumed = false;
|
|
223
375
|
return this.value;
|
|
224
376
|
}
|
|
377
|
+
/**
|
|
378
|
+
* Reads and fully evaluates the value.
|
|
379
|
+
*
|
|
380
|
+
* @returns The actual JavaScript value (string, number, boolean, null, object, or array)
|
|
381
|
+
*/
|
|
225
382
|
readValue() {
|
|
226
383
|
const value = this.read();
|
|
227
384
|
return value.read();
|
|
228
385
|
}
|
|
386
|
+
/**
|
|
387
|
+
* Asynchronously reads and fully evaluates the value.
|
|
388
|
+
*
|
|
389
|
+
* @returns A promise that resolves to the actual JavaScript value
|
|
390
|
+
*/
|
|
229
391
|
async readValueAsync() {
|
|
230
392
|
const value = await this.readAsync();
|
|
231
393
|
return await value.readAsync();
|
|
232
394
|
}
|
|
395
|
+
/**
|
|
396
|
+
* Asynchronously reads the value entity from a stream.
|
|
397
|
+
*
|
|
398
|
+
* @returns A promise that resolves to the JSON entity representing this value
|
|
399
|
+
*/
|
|
233
400
|
async readAsync() {
|
|
234
401
|
if (this.value) {
|
|
235
402
|
return this.value;
|
|
@@ -238,6 +405,9 @@ export class JsonValue extends JsonEntity {
|
|
|
238
405
|
this.consumed = false;
|
|
239
406
|
return this.value;
|
|
240
407
|
}
|
|
408
|
+
/**
|
|
409
|
+
* Consumes the value, ensuring it is fully read.
|
|
410
|
+
*/
|
|
241
411
|
consume() {
|
|
242
412
|
if (this.value && !this.value.consumed) {
|
|
243
413
|
this.value.consume();
|
|
@@ -246,6 +416,9 @@ export class JsonValue extends JsonEntity {
|
|
|
246
416
|
super.consume();
|
|
247
417
|
}
|
|
248
418
|
}
|
|
419
|
+
/**
|
|
420
|
+
* Asynchronously consumes the value, ensuring it is fully read.
|
|
421
|
+
*/
|
|
249
422
|
async consumeAsync() {
|
|
250
423
|
if (this.value && !this.value.consumed) {
|
|
251
424
|
await this.value.consumeAsync();
|
|
@@ -255,7 +428,19 @@ export class JsonValue extends JsonEntity {
|
|
|
255
428
|
}
|
|
256
429
|
}
|
|
257
430
|
}
|
|
431
|
+
/**
|
|
432
|
+
* Represents a JSON object.
|
|
433
|
+
* Provides streaming access to object members (key-value pairs).
|
|
434
|
+
*
|
|
435
|
+
* @typeParam T - The expected type of the object
|
|
436
|
+
*/
|
|
258
437
|
export class JsonObject extends JsonEntity {
|
|
438
|
+
/**
|
|
439
|
+
* Generator that yields object members as key-value pairs.
|
|
440
|
+
* Allows for streaming/incremental processing of large objects.
|
|
441
|
+
*
|
|
442
|
+
* @yields Object containing the key and value entities for each member
|
|
443
|
+
*/
|
|
259
444
|
*members() {
|
|
260
445
|
this.skipWhitespace();
|
|
261
446
|
if (this.buffer.peek() === BYTE_MAP.leftBrace) {
|
|
@@ -286,6 +471,12 @@ export class JsonObject extends JsonEntity {
|
|
|
286
471
|
this.buffer.expect(BYTE_MAP.rightBrace);
|
|
287
472
|
this.consumed = true;
|
|
288
473
|
}
|
|
474
|
+
/**
|
|
475
|
+
* Async generator that yields object members from a stream.
|
|
476
|
+
* Allows for asynchronous streaming/incremental processing.
|
|
477
|
+
*
|
|
478
|
+
* @yields Object containing the key and value entities for each member
|
|
479
|
+
*/
|
|
289
480
|
async *membersAsync() {
|
|
290
481
|
while (!this.buffer.atEof()) {
|
|
291
482
|
await this.buffer.readStream();
|
|
@@ -306,12 +497,25 @@ export class JsonObject extends JsonEntity {
|
|
|
306
497
|
}
|
|
307
498
|
}
|
|
308
499
|
}
|
|
500
|
+
/**
|
|
501
|
+
* Returns an iterator for object members.
|
|
502
|
+
* Enables use of for...of loops on JsonObject.
|
|
503
|
+
*/
|
|
309
504
|
[Symbol.iterator]() {
|
|
310
505
|
return this.members();
|
|
311
506
|
}
|
|
507
|
+
/**
|
|
508
|
+
* Returns an async iterator for object members.
|
|
509
|
+
* Enables use of for await...of loops on JsonObject.
|
|
510
|
+
*/
|
|
312
511
|
[Symbol.asyncIterator]() {
|
|
313
512
|
return this.membersAsync();
|
|
314
513
|
}
|
|
514
|
+
/**
|
|
515
|
+
* Parses the entire object into a JavaScript object.
|
|
516
|
+
*
|
|
517
|
+
* @returns The parsed object
|
|
518
|
+
*/
|
|
315
519
|
parse() {
|
|
316
520
|
const obj = {};
|
|
317
521
|
for (const { key, value } of this.members()) {
|
|
@@ -320,7 +524,19 @@ export class JsonObject extends JsonEntity {
|
|
|
320
524
|
return obj;
|
|
321
525
|
}
|
|
322
526
|
}
|
|
527
|
+
/**
|
|
528
|
+
* Represents a JSON array.
|
|
529
|
+
* Provides streaming access to array items.
|
|
530
|
+
*
|
|
531
|
+
* @typeParam T - The expected type of array elements
|
|
532
|
+
*/
|
|
323
533
|
export class JsonArray extends JsonEntity {
|
|
534
|
+
/**
|
|
535
|
+
* Generator that yields array items.
|
|
536
|
+
* Allows for streaming/incremental processing of large arrays.
|
|
537
|
+
*
|
|
538
|
+
* @yields Each item entity in the array
|
|
539
|
+
*/
|
|
324
540
|
*items() {
|
|
325
541
|
this.skipWhitespace();
|
|
326
542
|
if (this.buffer.peek() === BYTE_MAP.leftSquare) {
|
|
@@ -346,6 +562,12 @@ export class JsonArray extends JsonEntity {
|
|
|
346
562
|
this.buffer.expect(BYTE_MAP.rightSquare);
|
|
347
563
|
this.consumed = true;
|
|
348
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* Async generator that yields array items from a stream.
|
|
567
|
+
* Allows for asynchronous streaming/incremental processing.
|
|
568
|
+
*
|
|
569
|
+
* @yields Each item entity in the array
|
|
570
|
+
*/
|
|
349
571
|
async *itemsAsync() {
|
|
350
572
|
while (!this.buffer.atEof()) {
|
|
351
573
|
await this.buffer.readStream();
|
|
@@ -364,12 +586,25 @@ export class JsonArray extends JsonEntity {
|
|
|
364
586
|
}
|
|
365
587
|
}
|
|
366
588
|
}
|
|
589
|
+
/**
|
|
590
|
+
* Returns an iterator for array items.
|
|
591
|
+
* Enables use of for...of loops on JsonArray.
|
|
592
|
+
*/
|
|
367
593
|
[Symbol.iterator]() {
|
|
368
594
|
return this.items();
|
|
369
595
|
}
|
|
596
|
+
/**
|
|
597
|
+
* Returns an async iterator for array items.
|
|
598
|
+
* Enables use of for await...of loops on JsonArray.
|
|
599
|
+
*/
|
|
370
600
|
[Symbol.asyncIterator]() {
|
|
371
601
|
return this.itemsAsync();
|
|
372
602
|
}
|
|
603
|
+
/**
|
|
604
|
+
* Parses the entire array into a JavaScript array.
|
|
605
|
+
*
|
|
606
|
+
* @returns The parsed array
|
|
607
|
+
*/
|
|
373
608
|
parse() {
|
|
374
609
|
const values = [];
|
|
375
610
|
for (const value of this) {
|
|
@@ -378,14 +613,31 @@ export class JsonArray extends JsonEntity {
|
|
|
378
613
|
return values;
|
|
379
614
|
}
|
|
380
615
|
}
|
|
616
|
+
/**
|
|
617
|
+
* Parser that flattens nested JSON structures into key-value pairs.
|
|
618
|
+
* Useful for extracting specific values from complex JSON without parsing the entire structure.
|
|
619
|
+
*/
|
|
381
620
|
export class JsonKeyValueParser extends JsonEntity {
|
|
382
621
|
container;
|
|
383
622
|
parentKey;
|
|
623
|
+
/**
|
|
624
|
+
* Creates a new key-value parser.
|
|
625
|
+
*
|
|
626
|
+
* @param buffer - Optional ByteBuffer or ByteStream to read from
|
|
627
|
+
* @param container - The JSON container to parse (object, array, or value)
|
|
628
|
+
* @param parentKey - The parent key for nested structures (used for dot notation)
|
|
629
|
+
*/
|
|
384
630
|
constructor(buffer, container, parentKey) {
|
|
385
631
|
super(buffer);
|
|
386
632
|
this.container = container ?? new JsonValue(this.buffer);
|
|
387
633
|
this.parentKey = parentKey;
|
|
388
634
|
}
|
|
635
|
+
/**
|
|
636
|
+
* Generator that yields key-value pairs from the JSON structure.
|
|
637
|
+
* Flattens nested objects and arrays using dot notation and array indices.
|
|
638
|
+
*
|
|
639
|
+
* @yields Key-value pairs as [key, value] tuples
|
|
640
|
+
*/
|
|
389
641
|
*parse() {
|
|
390
642
|
if (this.container instanceof JsonObject) {
|
|
391
643
|
for (const { key: keyEntity, value: valueEntity } of this
|
|
@@ -428,6 +680,11 @@ export class JsonKeyValueParser extends JsonEntity {
|
|
|
428
680
|
yield* new JsonKeyValueParser(this.buffer, value, this.parentKey).parse();
|
|
429
681
|
}
|
|
430
682
|
}
|
|
683
|
+
/**
|
|
684
|
+
* Async generator that yields key-value pairs from a stream.
|
|
685
|
+
*
|
|
686
|
+
* @yields Key-value pairs as [key, value] tuples
|
|
687
|
+
*/
|
|
431
688
|
async *parseAsync() {
|
|
432
689
|
while (!this.buffer.atEof()) {
|
|
433
690
|
await this.buffer.readStream();
|
|
@@ -445,9 +702,17 @@ export class JsonKeyValueParser extends JsonEntity {
|
|
|
445
702
|
}
|
|
446
703
|
}
|
|
447
704
|
}
|
|
705
|
+
/**
|
|
706
|
+
* Returns an iterator for key-value pairs.
|
|
707
|
+
* Enables use of for...of loops on JsonKeyValueParser.
|
|
708
|
+
*/
|
|
448
709
|
[Symbol.iterator]() {
|
|
449
710
|
return this.parse();
|
|
450
711
|
}
|
|
712
|
+
/**
|
|
713
|
+
* Returns an async iterator for key-value pairs.
|
|
714
|
+
* Enables use of for await...of loops on JsonKeyValueParser.
|
|
715
|
+
*/
|
|
451
716
|
[Symbol.asyncIterator]() {
|
|
452
717
|
return this.parseAsync();
|
|
453
718
|
}
|
package/dist/stringify.d.ts
CHANGED
|
@@ -1,5 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for JSON streaming stringification.
|
|
3
|
+
*/
|
|
1
4
|
export type JsonStreamStringifyOptions = {
|
|
5
|
+
/** Maximum size of string chunks when yielding formatted strings */
|
|
2
6
|
stringChunkSize?: number;
|
|
3
7
|
};
|
|
8
|
+
/**
|
|
9
|
+
* Converts a JavaScript value to JSON format, yielding string chunks.
|
|
10
|
+
* Provides memory-efficient streaming stringification for large objects.
|
|
11
|
+
*
|
|
12
|
+
* @param value - The value to stringify
|
|
13
|
+
* @param replacer - Optional replacer function or array for filtering/transforming values
|
|
14
|
+
* @param indent - Number of spaces for indentation (0 for compact output)
|
|
15
|
+
* @param options - Additional stringification options
|
|
16
|
+
* @returns Generator yielding JSON string chunks
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```typescript
|
|
20
|
+
* const data = { name: "John", age: 30 };
|
|
21
|
+
* for (const chunk of jsonStreamStringify(data)) {
|
|
22
|
+
* process.stdout.write(chunk);
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
4
26
|
export declare function jsonStreamStringify(value: unknown, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<string>;
|
|
27
|
+
/**
|
|
28
|
+
* Converts a JavaScript value to JSON format, yielding Uint8Array byte chunks.
|
|
29
|
+
* Provides memory-efficient streaming stringification with binary output.
|
|
30
|
+
*
|
|
31
|
+
* @param value - The value to stringify
|
|
32
|
+
* @param replacer - Optional replacer function or array for filtering/transforming values
|
|
33
|
+
* @param indent - Number of spaces for indentation (0 for compact output)
|
|
34
|
+
* @param options - Additional stringification options
|
|
35
|
+
* @returns Generator yielding JSON as Uint8Array chunks
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* const data = { name: "John", age: 30 };
|
|
40
|
+
* for (const chunk of jsonStreamStringifyBytes(data)) {
|
|
41
|
+
* await stream.write(chunk);
|
|
42
|
+
* }
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
5
45
|
export declare function jsonStreamStringifyBytes(value: unknown, replacer?: any, indent?: number, options?: JsonStreamStringifyOptions): Generator<Uint8Array>;
|
package/dist/stringify.js
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formats a string value for JSON output, escaping special characters.
|
|
3
|
+
* Yields the formatted string in chunks for memory efficiency.
|
|
4
|
+
*
|
|
5
|
+
* @param str - The string to format
|
|
6
|
+
* @param chunkSize - Maximum size of each yielded chunk (default: 1024)
|
|
7
|
+
* @yields Formatted string chunks with proper JSON escaping
|
|
8
|
+
*/
|
|
1
9
|
function* formatString(str, chunkSize = 1024) {
|
|
2
10
|
if (str.length === 0) {
|
|
3
11
|
yield '""';
|
|
@@ -36,18 +44,49 @@ function* formatString(str, chunkSize = 1024) {
|
|
|
36
44
|
i += chunkSize;
|
|
37
45
|
}
|
|
38
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Determines if a value should be ignored during stringification.
|
|
49
|
+
* Functions and undefined values are not valid in JSON.
|
|
50
|
+
*
|
|
51
|
+
* @param value - The value to check
|
|
52
|
+
* @returns True if the value should be ignored
|
|
53
|
+
*/
|
|
39
54
|
function shouldIgnore(value) {
|
|
40
55
|
return typeof value === 'function' || value === undefined;
|
|
41
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Type guard to check if an object has a custom toJSON method.
|
|
59
|
+
*
|
|
60
|
+
* @param value - The object to check
|
|
61
|
+
* @returns True if the object has a toJSON method
|
|
62
|
+
*/
|
|
42
63
|
function hasCustomToJsonFunction(value) {
|
|
43
64
|
return 'toJSON' in value && typeof value.toJSON === 'function';
|
|
44
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* Type guard to check if an object has a custom toString method.
|
|
68
|
+
* Excludes default Object and Array toString methods.
|
|
69
|
+
*
|
|
70
|
+
* @param value - The object to check
|
|
71
|
+
* @returns True if the object has a custom toString method
|
|
72
|
+
*/
|
|
45
73
|
function hasCustomToStringFunction(value) {
|
|
46
74
|
return ('toString' in value &&
|
|
47
75
|
typeof value.toString === 'function' &&
|
|
48
76
|
value.toString !== Object.prototype.toString &&
|
|
49
77
|
value.toString !== Array.prototype.toString);
|
|
50
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* Internal recursive function that stringifies a value with depth tracking.
|
|
81
|
+
* Handles all JSON types including primitives, arrays, and objects.
|
|
82
|
+
*
|
|
83
|
+
* @param value - The value to stringify
|
|
84
|
+
* @param replacer - Optional replacer function for value transformation
|
|
85
|
+
* @param indent - Number of spaces for indentation (0 for compact)
|
|
86
|
+
* @param currentDepth - Current nesting depth for indentation
|
|
87
|
+
* @param options - Stringification options
|
|
88
|
+
* @yields String chunks representing the JSON output
|
|
89
|
+
*/
|
|
51
90
|
function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth = 0, options) {
|
|
52
91
|
if (replacer) {
|
|
53
92
|
value = replacer('', value);
|
|
@@ -124,10 +163,49 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
|
|
|
124
163
|
yield '}';
|
|
125
164
|
}
|
|
126
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* Converts a JavaScript value to JSON format, yielding string chunks.
|
|
168
|
+
* Provides memory-efficient streaming stringification for large objects.
|
|
169
|
+
*
|
|
170
|
+
* @param value - The value to stringify
|
|
171
|
+
* @param replacer - Optional replacer function or array for filtering/transforming values
|
|
172
|
+
* @param indent - Number of spaces for indentation (0 for compact output)
|
|
173
|
+
* @param options - Additional stringification options
|
|
174
|
+
* @returns Generator yielding JSON string chunks
|
|
175
|
+
*
|
|
176
|
+
* @example
|
|
177
|
+
* ```typescript
|
|
178
|
+
* const data = { name: "John", age: 30 };
|
|
179
|
+
* for (const chunk of jsonStreamStringify(data)) {
|
|
180
|
+
* process.stdout.write(chunk);
|
|
181
|
+
* }
|
|
182
|
+
* ```
|
|
183
|
+
*/
|
|
127
184
|
export function jsonStreamStringify(value, replacer, indent = 0, options) {
|
|
128
185
|
return jsonStreamStringifyWithDepth(value, replacer, indent, 0, options);
|
|
129
186
|
}
|
|
187
|
+
/**
|
|
188
|
+
* Shared TextEncoder instance for converting strings to UTF-8 bytes.
|
|
189
|
+
*/
|
|
130
190
|
const TEXT_ENCODER = new TextEncoder();
|
|
191
|
+
/**
|
|
192
|
+
* Converts a JavaScript value to JSON format, yielding Uint8Array byte chunks.
|
|
193
|
+
* Provides memory-efficient streaming stringification with binary output.
|
|
194
|
+
*
|
|
195
|
+
* @param value - The value to stringify
|
|
196
|
+
* @param replacer - Optional replacer function or array for filtering/transforming values
|
|
197
|
+
* @param indent - Number of spaces for indentation (0 for compact output)
|
|
198
|
+
* @param options - Additional stringification options
|
|
199
|
+
* @returns Generator yielding JSON as Uint8Array chunks
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```typescript
|
|
203
|
+
* const data = { name: "John", age: 30 };
|
|
204
|
+
* for (const chunk of jsonStreamStringifyBytes(data)) {
|
|
205
|
+
* await stream.write(chunk);
|
|
206
|
+
* }
|
|
207
|
+
* ```
|
|
208
|
+
*/
|
|
131
209
|
export function* jsonStreamStringifyBytes(value, replacer, indent = 0, options) {
|
|
132
210
|
const stringGenerator = jsonStreamStringify(value, replacer, indent, options);
|
|
133
211
|
for (const chunk of stringGenerator) {
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Union type representing valid JSON stream input formats.
|
|
3
|
+
*/
|
|
1
4
|
export type JsonStreamInput = string | number | number[] | Uint8Array;
|
|
5
|
+
/**
|
|
6
|
+
* An async iterable stream of JSON input that can be consumed incrementally.
|
|
7
|
+
* Supports strings, numbers, arrays of numbers, or Uint8Arrays as stream items.
|
|
8
|
+
*/
|
|
2
9
|
export type ByteStream = AsyncIterable<JsonStreamInput>;
|
|
10
|
+
/**
|
|
11
|
+
* Union type representing all JSON primitive value types.
|
|
12
|
+
*/
|
|
3
13
|
export type JsonPrimitive = string | number | boolean | null;
|
|
14
|
+
/**
|
|
15
|
+
* A tuple representing a flattened key-value pair from a JSON structure.
|
|
16
|
+
* The key is a string (potentially with dot notation for nested properties)
|
|
17
|
+
* and the value is a JSON primitive.
|
|
18
|
+
*/
|
|
4
19
|
export type JsonKeyValuePair = [string, JsonPrimitive];
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,3 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Converts a string to a Uint8Array of UTF-8 encoded bytes.
|
|
3
|
+
*
|
|
4
|
+
* @param str - The string to convert
|
|
5
|
+
* @returns A Uint8Array containing the UTF-8 encoded bytes
|
|
6
|
+
*/
|
|
1
7
|
export declare function stringToBytes(str: string): Uint8Array;
|
|
8
|
+
/**
|
|
9
|
+
* Converts a Uint8Array of UTF-8 encoded bytes to a string.
|
|
10
|
+
*
|
|
11
|
+
* @param bytes - The Uint8Array to decode
|
|
12
|
+
* @returns The decoded string
|
|
13
|
+
*/
|
|
2
14
|
export declare function bytesToString(bytes: Uint8Array): string;
|
|
15
|
+
/**
|
|
16
|
+
* Converts a Uint8Array of UTF-8 encoded bytes to a number.
|
|
17
|
+
*
|
|
18
|
+
* @param bytes - The Uint8Array representing a numeric string
|
|
19
|
+
* @returns The parsed number value
|
|
20
|
+
*/
|
|
3
21
|
export declare function bytesToNumber(bytes: Uint8Array): number;
|
package/dist/utils.js
CHANGED
|
@@ -1,9 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Converts a string to a Uint8Array of UTF-8 encoded bytes.
|
|
3
|
+
*
|
|
4
|
+
* @param str - The string to convert
|
|
5
|
+
* @returns A Uint8Array containing the UTF-8 encoded bytes
|
|
6
|
+
*/
|
|
1
7
|
export function stringToBytes(str) {
|
|
2
8
|
return new TextEncoder().encode(str);
|
|
3
9
|
}
|
|
10
|
+
/**
|
|
11
|
+
* Converts a Uint8Array of UTF-8 encoded bytes to a string.
|
|
12
|
+
*
|
|
13
|
+
* @param bytes - The Uint8Array to decode
|
|
14
|
+
* @returns The decoded string
|
|
15
|
+
*/
|
|
4
16
|
export function bytesToString(bytes) {
|
|
5
17
|
return new TextDecoder().decode(bytes);
|
|
6
18
|
}
|
|
19
|
+
/**
|
|
20
|
+
* Converts a Uint8Array of UTF-8 encoded bytes to a number.
|
|
21
|
+
*
|
|
22
|
+
* @param bytes - The Uint8Array representing a numeric string
|
|
23
|
+
* @returns The parsed number value
|
|
24
|
+
*/
|
|
7
25
|
export function bytesToNumber(bytes) {
|
|
8
26
|
const str = bytesToString(bytes);
|
|
9
27
|
return Number(str);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "json-stream-lite",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.12",
|
|
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",
|