json-stream-lite 1.2.2 → 1.3.1

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/EXAMPLES.md CHANGED
@@ -90,13 +90,13 @@ console.log('\n=== Example 2: Stream Array Items ===')
90
90
  import { JsonArray } from 'json-stream-lite'
91
91
 
92
92
  const numbersJson = '[10, 20, 30, 40, 50]'
93
- const numbersParser = new JsonArray()
93
+ const numbersParser = new JsonArray<number>()
94
94
  numbersParser.feed(...stringToBytes(numbersJson))
95
95
 
96
96
  console.log('Processing items one by one:')
97
97
  let sum = 0
98
98
  for (const item of numbersParser.items()) {
99
- const value = item.read() as number
99
+ const value = item.readValue()
100
100
  sum += value
101
101
  console.log(` Current value: ${value}, Running sum: ${sum}`)
102
102
  }
@@ -326,7 +326,7 @@ async function parseAsyncArray() {
326
326
  console.log('Processing items as they arrive:')
327
327
  let sum = 0
328
328
  for await (const item of parser) {
329
- const value = await item.readAsync()
329
+ const value = await item.readValueAsync()
330
330
  sum += value as number
331
331
  console.log(` Received: ${value}, Running sum: ${sum}`)
332
332
  }
@@ -1167,3 +1167,142 @@ for await (const streamChunk of jsonObject.streamAsync(2)) {
1167
1167
  * Received string chunk: le
1168
1168
  */
1169
1169
  ```
1170
+
1171
+ ## JSON Comments (JSONC) Parsing Example
1172
+
1173
+ ```typescript
1174
+ /**
1175
+ * This example demonstrates how to parse JSON with comments (JSONC format) using JsonComment.
1176
+ * Supports both single-line (//) and block (/* *\/) comments.
1177
+ */
1178
+
1179
+ import { JsonObject, JsonComment } from 'json-stream-lite'
1180
+
1181
+ // Helper to convert string to bytes
1182
+ function stringToBytes(str: string): number[] {
1183
+ return Array.from(new TextEncoder().encode(str))
1184
+ }
1185
+
1186
+ // Example 1: Parse single-line comments
1187
+ console.log('=== Example 1: Single-line Comments ===')
1188
+ const jsoncWithLineComments = `{
1189
+ // This is a name field
1190
+ // Another comment
1191
+ "name": "Alice",
1192
+ // Age in years
1193
+ "age": 30
1194
+ }`
1195
+
1196
+ const parser1 = new JsonObject()
1197
+ parser1.feed(...stringToBytes(jsoncWithLineComments))
1198
+
1199
+ // Access pre-comments for object members
1200
+ for (const { key: keyEntity, value: valueEntity } of parser1) {
1201
+ // Get comments before the key
1202
+ const preComments = keyEntity.preCommentStrings
1203
+
1204
+ const key = keyEntity.read()
1205
+ if (preComments.length > 0) {
1206
+ console.log(`Comment for "${key}":`, preComments.join(', '))
1207
+ }
1208
+
1209
+ const value = valueEntity.readValue()
1210
+ console.log(`${key}: ${value}`)
1211
+ }
1212
+
1213
+ // Example 2: Parse block comments
1214
+ console.log('\n=== Example 2: Block Comments ===')
1215
+ const jsoncWithBlockComments = `{
1216
+ /*
1217
+ * User identification
1218
+ * Required field
1219
+ */
1220
+ "id": 123,
1221
+ /* Status flag */ "active": true
1222
+ }`
1223
+
1224
+ const parser2 = new JsonObject()
1225
+ parser2.feed(...stringToBytes(jsoncWithBlockComments))
1226
+
1227
+ for (const { key: keyEntity, value: valueEntity } of parser2) {
1228
+ const preComment = keyEntity.singlePreCommentString
1229
+ const key = keyEntity.read()
1230
+
1231
+ if (preComment) {
1232
+ console.log(`Comment: ${preComment}`)
1233
+ }
1234
+
1235
+ const value = valueEntity.readValue()
1236
+ console.log(`Key: ${key}, Value: ${value}`)
1237
+ }
1238
+
1239
+ // Example 3: Direct JsonComment parsing
1240
+ console.log('\n=== Example 3: Direct Comment Parsing ===')
1241
+ const lineComment = '// This is a single-line comment\n'
1242
+ const commentParser1 = new JsonComment()
1243
+ commentParser1.feed(...stringToBytes(lineComment))
1244
+ const comment1 = commentParser1.read()
1245
+ console.log('Line comment:', comment1)
1246
+ console.log('Comment style:', commentParser1.style) // 'line'
1247
+
1248
+ const blockComment = '/* This is a block comment */'
1249
+ const commentParser2 = new JsonComment()
1250
+ commentParser2.feed(...stringToBytes(blockComment))
1251
+ const comment2 = commentParser2.read()
1252
+ console.log('Block comment:', comment2)
1253
+ console.log('Comment style:', commentParser2.style) // 'block'
1254
+
1255
+ // Example 4: Comments after values
1256
+ console.log('\n=== Example 4: Post-value Comments ===')
1257
+ const jsoncWithPostComments = `{
1258
+ "status": "ok" // Everything is fine
1259
+ }`
1260
+
1261
+ const parser4 = new JsonObject()
1262
+ parser4.feed(...stringToBytes(jsoncWithPostComments))
1263
+
1264
+ for (const { key: keyEntity, value: valueEntity } of parser4) {
1265
+ const key = keyEntity.read()
1266
+ const value = valueEntity.readValue()
1267
+
1268
+ // Get comments after the value
1269
+ const postComments = valueEntity.postCommentStrings
1270
+ if (postComments.length > 0) {
1271
+ console.log(`${key}: ${value} // ${postComments.join(', ')}`)
1272
+ } else {
1273
+ console.log(`${key}: ${value}`)
1274
+ }
1275
+ }
1276
+
1277
+ // Example 5: Mixed comments
1278
+ console.log('\n=== Example 5: Mixed Comment Styles ===')
1279
+ const jsoncMixed = `{
1280
+ // Configuration file
1281
+ "version": "1.0", /* semantic versioning */
1282
+ /*
1283
+ * Environment settings
1284
+ */
1285
+ "env": "production" // current environment
1286
+ }`
1287
+
1288
+ const parser5 = new JsonObject()
1289
+ parser5.feed(...stringToBytes(jsoncMixed))
1290
+
1291
+ console.log('Parsing JSONC with mixed comment styles:')
1292
+ for (const { key: keyEntity, value: valueEntity } of parser5) {
1293
+ const pre = keyEntity.preCommentStrings
1294
+ const key = keyEntity.read()
1295
+ const value = valueEntity.readValue()
1296
+ const post = valueEntity.postCommentStrings
1297
+
1298
+ if (pre.length > 0) {
1299
+ console.log(` [Pre] ${pre.join(' | ')}`)
1300
+ }
1301
+ console.log(` ${key}: ${value}`)
1302
+ if (post.length > 0) {
1303
+ console.log(` [Post] ${post.join(' | ')}`)
1304
+ }
1305
+ }
1306
+
1307
+ console.log('\n✅ All comment parsing examples completed!')
1308
+ ```
package/README.md CHANGED
@@ -4,6 +4,9 @@
4
4
 
5
5
  A lightweight, memory-efficient, zero-dependency streaming JSON parser and stringifier written in TypeScript. Process large JSON files without loading them entirely into memory.
6
6
 
7
+ [![npm version](https://img.shields.io/npm/v/json-stream-lite.svg)](https://www.npmjs.com/package/json-stream-lite)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+
7
10
  ## Features
8
11
 
9
12
  - 🚀 **Stream parsing**: Parse JSON incrementally as data arrives
@@ -182,6 +185,9 @@ import { jsonStreamStringifyBytes } from 'json-stream-lite'
182
185
 
183
186
  const data = { name: 'Alice', age: 30 }
184
187
 
188
+ // Example with a hypothetical writeToFile function
189
+ declare function writeToFile(data: Uint8Array): Promise<void>
190
+
185
191
  for (const bytes of jsonStreamStringifyBytes(data)) {
186
192
  // bytes is a Uint8Array
187
193
  await writeToFile(bytes)
@@ -215,6 +221,9 @@ See [docs](https://jacobshirley.github.io/json-stream-lite/v1).
215
221
  import { createReadStream } from 'fs'
216
222
  import { JsonObject } from 'json-stream-lite'
217
223
 
224
+ // Example processing function
225
+ declare function processRecord(key: string, value: unknown): Promise<void>
226
+
218
227
  async function processLargeFile(filePath: string) {
219
228
  const stream = createReadStream(filePath)
220
229
  const parser = new JsonObject(stream)
@@ -277,6 +286,8 @@ See [string streaming](./EXAMPLES.md#streaming-json-strings-advanced-usage) for
277
286
  ### 1. Processing API Responses
278
287
 
279
288
  ```typescript
289
+ import { JsonObject } from 'json-stream-lite'
290
+
280
291
  async function processApiResponse(url: string) {
281
292
  const response = await fetch(url)
282
293
  const parser = new JsonObject(response.body!)
@@ -329,7 +340,10 @@ async function generateLargeFile(data: unknown, outputPath: string) {
329
340
  ```typescript
330
341
  import { jsonStreamStringify } from 'json-stream-lite'
331
342
 
332
- async function* exportDatabase(query: string) {
343
+ async function* exportDatabase(
344
+ query: string,
345
+ db: { query: (sql: string) => Promise<unknown[]> },
346
+ ) {
333
347
  const records = await db.query(query)
334
348
 
335
349
  for (const chunk of jsonStreamStringify(records, null, 2)) {
@@ -337,10 +351,13 @@ async function* exportDatabase(query: string) {
337
351
  }
338
352
  }
339
353
 
340
- // Stream to client
341
- app.get('/export', async (req, res) => {
354
+ // Example usage with Express-like server
355
+ declare const db: { query: (sql: string) => Promise<unknown[]> }
356
+ declare const app: any
357
+
358
+ app.get('/export', async (req: any, res: any) => {
342
359
  res.setHeader('Content-Type', 'application/json')
343
- for await (const chunk of exportDatabase('SELECT * FROM users')) {
360
+ for await (const chunk of exportDatabase('SELECT * FROM users', db)) {
344
361
  res.write(chunk)
345
362
  }
346
363
  res.end()
@@ -22,6 +22,10 @@ export declare class ByteBuffer {
22
22
  protected buffer: number[];
23
23
  /** Optional async iterable input source */
24
24
  protected asyncIterable?: ByteStream;
25
+ /** Cached sync iterator */
26
+ private syncIterator?;
27
+ /** Cached async iterator */
28
+ private asyncIterator?;
25
29
  /**
26
30
  * Creates a new ByteBuffer instance.
27
31
  *
@@ -51,6 +55,11 @@ export declare class ByteBuffer {
51
55
  */
52
56
  feed(...input: StreamInput[]): void;
53
57
  push(byte: number): void;
58
+ /**
59
+ * Checks if the buffer has been fully consumed.
60
+ * @returns True if buffer index is at or beyond the end of the buffer
61
+ * */
62
+ atEnd(): boolean;
54
63
  /**
55
64
  * Checks if end of file has been reached and buffer is exhausted.
56
65
  *
@@ -44,6 +44,10 @@ export class ByteBuffer {
44
44
  buffer = [];
45
45
  /** Optional async iterable input source */
46
46
  asyncIterable;
47
+ /** Cached sync iterator */
48
+ syncIterator;
49
+ /** Cached async iterator */
50
+ asyncIterator;
47
51
  /**
48
52
  * Creates a new ByteBuffer instance.
49
53
  *
@@ -67,10 +71,12 @@ export class ByteBuffer {
67
71
  if (!this.asyncIterable || !(Symbol.iterator in this.asyncIterable)) {
68
72
  return false;
69
73
  }
70
- const iterator = this.asyncIterable[Symbol.iterator]();
74
+ if (!this.syncIterator) {
75
+ this.syncIterator = this.asyncIterable[Symbol.iterator]();
76
+ }
71
77
  let processed = false;
72
78
  while (this.length < this.maxBufferSize || !processed) {
73
- const next = iterator.next();
79
+ const next = this.syncIterator.next();
74
80
  processed = true;
75
81
  if (next.done) {
76
82
  this.eof = true;
@@ -91,11 +97,13 @@ export class ByteBuffer {
91
97
  !(Symbol.asyncIterator in this.asyncIterable)) {
92
98
  return;
93
99
  }
94
- const iterator = this.asyncIterable[Symbol.asyncIterator]();
100
+ if (!this.asyncIterator) {
101
+ this.asyncIterator = this.asyncIterable[Symbol.asyncIterator]();
102
+ }
95
103
  let processed = false;
96
104
  while (this.length < this.maxBufferSize || !processed) {
97
105
  processed = true;
98
- const next = await iterator.next();
106
+ const next = await this.asyncIterator.next();
99
107
  if (next.done) {
100
108
  this.eof = true;
101
109
  return;
@@ -148,13 +156,20 @@ export class ByteBuffer {
148
156
  }
149
157
  this.buffer.push(byte);
150
158
  }
159
+ /**
160
+ * Checks if the buffer has been fully consumed.
161
+ * @returns True if buffer index is at or beyond the end of the buffer
162
+ * */
163
+ atEnd() {
164
+ return this.bufferIndex >= this.buffer.length;
165
+ }
151
166
  /**
152
167
  * Checks if end of file has been reached and buffer is exhausted.
153
168
  *
154
169
  * @returns True if no more input is available
155
170
  */
156
171
  atEof() {
157
- return this.eof && this.bufferIndex >= this.buffer.length;
172
+ return this.eof && this.atEnd();
158
173
  }
159
174
  /**
160
175
  * Peeks at an item in the buffer without consuming it.
@@ -4,6 +4,7 @@ import { JsonKeyValuePair } from './types.js';
4
4
  * Flattens nested structures using dot notation and array indices.
5
5
  *
6
6
  * @param bytes - The JSON input as bytes or string
7
+ * @param options - Optional parser options (jsonc, strict)
7
8
  * @yields Key-value pairs as [key, value] tuples
8
9
  *
9
10
  * @example
@@ -5,6 +5,7 @@ import { stringToBytes } from './utils.js';
5
5
  * Flattens nested structures using dot notation and array indices.
6
6
  *
7
7
  * @param bytes - The JSON input as bytes or string
8
+ * @param options - Optional parser options (jsonc, strict)
8
9
  * @yields Key-value pairs as [key, value] tuples
9
10
  *
10
11
  * @example
package/dist/parser.d.ts CHANGED
@@ -16,6 +16,50 @@ export declare abstract class JsonEntity<T> {
16
16
  * @param buffer - Optional ByteBuffer or ByteStream to read from
17
17
  */
18
18
  constructor(buffer?: ByteBuffer | ByteStream);
19
+ /**
20
+ * Sets the end-of-file (EOF) state of the buffer, indicating whether no more data will be added.
21
+ */
22
+ set eof(value: boolean);
23
+ /**
24
+ * Skips whitespace and yields any comments encountered.
25
+ */
26
+ private getComments;
27
+ /**
28
+ * Asynchronously skips whitespace and yields any comments encountered, waiting for more data if needed.
29
+ */
30
+ private getCommentsAsync;
31
+ /**
32
+ * Generators for pre-comments. In JSONC, comments can appear before or after any value.
33
+ */
34
+ get preComments(): Generator<JsonComment>;
35
+ /**
36
+ * Generators for post-comments. In JSONC, comments can appear before or after any value.
37
+ */
38
+ get postComments(): Generator<JsonComment>;
39
+ /**
40
+ * Async generators for pre-comments. In JSONC, comments can appear before or after any value.
41
+ */
42
+ get preCommentsAsync(): AsyncGenerator<JsonComment>;
43
+ /**
44
+ * Async generators for post-comments. In JSONC, comments can appear before or after any value.
45
+ */
46
+ get postCommentsAsync(): AsyncGenerator<JsonComment>;
47
+ /**
48
+ * Convenience getters to read all pre comments as strings. Consumes the comments in the process.
49
+ */
50
+ get preCommentStrings(): string[];
51
+ /**
52
+ * Convenience getters to read all post comments as strings. Consumes the comments in the process.
53
+ */
54
+ get postCommentStrings(): string[];
55
+ /**
56
+ * Convenience getter to read a single pre comment as a string. Returns null if no comments are present. Consumes the comment in the process.
57
+ */
58
+ get singlePreCommentString(): string | null;
59
+ /**
60
+ * Convenience getter to read a single post comment as a string. Returns null if no comments are present. Consumes the comment in the process.
61
+ */
62
+ get singlePostCommentString(): string | null;
19
63
  /**
20
64
  * Gets the type name of this entity.
21
65
  *
@@ -55,7 +99,7 @@ export declare abstract class JsonEntity<T> {
55
99
  */
56
100
  protected abstract parse(): T;
57
101
  /**
58
- * Skips whitespace characters in the buffer.
102
+ * Skips whitespace characters (and comments when JSONC is enabled) in the buffer.
59
103
  */
60
104
  protected skipWhitespace(): void;
61
105
  /**
@@ -120,6 +164,21 @@ export declare abstract class JsonEntity<T> {
120
164
  *
121
165
  * @typeParam T - The specific string type (defaults to string)
122
166
  */
167
+ /**
168
+ * Represents a JSONC comment (single-line or block).
169
+ * Extends JsonEntity so it can be yielded alongside other entities in JSONC containers.
170
+ */
171
+ /**
172
+ * Represents a JSONC comment (single-line or block).
173
+ * Parses lazily from the buffer — the comment text is only decoded when read().
174
+ */
175
+ export declare class JsonComment extends JsonEntity<string> {
176
+ /** The comment style: 'line' for //, 'block' for /* * / */
177
+ style: 'line' | 'block';
178
+ protected parse(): string;
179
+ get preComments(): Generator<JsonComment>;
180
+ get postComments(): Generator<JsonComment>;
181
+ }
123
182
  export declare class JsonString<T extends string = string> extends JsonEntity<T> {
124
183
  /**
125
184
  * Parses a JSON string from the buffer.
@@ -228,6 +287,7 @@ export type JsonValueType<T = any> = T extends string ? JsonString<Extract<T, st
228
287
  export declare class JsonValue<T = any, K extends string = string> extends JsonEntity<JsonValueType<T>> {
229
288
  private key?;
230
289
  private value?;
290
+ hasReadValue: boolean;
231
291
  /**
232
292
  * Creates a new JsonValue entity.
233
293
  *
@@ -336,24 +396,24 @@ export declare class JsonArray<T = any> extends JsonEntity<T[]> {
336
396
  *
337
397
  * @yields Each item entity in the array
338
398
  */
339
- items(): Generator<JsonValueType<T>>;
399
+ items(): Generator<JsonValue<T>>;
340
400
  /**
341
401
  * Async generator that yields array items from a stream.
342
402
  * Allows for asynchronous streaming/incremental processing.
343
403
  *
344
404
  * @yields Each item entity in the array
345
405
  */
346
- itemsAsync(): AsyncGenerator<JsonValueType<T>>;
406
+ itemsAsync(): AsyncGenerator<JsonValue<T>>;
347
407
  /**
348
408
  * Returns an iterator for array items.
349
409
  * Enables use of for...of loops on JsonArray.
350
410
  */
351
- [Symbol.iterator](): Generator<JsonValueType<T>, any, any>;
411
+ [Symbol.iterator](): Generator<JsonValue<T, string>, any, any>;
352
412
  /**
353
413
  * Returns an async iterator for array items.
354
414
  * Enables use of for await...of loops on JsonArray.
355
415
  */
356
- [Symbol.asyncIterator](): AsyncGenerator<JsonValueType<T>, any, any>;
416
+ [Symbol.asyncIterator](): AsyncGenerator<JsonValue<T, string>, any, any>;
357
417
  /**
358
418
  * Parses the entire array into a JavaScript array.
359
419
  *
package/dist/parser.js CHANGED
@@ -36,6 +36,8 @@ const BYTE_MAP = {
36
36
  backslash: 92,
37
37
  formFeed: 12,
38
38
  backspace: 8,
39
+ slash: 47,
40
+ asterisk: 42,
39
41
  };
40
42
  /**
41
43
  * Checks if a byte represents a whitespace character.
@@ -101,6 +103,118 @@ export class JsonEntity {
101
103
  this.buffer =
102
104
  buffer instanceof ByteBuffer ? buffer : new ByteBuffer(buffer);
103
105
  }
106
+ /**
107
+ * Sets the end-of-file (EOF) state of the buffer, indicating whether no more data will be added.
108
+ */
109
+ set eof(value) {
110
+ this.buffer.eof = value;
111
+ }
112
+ /**
113
+ * Skips whitespace and yields any comments encountered.
114
+ */
115
+ *getComments() {
116
+ while (true) {
117
+ this.skipWhitespace();
118
+ if (this.buffer.peek() === BYTE_MAP.colon) {
119
+ this.buffer.next(); // consume :
120
+ }
121
+ this.skipWhitespace();
122
+ const byte = this.buffer.peek();
123
+ if (byte === BYTE_MAP.slash) {
124
+ const next = this.buffer.peek(1);
125
+ if (next === BYTE_MAP.slash || next === BYTE_MAP.asterisk) {
126
+ const comment = new JsonComment(this.buffer);
127
+ yield comment;
128
+ comment.consume();
129
+ continue;
130
+ }
131
+ }
132
+ break;
133
+ }
134
+ }
135
+ /**
136
+ * Asynchronously skips whitespace and yields any comments encountered, waiting for more data if needed.
137
+ */
138
+ async *getCommentsAsync() {
139
+ while (true) {
140
+ const comments = this.getComments();
141
+ const comment = this.tryParse(() => comments.next());
142
+ if (comment === undefined) {
143
+ await this.buffer.readStreamAsync();
144
+ continue;
145
+ }
146
+ if (comment.done) {
147
+ break;
148
+ }
149
+ yield comment.value;
150
+ }
151
+ }
152
+ /**
153
+ * Generators for pre-comments. In JSONC, comments can appear before or after any value.
154
+ */
155
+ get preComments() {
156
+ return this.getComments();
157
+ }
158
+ /**
159
+ * Generators for post-comments. In JSONC, comments can appear before or after any value.
160
+ */
161
+ get postComments() {
162
+ return this.getComments();
163
+ }
164
+ /**
165
+ * Async generators for pre-comments. In JSONC, comments can appear before or after any value.
166
+ */
167
+ get preCommentsAsync() {
168
+ return this.getCommentsAsync();
169
+ }
170
+ /**
171
+ * Async generators for post-comments. In JSONC, comments can appear before or after any value.
172
+ */
173
+ get postCommentsAsync() {
174
+ return this.getCommentsAsync();
175
+ }
176
+ /**
177
+ * Convenience getters to read all pre comments as strings. Consumes the comments in the process.
178
+ */
179
+ get preCommentStrings() {
180
+ const strings = [];
181
+ for (const comment of this.preComments) {
182
+ strings.push(comment.read());
183
+ }
184
+ return strings;
185
+ }
186
+ /**
187
+ * Convenience getters to read all post comments as strings. Consumes the comments in the process.
188
+ */
189
+ get postCommentStrings() {
190
+ const strings = [];
191
+ for (const comment of this.postComments) {
192
+ strings.push(comment.read());
193
+ }
194
+ return strings;
195
+ }
196
+ /**
197
+ * Convenience getter to read a single pre comment as a string. Returns null if no comments are present. Consumes the comment in the process.
198
+ */
199
+ get singlePreCommentString() {
200
+ const preComments = this.preComments;
201
+ const first = preComments.next();
202
+ if (first.done) {
203
+ return null;
204
+ }
205
+ return first.value.read();
206
+ }
207
+ /**
208
+ * Convenience getter to read a single post comment as a string. Returns null if no comments are present. Consumes the comment in the process.
209
+ */
210
+ get singlePostCommentString() {
211
+ const postComments = this.postComments;
212
+ const first = postComments.next();
213
+ if (first.done) {
214
+ return null;
215
+ }
216
+ return first.value.read();
217
+ }
104
218
  /**
105
219
  * Gets the type name of this entity.
106
220
  *
@@ -146,7 +260,7 @@ export class JsonEntity {
146
260
  }
147
261
  }
148
262
  /**
149
- * Skips whitespace characters in the buffer.
263
+ * Skips whitespace characters (and comments when JSONC is enabled) in the buffer.
150
264
  */
151
265
  skipWhitespace() {
152
266
  while (isWhitespace(this.buffer.peek())) {
@@ -163,6 +277,8 @@ export class JsonEntity {
163
277
  if (this.consumed) {
164
278
  throw new Error('JSON entity has already been consumed.');
165
279
  }
280
+ for (const _ of this.preComments) {
281
+ }
166
282
  const read = this.parse();
167
283
  this.consumed = true;
168
284
  if (this.buffer.canCompact())
@@ -213,9 +329,6 @@ export class JsonEntity {
213
329
  * @throws Error if the entity has already been consumed
214
330
  */
215
331
  tryParse(cb) {
216
- if (this.consumed) {
217
- throw new Error('JSON entity has already been consumed.');
218
- }
219
332
  this.buffer.locked = true;
220
333
  return this.buffer.resetOnFail(() => {
221
334
  const res = cb(this);
@@ -264,6 +377,77 @@ export class JsonEntity {
264
377
  *
265
378
  * @typeParam T - The specific string type (defaults to string)
266
379
  */
380
+ /**
381
+ * Represents a JSONC comment (single-line or block).
382
+ * Extends JsonEntity so it can be yielded alongside other entities in JSONC containers.
383
+ */
384
+ /**
385
+ * Represents a JSONC comment (single-line or block).
386
+ * Parses lazily from the buffer — the comment text is only decoded when read().
387
+ */
388
+ export class JsonComment extends JsonEntity {
389
+ /** The comment style: 'line' for //, 'block' for /* * / */
390
+ style = 'line';
391
+ parse() {
392
+ this.skipWhitespace();
393
+ if (this.buffer.peek() === BYTE_MAP.colon) {
394
+ this.buffer.next(); // consume :
395
+ }
396
+ this.skipWhitespace();
397
+ if (this.buffer.peek() !== BYTE_MAP.slash) {
398
+ return '';
399
+ }
400
+ // Consume opening // or /*
401
+ this.buffer.next(); // consume /
402
+ const second = this.buffer.next();
403
+ const bytes = [];
404
+ if (second === BYTE_MAP.slash) {
405
+ this.style = 'line';
406
+ while (true) {
407
+ const byte = this.buffer.peek();
408
+ if (byte === null ||
409
+ byte === BYTE_MAP.lineFeed ||
410
+ byte === BYTE_MAP.carriageReturn) {
411
+ if (byte === BYTE_MAP.carriageReturn) {
412
+ this.buffer.next();
413
+ if (this.buffer.peek() === BYTE_MAP.lineFeed) {
414
+ this.buffer.next();
415
+ }
416
+ }
417
+ else if (byte === BYTE_MAP.lineFeed) {
418
+ this.buffer.next();
419
+ }
420
+ break;
421
+ }
422
+ bytes.push(this.buffer.next());
423
+ }
424
+ }
425
+ else {
426
+ // asterisk — block comment
427
+ this.style = 'block';
428
+ while (true) {
429
+ const byte = this.buffer.peek();
430
+ if (byte === null)
431
+ break;
432
+ if (byte === BYTE_MAP.asterisk &&
433
+ this.buffer.peek(1) === BYTE_MAP.slash) {
434
+ this.buffer.next(); // *
435
+ this.buffer.next(); // /
436
+ break;
437
+ }
438
+ bytes.push(this.buffer.next());
439
+ }
440
+ }
441
+ const commentString = bytesToString(new Uint8Array(bytes)).trim();
442
+ return commentString;
443
+ }
444
+ get preComments() {
445
+ return (function* () { })();
446
+ }
447
+ get postComments() {
448
+ return (function* () { })();
449
+ }
450
+ }
267
451
  export class JsonString extends JsonEntity {
268
452
  /**
269
453
  * Parses a JSON string from the buffer.
@@ -504,6 +688,7 @@ export class JsonNull extends JsonEntity {
504
688
  export class JsonValue extends JsonEntity {
505
689
  key;
506
690
  value;
691
+ hasReadValue = false;
507
692
  /**
508
693
  * Creates a new JsonValue entity.
509
694
  *
@@ -567,6 +752,7 @@ export class JsonValue extends JsonEntity {
567
752
  }
568
753
  this.value = super.read();
569
754
  this.consumed = false;
755
+ this.hasReadValue = true;
570
756
  return this.value;
571
757
  }
572
758
  /**
@@ -753,10 +939,9 @@ export class JsonArray extends JsonEntity {
753
939
  this.buffer.next(); // consume ,
754
940
  this.skipWhitespace();
755
941
  }
756
- const value = new JsonValue(this.buffer).read();
757
- yield value;
758
- if (!value.consumed)
759
- value.read();
942
+ const valueObject = new JsonValue(this.buffer);
943
+ yield valueObject;
944
+ valueObject.consume();
760
945
  this.skipWhitespace();
761
946
  }
762
947
  this.buffer.expect(BYTE_MAP.rightSquare);
@@ -808,7 +993,7 @@ export class JsonArray extends JsonEntity {
808
993
  parse() {
809
994
  const values = [];
810
995
  for (const value of this) {
811
- values.push(value.read());
996
+ values.push(value.readValue());
812
997
  }
813
998
  return values;
814
999
  }
@@ -858,7 +1043,7 @@ export class JsonKeyValueParser extends JsonEntity {
858
1043
  else if (this.container instanceof JsonArray) {
859
1044
  let index = 0;
860
1045
  for (const valueEntity of this.container) {
861
- const value = valueEntity;
1046
+ const value = valueEntity.read();
862
1047
  const finalKey = this.parentKey
863
1048
  ? `${this.parentKey}[${index}]`
864
1049
  : `[${index}]`;
@@ -1,9 +1,20 @@
1
+ /**
2
+ * Comment entry for JSONC stringification.
3
+ */
4
+ export type JsoncStringifyComment = string | {
5
+ text: string;
6
+ style?: 'line' | 'block';
7
+ };
1
8
  /**
2
9
  * Options for JSON streaming stringification.
3
10
  */
4
11
  export type JsonStreamStringifyOptions = {
5
12
  /** Maximum size of string chunks when yielding formatted strings */
6
13
  stringChunkSize?: number;
14
+ /** Enable JSONC output (trailing commas after last items) */
15
+ jsonc?: boolean;
16
+ /** Comments to emit, keyed by dot-notation path. Only emitted when indent > 0. */
17
+ comments?: Record<string, JsoncStringifyComment | JsoncStringifyComment[]>;
7
18
  };
8
19
  /**
9
20
  * Converts a JavaScript value to JSON format, yielding string chunks.
package/dist/stringify.js CHANGED
@@ -90,6 +90,25 @@ function hasCustomToStringFunction(value) {
90
90
  value.toString !== Object.prototype.toString &&
91
91
  value.toString !== Array.prototype.toString);
92
92
  }
93
+ /**
94
+ * Yields comment string(s) for a given path from the comments map.
95
+ */
96
+ function* emitComments(path, options, indentStr) {
97
+ if (!options?.comments || !options.comments[path])
98
+ return;
99
+ const entries = options.comments[path];
100
+ const list = Array.isArray(entries) ? entries : [entries];
101
+ for (const entry of list) {
102
+ const text = typeof entry === 'string' ? entry : entry.text;
103
+ const style = typeof entry === 'string' ? 'line' : (entry.style ?? 'line');
104
+ if (style === 'line') {
105
+ yield `${indentStr}// ${text}\n`;
106
+ }
107
+ else {
108
+ yield `${indentStr}/* ${text} */\n`;
109
+ }
110
+ }
111
+ }
93
112
  /**
94
113
  * Internal recursive function that stringifies a value with depth tracking.
95
114
  * Handles all JSON types including primitives, arrays, and objects.
@@ -100,9 +119,10 @@ function hasCustomToStringFunction(value) {
100
119
  * @param currentDepth - Current nesting depth for indentation
101
120
  * @param start - Indicates if this is the start of the stringification
102
121
  * @param options - Stringification options
122
+ * @param currentPath - Current dot-notation path for comment matching
103
123
  * @yields String chunks representing the JSON output
104
124
  */
105
- function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth = 0, start = true, options) {
125
+ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth = 0, start = true, options, currentPath = '') {
106
126
  if (replacer) {
107
127
  value = replacer('', value);
108
128
  }
@@ -133,21 +153,31 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
133
153
  else if (Array.isArray(value)) {
134
154
  const len = value.length;
135
155
  const valueIndent = indent * (currentDepth + 1);
156
+ const valueIndentStr = indent > 0 ? ' '.repeat(valueIndent) : '';
157
+ const isJsonc = options?.jsonc === true;
136
158
  yield '[';
137
159
  for (let i = 0; i < len; i++) {
138
160
  const next = value[i];
161
+ const isLast = i === len - 1;
139
162
  if (i > 0) {
140
163
  yield ',';
141
164
  }
142
165
  if (indent > 0) {
143
166
  yield '\n';
144
- yield ' '.repeat(valueIndent);
167
+ const itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;
168
+ yield* emitComments(itemPath, options, valueIndentStr);
169
+ yield valueIndentStr;
145
170
  }
146
171
  if (shouldIgnore(next)) {
147
172
  yield 'null';
173
+ if (isLast && isJsonc)
174
+ yield ',';
148
175
  continue;
149
176
  }
150
- yield* jsonStreamStringifyWithDepth(next, replacer, indent > 0 ? indent : 0, currentDepth + 1, false, options);
177
+ const itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;
178
+ yield* jsonStreamStringifyWithDepth(next, replacer, indent > 0 ? indent : 0, currentDepth + 1, false, options, itemPath);
179
+ if (isLast && isJsonc)
180
+ yield ',';
151
181
  }
152
182
  if (indent > 0 && len > 0) {
153
183
  yield '\n' + ' '.repeat(indent * currentDepth);
@@ -158,7 +188,12 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
158
188
  const keys = Object.keys(value);
159
189
  const len = keys.length;
160
190
  const valueIndent = indent * (currentDepth + 1);
191
+ const valueIndentStr = indent > 0 ? ' '.repeat(valueIndent) : '';
192
+ const isJsonc = options?.jsonc === true;
161
193
  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;
162
197
  yield '{';
163
198
  for (let i = 0; i < len; i++) {
164
199
  const key = keys[i];
@@ -169,14 +204,18 @@ function* jsonStreamStringifyWithDepth(value, replacer, indent = 0, currentDepth
169
204
  if (count > 0) {
170
205
  yield ',';
171
206
  }
207
+ const memberPath = currentPath ? `${currentPath}.${key}` : key;
172
208
  if (indent > 0) {
173
209
  yield '\n';
174
- yield ' '.repeat(valueIndent);
210
+ yield* emitComments(memberPath, options, valueIndentStr);
211
+ yield valueIndentStr;
175
212
  }
176
213
  yield* formatString(key, options?.stringChunkSize);
177
214
  yield `:${indent > 0 ? ' ' : ''}`;
178
- yield* jsonStreamStringifyWithDepth(next, replacer, indent > 0 ? indent : 0, currentDepth + 1, false, options);
215
+ yield* jsonStreamStringifyWithDepth(next, replacer, indent > 0 ? indent : 0, currentDepth + 1, false, options, memberPath);
179
216
  count++;
217
+ if (count === totalValid && isJsonc)
218
+ yield ',';
180
219
  }
181
220
  if (indent > 0 && len > 0) {
182
221
  yield '\n' + ' '.repeat(indent * currentDepth);
package/dist/types.d.ts CHANGED
@@ -17,3 +17,12 @@ export type JsonPrimitive = string | number | boolean | null;
17
17
  * and the value is a JSON primitive.
18
18
  */
19
19
  export type JsonKeyValuePair = [string, JsonPrimitive];
20
+ /**
21
+ * Options for configuring JSON parsing behavior.
22
+ */
23
+ export type JsonParserOptions = {
24
+ /** Enable JSONC (JSON with Comments) parsing. Allows // and /* * / comments. */
25
+ jsonc?: boolean;
26
+ /** Enforce strict JSON parsing. When false, trailing commas are allowed. Default: true. */
27
+ strict?: boolean;
28
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-stream-lite",
3
- "version": "1.2.2",
3
+ "version": "1.3.1",
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",
@@ -46,7 +46,7 @@
46
46
  "author": "Jacob Shirley",
47
47
  "license": "MIT",
48
48
  "devDependencies": {
49
- "typescript": "^5.9.3",
49
+ "typescript": "^6.0.2",
50
50
  "vitest": "^4.0.14",
51
51
  "@vitest/browser": "^4.0.14",
52
52
  "@vitest/browser-playwright": "^4.0.14",