-
Notifications
You must be signed in to change notification settings - Fork 641
/
Copy pathparse_stream.ts
526 lines (501 loc) · 14.8 KB
/
parse_stream.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.
import {
convertRowToObject,
type LineReader,
parseRecord,
type ParseResult,
} from "./_io.ts";
import { TextDelimiterStream } from "@std/streams/text-delimiter-stream";
/** Options for {@linkcode CsvParseStream}. */
export interface CsvParseStreamOptions {
/** Character which separates values.
*
* @default {","}
*/
separator?: string;
/** Character to start a comment.
*
* Lines beginning with the comment character without preceding whitespace
* are ignored. With leading whitespace the comment character becomes part of
* the field, even you provide `trimLeadingSpace: true`.
*
* By default, no character is considered to be a start of a comment.
*/
comment?: string;
/** Flag to trim the leading space of the value.
*
* This is done even if the field delimiter, `separator`, is white space.
*
* @default {false}
*/
trimLeadingSpace?: boolean;
/**
* Allow unquoted quote in a quoted field or non-double-quoted quotes in
* quoted field.
*
* @default {false}
*/
lazyQuotes?: boolean;
/**
* Enabling checking number of expected fields for each row.
*
* If positive, each record is required to have the given number of fields.
* If 0, it will be set to the number of fields in the first row, so that
* future rows must have the same field count.
* If negative, no check is made and records may have a variable number of
* fields.
*
* If the wrong number of fields is in a row, a {@linkcode https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError | SyntaxError}
* is thrown.
*/
fieldsPerRecord?: number;
/**
* If you provide `skipFirstRow: true` and `columns`, the first line will be
* skipped.
* If you provide `skipFirstRow: true` but not `columns`, the first line will
* be skipped and used as header definitions.
*
* @default {false}
*/
skipFirstRow?: boolean;
/** List of names used for header definition. */
columns?: readonly string[];
}
class StreamLineReader implements LineReader {
#reader: ReadableStreamDefaultReader<string>;
#done = false;
constructor(reader: ReadableStreamDefaultReader<string>) {
this.#reader = reader;
}
async readLine(): Promise<string | null> {
const { value, done } = await this.#reader.read();
if (done) {
this.#done = true;
return null;
} else {
// NOTE: Remove trailing CR for compatibility with golang's `encoding/csv`
return stripLastCR(value!);
}
}
isEOF(): boolean {
return this.#done;
}
cancel() {
this.#reader.cancel();
}
}
function stripLastCR(s: string): string {
return s.endsWith("\r") ? s.slice(0, -1) : s;
}
/** Row return type. */
export type RowType<T> = T extends undefined ? string[]
: ParseResult<CsvParseStreamOptions, T>[number];
/**
* `CsvParseStream` transforms a stream of CSV-encoded text into a stream of
* parsed objects.
*
* A `CsvParseStream` expects input conforming to
* {@link https://www.rfc-editor.org/rfc/rfc4180.html | RFC 4180}.
*
* @example Usage with default options
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
* import { assertType, IsExact } from "@std/testing/types"
*
* const source = ReadableStream.from([
* "name,age\n",
* "Alice,34\n",
* "Bob,24\n",
* ]);
* const stream = source.pipeThrough(new CsvParseStream());
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [
* ["name", "age"],
* ["Alice", "34"],
* ["Bob", "24"],
* ]);
* assertType<IsExact<typeof result, string[][]>>(true);
* ```
*
* @example Skip first row with `skipFirstRow: true`
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
* import { assertType, IsExact } from "@std/testing/types"
*
* const source = ReadableStream.from([
* "name,age\n",
* "Alice,34\n",
* "Bob,24\n",
* ]);
* const stream = source.pipeThrough(new CsvParseStream({ skipFirstRow: true }));
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [
* { name: "Alice", age: "34" },
* { name: "Bob", age: "24" },
* ]);
* assertType<IsExact<typeof result, Record<string, string>[]>>(true);
* ```
*
* @example Specify columns with `columns` option
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
* import { assertType, IsExact } from "@std/testing/types"
*
* const source = ReadableStream.from([
* "Alice,34\n",
* "Bob,24\n",
* ]);
* const stream = source.pipeThrough(new CsvParseStream({
* columns: ["name", "age"]
* }));
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [
* { name: "Alice", age: "34" },
* { name: "Bob", age: "24" },
* ]);
* assertType<IsExact<typeof result, Record<"name" | "age", string>[]>>(true);
* ```
*
* @example Specify columns with `columns` option and skip first row with
* `skipFirstRow: true`
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
* import { assertType, IsExact } from "@std/testing/types"
*
* const source = ReadableStream.from([
* "Alice,34\n",
* "Bob,24\n",
* ]);
* const stream = source.pipeThrough(new CsvParseStream({
* columns: ["name", "age"],
* skipFirstRow: true,
* }));
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [{ name: "Bob", age: "24" }]);
* assertType<IsExact<typeof result, Record<"name" | "age", string>[]>>(true);
* ```
*
* @example TSV (tab-separated values) with `separator: "\t"`
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
*
* const source = ReadableStream.from([
* "Alice\t34\n",
* "Bob\t24\n",
* ]);
* const stream = source.pipeThrough(new CsvParseStream({
* separator: "\t",
* }));
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [
* ["Alice", "34"],
* ["Bob", "24"],
* ]);
* ```
*
* @example Trim leading space with `trimLeadingSpace: true`
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
*
* const source = ReadableStream.from([
* " Alice,34\n ",
* "Bob, 24\n",
* ]);
* const stream = source.pipeThrough(new CsvParseStream({
* trimLeadingSpace: true,
* }));
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [
* ["Alice", "34"],
* ["Bob", "24"],
* ]);
* ```
*
* @example Quoted fields
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
*
* const source = ReadableStream.from([
* `"a ""word""","com`,
* `ma,","newline`,
* `\n"\nfoo,bar,b`,
* `az\n`,
* ]);
* const stream = source.pipeThrough(new CsvParseStream());
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [
* ['a "word"', "comma,", "newline\n"],
* ["foo", "bar", "baz"]
* ]);
* ```
*
* @example Allow lazy quotes with `lazyQuotes: true`
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
*
* const source = ReadableStream.from([
* `a "word","1"`,
* `2",a","b`,
* ]);
* const stream = source.pipeThrough(new CsvParseStream({
* lazyQuotes: true,
* }));
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [['a "word"', '1"2', 'a"', 'b']]);
* ```
*
* @example Define comment prefix with `comment` option
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
*
* const source = ReadableStream.from([
* "Alice,34\n",
* "# THIS IS A COMMENT\n",
* "Bob,24\n",
* ]);
* const stream = source.pipeThrough(new CsvParseStream({
* comment: "#",
* }));
* const result = await Array.fromAsync(stream);
*
* assertEquals(result, [
* ["Alice", "34"],
* ["Bob", "24"],
* ]);
* ```
*
* @example Infer the number of fields from the first row with
* `fieldsPerRecord: 0`
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
* import { assertRejects } from "@std/assert/rejects";
*
* const source = ReadableStream.from([
* "Alice,34\n",
* "Bob,24,CA\n", // Note that this row has more fields than the first row
* ]);
* const stream = source.pipeThrough(new CsvParseStream({
* fieldsPerRecord: 0,
* }));
* const reader = stream.getReader();
* assertEquals(await reader.read(), { done: false, value: ["Alice", "34"] });
* await assertRejects(
* () => reader.read(),
* SyntaxError,
* "Syntax error on line 2: expected 2 fields but got 3",
* );
* ```
*
* @example Enforce the number of field for each row with `fieldsPerRecord: 2`
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
* import { assertRejects } from "@std/assert/rejects";
*
* const source = ReadableStream.from([
* "Alice,34\n",
* "Bob,24,CA\n",
* ]);
* const stream = source.pipeThrough(new CsvParseStream({
* fieldsPerRecord: 2,
* }));
* const reader = stream.getReader();
* assertEquals(await reader.read(), { done: false, value: ["Alice", "34"] });
* await assertRejects(
* () => reader.read(),
* SyntaxError,
* "Syntax error on line 2: expected 2 fields but got 3",
* );
* ```
*
* @typeParam T The type of options for the stream.
*/
export class CsvParseStream<
const T extends CsvParseStreamOptions | undefined = undefined,
> implements TransformStream<string, RowType<T>> {
readonly #readable: ReadableStream<
string[] | Record<string, string | unknown>
>;
readonly #options: CsvParseStreamOptions;
readonly #lineReader: StreamLineReader;
readonly #lines: TextDelimiterStream;
#zeroBasedLineIndex = 0;
#isFirstRow = true;
// The number of fields per record that is either inferred from the first row
// (when options.fieldsPerRecord = 0), or set by the caller (when
// options.fieldsPerRecord > 0).
//
// Each possible variant means the following:
// "ANY": Variable number of fields is allowed.
// "UNINITIALIZED": The first row has not been read yet. Once it's read, the
// number of fields will be set.
// <number>: The number of fields per record that every record must follow.
#fieldsPerRecord: "ANY" | "UNINITIALIZED" | number;
#headers: readonly string[] = [];
/** Construct a new instance.
*
* @param options Options for the stream.
*/
constructor(options?: T) {
this.#options = {
...options,
separator: options?.separator ?? ",",
trimLeadingSpace: options?.trimLeadingSpace ?? false,
};
if (
this.#options.fieldsPerRecord === undefined ||
this.#options.fieldsPerRecord < 0
) {
this.#fieldsPerRecord = "ANY";
} else if (this.#options.fieldsPerRecord === 0) {
this.#fieldsPerRecord = "UNINITIALIZED";
} else {
// TODO: Should we check if it's a valid integer?
this.#fieldsPerRecord = this.#options.fieldsPerRecord;
}
this.#lines = new TextDelimiterStream("\n");
this.#lineReader = new StreamLineReader(this.#lines.readable.getReader());
this.#readable = new ReadableStream({
pull: (controller) => this.#pull(controller),
cancel: () => this.#lineReader.cancel(),
});
}
async #pull(
controller: ReadableStreamDefaultController<
string[] | Record<string, string | unknown>
>,
): Promise<void> {
const line = await this.#lineReader.readLine();
if (line === "") {
// Found an empty line
this.#zeroBasedLineIndex++;
return this.#pull(controller);
}
if (line === null) {
// Reached to EOF
controller.close();
this.#lineReader.cancel();
return;
}
const record = await parseRecord(
line,
this.#lineReader,
this.#options,
this.#zeroBasedLineIndex,
);
if (this.#isFirstRow) {
this.#isFirstRow = false;
if (this.#options.skipFirstRow || this.#options.columns) {
this.#headers = [];
if (this.#options.skipFirstRow) {
const head = record;
this.#headers = head;
}
if (this.#options.columns) {
this.#headers = this.#options.columns;
}
}
if (this.#options.skipFirstRow) {
return this.#pull(controller);
}
if (this.#fieldsPerRecord === "UNINITIALIZED") {
this.#fieldsPerRecord = record.length;
}
}
if (
typeof this.#fieldsPerRecord === "number" &&
record.length !== this.#fieldsPerRecord
) {
throw new SyntaxError(
`Syntax error on line ${
this.#zeroBasedLineIndex + 1
}: expected ${this.#fieldsPerRecord} fields but got ${record.length}`,
);
}
this.#zeroBasedLineIndex++;
if (record.length > 0) {
if (this.#options.skipFirstRow || this.#options.columns) {
controller.enqueue(convertRowToObject(
record,
this.#headers,
this.#zeroBasedLineIndex,
));
} else {
controller.enqueue(record);
}
} else {
return this.#pull(controller);
}
}
/**
* The instance's {@linkcode ReadableStream}.
*
* @example Usage
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
*
* const source = ReadableStream.from([
* "name,age\n",
* "Alice,34\n",
* "Bob,24\n",
* ]);
* const parseStream = new CsvParseStream({ skipFirstRow: true });
* const parts = source.pipeTo(parseStream.writable);
* assertEquals(await Array.fromAsync(parseStream.readable), [
* { name: "Alice", age: "34" },
* { name: "Bob", age: "24" },
* ]);
* ```
*
* @returns The instance's {@linkcode ReadableStream}.
*/
get readable(): ReadableStream<RowType<T>> {
return this.#readable as ReadableStream<RowType<T>>;
}
/**
* The instance's {@linkcode WritableStream}.
*
* @example Usage
* ```ts
* import { CsvParseStream } from "@std/csv/parse-stream";
* import { assertEquals } from "@std/assert/equals";
*
* const source = ReadableStream.from([
* "name,age\n",
* "Alice,34\n",
* "Bob,24\n",
* ]);
* const parseStream = new CsvParseStream({ skipFirstRow: true });
* const parts = source.pipeTo(parseStream.writable);
* assertEquals(await Array.fromAsync(parseStream.readable), [
* { name: "Alice", age: "34" },
* { name: "Bob", age: "24" },
* ]);
* ```
*
* @returns The instance's {@linkcode WritableStream}.
*/
get writable(): WritableStream<string> {
return this.#lines.writable;
}
}