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
527
528
529
530
531 |
 
 
 
x14
x14
x14
x14
 
 
 
x14
x14
 
 
 
x14
 
x14
x14
x130
x14
 
 
 
 
 
 
x14
x14
x14
x14
x14
x14
x14
x130
x130
x130
x130
x130
x130
x130
x130
x14
x328
 
x856
x856
x328
x1755
x1775
x1775
x1775
x1775
x1755
x1755
x1755
x1867
x1867
x1867
x1867
x3050
x3050
x3050
x328
x335
x335
 
x543
x328
x14
x335
x335
x14
x312
x312
x312
x324
x324
 
x800
 
 
x312
x320
x320
 
x495
x495
x495
x495
x495
x495
x312
x742
x779
x779
 
x742
 
x1115
x1115
x1115
x1332
x1332
 
x1115
x1480
x1480
x1484
x1484
 
x1484
x1484
x1484
x1484
x1484
 
 
x1484
x1480
x1484
x1484
x1115
x1330
x1330
x1330
x1269
x742
 
x799
x799
x885
x885
 
x953
x953
x953
 
x966
x966
x953
 
x1094
x1094
x1094
x1062
 
x1100
x1100
x1085
 
x1097
x1097
 
x1097
x1097
 
x1097
x1097
 
x1097
x885
 
x919
x919
x919
x919
x919
 
x923
x925
x925
x925
x925
x925
x925
 
 
x925
x925
x925
x925
x931
x931
x903
 
x905
x906
x906
x906
 
x906
x906
x906
x906
x885
x799
x742
x484
x484
x312
x726
x726
x726
x484
x312
x14
x130
x130
x130
 
x130
x130
x130
 
x650
 
x130
x130
x130
x130
x130
x130
x130
x136
x136
 
 
 
 
 
 
 
 
 
 
x240
x130
x232
x130
x141
x138
 
x143
x143
 
x130
x428
x428
x916
x916
 
 
x724
x824
x824
x827
x827
x824
 
x717
x889
x1063
x1063
 
x1063
x1227
x1227
x428
x225
x130
x14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x14
x14
x274
 
x130
x130
 
x130
x265
 
x265
x279
x279
x280
x280
x292
x292
 
x265
x277
x277
 
x265
x265
x295
x265
x265
x318
x130 |
|
// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.
import {
convertRowToObject,
createBareQuoteErrorMessage,
createQuoteErrorMessage,
type ParseResult,
type ReadOptions,
type RecordWithColumn,
} from "./_io.ts";
import { codePointLength } from "./_shared.ts";
export type { ParseResult, RecordWithColumn };
const BYTE_ORDER_MARK = "\ufeff";
class Parser {
#input = "";
#cursor = 0;
#options: {
separator: string;
trimLeadingSpace: boolean;
comment: string | undefined;
lazyQuotes: boolean | undefined;
fieldsPerRecord: number | undefined;
};
constructor({
separator = ",",
trimLeadingSpace = false,
comment,
lazyQuotes,
fieldsPerRecord,
}: ReadOptions = {}) {
this.#options = {
separator,
trimLeadingSpace,
comment,
lazyQuotes,
fieldsPerRecord,
};
}
#readLine(): string | null {
if (this.#isEOF()) return null;
let buffer = "";
let hadNewline = false;
while (this.#cursor < this.#input.length) {
if (this.#input.startsWith("\r\n", this.#cursor)) {
hadNewline = true;
this.#cursor += 2;
break;
}
if (
this.#input.startsWith("\n", this.#cursor)
) {
hadNewline = true;
this.#cursor += 1;
break;
}
buffer += this.#input[this.#cursor];
this.#cursor += 1;
}
if (!hadNewline && buffer.endsWith("\r")) {
buffer = buffer.slice(0, -1);
}
return buffer;
}
#isEOF(): boolean {
return this.#cursor >= this.#input.length;
}
#parseRecord(zeroBasedStartLine: number): string[] | null {
let fullLine = this.#readLine();
if (fullLine === null) return null;
if (fullLine.length === 0) {
return [];
}
let zeroBasedLine = zeroBasedStartLine;
// line starting with comment character is ignored
if (this.#options.comment && fullLine[0] === this.#options.comment) {
return [];
}
let line = fullLine;
const quote = '"';
const quoteLen = quote.length;
const separatorLen = this.#options.separator.length;
let recordBuffer = "";
const fieldIndexes = [] as number[];
parseField: while (true) {
if (this.#options.trimLeadingSpace) {
line = line.trimStart();
}
if (line.length === 0 || !line.startsWith(quote)) {
// Non-quoted string field
const i = line.indexOf(this.#options.separator);
let field = line;
if (i >= 0) {
field = field.substring(0, i);
}
// Check to make sure a quote does not appear in field.
if (!this.#options.lazyQuotes) {
const j = field.indexOf(quote);
if (j >= 0) {
const col = codePointLength(
fullLine.slice(0, fullLine.length - line.slice(j).length),
);
throw new SyntaxError(
createBareQuoteErrorMessage(
zeroBasedStartLine,
zeroBasedLine,
col,
),
);
}
}
recordBuffer += field;
fieldIndexes.push(recordBuffer.length);
if (i >= 0) {
line = line.substring(i + separatorLen);
continue parseField;
}
break parseField;
} else {
// Quoted string field
line = line.substring(quoteLen);
while (true) {
const i = line.indexOf(quote);
if (i >= 0) {
// Hit next quote.
recordBuffer += line.substring(0, i);
line = line.substring(i + quoteLen);
if (line.startsWith(quote)) {
// `""` sequence (append quote).
recordBuffer += quote;
line = line.substring(quoteLen);
} else if (line.startsWith(this.#options.separator)) {
// `","` sequence (end of field).
line = line.substring(separatorLen);
fieldIndexes.push(recordBuffer.length);
continue parseField;
} else if (0 === line.length) {
// `"\n` sequence (end of line).
fieldIndexes.push(recordBuffer.length);
break parseField;
} else if (this.#options.lazyQuotes) {
// `"` sequence (bare quote).
recordBuffer += quote;
} else {
// `"*` sequence (invalid non-escaped quote).
const col = codePointLength(
fullLine.slice(0, fullLine.length - line.length - quoteLen),
);
throw new SyntaxError(
createQuoteErrorMessage(zeroBasedStartLine, zeroBasedLine, col),
);
}
} else if (line.length > 0 || !(this.#isEOF())) {
// Hit end of line (copy all data so far).
recordBuffer += line;
const r = this.#readLine();
line = r ?? ""; // This is a workaround for making this module behave similarly to the encoding/csv/reader.go.
fullLine = line;
if (r === null) {
// Abrupt end of file (EOF or error).
if (!this.#options.lazyQuotes) {
const col = codePointLength(fullLine);
throw new SyntaxError(
createQuoteErrorMessage(
zeroBasedStartLine,
zeroBasedLine,
col,
),
);
}
fieldIndexes.push(recordBuffer.length);
break parseField;
}
zeroBasedLine++;
recordBuffer += "\n"; // preserve line feed (This is because TextProtoReader removes it.)
} else {
// Abrupt end of file (EOF on error).
if (!this.#options.lazyQuotes) {
const col = codePointLength(fullLine);
throw new SyntaxError(
createQuoteErrorMessage(zeroBasedStartLine, zeroBasedLine, col),
);
}
fieldIndexes.push(recordBuffer.length);
break parseField;
}
}
}
}
const result = [] as string[];
let preIdx = 0;
for (const i of fieldIndexes) {
result.push(recordBuffer.slice(preIdx, i));
preIdx = i;
}
return result;
}
parse(input: string): string[][] {
this.#input = input.startsWith(BYTE_ORDER_MARK) ? input.slice(1) : input;
this.#cursor = 0;
const result: string[][] = [];
let lineResult: string[];
let first = true;
let lineIndex = 0;
const INVALID_RUNE = ["\r", "\n", '"'];
const options = this.#options;
if (
INVALID_RUNE.includes(options.separator) ||
(typeof options.comment === "string" &&
INVALID_RUNE.includes(options.comment)) ||
options.separator === options.comment
) {
throw new Error("Cannot parse input: invalid delimiter");
}
// 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.
let _nbFields: "ANY" | "UNINITIALIZED" | number;
if (options.fieldsPerRecord === undefined || options.fieldsPerRecord < 0) {
_nbFields = "ANY";
} else if (options.fieldsPerRecord === 0) {
_nbFields = "UNINITIALIZED";
} else {
// TODO: Should we check if it's a valid integer?
_nbFields = options.fieldsPerRecord;
}
while (true) {
const r = this.#parseRecord(lineIndex);
if (r === null) break;
lineResult = r;
lineIndex++;
// If fieldsPerRecord is 0, Read sets it to
// the number of fields in the first record
if (first) {
first = false;
if (_nbFields === "UNINITIALIZED") {
_nbFields = lineResult.length;
}
}
if (lineResult.length > 0) {
if (typeof _nbFields === "number" && _nbFields !== lineResult.length) {
throw new SyntaxError(
`Syntax error on line ${lineIndex}: expected ${_nbFields} fields but got ${lineResult.length}`,
);
}
result.push(lineResult);
}
}
return result;
}
}
/** Options for {@linkcode parse}. */
export interface ParseOptions {
/** 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 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[];
}
/**
* Parses CSV string into an array of arrays of strings.
*
* @example Usage
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
*
* const string = "a,b,c\n#d,e,f";
*
* assertEquals(parse(string), [["a", "b", "c"], ["#d", "e", "f"]]);
* ```
*
* @example Quoted fields
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
*
* const string = `"a ""word""","comma,","newline\n"\nfoo,bar,baz`;
* const result = parse(string);
*
* assertEquals(result, [
* ['a "word"', "comma,", "newline\n"],
* ["foo", "bar", "baz"]
* ]);
* ```
*
* @param input The input to parse.
* @returns The parsed data.
*/
export function parse(input: string): string[][];
/**
* Parses CSV string into an array of objects or an array of arrays of strings.
*
* If `columns` or `skipFirstRow` option is provided, it returns an array of
* objects, otherwise it returns an array of arrays of string.
*
* @example Don't skip first row with `skipFirstRow: false`
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
* import { assertType, IsExact } from "@std/testing/types"
*
* const string = "a,b,c\nd,e,f";
* const result = parse(string, { skipFirstRow: false });
*
* assertEquals(result, [["a", "b", "c"], ["d", "e", "f"]]);
* assertType<IsExact<typeof result, string[][]>>(true);
* ```
*
* @example Skip first row with `skipFirstRow: true`
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
* import { assertType, IsExact } from "@std/testing/types"
*
* const string = "a,b,c\nd,e,f";
* const result = parse(string, { skipFirstRow: true });
*
* assertEquals(result, [{ a: "d", b: "e", c: "f" }]);
* assertType<IsExact<typeof result, Record<string, string>[]>>(true);
* ```
*
* @example Specify columns with `columns` option
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
* import { assertType, IsExact } from "@std/testing/types"
*
* const string = "a,b,c\nd,e,f";
* const result = parse(string, { columns: ["x", "y", "z"] });
*
* assertEquals(result, [{ x: "a", y: "b", z: "c" }, { x: "d", y: "e", z: "f" }]);
* assertType<IsExact<typeof result, Record<"x" | "y" | "z", string>[]>>(true);
* ```
*
* @example Specify columns with `columns` option and skip first row with
* `skipFirstRow: true`
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
* import { assertType, IsExact } from "@std/testing/types"
*
* const string = "a,b,c\nd,e,f";
* const result = parse(string, { columns: ["x", "y", "z"], skipFirstRow: true });
*
* assertEquals(result, [{ x: "d", y: "e", z: "f" }]);
* assertType<IsExact<typeof result, Record<"x" | "y" | "z", string>[]>>(true);
* ```
*
* @example TSV (tab-separated values) with `separator: "\t"`
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
*
* const string = "a\tb\tc\nd\te\tf";
* const result = parse(string, { separator: "\t" });
*
* assertEquals(result, [["a", "b", "c"], ["d", "e", "f"]]);
* ```
*
* @example Trim leading space with `trimLeadingSpace: true`
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
*
* const string = " a, b, c\n";
* const result = parse(string, { trimLeadingSpace: true });
*
* assertEquals(result, [["a", "b", "c"]]);
* ```
*
* @example Lazy quotes with `lazyQuotes: true`
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
*
* const string = `a "word","1"2",a","b`;
* const result = parse(string, { lazyQuotes: true });
*
* assertEquals(result, [['a "word"', '1"2', 'a"', 'b']]);
* ```
*
* @example Set comment prefix with `comment` option
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertEquals } from "@std/assert/equals";
*
* const string = "a,b,c\n# THIS IS A COMMENT LINE\nd,e,f";
* const result = parse(string, { comment: "#" });
*
* assertEquals(result, [["a", "b", "c"], ["d", "e", "f"]]);
* ```
*
* @example Infer the number of fields from the first row with `fieldsPerRecord: 0`
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertThrows } from "@std/assert/throws";
*
* // Note that the second row has more fields than the first row
* const string = "a,b\nc,d,e";
* assertThrows(
* () => parse(string, { fieldsPerRecord: 0 }),
* SyntaxError,
* "Syntax error on line 2: expected 2 fields but got 3",
* );
* ```
*
* @example Enforce the number of fields for each row with `fieldsPerRecord: 2`
* ```ts
* import { parse } from "@std/csv/parse";
* import { assertThrows } from "@std/assert/throws";
*
* const string = "a,b\nc,d,e";
* assertThrows(
* () => parse(string, { fieldsPerRecord: 2 }),
* SyntaxError,
* "Syntax error on line 2: expected 2 fields but got 3",
* );
* ```
*
* @typeParam T The options' type for parsing.
* @param input The input to parse.
* @param options The options for parsing.
* @returns If you don't provide `options.skipFirstRow` or `options.columns`, it
* returns `string[][]`. If you provide `options.skipFirstRow` or
* `options.columns`, it returns `Record<string, string>[]`.
*/
export function parse<const T extends ParseOptions>(
input: string,
options: T,
): ParseResult<ParseOptions, T>;
export function parse<const T extends ParseOptions>(
input: string,
options: T = { skipFirstRow: false } as T,
): ParseResult<ParseOptions, T> {
const parser = new Parser(options);
const r = parser.parse(input);
if (options.skipFirstRow || options.columns) {
let headers: readonly string[] = [];
if (options.skipFirstRow) {
const head = r.shift();
if (head === undefined) {
throw new TypeError("Cannot parse input: headers must be defined");
}
headers = head;
}
if (options.columns) {
headers = options.columns;
}
const zeroBasedFirstLineIndex = options.skipFirstRow ? 1 : 0;
return r.map((row, i) => {
return convertRowToObject(row, headers, zeroBasedFirstLineIndex + i);
}) as ParseResult<ParseOptions, T>;
}
return r as ParseResult<ParseOptions, T>;
}
|