@konstit/csv 0.4.1 → 0.5.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 (65) hide show
  1. package/README.md +152 -463
  2. package/THIRD_PARTY_NOTICES.md +7 -1
  3. package/dist/api.d.ts +169 -44
  4. package/dist/api.js +75 -368
  5. package/dist/batches.d.ts +250 -7
  6. package/dist/batches.js +135 -83
  7. package/dist/cli-command.d.ts +7 -0
  8. package/dist/cli-command.js +350 -0
  9. package/dist/cli-schema.d.ts +111 -0
  10. package/dist/cli-schema.js +219 -0
  11. package/dist/cli.js +2 -604
  12. package/dist/file-stream.d.ts +57 -2
  13. package/dist/file-stream.js +244 -36
  14. package/dist/files.d.ts +149 -3
  15. package/dist/files.js +37 -29
  16. package/dist/filter.d.ts +80 -0
  17. package/dist/format-bytes.d.ts +1 -0
  18. package/dist/format-bytes.js +11 -0
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +2 -14
  21. package/dist/inspect-file.d.ts +12 -0
  22. package/dist/inspect-file.js +88 -0
  23. package/dist/latin1-rows.d.ts +5 -0
  24. package/dist/latin1-rows.js +122 -0
  25. package/dist/materialize-field.d.ts +3 -0
  26. package/dist/materialize-field.js +31 -0
  27. package/dist/native.d.ts +51 -2
  28. package/dist/native.js +43 -4
  29. package/dist/normalize.d.ts +32 -2
  30. package/dist/normalize.js +51 -2
  31. package/dist/options-snapshot.d.ts +3 -0
  32. package/dist/options-snapshot.js +51 -0
  33. package/dist/options.d.ts +25 -10
  34. package/dist/options.js +0 -6
  35. package/dist/parser.d.ts +309 -4
  36. package/dist/parser.js +128 -31
  37. package/dist/strict-schema.d.ts +5 -3
  38. package/dist/strict-schema.js +4 -1
  39. package/dist/types.d.ts +355 -121
  40. package/dist/zip-reader.d.ts +11 -1
  41. package/dist/zip-reader.js +12 -3
  42. package/package.json +44 -29
  43. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  44. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  45. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  46. package/prebuilds/manifest.json +9 -8
  47. package/prebuilds/provenance/darwin-arm64.json +1 -1
  48. package/prebuilds/provenance/darwin-x64.json +1 -1
  49. package/prebuilds/provenance/linux-x64.json +1 -1
  50. package/dist/worker-count.d.ts +0 -2
  51. package/dist/worker-count.js +0 -96
  52. package/dist/worker-factory.d.ts +0 -3
  53. package/dist/worker-factory.js +0 -9
  54. package/dist/worker-filter.d.ts +0 -29
  55. package/dist/worker-filter.js +0 -46
  56. package/dist/worker-module.d.ts +0 -1
  57. package/dist/worker-module.js +0 -4
  58. package/dist/worker-pool.d.ts +0 -17
  59. package/dist/worker-pool.js +0 -290
  60. package/dist/worker-rows.d.ts +0 -8
  61. package/dist/worker-rows.js +0 -118
  62. package/dist/workers/count.worker.d.ts +0 -1
  63. package/dist/workers/count.worker.js +0 -49
  64. package/dist/workers/rows.worker.d.ts +0 -1
  65. package/dist/workers/rows.worker.js +0 -85
@@ -325,7 +325,7 @@ SOFTWARE.
325
325
  - Source: https://github.com/zlib-ng/zlib-ng
326
326
  - Version: 2.3.3
327
327
  - License: zlib License
328
- - Use in this project: compiled into the distributed native library for streaming ZIP DEFLATE and CRC32 processing.
328
+ - Use in this project: compiled into the Linux x64 and macOS x64 native libraries for ZIP DEFLATE and CRC32 processing. The macOS arm64 library uses the operating system's zlib.
329
329
 
330
330
  Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
331
331
 
@@ -350,6 +350,12 @@ it and redistribute it freely, subject to the following restrictions:
350
350
  - Use in this repo: compatibility fixtures loaded by `test/csv-parser/spectrum.test.ts`.
351
351
  - Notice: csv-spectrum is copyright its authors and contributors. Redistribution of source or binary forms must retain the BSD-2-Clause copyright notice, conditions, and disclaimer.
352
352
 
353
+ ## TurboCSV
354
+
355
+ - Source: [TurboCSV library comparison](https://github.com/bytebrujo/bun-csv/blob/d1217818230788a8a4f48ebc023a71cd1a57feb4/test/benchmark-comparison.ts)
356
+ - License: [MIT](./LICENSE), TurboCSV Contributors.
357
+ - Use in this repo: synthetic fixture recipe and file parsing workloads adapted in `bench/comparison/libs-comparison.ts`.
358
+
353
359
  ## csvkit
354
360
 
355
361
  - Source: https://github.com/wireservice/csvkit
package/dist/api.d.ts CHANGED
@@ -1,81 +1,206 @@
1
1
  import type { NativeCsvBatch } from './batches.js';
2
+ import type { CsvFileProbe } from './file-stream.js';
2
3
  import { all, any, column, not, re } from './filter.js';
3
- import type { CsvBatchesOptions, CsvColumnarBatchCallback, CsvColumnarBatchOptions, CsvColumns, CsvCountOptions, CsvParseOptions, CsvProjectedRow, CsvRowsOptions, CsvRowViewCallback, CsvRowViewsOptions, CsvShard, CsvShardingOptions, CsvWorkerPoolOptions } from './types.js';
4
- import { parallelCount } from './worker-count.js';
5
- import { CsvWorkerPool } from './worker-pool.js';
6
- import { parallelRows } from './worker-rows.js';
4
+ import type { CsvBatchesOptions, CsvColumns, CsvCountOptions, CsvParseOptions, CsvProjectedRow, CsvRowsOptions, CsvShard, CsvShardingOptions } from './types.js';
7
5
  /**
8
- * Parse one in-memory chunk into materialized rows.
6
+ * Parse one in-memory CSV buffer into materialized rows.
9
7
  *
10
- * Use this when you already own buffering and still want the high-level row API.
11
- * Accepts only single-thread row options, so `workerCount` is intentionally unavailable.
8
+ * Use this when the input is already buffered and a single promise containing all rows is suitable.
9
+ * The buffer is parsed as one complete input, so a record may not be split across calls. Use
10
+ * {@link rows} for file streaming. `columns` projects the
11
+ * returned rows, while strict validation (when enabled) still validates the complete row.
12
+ *
13
+ * @typeParam TColumns - Literal projected column indexes, when a projection is supplied.
14
+ * @param buffer - CSV bytes in a typed array or `DataView`.
15
+ * @param suppliedOptions - Parser options for uncompressed bytes with a fixed delimiter.
16
+ * @returns A promise that resolves to the materialized rows in input order.
17
+ * @throws {Error} If the options request compression, automatic delimiter detection, or an
18
+ * unsupported filtered strict-validation combination.
12
19
  */
13
- export declare function parse<TColumns extends CsvColumns | undefined = undefined>(buffer: NodeJS.TypedArray | DataView, options?: CsvParseOptions<TColumns>): Promise<CsvProjectedRow<TColumns>[]>;
20
+ export declare function parse<TColumns extends CsvColumns | undefined = undefined>(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParseOptions<TColumns>): Promise<CsvProjectedRow<TColumns>[]>;
14
21
  /**
15
22
  * Stream materialized rows from a CSV file.
16
23
  *
17
- * Use this for the most direct high-level API. With `workerCount > 1`, the work
18
- * fans out across Bun workers.
24
+ * Each yielded value is one parser batch represented as ordinary string arrays. Options are
25
+ * captured when this function is called, before iteration starts, so mutating the caller-owned
26
+ * options object later does not change the stream. With `reuseArrays: true`, batches and their
27
+ * rows are borrowed until the next iteration. Copy a row with `row.slice()` to retain it.
28
+ *
29
+ * @typeParam TColumns - Literal projected column indexes, when a projection is supplied.
30
+ * @param path - Path to the CSV file.
31
+ * @param options - File, projection, filter, and validation settings.
32
+ * @returns An async generator of row batches in file order.
33
+ * @throws {Error} During iteration when the file cannot be read or the selected options are
34
+ * incompatible, such as a filter combined with strict validation.
19
35
  */
20
36
  export declare function rows<TColumns extends CsvColumns | undefined = undefined>(path: string, options?: CsvRowsOptions<TColumns>): AsyncGenerator<CsvProjectedRow<TColumns>[], void>;
21
- export { parallelRows };
22
- export { CsvWorkerPool };
37
+ export declare function iterateRows<TColumns extends CsvColumns | undefined>(path: string, options: CsvRowsOptions<TColumns>, probeFormat?: CsvFileProbe): AsyncGenerator<CsvProjectedRow<TColumns>[], void>;
23
38
  /**
24
39
  * Stream native batches with explicit lifetime control.
25
40
  *
26
- * Use this when you want low-allocation access to row views or byte ranges and
27
- * are comfortable closing each batch yourself.
41
+ * Use this when you want low-allocation access to row views, byte ranges, and native-backed
42
+ * column data. Every yielded batch owns native memory and must be closed after use; prefer
43
+ * `for await (using batch of csv.batches(...))` to close each batch at the end of the iteration.
44
+ * Options are captured at invocation time. Projection selects the stored fields in the requested
45
+ * order. Accessors use output positions and filters use physical input indexes.
46
+ *
47
+ * @param path - Path to the CSV file.
48
+ * @param options - File and parser options.
49
+ * @returns An async generator of disposable native batches.
50
+ * @throws {Error} During iteration when the file or validation fails, or when strict validation
51
+ * is combined with projection or filtering.
28
52
  */
29
53
  export declare function batches(path: string, options?: CsvBatchesOptions): AsyncGenerator<NativeCsvBatch, void>;
30
- export declare function withBatches(path: string, options: CsvBatchesOptions, callback: (batch: NativeCsvBatch) => void | Promise<void>): Promise<void>;
31
54
  /**
32
- * Stream reusable columnar batch views without materializing one JS string per field.
55
+ * Count CSV records without materializing them.
33
56
  *
34
- * When `columns` is defined, batch column indexes are relative to the projected
35
- * output order. This API is synchronous by design so the view can be safely reused.
57
+ * Filters created with `csv.column()` and composed with `csv.all()`, `csv.any()`, or `csv.not()`
58
+ * are evaluated by native fast paths. The input may be compressed or use automatic delimiter
59
+ * detection.
60
+ *
61
+ * @param path - Path to the CSV file.
62
+ * @param suppliedOptions - File, filter, and validation settings.
63
+ * @returns A promise containing the record count.
64
+ * @throws {Error} If strict validation is combined with a filter or reading or parsing fails.
36
65
  */
37
- export declare function forEachColumnarBatches<TColumns extends CsvColumns | undefined = undefined>(path: string, options: CsvColumnarBatchOptions<TColumns>, callback: CsvColumnarBatchCallback<TColumns>): Promise<void>;
38
- export declare function forEachColumnarBatches(path: string, options: CsvColumnarBatchOptions | undefined, callback: CsvColumnarBatchCallback): Promise<void>;
39
- export declare function withColumnarBatches<TColumns extends CsvColumns | undefined = undefined>(path: string, options: CsvColumnarBatchOptions<TColumns>, callback: CsvColumnarBatchCallback<TColumns>): Promise<void>;
66
+ export declare function count(path: string, suppliedOptions?: CsvCountOptions): Promise<number>;
40
67
  /**
41
- * Stream reusable row views without materializing row arrays.
68
+ * Find byte offsets that divide a CSV file only at record boundaries.
69
+ *
70
+ * The returned array contains shard start offsets followed by the terminal file boundary. Quoted
71
+ * fields and embedded newlines are respected. The operation scans original UTF-8 or Latin-1
72
+ * bytes in an uncompressed file with a fixed delimiter.
73
+ *
74
+ * @param path - Path to the uncompressed CSV file.
75
+ * @param shardCount - Desired number of partitions; the result may contain fewer non-empty shards.
76
+ * @param suppliedOptions - Explicit delimiter and file parser options. Compression is unavailable.
77
+ * @returns Monotonically increasing byte offsets, including `0` and the file-length boundary.
78
+ * @throws {RangeError} If `shardCount` is not a positive integer.
79
+ * @throws {Error} If the input is compressed, the encoding requires transcoding, or the delimiter is automatic or invalid.
80
+ */
81
+ declare function findCsvSafeSplitOffsets(path: string, shardCount: number, suppliedOptions?: CsvShardingOptions): number[];
82
+ /**
83
+ * Find non-empty CSV byte ranges that begin and end at record boundaries.
84
+ *
85
+ * Shards use inclusive `start` and `end` offsets and never split quoted fields or embedded
86
+ * newlines. A small file can produce fewer non-empty shards than requested. The operation
87
+ * requires original UTF-8 or Latin-1 bytes in an uncompressed file with a fixed delimiter.
42
88
  *
43
- * `selectedColumns` on the row view is metadata only. Row accessors still use
44
- * physical CSV column indexes; use `row.getPhysical()` for explicit call sites.
45
- * This API is synchronous by design so the view can be safely reused.
89
+ * @param path - Path to the uncompressed CSV file.
90
+ * @param shardCount - Desired number of partitions; the result may contain fewer shards.
91
+ * @param suppliedOptions - Explicit delimiter and file parser options. Compression is unavailable.
92
+ * @returns Non-empty, ordered byte ranges with inclusive endpoints.
93
+ * @throws {RangeError} If `shardCount` is not a positive integer.
94
+ * @throws {Error} If the input is compressed, the encoding requires transcoding, or the delimiter is automatic or invalid.
46
95
  */
47
- export declare function forEachRowViews<TColumns extends CsvColumns | undefined = undefined>(path: string, options: CsvRowViewsOptions<TColumns>, callback: CsvRowViewCallback<TColumns>): Promise<void>;
48
- export declare function forEachRowViews(path: string, options: CsvRowViewsOptions | undefined, callback: CsvRowViewCallback): Promise<void>;
49
- export declare function withRowViews<TColumns extends CsvColumns | undefined = undefined>(path: string, options: CsvRowViewsOptions<TColumns>, callback: CsvRowViewCallback<TColumns>): Promise<void>;
96
+ declare function findCsvSafeShards(path: string, shardCount: number, suppliedOptions?: CsvShardingOptions): CsvShard[];
50
97
  /**
51
- * Count rows without materializing them.
98
+ * The package's file-oriented API namespace.
52
99
  *
53
- * Full filter support exists here because count has native fast paths for
54
- * filters created with `csv.column()` and grouped with `csv.all()`, `csv.any()`, and `csv.not()`.
100
+ * The namespace combines materialization, counting, filtering, native batches, and
101
+ * record-safe sharding helpers in one discoverable object.
55
102
  */
56
- export declare function count(path: string, options?: CsvCountOptions): Promise<number>;
57
- export { parallelCount };
58
- export declare function findCsvSafeSplitOffsets(path: string, shardCount: number, options?: CsvShardingOptions): number[];
59
- export declare function findCsvSafeShards(path: string, shardCount: number, options?: CsvShardingOptions): CsvShard[];
60
- export declare function workerPool<TColumns extends CsvColumns | undefined = undefined>(path: string, options: CsvWorkerPoolOptions<TColumns>): CsvWorkerPool<TColumns>;
61
103
  export declare const csv: {
104
+ /**
105
+ * Combine one or more filters with logical AND semantics.
106
+ * @param first - First filter in the group.
107
+ * @param rest - Additional filters that must match.
108
+ * @returns An immutable conjunction filter.
109
+ */
62
110
  all: typeof all;
111
+ /**
112
+ * Combine one or more filters with logical OR semantics.
113
+ * @param first - First filter in the group.
114
+ * @param rest - Additional filters, any one of which may match.
115
+ * @returns An immutable disjunction filter.
116
+ */
63
117
  any: typeof any;
118
+ /**
119
+ * Select a zero-based physical CSV column for building reusable filters.
120
+ * @param columnIndex - Column index from 0 through 2024.
121
+ * @returns An immutable column predicate builder.
122
+ */
64
123
  column: typeof column;
124
+ /**
125
+ * Negate a filter while preserving missing-column unknown semantics.
126
+ * @param filter - Filter created by this API.
127
+ * @returns An immutable negation filter.
128
+ */
65
129
  not: typeof not;
130
+ /**
131
+ * Validate and brand a JavaScript regular expression for native matching.
132
+ * @param pattern - Expression using the supported RE2-compatible syntax and flags.
133
+ * @returns An immutable `CsvRegex` descriptor for low-level filter values.
134
+ */
66
135
  re: typeof re;
67
- workerPool: typeof workerPool;
136
+ /**
137
+ * Parse one in-memory buffer into materialized rows.
138
+ * Supply uncompressed bytes with a fixed delimiter.
139
+ * @param buffer - CSV bytes in a typed array or `DataView`.
140
+ * @param suppliedOptions - In-memory parser and projection options.
141
+ * @returns A promise containing materialized rows in input order.
142
+ * @example
143
+ * ```ts
144
+ * import { csv } from '@konstit/csv';
145
+ * const rows = await csv.parse(Buffer.from('1,Ada\n2,Grace\n'), { columns: [1] });
146
+ * // [['Ada'], ['Grace']]
147
+ * ```
148
+ */
68
149
  parse: typeof parse;
150
+ /**
151
+ * Stream materialized row batches from a CSV file.
152
+ * Options are captured at invocation. Batches are yielded in file order.
153
+ * @param path - Path to the CSV file.
154
+ * @param options - File, projection, filter, and validation settings.
155
+ * @returns An async generator of row batches.
156
+ * @example
157
+ * ```ts
158
+ * import { csv } from '@konstit/csv';
159
+ * for await (const rows of csv.rows('data.csv', { columns: [0, 2], delimiter: ';' })) {
160
+ * for (const row of rows) console.log(row);
161
+ * }
162
+ * ```
163
+ */
69
164
  rows: typeof rows;
70
- parallelCount: typeof parallelCount;
71
- parallelRows: typeof parallelRows;
165
+ /**
166
+ * Stream disposable native-backed batches.
167
+ * Columns select stored fields in output order. Filters address the input record.
168
+ * Close each yielded batch, or use `for await (using batch of ...)`.
169
+ * @param path - Path to the CSV file.
170
+ * @param options - File and parser options.
171
+ * @returns An async generator of `NativeCsvBatch` objects.
172
+ */
72
173
  batches: typeof batches;
73
- withBatches: typeof withBatches;
74
- forEachColumnarBatches: typeof forEachColumnarBatches;
75
- withColumnarBatches: typeof withColumnarBatches;
76
- forEachRowViews: typeof forEachRowViews;
77
- withRowViews: typeof withRowViews;
174
+ /**
175
+ * Count CSV records without materializing them.
176
+ * Counting supports compression and automatic encoding and delimiter detection. Filters require non-strict parsing.
177
+ * @param path - Path to the CSV file.
178
+ * @param suppliedOptions - File, filter, and validation settings.
179
+ * @returns A promise containing the record count.
180
+ * @example
181
+ * ```ts
182
+ * import { csv } from '@konstit/csv';
183
+ * const activeRows = await csv.count('data.csv', { where: csv.column(2).equals('active') });
184
+ * ```
185
+ */
78
186
  count: typeof count;
187
+ /**
188
+ * Find record-safe byte offsets, including the terminal file boundary.
189
+ * Compressed input and automatic delimiter detection are unsupported.
190
+ * @param path - Path to an uncompressed CSV file.
191
+ * @param shardCount - Desired number of partitions.
192
+ * @param suppliedOptions - Explicit delimiter and sharding options.
193
+ * @returns Monotonically increasing byte offsets.
194
+ */
79
195
  findCsvSafeSplitOffsets: typeof findCsvSafeSplitOffsets;
196
+ /**
197
+ * Find non-empty record-safe byte ranges for independent processing.
198
+ * Ranges use inclusive `start` and `end` offsets and may be fewer than requested.
199
+ * @param path - Path to an uncompressed CSV file.
200
+ * @param shardCount - Desired number of partitions.
201
+ * @param suppliedOptions - Explicit delimiter and sharding options.
202
+ * @returns Ordered, non-empty CSV byte ranges.
203
+ */
80
204
  findCsvSafeShards: typeof findCsvSafeShards;
81
205
  };
206
+ export {};