@konstit/csv 0.6.0 → 0.7.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.
Files changed (53) hide show
  1. package/README.md +113 -101
  2. package/THIRD_PARTY_NOTICES.md +27 -0
  3. package/dist/api.d.ts +84 -57
  4. package/dist/api.js +211 -40
  5. package/dist/batch-pipeline.d.ts +10 -0
  6. package/dist/batch-pipeline.js +83 -0
  7. package/dist/batches.d.ts +36 -1
  8. package/dist/batches.js +241 -5
  9. package/dist/cli-command.d.ts +7 -7
  10. package/dist/cli-command.js +325 -164
  11. package/dist/cli-schema.d.ts +51 -21
  12. package/dist/cli-schema.js +126 -65
  13. package/dist/cli.js +1 -1
  14. package/dist/file-stream.d.ts +66 -18
  15. package/dist/file-stream.js +534 -199
  16. package/dist/files.d.ts +17 -37
  17. package/dist/files.js +50 -21
  18. package/dist/gzip-reader.d.ts +2 -0
  19. package/dist/gzip-reader.js +37 -0
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +2 -2
  22. package/dist/inspect-file.d.ts +26 -3
  23. package/dist/inspect-file.js +169 -74
  24. package/dist/inspect-zip.d.ts +26 -0
  25. package/dist/inspect-zip.js +59 -0
  26. package/dist/latin1-rows.d.ts +11 -3
  27. package/dist/latin1-rows.js +276 -75
  28. package/dist/materialize-field.d.ts +6 -0
  29. package/dist/materialize-field.js +9 -0
  30. package/dist/native.d.ts +118 -20
  31. package/dist/native.js +53 -23
  32. package/dist/normalize.d.ts +7 -1
  33. package/dist/normalize.js +49 -9
  34. package/dist/options.d.ts +27 -12
  35. package/dist/parser.d.ts +34 -14
  36. package/dist/parser.js +296 -102
  37. package/dist/strict-schema.d.ts +7 -8
  38. package/dist/strict-schema.js +45 -83
  39. package/dist/transforms.d.ts +1 -3
  40. package/dist/transforms.js +17 -16
  41. package/dist/types.d.ts +192 -75
  42. package/dist/zip-entry.d.ts +14 -0
  43. package/dist/zip-entry.js +155 -0
  44. package/dist/zip-reader.d.ts +14 -3
  45. package/dist/zip-reader.js +65 -23
  46. package/package.json +34 -23
  47. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  48. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  49. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  50. package/prebuilds/manifest.json +18 -8
  51. package/prebuilds/provenance/darwin-arm64.json +1 -1
  52. package/prebuilds/provenance/darwin-x64.json +1 -1
  53. package/prebuilds/provenance/linux-x64.json +1 -1
@@ -1,94 +1,56 @@
1
- import { snapshotCsvOptions } from "./options-snapshot.js";
1
+ import { NativeCsvBatch } from "./batches.js";
2
+ import {
3
+ native,
4
+ u64ToSafeNumber
5
+ } from "./native.js";
2
6
 
3
7
  export class CsvStrictSchemaValidator {
4
- #options;
5
- #seenHeader = !1;
6
- #dataRows = 0;
7
- constructor(suppliedOptions) {
8
- const options = snapshotCsvOptions(suppliedOptions);
9
- this.#options = {
10
- expectedHeaders: options.expectedHeaders,
11
- minDataRows: normalizeMinDataRows(options.minDataRows),
12
- requireHeader: options.requireHeader
13
- };
14
- }
15
- get enabled() {
16
- return this.#options.expectedHeaders !== void 0 || this.#options.requireHeader === !0 || this.#options.minDataRows !== void 0;
17
- }
18
- validateRows(rows) {
19
- for (const row of rows)
20
- this.#validateRow(row);
21
- }
22
- validateBatch(batch) {
23
- const rowCount = batch.rowCount;
24
- for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex)
25
- this.#validateHeaderFromBatch(batch, rowIndex);
26
- }
27
- finish(skippedDataRows = 0) {
28
- if (!this.enabled)
29
- return;
30
- if (!this.#seenHeader && (this.#options.requireHeader === !0 || this.#options.expectedHeaders !== void 0))
31
- throw Error("strict CSV schema error: missing header row");
32
- const minDataRows = this.#options.minDataRows;
33
- const dataRows = this.#dataRows + skippedDataRows;
34
- if (minDataRows !== void 0 && dataRows < minDataRows)
35
- throw Error(`strict CSV schema error: expected at least ${String(minDataRows)} data row(s), got ${String(dataRows)}`);
36
- }
37
- #validateRow(row) {
38
- if (!this.#seenHeader) {
39
- this.#seenHeader = !0;
40
- this.#validateHeader(row);
41
- return;
8
+ #expectedHeaders;
9
+ #requireHeader;
10
+ #minDataRows;
11
+ constructor(options) {
12
+ const min = options.minDataRows;
13
+ if (min !== void 0 && (!Number.isSafeInteger(min) || min < 0))
14
+ throw RangeError(`minDataRows must be a non-negative safe integer: ${String(min)}`);
15
+ this.#minDataRows = min;
16
+ this.#expectedHeaders = options.expectedHeaders?.slice();
17
+ this.#requireHeader = options.requireHeader === !0 || this.#expectedHeaders !== void 0;
18
+ }
19
+ validateNative(handle, final, encoding = "utf8") {
20
+ const header = native.symbols.csv_parser_take_skipped_header(handle);
21
+ if (header !== null) {
22
+ using first = new NativeCsvBatch(header);
23
+ const record = u64ToSafeNumber(native.symbols.csv_parser_header_record(handle), "CSV header record number");
24
+ this.validateHeader(first, record, encoding);
42
25
  }
43
- ++this.#dataRows;
26
+ if (final)
27
+ this.finish(u64ToSafeNumber(native.symbols.csv_parser_schema_rows(handle), "CSV schema row count"));
44
28
  }
45
- #validateHeaderFromBatch(batch, rowIndex) {
46
- if (!this.#seenHeader) {
47
- this.#seenHeader = !0;
48
- const expectedHeaders = this.#options.expectedHeaders;
49
- if (expectedHeaders === void 0)
50
- return;
51
- const actualLength = batch.rowFieldCount(rowIndex);
52
- if (actualLength !== expectedHeaders.length)
53
- throw Error(`strict CSV schema error: expected ${String(expectedHeaders.length)} header field(s), got ${String(actualLength)}`);
54
- for (let column = 0;column < expectedHeaders.length; ++column) {
55
- const actual = batch.fieldString(rowIndex, column) ?? "";
56
- const expected = expectedHeaders[column] ?? "";
57
- if (actual !== expected)
58
- throw Error(`strict CSV schema error: header mismatch at column ${String(column)}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
59
- }
29
+ validateHeader(batch, record, encoding = "utf8") {
30
+ const expected = this.#expectedHeaders;
31
+ if (expected === void 0)
60
32
  return;
33
+ const width = batch.rowFieldCount(0);
34
+ if (width !== expected.length) {
35
+ const field = Math.min(width, expected.length) + 1;
36
+ throw Error(`strict CSV schema error: expected ${expected.length} header field(s), got ${width} at record ${record}, field ${field}`);
61
37
  }
62
- ++this.#dataRows;
63
- }
64
- #validateHeader(row) {
65
- const expectedHeaders = this.#options.expectedHeaders;
66
- if (expectedHeaders === void 0)
67
- return;
68
- if (row.length !== expectedHeaders.length)
69
- throw Error(`strict CSV schema error: expected ${String(expectedHeaders.length)} header field(s), got ${String(row.length)}`);
70
- for (let column = 0;column < expectedHeaders.length; ++column) {
71
- const actual = row[column] ?? "";
72
- const expected = expectedHeaders[column] ?? "";
73
- if (actual !== expected)
74
- throw Error(`strict CSV schema error: header mismatch at column ${String(column)}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
38
+ for (const [column, value] of expected.entries()) {
39
+ const actual = encoding === "latin1" ? batch.fieldBuffer(0, column)?.toString("latin1") ?? null : batch.fieldString(0, column);
40
+ if (value !== actual)
41
+ throw Error(`strict CSV schema error: header mismatch at column ${column}: expected ${JSON.stringify(value)}, got ${JSON.stringify(actual)} at record ${record}, field ${column + 1}`);
75
42
  }
76
43
  }
44
+ finish(records) {
45
+ if (records === 0 && this.#requireHeader)
46
+ throw Error("strict CSV schema error: missing header row");
47
+ const dataRows = Math.max(0, records - 1);
48
+ if (this.#minDataRows !== void 0 && dataRows < this.#minDataRows)
49
+ throw Error(`strict CSV schema error: expected at least ${this.#minDataRows} data row(s), got ${dataRows}`);
50
+ }
77
51
  }
78
52
  export function strictSchemaValidator(options) {
79
- if (options.strict !== !0)
80
- return;
81
- const validator = new CsvStrictSchemaValidator(options);
82
- return validator.enabled ? validator : void 0;
83
- }
84
- export function rejectStrictSchemaUnsupported(options, operation) {
85
- if (strictSchemaValidator(options) !== void 0)
86
- throw Error(`strict CSV schema validation is not supported for ${operation}`);
87
- }
88
- function normalizeMinDataRows(value) {
89
- if (value === void 0)
90
- return;
91
- if (!Number.isInteger(value) || value < 0)
92
- throw RangeError(`minDataRows must be a non-negative integer: ${String(value)}`);
93
- return value;
53
+ if (options.strict && (options.expectedHeaders !== void 0 || options.requireHeader || options.minDataRows !== void 0))
54
+ return new CsvStrictSchemaValidator(options);
55
+ return;
94
56
  }
@@ -4,8 +4,6 @@ import type { CsvColumns, CsvTransform, CsvTransformChain, CsvTransformMethods }
4
4
  export declare function transform(): CsvTransformMethods<CsvTransformChain>;
5
5
  export declare function transformMethods(column: number): CsvTransformMethods;
6
6
  export declare function snapshotTransforms(transforms: readonly CsvTransform[] | undefined): readonly CsvTransform[] | undefined;
7
- export declare function hasOnlyCleanupTransforms(tokens: readonly CsvTransform[]): boolean;
8
- /** Strict row projection happens after full-width validation and transformation. */
9
- export declare function selectTransforms(tokens: readonly CsvTransform[], columns: CsvColumns): readonly CsvTransform[];
7
+ export declare function hasLatin1SpanTransforms(tokens: readonly CsvTransform[]): boolean;
10
8
  /** Copy each selected chain into its parser. Native writes never reference caller-owned data. */
11
9
  export declare function prepareTransforms(handle: NativePointer, tokens: readonly CsvTransform[], selected: CsvColumns | undefined): boolean;
@@ -128,28 +128,29 @@ export function snapshotTransforms(transforms) {
128
128
  return Object.freeze(captured);
129
129
  }
130
130
  const cleanupOps = new Set([0 /* Trim */, 1 /* Upper */, 2 /* Lower */, 3 /* Unaccent */]);
131
- export function hasOnlyCleanupTransforms(tokens) {
131
+ const leadingZeros = Buffer.from("^0+");
132
+ const nonDigits = Buffer.from("[^0-9]+");
133
+ function deletesPattern(step, pattern) {
134
+ return step.kind === 9 /* ReplaceRegex */ && step.replacement === "" && step.search.length === pattern.length && step.search.every((byte, index) => byte === pattern[index]);
135
+ }
136
+ export function hasLatin1SpanTransforms(tokens) {
132
137
  return tokens.every((token) => {
133
138
  const binding = bindings.get(token);
134
- for (let node = binding?.chain;node; node = node.previous)
139
+ if (binding === void 0)
140
+ return !1;
141
+ const { step, previous } = binding.chain;
142
+ if (previous === void 0 && (deletesPattern(step, leadingZeros) || deletesPattern(step, nonDigits)))
143
+ return !0;
144
+ if (step.kind === 5 /* Map */ && step.defaultValue === void 0 && step.values.size === 1 && previous !== void 0 && previous.previous === void 0 && deletesPattern(previous.step, nonDigits)) {
145
+ const replacement = step.values.get("");
146
+ return replacement !== void 0 && Buffer.byteLength(replacement) === replacement.length;
147
+ }
148
+ for (let node = binding.chain;node; node = node.previous)
135
149
  if (!cleanupOps.has(node.step.kind))
136
150
  return !1;
137
- return binding !== void 0;
151
+ return !0;
138
152
  });
139
153
  }
140
- export function selectTransforms(tokens, columns) {
141
- const selected = new Set(columns);
142
- const result = [];
143
- for (const token of tokens) {
144
- const binding = bindings.get(token);
145
- if (!binding)
146
- throw TypeError("expected a bound transform chain");
147
- const targets = binding.columns.filter((column) => selected.has(column));
148
- if (targets.length)
149
- result.push(targets.length === binding.columns.length ? token : createChain(binding.chain, targets));
150
- }
151
- return result;
152
- }
153
154
  export function prepareTransforms(handle, tokens, selected) {
154
155
  const columns = selected === void 0 ? void 0 : new Set(selected);
155
156
  let active = !1;
package/dist/types.d.ts CHANGED
@@ -2,11 +2,11 @@ import type { NativeCsvRowView } from './batches.js';
2
2
  /**
3
3
  * Text encoding used when CSV fields are decoded into JavaScript strings.
4
4
  *
5
- * The values are labels accepted by Bun's `TextDecoder`. `utf8` is the
6
- * default. The `latin1`, `iso88591`, and `iso-8859-1` spellings retain the
7
- * parser's native Latin-1 byte mapping.
5
+ * Accepts Bun's `TextDecoder` labels and `cp949`, a case-insensitive alias for
6
+ * `windows-949`. The default is `utf8`. The `latin1`, `iso88591`, and `iso-8859-1`
7
+ * spellings retain the parser's native Latin-1 byte mapping.
8
8
  */
9
- export type CsvEncoding = Bun.Encoding;
9
+ export type CsvEncoding = Bun.Encoding | `${'c' | 'C'}${'p' | 'P'}949`;
10
10
  /** File readers accept explicit encoding labels or infer an encoding from the decompressed prefix. */
11
11
  export type CsvFileEncoding = CsvEncoding | 'auto';
12
12
  /** Encoding labels that can be passed directly to the native parser. */
@@ -14,8 +14,8 @@ export type CsvNativeEncoding = 'unicode-1-1-utf-8' | 'unicode11utf8' | 'unicode
14
14
  /**
15
15
  * Selects one CSV entry from a ZIP archive.
16
16
  *
17
- * ZIP input is available to file parsing operations. The `entry` name must
18
- * match the archive member exactly. `'*'` selects the only file after ignoring
17
+ * Select an exact member path first, or use a glob that matches one file.
18
+ * Use `/` or `!/` to reach a member in a nested ZIP. `'*'` selects the only file after ignoring
19
19
  * directories and OS metadata. This includes files in `__MACOSX/` or
20
20
  * `.AppleDouble/` directories, `._*` files, and the case-insensitive filenames
21
21
  * `.DS_Store`, `Thumbs.db`, `ehthumbs.db`, `ehthumbs_vista.db`, and `desktop.ini`.
@@ -23,17 +23,17 @@ export type CsvNativeEncoding = 'unicode-1-1-utf-8' | 'unicode11utf8' | 'unicode
23
23
  export interface CsvZipCompression {
24
24
  /** ZIP is the selected container format. */
25
25
  readonly format: 'zip';
26
- /** Exact archive member name, or `'*'` for the only file after ignoring directories and OS metadata. */
26
+ /** Exact path, nested path, unique glob, or `'*'` for automatic single-file selection. */
27
27
  readonly entry: string;
28
28
  /**
29
- * Maximum allowed decompressed-to-compressed byte ratio for the selected entry.
29
+ * Maximum allowed decompressed-to-compressed byte ratio for each entry opened.
30
30
  *
31
31
  * Must be a positive integer no greater than `4_294_967_295`. The default is
32
32
  * `1000`; lower values tighten protection against highly compressed entries.
33
33
  */
34
34
  readonly maxCompressionRatio?: number;
35
35
  /**
36
- * Maximum decompressed bytes accepted from the entry.
36
+ * Maximum decompressed bytes accepted from each entry opened.
37
37
  *
38
38
  * Must be a positive safe integer. The default is 64 GiB.
39
39
  */
@@ -52,9 +52,8 @@ export type CsvCompression = Bun.CompressionFormat | 'auto' | 'none' | CsvZipCom
52
52
  /**
53
53
  * Field delimiter used by the CSV parser.
54
54
  *
55
- * Omit the option to use comma. `'auto'` is supported by file parsing
56
- * operations and probes the input for a stable common delimiter. Other strings
57
- * are accepted by TypeScript, but runtime parsing requires one character.
55
+ * The default, `'auto'`, probes the input for a stable common delimiter.
56
+ * An explicit delimiter must be a single byte in the parser encoding.
58
57
  */
59
58
  export type CsvDelimiter = 'auto' | ',' | ';' | '\t' | '|' | ':' | '^' | '~' | '@' | (string & {});
60
59
  /** A materialized CSV row, with one decoded string per field. */
@@ -100,9 +99,10 @@ export interface CsvTransform extends CsvTransformMethods {
100
99
  /** Reuse these steps on a new set of physical columns. */
101
100
  readonly on: CsvTransformChain['on'];
102
101
  }
103
- /** A physical input column can start a filter or a transform. */
102
+ /** A zero-based input column with methods for building filters and transforms. */
104
103
  export interface CsvColumn extends CsvFilterColumn, CsvTransformMethods {
105
104
  }
105
+ /** Field transforms to apply while producing parsed rows or field batches. */
106
106
  export interface CsvTransformOptions {
107
107
  /** Apply one chain per physical column to present, selected fields after filtering. */
108
108
  readonly transform?: readonly CsvTransform[] | undefined;
@@ -226,11 +226,28 @@ export interface CsvShard {
226
226
  end: number;
227
227
  }
228
228
  interface CsvRowSelectionOptions {
229
- /** Number of initial input records to skip, including any header, before filtering. Defaults to zero. */
229
+ /**
230
+ * Number of initial input records to skip before filtering. Defaults to zero.
231
+ * The count includes headers and empty records, even with `headers: true` or `skipEmptyLines: true`.
232
+ * Use a non-negative safe integer.
233
+ */
230
234
  readonly skipRows?: number;
231
- /** Maximum number of matching rows to emit or count across the entire input. Defaults to unlimited. */
235
+ /** Ignore empty records. Whitespace-only records and quoted empty fields are kept. Defaults to false. */
236
+ readonly skipEmptyLines?: boolean;
237
+ /** Maximum number of matching rows to emit or count across the input. Defaults to unlimited. Use a non-negative safe integer. */
232
238
  readonly limit?: number;
233
239
  }
240
+ /** CSV quoting and record terminator settings. */
241
+ export interface CsvDialectOptions {
242
+ /** Treat double quotes as literal data when false. Defaults to true, which strict validation requires. */
243
+ readonly quote?: boolean;
244
+ /** End records at LF outside quotes and retain CR as data. The default recognizes CRLF, LF, and CR. */
245
+ readonly recordDelimiter?: '\n';
246
+ }
247
+ interface CsvInputProjection {
248
+ /** Zero-based input column indexes to emit when reading rows, in the requested order. Defaults to all columns. */
249
+ readonly columns?: CsvColumns;
250
+ }
234
251
  /**
235
252
  * Parser configuration shared by in-memory parsing and file APIs.
236
253
  *
@@ -241,13 +258,13 @@ interface CsvRowSelectionOptions {
241
258
  * @typeParam TEncoding - Defaults to the native parser's labels. File and buffer
242
259
  * parsing accept the full {@link CsvEncoding} set.
243
260
  */
244
- export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeEncoding> extends CsvRowSelectionOptions {
261
+ export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeEncoding> extends CsvRowSelectionOptions, CsvDialectOptions, CsvInputProjection {
262
+ /** Maximum parser-input bytes per record, including quotes and field separators and excluding the record terminator. */
263
+ readonly maxRecordBytes?: number;
245
264
  /** Input field encoding used when decoding bytes into JavaScript strings. Defaults to `'utf8'`. */
246
265
  readonly encoding?: TEncoding;
247
- /** Field separator. Defaults to comma. File parsing also accepts `'auto'`. */
266
+ /** Field separator. Defaults to `'auto'`. */
248
267
  readonly delimiter?: CsvDelimiter;
249
- /** Physical columns to emit from each row, in the requested output order. */
250
- readonly columns?: CsvColumns;
251
268
  /** Require exactly this many fields per row; malformed rows fail instead of being padded or truncated. */
252
269
  readonly fixedColumns?: number;
253
270
  /** Enable RFC-style quote and schema validation. Defaults to `false`. */
@@ -256,9 +273,11 @@ export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeE
256
273
  readonly expectedHeaders?: readonly string[];
257
274
  /** Require a first row when strict schema validation is enabled. */
258
275
  readonly requireHeader?: boolean;
259
- /** Minimum number of data rows after the header, checked in strict mode. */
276
+ /** Minimum number of data rows after the header as a non-negative safe integer, checked in strict mode. */
260
277
  readonly minDataRows?: number;
261
278
  }
279
+ /** A filesystem path or a single-pass source of CSV bytes, including a Web ReadableStream. */
280
+ export type CsvInput = string | AsyncIterable<Uint8Array>;
262
281
  /**
263
282
  * File input options, including parser settings and stream controls.
264
283
  *
@@ -268,7 +287,7 @@ export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeE
268
287
  export interface CsvFileOptions extends CsvParserOptions<CsvFileEncoding> {
269
288
  /** Defaults to `'auto'`, probing up to 64 KiB after decompression, independently of the delimiter. */
270
289
  readonly encoding?: CsvFileEncoding;
271
- /** Read-stream chunk size in bytes. Defaults to 1 MiB. */
290
+ /** Read-stream chunk size from 1 byte through 64 MiB. Defaults to 1 MiB. */
272
291
  readonly chunkSize?: number;
273
292
  /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
274
293
  readonly compression?: CsvCompression;
@@ -276,54 +295,48 @@ export interface CsvFileOptions extends CsvParserOptions<CsvFileEncoding> {
276
295
  /**
277
296
  * File options accepted by byte-offset sharding helpers.
278
297
  *
279
- * Compression is excluded because compressed byte streams cannot be split into
280
- * independently readable file ranges.
298
+ * Only the field delimiter and input encoding affect the boundary scan. The
299
+ * other file parser options can be reused when reading the resulting ranges.
281
300
  */
282
- export type CsvShardingOptions = Omit<CsvFileOptions, 'compression' | 'encoding' | keyof CsvRowSelectionOptions> & {
301
+ export type CsvShardingOptions = Omit<CsvFileOptions, 'compression' | 'delimiter' | 'encoding' | 'maxRecordBytes' | keyof CsvRowSelectionOptions | keyof CsvDialectOptions> & {
283
302
  /** Compression is unsupported for byte-offset sharding. */
284
303
  readonly compression?: never;
304
+ /** Field separator for the boundary scan. Defaults to `'auto'`. */
305
+ readonly delimiter?: CsvDelimiter;
285
306
  /** Sharding scans raw file bytes and supports native encodings only. */
286
307
  readonly encoding?: CsvNativeEncoding;
287
308
  };
288
- /** Native equality predicate used by projection and count fast paths. */
289
- export interface CsvEqualsFilter {
309
+ interface CsvPhysicalFilter {
290
310
  /** Zero-based physical column to inspect. */
291
311
  readonly column: number;
312
+ }
313
+ /** Native equality predicate used by projection and count fast paths. */
314
+ export interface CsvEqualsFilter extends CsvPhysicalFilter {
292
315
  /** Field bytes or text that must equal the input field. */
293
316
  readonly value: CsvFieldValue;
294
317
  }
295
318
  /** Native membership predicate used by projection and count fast paths. */
296
- export interface CsvInFilter {
297
- /** Zero-based physical column to inspect. */
298
- readonly column: number;
319
+ export interface CsvInFilter extends CsvPhysicalFilter {
299
320
  /** Values for which the input field matches. */
300
321
  readonly values: readonly CsvFieldValue[];
301
322
  }
302
323
  /** Native inequality predicate used by projection and count fast paths. */
303
- export interface CsvNotEqualsFilter {
304
- /** Zero-based physical column to inspect. */
305
- readonly column: number;
324
+ export interface CsvNotEqualsFilter extends CsvPhysicalFilter {
306
325
  /** Field bytes or text that must differ from the input field. */
307
326
  readonly notEquals: CsvFieldValue;
308
327
  }
309
328
  /** Native negative-membership predicate used by projection and count fast paths. */
310
- export interface CsvNotInFilter {
311
- /** Zero-based physical column to inspect. */
312
- readonly column: number;
329
+ export interface CsvNotInFilter extends CsvPhysicalFilter {
313
330
  /** Values that the input field must not match. */
314
331
  readonly notIn: readonly CsvFieldValue[];
315
332
  }
316
333
  /** Native prefix predicate used by projection and count fast paths. */
317
- export interface CsvStartsWithFilter {
318
- /** Zero-based physical column to inspect. */
319
- readonly column: number;
334
+ export interface CsvStartsWithFilter extends CsvPhysicalFilter {
320
335
  /** Field bytes or text that must occur at the start of the input field. */
321
336
  readonly prefix: CsvFieldValue;
322
337
  }
323
338
  /** Native regular-expression predicate used by projection and count fast paths. */
324
- export interface CsvRegexFilter {
325
- /** Zero-based physical column to inspect. */
326
- readonly column: number;
339
+ export interface CsvRegexFilter extends CsvPhysicalFilter {
327
340
  /** Validated pattern created by `csv.re()`. */
328
341
  readonly regex: CsvRegex;
329
342
  }
@@ -341,9 +354,7 @@ export type CsvNativeFilter = CsvEqualsFilter | CsvInFilter | CsvNotInFilter | C
341
354
  * `equalsFilter` and `filters` are mutually exclusive. When `filters` contains
342
355
  * several entries, the native path combines them with an AND operation.
343
356
  */
344
- export interface CsvNativeProjectionOptions {
345
- /** Physical columns to emit, in output order. */
346
- readonly columns?: CsvColumns;
357
+ export interface CsvNativeProjectionOptions extends CsvInputProjection {
347
358
  /** One equality predicate on a physical column. */
348
359
  readonly equalsFilter?: CsvEqualsFilter;
349
360
  /** Native predicates combined for the operation. */
@@ -367,6 +378,7 @@ export interface CsvNativeFilterOperator {
367
378
  *
368
379
  * Place predicates before the operators that consume them. A complete program
369
380
  * must leave exactly one result on the stack and contain at most 4096 entries.
381
+ * A filter branch can contain up to 128 nested Boolean operators.
370
382
  * Most applications can use `csv.column()` and its boolean combinators instead.
371
383
  */
372
384
  export type CsvNativeFilterProgramEntry = CsvNativeFilter | CsvNativeFilterOperator;
@@ -380,14 +392,26 @@ export interface CsvApiFileOptions extends CsvFileOptions {
380
392
  /** Opaque filter created by `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. */
381
393
  readonly where?: CsvFilter;
382
394
  }
383
- /** Retains the literal input indexes and their order for projected row types. */
384
- export interface CsvColumnSelection<TColumns extends CsvColumns | undefined> {
385
- /** Physical columns to emit from each row, in the requested output order. */
395
+ type CsvIndexedProjection<TColumns extends CsvColumns | undefined> = {
396
+ /** Zero-based physical column indexes to emit, in the requested output order. Defaults to all columns. */
386
397
  readonly columns?: TColumns;
398
+ };
399
+ /** Retains the literal input indexes and their order for projected row types. */
400
+ export interface CsvColumnSelection<TColumns extends CsvColumns | undefined> extends CsvIndexedProjection<TColumns> {
401
+ }
402
+ type CsvRequiredIndexedProjection<TColumns extends CsvColumns> = {
403
+ /** Zero-based physical column indexes to emit, in the requested output order. */
404
+ readonly columns: TColumns;
405
+ };
406
+ interface CsvIndexedFilterOptions {
407
+ /** Filter records using predicates on the physical input columns. */
408
+ readonly where?: CsvFilter | undefined;
387
409
  }
388
- /** Shared operation properties have declarations that editors can use for hover documentation. */
389
- interface CsvOperationOptions<TColumns extends CsvColumns | undefined> extends CsvColumnSelection<TColumns>, CsvRowSelectionOptions {
390
- /** Field separator. Defaults to comma. File parsing also accepts `'auto'`. */
410
+ /** Record selection and validation shared by buffer and file operations. */
411
+ interface CsvOperationOptions extends CsvRowSelectionOptions {
412
+ /** Maximum bytes in a logical record after transcoding, excluding its record terminator. */
413
+ readonly maxRecordBytes?: number;
414
+ /** Field separator. Defaults to `'auto'`. */
391
415
  readonly delimiter?: CsvDelimiter;
392
416
  /** Require exactly this many fields per row; malformed rows fail instead of being padded or truncated. */
393
417
  readonly fixedColumns?: number;
@@ -395,48 +419,137 @@ interface CsvOperationOptions<TColumns extends CsvColumns | undefined> extends C
395
419
  readonly expectedHeaders?: readonly string[];
396
420
  /** Require a first row when strict schema validation is enabled. */
397
421
  readonly requireHeader?: boolean;
398
- /** Minimum number of data rows after the header, checked in strict mode. */
422
+ /** Minimum number of data rows after the header as a non-negative safe integer, checked in strict mode. */
399
423
  readonly minDataRows?: number;
400
- /** Read-stream chunk size in bytes. Defaults to 1 MiB. Used by file operations only. */
424
+ /** Read-stream chunk size from 1 byte through 64 MiB for file and stream operations. Defaults to 1 MiB. */
401
425
  readonly chunkSize?: number;
402
426
  }
427
+ interface CsvCompressionOptions {
428
+ /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
429
+ readonly compression?: CsvCompression;
430
+ }
403
431
  /** File operations support encoding detection and streamed decompression. */
404
- interface CsvFileOperationOptions<TColumns extends CsvColumns | undefined> extends CsvOperationOptions<TColumns> {
432
+ interface CsvFileOperationOptions extends CsvOperationOptions, CsvCompressionOptions {
405
433
  /** Defaults to `'auto'`, probing up to 64 KiB after decompression, independently of the delimiter. */
406
434
  readonly encoding?: CsvFileEncoding;
407
- /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
408
- readonly compression?: CsvCompression;
409
435
  }
410
- /** Non-strict operations can filter input records. */
411
- interface CsvFilteredOperationOptions {
412
- /** Enable RFC-style quote and schema validation. Defaults to `false`. Requires unfiltered input. */
436
+ interface CsvNonStrictOperationOptions {
437
+ /** Enable strict quote and width validation. Defaults to false. */
413
438
  readonly strict?: false | undefined;
414
- /** Filter records with `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. Requires `strict` to be false or omitted. */
415
- readonly where?: CsvFilter | undefined;
416
439
  }
417
- /** Strict validation requires unfiltered input. */
418
440
  interface CsvStrictOperationOptions {
419
- /** Enable RFC-style quote and schema validation. Requires unfiltered input. */
441
+ /** Validate physical records before filtering or projection. */
420
442
  readonly strict: true;
421
- /** Filtering is unavailable with strict validation, which checks every input record. */
422
- readonly where?: undefined;
443
+ /** Strict validation requires double quotes to be interpreted as CSV quoting. */
444
+ readonly quote?: true;
445
+ /** Strict validation uses the default record delimiters CRLF, LF, and CR. */
446
+ readonly recordDelimiter?: undefined;
423
447
  }
424
- /** Each branch keeps its documented properties and enforces the strict/filter constraint. */
425
- type CsvValidationOptions = CsvFilteredOperationOptions | CsvStrictOperationOptions;
426
- /** Options for parsing an in-memory buffer into materialized rows. */
427
- export type CsvParseOptions<TColumns extends CsvColumns | undefined = undefined> = CsvOperationOptions<TColumns> & CsvTransformOptions & CsvValidationOptions & {
448
+ /** Dialect choices as constrained by strict validation. */
449
+ export type CsvOperationDialect = (CsvNonStrictOperationOptions & CsvDialectOptions) | CsvStrictOperationOptions;
450
+ type CsvValidationOptions<TOptions> = TOptions & CsvOperationDialect;
451
+ type CsvParseBaseOptions = CsvOperationOptions & CsvIndexedFilterOptions & CsvTransformOptions & {
428
452
  /** Input field encoding used when decoding bytes into JavaScript strings. Defaults to `'utf8'`. */
429
453
  readonly encoding?: CsvEncoding;
430
454
  };
431
- /** Options for streaming materialized rows in file order. */
432
- export type CsvRowsOptions<TColumns extends CsvColumns | undefined = undefined> = CsvFileOperationOptions<TColumns> & CsvTransformOptions & CsvValidationOptions & {
455
+ /** Options for parsing an in-memory buffer into materialized rows. */
456
+ export type CsvParseOptions<TColumns extends CsvColumns | undefined = undefined> = CsvValidationOptions<CsvParseBaseOptions & CsvIndexedProjection<TColumns>>;
457
+ /** Buffer options that guarantee the specified projection for every returned record. */
458
+ export type CsvProjectedParseOptions<TColumns extends CsvColumns> = CsvValidationOptions<CsvParseBaseOptions & CsvRequiredIndexedProjection<TColumns>>;
459
+ interface CsvIndexedHeaderOptions {
460
+ /** Set `headers` to `true` to read the input header, or supply names to address columns by name. */
461
+ readonly headers?: undefined;
462
+ }
463
+ /** Indexed row options shared by the projected and unprojected overloads. */
464
+ export type CsvIndexedRowsBaseOptions = CsvFileOperationOptions & CsvTransformOptions & CsvIndexedFilterOptions & CsvIndexedHeaderOptions & {
465
+ /** Emit array rows. Object rows require `headers` and `mapped: true`. */
466
+ readonly mapped?: false;
433
467
  /** Refill the batch and its row arrays across iterations. Copy any row you want to keep. Defaults to false. */
434
468
  readonly reuseArrays?: boolean;
469
+ /** Maximum owned rows per yield, independent of `chunkSize`. Use a positive safe integer with `reuseArrays` disabled. */
470
+ readonly maxBatchRows?: number;
471
+ };
472
+ /** Options for streaming materialized rows in file order. */
473
+ export type CsvRowsOptions<TColumns extends CsvColumns | undefined = undefined> = CsvValidationOptions<CsvIndexedRowsBaseOptions & CsvIndexedProjection<TColumns>>;
474
+ /** Row options that guarantee the specified projection for every emitted record. */
475
+ export type CsvProjectedRowsOptions<TColumns extends CsvColumns> = CsvValidationOptions<CsvIndexedRowsBaseOptions & CsvRequiredIndexedProjection<TColumns>>;
476
+ /** Resolve a header name to a builder for filters and transforms on its physical column. */
477
+ export type CsvHeaderColumn<TName extends string = string> = (name: TName) => CsvColumn;
478
+ /** Read column names from the input header or supply names in physical input order. */
479
+ export type CsvHeaderSource = true | readonly string[];
480
+ /** Names known at compile time, or any string when the names come from the input. */
481
+ export type CsvHeaderName<THeaders extends CsvHeaderSource> = THeaders extends readonly string[] ? THeaders[number] : string;
482
+ type CsvNamedFilterOptions<THeaders extends CsvHeaderSource> = {
483
+ /**
484
+ * Read and consume the first record with `true`, or the first nonempty record with `skipEmptyLines`.
485
+ * Supply an array of unique names in physical input order to assign names without consuming a record.
486
+ */
487
+ readonly headers: THeaders;
488
+ /** A filter or a callback that builds a filter using input header names. */
489
+ readonly where?: CsvFilter | ((column: CsvHeaderColumn<NoInfer<CsvHeaderName<THeaders>>>) => CsvFilter) | undefined;
490
+ };
491
+ type CsvNamedRowsCoreOptions<THeaders extends CsvHeaderSource, TMapped extends boolean | undefined> = CsvFileOperationOptions & CsvNamedFilterOptions<THeaders> & {
492
+ /** Transform chains or a callback that builds chains using input header names. */
493
+ readonly transform?: readonly CsvTransform[] | ((column: CsvHeaderColumn<NoInfer<CsvHeaderName<THeaders>>>) => readonly CsvTransform[]) | undefined;
494
+ /** Refill batches and rows in array mode. Copy rows that need to outlive the current batch. Defaults to false. */
495
+ readonly reuseArrays?: TMapped extends true ? false : boolean;
496
+ /** Maximum owned rows per yield, independent of `chunkSize`. Use a positive safe integer with `reuseArrays` disabled. */
497
+ readonly maxBatchRows?: number;
498
+ };
499
+ type CsvNamedColumns<TColumns> = {
500
+ /** Unique header names to emit, in the requested output order. Defaults to all columns. */
501
+ readonly columns?: TColumns;
502
+ };
503
+ type CsvRequiredNamedColumns<TColumns> = {
504
+ /** Unique header names to emit, in the requested output order. */
505
+ readonly columns: TColumns;
506
+ };
507
+ type CsvMappedOutput<TMapped> = {
508
+ /** Emit fresh objects keyed by the selected header names. Defaults to array rows. */
509
+ readonly mapped?: TMapped;
510
+ };
511
+ type CsvRequiredMappedOutput<TMapped> = {
512
+ /** Emit fresh objects keyed by the selected header names when true. */
513
+ readonly mapped: TMapped;
514
+ };
515
+ /** Named row options shared by the array and object output overloads. */
516
+ export type CsvNamedRowsBaseOptions<THeaders extends CsvHeaderSource, TColumns extends readonly NoInfer<CsvHeaderName<THeaders>>[] | undefined, TMapped extends boolean | undefined> = CsvNamedRowsCoreOptions<THeaders, TMapped> & CsvNamedColumns<TColumns> & CsvMappedOutput<TMapped>;
517
+ /** Stream rows with names from the file header or from the caller. */
518
+ export type CsvNamedRowsOptions<THeaders extends CsvHeaderSource = readonly string[], TColumns extends readonly NoInfer<CsvHeaderName<THeaders>>[] | undefined = readonly NoInfer<CsvHeaderName<THeaders>>[] | undefined, TMapped extends boolean | undefined = boolean | undefined> = CsvValidationOptions<CsvNamedRowsBaseOptions<THeaders, TColumns, TMapped>>;
519
+ /** Named row options with an explicit projection, output shape, or both. */
520
+ export type CsvRequiredNamedRowsOptions<THeaders extends CsvHeaderSource, TColumns extends readonly NoInfer<CsvHeaderName<THeaders>>[] | undefined, TMapped extends boolean | undefined, TRequired extends 'columns' | 'mapped'> = CsvValidationOptions<CsvNamedRowsCoreOptions<THeaders, TMapped> & ('columns' extends TRequired ? CsvRequiredNamedColumns<TColumns> : CsvNamedColumns<TColumns>) & ('mapped' extends TRequired ? CsvRequiredMappedOutput<TMapped> : CsvMappedOutput<TMapped>)>;
521
+ /** Batches of parsed fields, optionally projected after validation of the source row. */
522
+ export type CsvBatchesOptions = CsvTransformOptions & {
523
+ /** Return parsed field batches. This is the default output. */
524
+ readonly output?: 'fields';
525
+ } & CsvValidationOptions<CsvFileOperationOptions & CsvIndexedProjection<CsvColumns | undefined> & CsvIndexedFilterOptions>;
526
+ /** Batches of original decompressed records using the literal LF dialect. */
527
+ export type CsvRawRecordBatchesOptions = CsvOperationOptions & CsvCompressionOptions & CsvIndexedFilterOptions & CsvNonStrictOperationOptions & {
528
+ /** Return original decompressed record bytes. Requires `quote: false` and `recordDelimiter: '\n'`. */
529
+ readonly output: 'raw-records';
530
+ /** Interpret double quotes as ordinary bytes for raw-record output. */
531
+ readonly quote: false;
532
+ /** Terminate raw records at LF and retain any CR as data. */
533
+ readonly recordDelimiter: '\n';
534
+ /** Raw-record batches contain complete records. Use parsed field output to select columns. */
535
+ readonly columns?: undefined;
536
+ /** Encoding for filter comparisons. Defaults to UTF-8. Output bytes are unchanged. */
537
+ readonly encoding?: CsvNativeEncoding;
538
+ /** For field transforms, use parsed field output instead. */
539
+ readonly transform?: undefined;
540
+ };
541
+ /** Indexed count options before dialect validation. */
542
+ export type CsvCountBaseOptions = CsvCountOperationOptions & CsvIndexedFilterOptions & CsvIndexedHeaderOptions;
543
+ type CsvCountOperationOptions = CsvFileOperationOptions & {
544
+ /** Optional input column indexes to validate. Counting always uses the original records. */
545
+ readonly columns?: CsvColumns | undefined;
435
546
  };
436
- /** Strict native batches require unfiltered, unprojected input. */
437
- export type CsvBatchesOptions = CsvTransformOptions & ((CsvFileOperationOptions<CsvColumns | undefined> & CsvFilteredOperationOptions) | (CsvFileOperationOptions<undefined> & CsvStrictOperationOptions));
438
- /** Options accepted by `csv.count()`. */
439
- export type CsvCountOptions = CsvFileOperationOptions<CsvColumns | undefined> & CsvValidationOptions;
547
+ /** Options for counting with zero-based column indexes. */
548
+ export type CsvCountOptions = CsvValidationOptions<CsvCountBaseOptions>;
549
+ /** Options shared by counts with caller-supplied names or a header read from input. */
550
+ export type CsvNamedCountBaseOptions<THeaders extends CsvHeaderSource> = CsvCountOperationOptions & CsvNamedFilterOptions<THeaders>;
551
+ /** Count records using optional predicates addressed by header name. */
552
+ export type CsvNamedCountOptions<THeaders extends CsvHeaderSource = CsvHeaderSource> = CsvValidationOptions<CsvNamedCountBaseOptions<THeaders>>;
440
553
  /**
441
554
  * Materialized row type inferred from a literal projection tuple.
442
555
  *
@@ -444,9 +557,13 @@ export type CsvCountOptions = CsvFileOperationOptions<CsvColumns | undefined> &
444
557
  * string tuple. Without a projection tuple the result is the variable-length
445
558
  * `CsvRow` shape.
446
559
  */
447
- export type CsvProjectedRow<TColumns extends CsvColumns | undefined> = TColumns extends readonly unknown[] ? {
560
+ export type CsvProjectedRow<TColumns extends CsvColumns | readonly string[] | undefined> = TColumns extends readonly unknown[] ? {
448
561
  -readonly [Index in keyof TColumns]: string;
449
562
  } : CsvRow;
563
+ /** Materialized object row. A runtime list of names cannot guarantee a particular key. */
564
+ export type CsvMappedRow<TKeys extends readonly string[] = readonly string[]> = number extends TKeys['length'] ? Partial<Record<TKeys[number], string>> : Record<TKeys[number], string>;
565
+ /** A homogeneous batch of array or object rows with the requested projection. */
566
+ export type CsvNamedRowsBatch<THeaders extends CsvHeaderSource, TColumns extends readonly NoInfer<CsvHeaderName<THeaders>>[] | undefined, TMapped extends boolean | undefined> = TMapped extends true ? CsvMappedRow<TColumns extends readonly string[] ? TColumns : THeaders extends readonly string[] ? THeaders : readonly string[]>[] : CsvProjectedRow<TColumns>[];
450
567
  /**
451
568
  * Synchronous callback invoked by `NativeCsvBatch.forEachRow()`.
452
569
  *