json-stream-lite 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,175 @@
1
+ import { bytesToString } from './utils';
2
+ export class NoMoreTokensError extends Error {
3
+ }
4
+ export class EofReachedError extends Error {
5
+ }
6
+ export class ByteBuffer {
7
+ /** Maximum size of the buffer before compaction */
8
+ maxBufferSize = 1000;
9
+ /** Whether end of file has been signaled */
10
+ eof = false;
11
+ /** Current position in the buffer */
12
+ bufferIndex = 0;
13
+ /** Whether the buffer is locked against compaction */
14
+ locked = false;
15
+ /** Current position in the input stream */
16
+ inputOffset = 0;
17
+ /** Number of outputs generated */
18
+ outputOffset = 0;
19
+ /** Buffer holding input items */
20
+ buffer = [];
21
+ /** Optional async iterable input source */
22
+ asyncIterable;
23
+ constructor(asyncIterable) {
24
+ this.asyncIterable = asyncIterable;
25
+ }
26
+ async readStream() {
27
+ if (!this.asyncIterable) {
28
+ return;
29
+ }
30
+ let i = 0;
31
+ while (i < this.maxBufferSize) {
32
+ const nextByte = await this.asyncIterable[Symbol.asyncIterator]().next();
33
+ if (nextByte.done) {
34
+ this.eof = true;
35
+ break;
36
+ }
37
+ this.feed(nextByte.value);
38
+ i++;
39
+ }
40
+ }
41
+ get length() {
42
+ return this.buffer.length;
43
+ }
44
+ /**
45
+ * Feeds input items into the parser buffer.
46
+ *
47
+ * @param input - Input items to add to the buffer
48
+ */
49
+ feed(...input) {
50
+ for (const item of input) {
51
+ if (Array.isArray(item)) {
52
+ for (const subItem of item) {
53
+ this.buffer.push(subItem);
54
+ }
55
+ continue;
56
+ }
57
+ else if (item instanceof Uint8Array) {
58
+ for (const subItem of item) {
59
+ this.buffer.push(subItem);
60
+ }
61
+ continue;
62
+ }
63
+ this.buffer.push(item);
64
+ }
65
+ }
66
+ /**
67
+ * Checks if end of file has been reached and buffer is exhausted.
68
+ *
69
+ * @returns True if no more input is available
70
+ */
71
+ atEof() {
72
+ return this.eof && this.bufferIndex >= this.buffer.length;
73
+ }
74
+ /**
75
+ * Peeks at an item in the buffer without consuming it.
76
+ *
77
+ * @param ahead - Number of positions to look ahead (default: 0)
78
+ * @returns The item at the peek position, or null if at EOF
79
+ * @throws NoMoreTokensError if more input is needed and EOF not signaled
80
+ */
81
+ peek(ahead = 0) {
82
+ const index = this.bufferIndex + ahead;
83
+ if (index >= this.buffer.length) {
84
+ if (!this.eof) {
85
+ throw new NoMoreTokensError('Buffer empty');
86
+ }
87
+ return null;
88
+ }
89
+ return this.buffer[index];
90
+ }
91
+ /**
92
+ * Consumes and returns the next item from the buffer.
93
+ *
94
+ * @returns The next item
95
+ * @throws NoMoreTokensError if more input is needed and EOF not signaled
96
+ * @throws EofReachedError if at EOF and no more items available
97
+ */
98
+ next() {
99
+ if (this.bufferIndex >= this.buffer.length) {
100
+ if (!this.eof) {
101
+ throw new NoMoreTokensError('No more items available');
102
+ }
103
+ throw new EofReachedError('End of file reached');
104
+ }
105
+ this.inputOffset++;
106
+ return this.buffer[this.bufferIndex++];
107
+ }
108
+ /**
109
+ * Consumes and validates the next item against an expected type or value.
110
+ *
111
+ * @typeParam T - The expected item type
112
+ * @param itemType - Constructor or value to match against
113
+ * @returns The consumed item cast to the expected type
114
+ * @throws Error if the item doesn't match the expected type/value
115
+ */
116
+ expect(itemType) {
117
+ const item = this.next();
118
+ if (item !== itemType) {
119
+ throw new Error(`Expected ${itemType} but got ${item}`);
120
+ }
121
+ return itemType;
122
+ }
123
+ /**
124
+ * Compacts the buffer by removing consumed items
125
+ */
126
+ compact() {
127
+ if (!this.locked && this.bufferIndex > 0) {
128
+ this.buffer = this.buffer.slice(this.bufferIndex);
129
+ this.bufferIndex = 0;
130
+ }
131
+ }
132
+ /**
133
+ * Override to customize when to compact the buffer
134
+ * By default, compacts when more than 1000 items have been consumed
135
+ *
136
+ * @returns boolean indicating whether to compact the buffer
137
+ */
138
+ canCompact() {
139
+ return this.bufferIndex > this.maxBufferSize;
140
+ }
141
+ resetOnFail(tryFn, onFail) {
142
+ const bufferIndex = this.bufferIndex;
143
+ try {
144
+ const result = tryFn();
145
+ if (this.canCompact()) {
146
+ this.compact();
147
+ }
148
+ return result;
149
+ }
150
+ catch (e) {
151
+ if (e instanceof NoMoreTokensError) {
152
+ this.bufferIndex = bufferIndex;
153
+ onFail?.(e);
154
+ }
155
+ else {
156
+ throw e;
157
+ }
158
+ }
159
+ return undefined;
160
+ }
161
+ toString() {
162
+ return [
163
+ 'ByteBuffer {',
164
+ ` buffer: [${this.buffer.join(', ')}],`,
165
+ ` bufferIndex: ${this.bufferIndex},`,
166
+ ` inputOffset: ${this.inputOffset},`,
167
+ ` outputOffset: ${this.outputOffset},`,
168
+ ` eof: ${this.eof},`,
169
+ ` as string: ${bytesToString(new Uint8Array(this.buffer))}`,
170
+ ' as string from bufferIndex: ' +
171
+ bytesToString(new Uint8Array(this.buffer.slice(this.bufferIndex))),
172
+ '}',
173
+ ].join('\n');
174
+ }
175
+ }
@@ -0,0 +1,3 @@
1
+ import { JsonKeyValuePair } from './types';
2
+ export declare function jsonKeyValueParser(bytes: Iterable<number> | string): Generator<JsonKeyValuePair>;
3
+ export declare function jsonKeyValueParserAsync(bytes: Iterable<number> | AsyncIterable<number> | string | ReadableStream<number> | ReadableStream<Uint8Array> | ReadableStream<string>): AsyncGenerator<JsonKeyValuePair>;
@@ -0,0 +1,51 @@
1
+ import { JsonKeyValueParser } from './parser';
2
+ import { stringToBytes } from './utils';
3
+ export function* jsonKeyValueParser(bytes) {
4
+ if (typeof bytes === 'string') {
5
+ bytes = stringToBytes(bytes);
6
+ }
7
+ const parser = new JsonKeyValueParser();
8
+ for (const byte of bytes) {
9
+ parser.feed(byte);
10
+ }
11
+ yield* parser.parse();
12
+ }
13
+ export async function* jsonKeyValueParserAsync(bytes) {
14
+ if (typeof bytes === 'string') {
15
+ bytes = stringToBytes(bytes);
16
+ }
17
+ async function* byteStream() {
18
+ if (typeof bytes === 'string') {
19
+ yield* stringToBytes(bytes);
20
+ }
21
+ else if (bytes instanceof ReadableStream) {
22
+ const reader = bytes.getReader();
23
+ while (true) {
24
+ const { done, value } = await reader.read();
25
+ if (done)
26
+ break;
27
+ if (value instanceof Uint8Array) {
28
+ yield* value;
29
+ }
30
+ else if (typeof value === 'string') {
31
+ yield* stringToBytes(value);
32
+ }
33
+ else {
34
+ yield value;
35
+ }
36
+ }
37
+ }
38
+ else if (Symbol.asyncIterator in bytes) {
39
+ for await (const byte of bytes) {
40
+ yield byte;
41
+ }
42
+ }
43
+ else {
44
+ for (const byte of bytes) {
45
+ yield byte;
46
+ }
47
+ }
48
+ }
49
+ const parser = new JsonKeyValueParser(byteStream());
50
+ yield* parser.parseAsync();
51
+ }
@@ -0,0 +1,103 @@
1
+ import { Parser } from './parser';
2
+ /**
3
+ * Error thrown when the parser needs more input to continue parsing.
4
+ */
5
+ export declare class NoMoreTokensError extends Error {
6
+ }
7
+ /**
8
+ * Error thrown when the end of file has been reached and no more input is available.
9
+ */
10
+ export declare class EofReachedError extends Error {
11
+ }
12
+ /**
13
+ * Abstract base class for incremental parsers that can process input as it becomes available.
14
+ * Supports buffering, lookahead, and backtracking for complex parsing scenarios.
15
+ *
16
+ * @typeParam I - The input item type
17
+ * @typeParam O - The output item type
18
+ */
19
+ export declare abstract class IncrementalParser<I, O> extends Parser<I, O> {
20
+ /** Current position in the input stream */
21
+ protected inputOffset: number;
22
+ /** Number of outputs generated */
23
+ protected outputOffset: number;
24
+ /** Buffer holding input items */
25
+ protected buffer: I[];
26
+ /** Current position in the buffer */
27
+ protected bufferIndex: number;
28
+ /** Whether end of file has been signaled */
29
+ eof: boolean;
30
+ /**
31
+ * Feeds input items into the parser buffer.
32
+ *
33
+ * @param input - Input items to add to the buffer
34
+ */
35
+ feed(...input: (I | I[])[]): void;
36
+ /**
37
+ * Checks if end of file has been reached and buffer is exhausted.
38
+ *
39
+ * @returns True if no more input is available
40
+ */
41
+ protected atEof(): boolean;
42
+ /**
43
+ * Peeks at an item in the buffer without consuming it.
44
+ *
45
+ * @param ahead - Number of positions to look ahead (default: 0)
46
+ * @returns The item at the peek position, or null if at EOF
47
+ * @throws NoMoreTokensError if more input is needed and EOF not signaled
48
+ */
49
+ protected peek(ahead?: number): I | null;
50
+ /**
51
+ * Consumes and returns the next item from the buffer.
52
+ *
53
+ * @returns The next item
54
+ * @throws NoMoreTokensError if more input is needed and EOF not signaled
55
+ * @throws EofReachedError if at EOF and no more items available
56
+ */
57
+ protected next(): I;
58
+ private expectValue;
59
+ /**
60
+ * Consumes and validates the next item against an expected type or value.
61
+ *
62
+ * @typeParam T - The expected item type
63
+ * @param itemType - Constructor or value to match against
64
+ * @returns The consumed item cast to the expected type
65
+ * @throws Error if the item doesn't match the expected type/value
66
+ */
67
+ protected expect<T extends I>(itemType: (new (...args: any[]) => T) | T): T;
68
+ /**
69
+ * Tries multiple parsing functions and returns the first successful result.
70
+ * Automatically backtracks on failure.
71
+ *
72
+ * @param fn - Array of parsing functions to try
73
+ * @returns The result from the first successful parsing function
74
+ * @throws NoMoreTokensError if any function needs more input
75
+ * @throws Error if all parsing functions fail
76
+ */
77
+ protected oneOf(...fn: (() => O)[]): O;
78
+ /**
79
+ * Compacts the buffer by removing consumed items
80
+ */
81
+ protected compact(): void;
82
+ /**
83
+ * Override to customize when to compact the buffer
84
+ * By default, compacts when more than 1000 items have been consumed
85
+ *
86
+ * @returns boolean indicating whether to compact the buffer
87
+ */
88
+ protected canCompact(): boolean;
89
+ /**
90
+ * Generates parsed output items from the buffer.
91
+ * Handles backtracking when more input is needed.
92
+ *
93
+ * @returns A generator yielding parsed output items
94
+ */
95
+ parseNext(): Generator<O>;
96
+ /**
97
+ * Abstract method to parse the next output item from the buffer.
98
+ * Subclasses must implement this to define parsing logic.
99
+ *
100
+ * @returns The parsed output item
101
+ */
102
+ protected abstract parse(): O;
103
+ }
@@ -0,0 +1,184 @@
1
+ import { Parser } from './parser';
2
+ /**
3
+ * Error thrown when the parser needs more input to continue parsing.
4
+ */
5
+ export class NoMoreTokensError extends Error {
6
+ }
7
+ /**
8
+ * Error thrown when the end of file has been reached and no more input is available.
9
+ */
10
+ export class EofReachedError extends Error {
11
+ }
12
+ /**
13
+ * Abstract base class for incremental parsers that can process input as it becomes available.
14
+ * Supports buffering, lookahead, and backtracking for complex parsing scenarios.
15
+ *
16
+ * @typeParam I - The input item type
17
+ * @typeParam O - The output item type
18
+ */
19
+ export class IncrementalParser extends Parser {
20
+ /** Current position in the input stream */
21
+ inputOffset = 0;
22
+ /** Number of outputs generated */
23
+ outputOffset = 0;
24
+ /** Buffer holding input items */
25
+ buffer = [];
26
+ /** Current position in the buffer */
27
+ bufferIndex = 0;
28
+ /** Whether end of file has been signaled */
29
+ eof = false;
30
+ /**
31
+ * Feeds input items into the parser buffer.
32
+ *
33
+ * @param input - Input items to add to the buffer
34
+ */
35
+ feed(...input) {
36
+ for (const item of input) {
37
+ if (Array.isArray(item)) {
38
+ for (const subItem of item) {
39
+ this.buffer.push(subItem);
40
+ }
41
+ continue;
42
+ }
43
+ this.buffer.push(item);
44
+ }
45
+ }
46
+ /**
47
+ * Checks if end of file has been reached and buffer is exhausted.
48
+ *
49
+ * @returns True if no more input is available
50
+ */
51
+ atEof() {
52
+ return this.eof && this.bufferIndex >= this.buffer.length;
53
+ }
54
+ /**
55
+ * Peeks at an item in the buffer without consuming it.
56
+ *
57
+ * @param ahead - Number of positions to look ahead (default: 0)
58
+ * @returns The item at the peek position, or null if at EOF
59
+ * @throws NoMoreTokensError if more input is needed and EOF not signaled
60
+ */
61
+ peek(ahead = 0) {
62
+ const index = this.bufferIndex + ahead;
63
+ if (index >= this.buffer.length) {
64
+ if (!this.eof) {
65
+ throw new NoMoreTokensError('No more items available');
66
+ }
67
+ return null;
68
+ }
69
+ return this.buffer[index];
70
+ }
71
+ /**
72
+ * Consumes and returns the next item from the buffer.
73
+ *
74
+ * @returns The next item
75
+ * @throws NoMoreTokensError if more input is needed and EOF not signaled
76
+ * @throws EofReachedError if at EOF and no more items available
77
+ */
78
+ next() {
79
+ if (this.bufferIndex >= this.buffer.length) {
80
+ if (!this.eof) {
81
+ throw new NoMoreTokensError('No more items available');
82
+ }
83
+ throw new EofReachedError('End of file reached');
84
+ }
85
+ this.inputOffset++;
86
+ return this.buffer[this.bufferIndex++];
87
+ }
88
+ expectValue(value, itemType) {
89
+ if (typeof itemType === 'function') {
90
+ if (!(value instanceof itemType)) {
91
+ throw new Error(`[offset: ${this.inputOffset}] Expected ${itemType.name} but got ${value}`);
92
+ }
93
+ return value;
94
+ }
95
+ if (value !== itemType) {
96
+ const type = typeof value === 'object'
97
+ ? (value?.constructor.name ?? value)
98
+ : value;
99
+ throw new Error(`[offset: ${this.inputOffset}] Expected ${itemType} but got ${type}`);
100
+ }
101
+ return value;
102
+ }
103
+ /**
104
+ * Consumes and validates the next item against an expected type or value.
105
+ *
106
+ * @typeParam T - The expected item type
107
+ * @param itemType - Constructor or value to match against
108
+ * @returns The consumed item cast to the expected type
109
+ * @throws Error if the item doesn't match the expected type/value
110
+ */
111
+ expect(itemType) {
112
+ const item = this.next();
113
+ return this.expectValue(item, itemType);
114
+ }
115
+ /**
116
+ * Tries multiple parsing functions and returns the first successful result.
117
+ * Automatically backtracks on failure.
118
+ *
119
+ * @param fn - Array of parsing functions to try
120
+ * @returns The result from the first successful parsing function
121
+ * @throws NoMoreTokensError if any function needs more input
122
+ * @throws Error if all parsing functions fail
123
+ */
124
+ oneOf(...fn) {
125
+ for (const f of fn) {
126
+ const savedOffset = this.inputOffset;
127
+ const savedIndex = this.bufferIndex;
128
+ try {
129
+ return f.bind(this)();
130
+ }
131
+ catch (err) {
132
+ if (err instanceof NoMoreTokensError) {
133
+ throw err;
134
+ }
135
+ this.inputOffset = savedOffset;
136
+ this.bufferIndex = savedIndex;
137
+ }
138
+ }
139
+ throw new Error('No parsing function succeeded');
140
+ }
141
+ /**
142
+ * Compacts the buffer by removing consumed items
143
+ */
144
+ compact() {
145
+ if (this.bufferIndex > 0) {
146
+ this.buffer = this.buffer.slice(this.bufferIndex);
147
+ this.bufferIndex = 0;
148
+ }
149
+ }
150
+ /**
151
+ * Override to customize when to compact the buffer
152
+ * By default, compacts when more than 1000 items have been consumed
153
+ *
154
+ * @returns boolean indicating whether to compact the buffer
155
+ */
156
+ canCompact() {
157
+ return this.bufferIndex > 1000;
158
+ }
159
+ /**
160
+ * Generates parsed output items from the buffer.
161
+ * Handles backtracking when more input is needed.
162
+ *
163
+ * @returns A generator yielding parsed output items
164
+ */
165
+ *parseNext() {
166
+ while (!this.atEof()) {
167
+ const savedIndex = this.bufferIndex;
168
+ try {
169
+ yield this.parse();
170
+ this.outputOffset++;
171
+ if (this.canCompact()) {
172
+ this.compact();
173
+ }
174
+ }
175
+ catch (err) {
176
+ if (!(err instanceof NoMoreTokensError)) {
177
+ throw err;
178
+ }
179
+ this.bufferIndex = savedIndex;
180
+ break;
181
+ }
182
+ }
183
+ }
184
+ }
@@ -0,0 +1,4 @@
1
+ export * from './generators.js';
2
+ export * from './types.js';
3
+ export * from './stringify.js';
4
+ export * from './parser.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './generators.js';
2
+ export * from './types.js';
3
+ export * from './stringify.js';
4
+ export * from './parser.js';
@@ -0,0 +1,6 @@
1
+ export type JsonPrimitive = string | number | boolean | null;
2
+ export declare class JsonKeyValuePair {
3
+ key: string;
4
+ value: JsonPrimitive;
5
+ constructor(key: string, value: JsonPrimitive);
6
+ }
@@ -0,0 +1,8 @@
1
+ export class JsonKeyValuePair {
2
+ key;
3
+ value;
4
+ constructor(key, value) {
5
+ this.key = key;
6
+ this.value = value;
7
+ }
8
+ }
@@ -0,0 +1,64 @@
1
+ import { ByteBuffer } from './byte-buffer.js';
2
+ import { JsonKeyValuePair } from './types.js';
3
+ export declare abstract class JsonEntity<T> {
4
+ consumed: boolean;
5
+ protected buffer: ByteBuffer;
6
+ constructor(buffer?: ByteBuffer | AsyncIterable<number>);
7
+ get entityType(): string;
8
+ set maxBufferSize(size: number);
9
+ feed(...input: (number | number[])[]): void;
10
+ protected abstract parse(): T;
11
+ protected skipWhitespace(): void;
12
+ read(): T;
13
+ readAsync(): Promise<T>;
14
+ consume(): void;
15
+ consumeAsync(): Promise<void>;
16
+ tryParse<T = this>(cb: (entity: this) => T): T | null;
17
+ }
18
+ export declare class JsonString extends JsonEntity<string> {
19
+ protected parse(): string;
20
+ }
21
+ export declare class JsonNumber extends JsonEntity<number> {
22
+ protected parse(): number;
23
+ }
24
+ export declare class JsonBoolean extends JsonEntity<boolean> {
25
+ protected parse(): boolean;
26
+ }
27
+ export declare class JsonNull extends JsonEntity<null> {
28
+ protected parse(): null;
29
+ }
30
+ export type JsonPrimitiveType = JsonString | JsonNumber | JsonBoolean | JsonNull;
31
+ export type JsonValueType = JsonPrimitiveType | JsonObject | JsonArray;
32
+ export declare class JsonValue extends JsonEntity<JsonValueType> {
33
+ private key?;
34
+ private value?;
35
+ constructor(buffer?: ByteBuffer, key?: JsonString);
36
+ protected parse(): JsonValueType;
37
+ read(): JsonValueType;
38
+ readAsync(): Promise<JsonValueType>;
39
+ consume(): void;
40
+ consumeAsync(): Promise<void>;
41
+ }
42
+ export declare class JsonObject<T = unknown> extends JsonEntity<T> {
43
+ members(): Generator<[JsonString, JsonValue]>;
44
+ membersAsync(): AsyncGenerator<[JsonString, JsonValue]>;
45
+ [Symbol.iterator](): Generator<[JsonString, JsonValue], any, any>;
46
+ [Symbol.asyncIterator](): AsyncGenerator<[JsonString, JsonValue], any, any>;
47
+ protected parse(): T;
48
+ }
49
+ export declare class JsonArray<T = unknown> extends JsonEntity<T[]> {
50
+ items(): Generator<JsonValueType>;
51
+ itemsAsync(): AsyncGenerator<JsonValueType>;
52
+ [Symbol.iterator](): Generator<JsonValueType, any, any>;
53
+ [Symbol.asyncIterator](): AsyncGenerator<JsonValueType, any, any>;
54
+ protected parse(): T[];
55
+ }
56
+ export declare class JsonKeyValueParser {
57
+ private container;
58
+ private parentKey?;
59
+ constructor(container?: JsonObject | JsonArray | JsonValue, parentKey?: string);
60
+ tryParse<T>(cb: (parser: this) => T): T | null;
61
+ feed(...input: (number | number[])[]): void;
62
+ parse(): Generator<JsonKeyValuePair>;
63
+ [Symbol.iterator](): Generator<JsonKeyValuePair, any, any>;
64
+ }