@konstit/csv 0.6.1 → 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 (52) hide show
  1. package/README.md +108 -102
  2. package/THIRD_PARTY_NOTICES.md +27 -0
  3. package/dist/api.d.ts +78 -55
  4. package/dist/api.js +191 -40
  5. package/dist/batch-pipeline.d.ts +10 -0
  6. package/dist/batch-pipeline.js +83 -0
  7. package/dist/batches.d.ts +16 -2
  8. package/dist/batches.js +179 -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 +62 -15
  15. package/dist/file-stream.js +494 -205
  16. package/dist/files.d.ts +17 -37
  17. package/dist/files.js +48 -21
  18. package/dist/gzip-reader.js +2 -2
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +1 -1
  21. package/dist/inspect-file.d.ts +26 -3
  22. package/dist/inspect-file.js +169 -74
  23. package/dist/inspect-zip.d.ts +26 -0
  24. package/dist/inspect-zip.js +59 -0
  25. package/dist/latin1-rows.d.ts +11 -3
  26. package/dist/latin1-rows.js +276 -75
  27. package/dist/materialize-field.d.ts +6 -0
  28. package/dist/materialize-field.js +9 -0
  29. package/dist/native.d.ts +89 -19
  30. package/dist/native.js +45 -23
  31. package/dist/normalize.d.ts +5 -0
  32. package/dist/normalize.js +42 -9
  33. package/dist/options.d.ts +27 -12
  34. package/dist/parser.d.ts +30 -13
  35. package/dist/parser.js +264 -102
  36. package/dist/strict-schema.d.ts +7 -8
  37. package/dist/strict-schema.js +45 -83
  38. package/dist/transforms.d.ts +1 -3
  39. package/dist/transforms.js +17 -16
  40. package/dist/types.d.ts +175 -77
  41. package/dist/zip-entry.d.ts +14 -0
  42. package/dist/zip-entry.js +155 -0
  43. package/dist/zip-reader.d.ts +14 -3
  44. package/dist/zip-reader.js +65 -23
  45. package/package.json +34 -23
  46. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  47. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  48. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  49. package/prebuilds/manifest.json +15 -8
  50. package/prebuilds/provenance/darwin-arm64.json +1 -1
  51. package/prebuilds/provenance/darwin-x64.json +1 -1
  52. package/prebuilds/provenance/linux-x64.json +1 -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,17 +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
  }
234
- interface CsvDialectOptions {
240
+ /** CSV quoting and record terminator settings. */
241
+ export interface CsvDialectOptions {
235
242
  /** Treat double quotes as literal data when false. Defaults to true, which strict validation requires. */
236
243
  readonly quote?: boolean;
237
244
  /** End records at LF outside quotes and retain CR as data. The default recognizes CRLF, LF, and CR. */
238
245
  readonly recordDelimiter?: '\n';
239
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
+ }
240
251
  /**
241
252
  * Parser configuration shared by in-memory parsing and file APIs.
242
253
  *
@@ -247,13 +258,13 @@ interface CsvDialectOptions {
247
258
  * @typeParam TEncoding - Defaults to the native parser's labels. File and buffer
248
259
  * parsing accept the full {@link CsvEncoding} set.
249
260
  */
250
- export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeEncoding> extends CsvRowSelectionOptions, CsvDialectOptions {
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;
251
264
  /** Input field encoding used when decoding bytes into JavaScript strings. Defaults to `'utf8'`. */
252
265
  readonly encoding?: TEncoding;
253
- /** Field separator. Defaults to comma. File parsing also accepts `'auto'`. */
266
+ /** Field separator. Defaults to `'auto'`. */
254
267
  readonly delimiter?: CsvDelimiter;
255
- /** Physical columns to emit from each row, in the requested output order. */
256
- readonly columns?: CsvColumns;
257
268
  /** Require exactly this many fields per row; malformed rows fail instead of being padded or truncated. */
258
269
  readonly fixedColumns?: number;
259
270
  /** Enable RFC-style quote and schema validation. Defaults to `false`. */
@@ -262,9 +273,11 @@ export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeE
262
273
  readonly expectedHeaders?: readonly string[];
263
274
  /** Require a first row when strict schema validation is enabled. */
264
275
  readonly requireHeader?: boolean;
265
- /** 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. */
266
277
  readonly minDataRows?: number;
267
278
  }
279
+ /** A filesystem path or a single-pass source of CSV bytes, including a Web ReadableStream. */
280
+ export type CsvInput = string | AsyncIterable<Uint8Array>;
268
281
  /**
269
282
  * File input options, including parser settings and stream controls.
270
283
  *
@@ -274,7 +287,7 @@ export interface CsvParserOptions<TEncoding extends CsvFileEncoding = CsvNativeE
274
287
  export interface CsvFileOptions extends CsvParserOptions<CsvFileEncoding> {
275
288
  /** Defaults to `'auto'`, probing up to 64 KiB after decompression, independently of the delimiter. */
276
289
  readonly encoding?: CsvFileEncoding;
277
- /** 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. */
278
291
  readonly chunkSize?: number;
279
292
  /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
280
293
  readonly compression?: CsvCompression;
@@ -282,54 +295,48 @@ export interface CsvFileOptions extends CsvParserOptions<CsvFileEncoding> {
282
295
  /**
283
296
  * File options accepted by byte-offset sharding helpers.
284
297
  *
285
- * Compression is excluded because compressed byte streams cannot be split into
286
- * 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.
287
300
  */
288
- export type CsvShardingOptions = Omit<CsvFileOptions, 'compression' | 'encoding' | keyof CsvRowSelectionOptions | keyof CsvDialectOptions> & {
301
+ export type CsvShardingOptions = Omit<CsvFileOptions, 'compression' | 'delimiter' | 'encoding' | 'maxRecordBytes' | keyof CsvRowSelectionOptions | keyof CsvDialectOptions> & {
289
302
  /** Compression is unsupported for byte-offset sharding. */
290
303
  readonly compression?: never;
304
+ /** Field separator for the boundary scan. Defaults to `'auto'`. */
305
+ readonly delimiter?: CsvDelimiter;
291
306
  /** Sharding scans raw file bytes and supports native encodings only. */
292
307
  readonly encoding?: CsvNativeEncoding;
293
308
  };
294
- /** Native equality predicate used by projection and count fast paths. */
295
- export interface CsvEqualsFilter {
309
+ interface CsvPhysicalFilter {
296
310
  /** Zero-based physical column to inspect. */
297
311
  readonly column: number;
312
+ }
313
+ /** Native equality predicate used by projection and count fast paths. */
314
+ export interface CsvEqualsFilter extends CsvPhysicalFilter {
298
315
  /** Field bytes or text that must equal the input field. */
299
316
  readonly value: CsvFieldValue;
300
317
  }
301
318
  /** Native membership predicate used by projection and count fast paths. */
302
- export interface CsvInFilter {
303
- /** Zero-based physical column to inspect. */
304
- readonly column: number;
319
+ export interface CsvInFilter extends CsvPhysicalFilter {
305
320
  /** Values for which the input field matches. */
306
321
  readonly values: readonly CsvFieldValue[];
307
322
  }
308
323
  /** Native inequality predicate used by projection and count fast paths. */
309
- export interface CsvNotEqualsFilter {
310
- /** Zero-based physical column to inspect. */
311
- readonly column: number;
324
+ export interface CsvNotEqualsFilter extends CsvPhysicalFilter {
312
325
  /** Field bytes or text that must differ from the input field. */
313
326
  readonly notEquals: CsvFieldValue;
314
327
  }
315
328
  /** Native negative-membership predicate used by projection and count fast paths. */
316
- export interface CsvNotInFilter {
317
- /** Zero-based physical column to inspect. */
318
- readonly column: number;
329
+ export interface CsvNotInFilter extends CsvPhysicalFilter {
319
330
  /** Values that the input field must not match. */
320
331
  readonly notIn: readonly CsvFieldValue[];
321
332
  }
322
333
  /** Native prefix predicate used by projection and count fast paths. */
323
- export interface CsvStartsWithFilter {
324
- /** Zero-based physical column to inspect. */
325
- readonly column: number;
334
+ export interface CsvStartsWithFilter extends CsvPhysicalFilter {
326
335
  /** Field bytes or text that must occur at the start of the input field. */
327
336
  readonly prefix: CsvFieldValue;
328
337
  }
329
338
  /** Native regular-expression predicate used by projection and count fast paths. */
330
- export interface CsvRegexFilter {
331
- /** Zero-based physical column to inspect. */
332
- readonly column: number;
339
+ export interface CsvRegexFilter extends CsvPhysicalFilter {
333
340
  /** Validated pattern created by `csv.re()`. */
334
341
  readonly regex: CsvRegex;
335
342
  }
@@ -347,9 +354,7 @@ export type CsvNativeFilter = CsvEqualsFilter | CsvInFilter | CsvNotInFilter | C
347
354
  * `equalsFilter` and `filters` are mutually exclusive. When `filters` contains
348
355
  * several entries, the native path combines them with an AND operation.
349
356
  */
350
- export interface CsvNativeProjectionOptions {
351
- /** Physical columns to emit, in output order. */
352
- readonly columns?: CsvColumns;
357
+ export interface CsvNativeProjectionOptions extends CsvInputProjection {
353
358
  /** One equality predicate on a physical column. */
354
359
  readonly equalsFilter?: CsvEqualsFilter;
355
360
  /** Native predicates combined for the operation. */
@@ -373,6 +378,7 @@ export interface CsvNativeFilterOperator {
373
378
  *
374
379
  * Place predicates before the operators that consume them. A complete program
375
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.
376
382
  * Most applications can use `csv.column()` and its boolean combinators instead.
377
383
  */
378
384
  export type CsvNativeFilterProgramEntry = CsvNativeFilter | CsvNativeFilterOperator;
@@ -386,14 +392,26 @@ export interface CsvApiFileOptions extends CsvFileOptions {
386
392
  /** Opaque filter created by `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. */
387
393
  readonly where?: CsvFilter;
388
394
  }
389
- /** Retains the literal input indexes and their order for projected row types. */
390
- export interface CsvColumnSelection<TColumns extends CsvColumns | undefined> {
391
- /** 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. */
392
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> {
393
401
  }
394
- /** Shared operation properties have declarations that editors can use for hover documentation. */
395
- interface CsvOperationOptions<TColumns extends CsvColumns | undefined> extends CsvColumnSelection<TColumns>, CsvRowSelectionOptions, CsvDialectOptions {
396
- /** Field separator. Defaults to comma. File parsing also accepts `'auto'`. */
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;
409
+ }
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'`. */
397
415
  readonly delimiter?: CsvDelimiter;
398
416
  /** Require exactly this many fields per row; malformed rows fail instead of being padded or truncated. */
399
417
  readonly fixedColumns?: number;
@@ -401,61 +419,137 @@ interface CsvOperationOptions<TColumns extends CsvColumns | undefined> extends C
401
419
  readonly expectedHeaders?: readonly string[];
402
420
  /** Require a first row when strict schema validation is enabled. */
403
421
  readonly requireHeader?: boolean;
404
- /** 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. */
405
423
  readonly minDataRows?: number;
406
- /** 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. */
407
425
  readonly chunkSize?: number;
408
426
  }
427
+ interface CsvCompressionOptions {
428
+ /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
429
+ readonly compression?: CsvCompression;
430
+ }
409
431
  /** File operations support encoding detection and streamed decompression. */
410
- interface CsvFileOperationOptions<TColumns extends CsvColumns | undefined> extends CsvOperationOptions<TColumns> {
432
+ interface CsvFileOperationOptions extends CsvOperationOptions, CsvCompressionOptions {
411
433
  /** Defaults to `'auto'`, probing up to 64 KiB after decompression, independently of the delimiter. */
412
434
  readonly encoding?: CsvFileEncoding;
413
- /** Compression format or ZIP entry selection. Defaults to `'auto'`; `'none'` skips detection. */
414
- readonly compression?: CsvCompression;
415
435
  }
416
- /** Non-strict operations can filter input records. */
417
- interface CsvFilteredOperationOptions {
418
- /** 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. */
419
438
  readonly strict?: false | undefined;
420
- /** Filter records with `csv.column()`, `csv.all()`, `csv.any()`, or `csv.not()`. Requires `strict` to be false or omitted. */
421
- readonly where?: CsvFilter | undefined;
422
439
  }
423
- /** Strict validation requires unfiltered input. */
424
440
  interface CsvStrictOperationOptions {
425
- /** Enable RFC-style quote and schema validation. Requires unfiltered input. */
441
+ /** Validate physical records before filtering or projection. */
426
442
  readonly strict: true;
443
+ /** Strict validation requires double quotes to be interpreted as CSV quoting. */
427
444
  readonly quote?: true;
445
+ /** Strict validation uses the default record delimiters CRLF, LF, and CR. */
428
446
  readonly recordDelimiter?: undefined;
429
- /** Filtering is unavailable with strict validation, which checks every input record. */
430
- readonly where?: undefined;
431
447
  }
432
- /** Each branch keeps its documented properties and enforces the strict/filter constraint. */
433
- type CsvValidationOptions = CsvFilteredOperationOptions | CsvStrictOperationOptions;
434
- /** Options for parsing an in-memory buffer into materialized rows. */
435
- 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 & {
436
452
  /** Input field encoding used when decoding bytes into JavaScript strings. Defaults to `'utf8'`. */
437
453
  readonly encoding?: CsvEncoding;
438
454
  };
439
- /** Options for streaming materialized rows in file order. */
440
- 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;
441
467
  /** Refill the batch and its row arrays across iterations. Copy any row you want to keep. Defaults to false. */
442
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;
443
471
  };
444
- /** Batches of parsed fields. Strict validation requires unfiltered, unprojected input. */
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. */
445
522
  export type CsvBatchesOptions = CsvTransformOptions & {
523
+ /** Return parsed field batches. This is the default output. */
446
524
  readonly output?: 'fields';
447
- } & ((CsvFileOperationOptions<CsvColumns | undefined> & CsvFilteredOperationOptions) | (CsvFileOperationOptions<undefined> & CsvStrictOperationOptions));
525
+ } & CsvValidationOptions<CsvFileOperationOptions & CsvIndexedProjection<CsvColumns | undefined> & CsvIndexedFilterOptions>;
448
526
  /** Batches of original decompressed records using the literal LF dialect. */
449
- export type CsvRawRecordBatchesOptions = Omit<CsvFileOperationOptions<undefined>, 'encoding'> & CsvFilteredOperationOptions & {
527
+ export type CsvRawRecordBatchesOptions = CsvOperationOptions & CsvCompressionOptions & CsvIndexedFilterOptions & CsvNonStrictOperationOptions & {
528
+ /** Return original decompressed record bytes. Requires `quote: false` and `recordDelimiter: '\n'`. */
450
529
  readonly output: 'raw-records';
530
+ /** Interpret double quotes as ordinary bytes for raw-record output. */
451
531
  readonly quote: false;
532
+ /** Terminate raw records at LF and retain any CR as data. */
452
533
  readonly recordDelimiter: '\n';
534
+ /** Raw-record batches contain complete records. Use parsed field output to select columns. */
535
+ readonly columns?: undefined;
453
536
  /** Encoding for filter comparisons. Defaults to UTF-8. Output bytes are unchanged. */
454
537
  readonly encoding?: CsvNativeEncoding;
538
+ /** For field transforms, use parsed field output instead. */
455
539
  readonly transform?: undefined;
456
540
  };
457
- /** Options accepted by `csv.count()`. */
458
- export type CsvCountOptions = CsvFileOperationOptions<CsvColumns | undefined> & CsvValidationOptions;
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;
546
+ };
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>>;
459
553
  /**
460
554
  * Materialized row type inferred from a literal projection tuple.
461
555
  *
@@ -463,9 +557,13 @@ export type CsvCountOptions = CsvFileOperationOptions<CsvColumns | undefined> &
463
557
  * string tuple. Without a projection tuple the result is the variable-length
464
558
  * `CsvRow` shape.
465
559
  */
466
- 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[] ? {
467
561
  -readonly [Index in keyof TColumns]: string;
468
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>[];
469
567
  /**
470
568
  * Synchronous callback invoked by `NativeCsvBatch.forEachRow()`.
471
569
  *
@@ -0,0 +1,14 @@
1
+ import type { CsvZipCompression } from './types.js';
2
+ import { NativeZipReader, type VerifiedNestedZip, type ZipSource } from './zip-reader.js';
3
+ export declare const MAX_NESTED_ZIP_DEPTH = 32;
4
+ type ReadZipEntry<T> = (reader: NativeZipReader, prefix: string) => T | Promise<T>;
5
+ export declare class AmbiguousZipGlobError extends Error {
6
+ readonly candidates: readonly string[];
7
+ constructor(candidates: readonly string[]);
8
+ }
9
+ export declare function readZipEntryChunks(path: string, options: CsvZipCompression, chunkSize: number, readAhead?: boolean, onEntryName?: (name: string) => void, parallel?: boolean): AsyncGenerator<Uint8Array, void>;
10
+ /** Resolve a selector and keep its nested archives and reader open in the caller's scope. */
11
+ export declare function withZipEntry<T>(source: ZipSource, options: CsvZipCompression, resources: AsyncDisposableStack, read: ReadZipEntry<T>, depth?: number, prefix?: string): Promise<T>;
12
+ export declare function openNestedZip(source: ZipSource, options: CsvZipCompression, resources: AsyncDisposableStack): Promise<VerifiedNestedZip>;
13
+ export declare function isZipMember(path: string): boolean;
14
+ export {};
@@ -0,0 +1,155 @@
1
+ import { validateChunkSize } from "./normalize.js";
2
+ import {
3
+ NativeZipReader,
4
+ readZipDirectory
5
+ } from "./zip-reader.js";
6
+ export const MAX_NESTED_ZIP_DEPTH = 32;
7
+ const ZIP_ENTRY_SEPARATOR = "!/";
8
+
9
+ export class AmbiguousZipGlobError extends Error {
10
+ candidates;
11
+ constructor(candidates) {
12
+ super(`ZIP entry glob matches ${candidates.length} files`);
13
+ this.candidates = candidates;
14
+ }
15
+ }
16
+ export async function* readZipEntryChunks(path, options, chunkSize, readAhead = !1, onEntryName, parallel = !1) {
17
+ validateChunkSize(chunkSize);
18
+ await using resources = new AsyncDisposableStack;
19
+ const reader = await withZipEntry(path, options, resources, (entry) => entry);
20
+ onEntryName?.(reader.entryName);
21
+ yield* reader.chunks(chunkSize, readAhead, parallel);
22
+ }
23
+ export async function withZipEntry(source, options, resources, read, depth = 0, prefix = "") {
24
+ const { entry } = options;
25
+ const hasBoundary = hasZipBoundary(entry);
26
+ const isPattern = isZipGlob(entry);
27
+ const zipEntries = hasBoundary || isPattern ? readZipDirectory(source) : void 0;
28
+ const exact = zipEntries?.includes(entry) === !0;
29
+ const nested = hasBoundary && !exact && zipEntries !== void 0 ? nestedZipRoute(zipEntries, entry) : void 0;
30
+ if (nested === void 0) {
31
+ const member = isPattern && !exact && zipEntries !== void 0 ? matchZipGlob(zipEntries, entry, prefix) : entry;
32
+ return read(resources.use(new NativeZipReader(source, { ...options, entry: member })), prefix);
33
+ }
34
+ const [archive] = nested.archives;
35
+ if (nested.archives.length === 1)
36
+ return withNestedZip(source, { ...options, entry: archive }, depth, resources, (innerSource) => withZipEntry(innerSource, { ...options, entry: nested.entry }, resources, read, depth + 1, `${prefix}${archive}${ZIP_ENTRY_SEPARATOR}`));
37
+ const matches = await findNestedZipMatches(source, options, nested, depth);
38
+ const [match] = matches;
39
+ if (match === void 0)
40
+ throw Error("ZIP entry glob did not match any files");
41
+ if (matches.length > 1)
42
+ throw new AmbiguousZipGlobError(matches.map(({ archives, entry }) => prefix + [...archives, entry].join(ZIP_ENTRY_SEPARATOR)).sort());
43
+ return readResolvedEntry(source, match, options, resources, read, prefix, depth, 0);
44
+ }
45
+ async function withNestedZip(source, options, depth, resources, read) {
46
+ if (depth >= MAX_NESTED_ZIP_DEPTH)
47
+ throw Error(`ZIP nesting exceeds ${MAX_NESTED_ZIP_DEPTH} levels`);
48
+ try {
49
+ return await read(await openNestedZip(source, options, resources));
50
+ } catch (error) {
51
+ if (error instanceof AmbiguousZipGlobError)
52
+ throw error;
53
+ const message = error instanceof Error && !("path" in error) ? error.message : "Failed to read nested ZIP archive";
54
+ throw Error(`Cannot open nested ZIP ${JSON.stringify(options.entry)}: ${message}`, { cause: error });
55
+ }
56
+ }
57
+ function matchZipGlob(zipEntries, pattern, prefix) {
58
+ const matches = zipGlobMatches(zipEntries, pattern);
59
+ const [match] = matches;
60
+ if (match === void 0)
61
+ throw Error("ZIP entry glob did not match any files");
62
+ if (matches.length > 1) {
63
+ matches.sort();
64
+ throw new AmbiguousZipGlobError(matches.map((entry) => prefix + entry));
65
+ }
66
+ return match;
67
+ }
68
+ function zipGlobMatches(zipEntries, pattern) {
69
+ const glob = new Bun.Glob(pattern);
70
+ return zipEntries.filter((entry) => !entry.endsWith("/") && glob.match(entry));
71
+ }
72
+ function nestedZipRoute(zipEntries, entry) {
73
+ const literal = nestedArchiveInPath(zipEntries, entry);
74
+ const literalRoute = literal === void 0 ? void 0 : { archives: [literal.path], entry: entry.slice(literal.path.length + literal.separator.length) };
75
+ if (literal?.separator === ZIP_ENTRY_SEPARATOR)
76
+ return literalRoute;
77
+ let archives;
78
+ let explicit;
79
+ let implicit;
80
+ for (const boundary of entry.matchAll(/!\/|(?<=\.zip)\//gi)) {
81
+ const pattern = entry.slice(0, boundary.index);
82
+ if (!isZipGlob(pattern))
83
+ continue;
84
+ archives ??= zipEntries.filter(isZipMember);
85
+ const [first, ...others] = zipGlobMatches(archives, pattern);
86
+ if (first === void 0)
87
+ continue;
88
+ const route = { archives: [first, ...others], entry: entry.slice(boundary.index + boundary[0].length) };
89
+ if (boundary[0] === ZIP_ENTRY_SEPARATOR)
90
+ explicit = route;
91
+ else
92
+ implicit = route;
93
+ }
94
+ return explicit ?? literalRoute ?? implicit;
95
+ }
96
+ async function findNestedZipMatches(source, options, route, depth) {
97
+ const matches = [];
98
+ for (const archive of new Set(route.archives)) {
99
+ await using resources = new AsyncDisposableStack;
100
+ const resolved = await withNestedZip(source, { ...options, entry: archive }, depth, resources, async (innerSource) => {
101
+ const { entry } = route;
102
+ if (entry === "*") {
103
+ using reader = new NativeZipReader(innerSource, { ...options, entry });
104
+ return [{ archives: [], entry: reader.entryName }];
105
+ }
106
+ const zipEntries = readZipDirectory(innerSource);
107
+ if (zipEntries.includes(entry))
108
+ return entry.endsWith("/") ? [] : [{ archives: [], entry }];
109
+ const nested = hasZipBoundary(entry) ? nestedZipRoute(zipEntries, entry) : void 0;
110
+ if (nested !== void 0)
111
+ return findNestedZipMatches(innerSource, options, nested, depth + 1);
112
+ return isZipGlob(entry) ? zipGlobMatches(zipEntries, entry).map((name) => ({ archives: [], entry: name })) : [];
113
+ });
114
+ for (const match of resolved)
115
+ matches.push({ ...match, archives: [archive, ...match.archives] });
116
+ }
117
+ return matches;
118
+ }
119
+ async function readResolvedEntry(source, match, options, resources, read, prefix, depth, archiveIndex) {
120
+ const archive = match.archives[archiveIndex];
121
+ if (archive === void 0)
122
+ return read(resources.use(new NativeZipReader(source, { ...options, entry: match.entry })), prefix);
123
+ return withNestedZip(source, { ...options, entry: archive }, depth + archiveIndex, resources, (innerSource) => readResolvedEntry(innerSource, match, options, resources, read, `${prefix}${archive}${ZIP_ENTRY_SEPARATOR}`, depth, archiveIndex + 1));
124
+ }
125
+ function nestedArchiveInPath(zipEntries, entry) {
126
+ let explicit;
127
+ let implicit;
128
+ for (const nested of zipEntries) {
129
+ if (!isZipMember(nested))
130
+ continue;
131
+ if (entry.startsWith(nested + ZIP_ENTRY_SEPARATOR) && nested.length > (explicit?.length ?? 0))
132
+ explicit = nested;
133
+ else if (entry.startsWith(`${nested}/`) && nested.length > (implicit?.length ?? 0))
134
+ implicit = nested;
135
+ }
136
+ if (explicit !== void 0)
137
+ return { path: explicit, separator: ZIP_ENTRY_SEPARATOR };
138
+ return implicit === void 0 ? void 0 : { path: implicit, separator: "/" };
139
+ }
140
+ export async function openNestedZip(source, options, resources) {
141
+ using entry = new DisposableStack;
142
+ const reader = entry.use(new NativeZipReader(source, options));
143
+ const archive = await reader.verifyNestedArchive();
144
+ resources.use(entry.move());
145
+ return archive;
146
+ }
147
+ export function isZipMember(path) {
148
+ return path.toLowerCase().endsWith(".zip");
149
+ }
150
+ function hasZipBoundary(entry) {
151
+ return entry.includes(ZIP_ENTRY_SEPARATOR) || /\.zip\//i.test(entry);
152
+ }
153
+ function isZipGlob(entry) {
154
+ return entry !== "*" && /[*?[{\\]|^!|[!+@]\(/.test(entry);
155
+ }
@@ -1,14 +1,25 @@
1
+ import { type Pointer } from './native.js';
1
2
  import type { CsvZipCompression } from './types.js';
3
+ type ZipReaderPointer = Pointer | bigint;
4
+ declare const verifiedZipHandle: unique symbol;
5
+ export interface VerifiedNestedZip {
6
+ readonly [verifiedZipHandle]: () => ZipReaderPointer;
7
+ }
8
+ export type ZipSource = string | VerifiedNestedZip;
2
9
  export declare class NativeZipReader {
3
10
  #private;
4
- constructor(path: string, options: CsvZipCompression);
11
+ constructor(source: ZipSource, options: CsvZipCompression);
5
12
  get status(): number;
6
13
  get entryName(): string;
14
+ /** Open a seekable source after checking the enclosing entry's size and CRC. */
15
+ verifyNestedArchive(): Promise<VerifiedNestedZip>;
7
16
  enableReadAhead(chunkSize: number): void;
8
17
  read(output: Uint8Array): number;
9
18
  lastError(): string;
10
- chunks(outputSize: number, readAhead?: boolean): Generator<Uint8Array, void>;
19
+ chunks(outputSize: number, readAhead?: boolean, parallel?: boolean): Generator<Uint8Array, void>;
11
20
  close(): void;
12
21
  [Symbol.dispose](): void;
13
22
  }
14
- export declare function readZipEntryChunks(path: string, options: CsvZipCompression, chunkSize: number, readAhead?: boolean): AsyncGenerator<Uint8Array, void>;
23
+ /** Read the names recorded in the central directory without opening an entry. */
24
+ export declare function readZipDirectory(source: ZipSource): string[];
25
+ export {};