@konstit/csv 0.5.1 → 0.6.1
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.
- package/README.md +34 -1
- package/THIRD_PARTY_NOTICES.md +99 -0
- package/dist/api.d.ts +16 -9
- package/dist/api.js +40 -20
- package/dist/batches.d.ts +21 -0
- package/dist/batches.js +154 -20
- package/dist/cli-command.js +107 -2
- package/dist/cli-schema.d.ts +4 -0
- package/dist/cli-schema.js +11 -1
- package/dist/file-stream.d.ts +10 -6
- package/dist/file-stream.js +97 -47
- package/dist/files.js +3 -2
- package/dist/filter.d.ts +2 -2
- package/dist/filter.js +2 -0
- package/dist/gzip-reader.d.ts +2 -0
- package/dist/gzip-reader.js +37 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/latin1-rows.d.ts +3 -2
- package/dist/latin1-rows.js +52 -12
- package/dist/materialize-field.d.ts +1 -0
- package/dist/materialize-field.js +10 -1
- package/dist/native.d.ts +55 -3
- package/dist/native.js +27 -3
- package/dist/normalize.d.ts +2 -1
- package/dist/normalize.js +7 -0
- package/dist/options-snapshot.d.ts +2 -2
- package/dist/options-snapshot.js +2 -0
- package/dist/parser.d.ts +9 -6
- package/dist/parser.js +64 -11
- package/dist/transforms.d.ts +11 -0
- package/dist/transforms.js +192 -0
- package/dist/types.d.ts +64 -9
- package/package.json +1 -1
- package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
- package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
- package/prebuilds/linux-x64/libcsv_native.so +0 -0
- package/prebuilds/manifest.json +17 -8
- package/prebuilds/provenance/darwin-arm64.json +1 -1
- package/prebuilds/provenance/darwin-x64.json +1 -1
- package/prebuilds/provenance/linux-x64.json +1 -1
package/README.md
CHANGED
|
@@ -143,6 +143,33 @@ The filter also applies to the header, which does not match `'SP'` here. Combine
|
|
|
143
143
|
See [Filters](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#filters) for matching rules
|
|
144
144
|
and supported regex syntax.
|
|
145
145
|
|
|
146
|
+
### Transform accepted rows
|
|
147
|
+
|
|
148
|
+
To print each person's name and state from `data.csv`, expand the state abbreviation in column 2. If you also supply `where`, it checks the original fields before the transforms run.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
import { csv } from '@konstit/csv';
|
|
152
|
+
|
|
153
|
+
const stateName = csv.column(2).map({ SP: 'São Paulo', RJ: 'Rio de Janeiro' });
|
|
154
|
+
for await (
|
|
155
|
+
const batch of csv.rows('data.csv', {
|
|
156
|
+
skipRows: 1,
|
|
157
|
+
columns: [1, 2],
|
|
158
|
+
transform: [stateName],
|
|
159
|
+
})
|
|
160
|
+
) {
|
|
161
|
+
for (const [name, state,] of batch) {
|
|
162
|
+
console.log(`${name}, ${state}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// Ada, São Paulo
|
|
166
|
+
// Grace, Rio de Janeiro
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
Run `bun run examples/api-rows-transforms.ts` from the repository to try two more [streaming examples](https://github.com/Konstit-Engenharia/csv-parser/blob/main/examples/api-rows-transforms.ts) with sample orders. The first cleans names, cities, and amounts. The second formats order IDs using numbered and named captures.
|
|
170
|
+
|
|
171
|
+
See [field transforms](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#field-transforms) for Unicode rules, replacement, value mapping, and date formatting.
|
|
172
|
+
|
|
146
173
|
### Read compressed files
|
|
147
174
|
|
|
148
175
|
Create a gzip copy of the sample file:
|
|
@@ -167,13 +194,19 @@ for await (
|
|
|
167
194
|
|
|
168
195
|
File APIs and the CLI detect compression by default and read plain CSV, TSV, and text files directly.
|
|
169
196
|
For a plain file with an unrecognized name, use `compression: 'none'` or `--compression none`.
|
|
170
|
-
|
|
197
|
+
Regular gzip files use native read-ahead, whether gzip is detected or specified explicitly.
|
|
198
|
+
Gzip from pipes and other non-regular inputs uses Bun's `DecompressionStream`.
|
|
171
199
|
|
|
172
200
|
ZIP archives automatically select the only data file, ignoring directories and OS metadata.
|
|
173
201
|
For archives with multiple data files, select an entry with `compression: { format: 'zip', entry: 'data.csv' }`. See
|
|
174
202
|
[Compression](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#compression-and-delimiter-detection)
|
|
175
203
|
for supported formats, detection rules, and limits.
|
|
176
204
|
|
|
205
|
+
For TSV exports with quoting disabled, use `quote: false` and `recordDelimiter: '\n'`.
|
|
206
|
+
Use `csv.batches()` with `output: 'raw-records'` to filter these files and access each record's original
|
|
207
|
+
decompressed bytes, including its line ending. See
|
|
208
|
+
[Raw record batches](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#raw-record-batches).
|
|
209
|
+
|
|
177
210
|
### Validate input
|
|
178
211
|
|
|
179
212
|
```ts
|
package/THIRD_PARTY_NOTICES.md
CHANGED
|
@@ -2,6 +2,105 @@
|
|
|
2
2
|
|
|
3
3
|
This file tracks third-party code incorporated into distributed native binaries and third-party test data, examples, and compatibility references used by this repository.
|
|
4
4
|
|
|
5
|
+
## uni-algo and the Unicode Character Database
|
|
6
|
+
|
|
7
|
+
The native library uses [uni-algo v1.2.0](https://github.com/uni-algo/uni-algo/tree/v1.2.0) under its public domain license and incorporates its Unicode 15.1 data for normalization, casing and whitespace.
|
|
8
|
+
The Diacritic property table is derived from [Unicode 17.0 PropList.txt](https://www.unicode.org/Public/17.0.0/ucd/PropList.txt).
|
|
9
|
+
|
|
10
|
+
### Unicode 15.1 data license
|
|
11
|
+
|
|
12
|
+
This software contains data derived from processing the Unicode data files.
|
|
13
|
+
The following license applies to the data files: https://www.unicode.org/license.txt
|
|
14
|
+
|
|
15
|
+
UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
|
|
16
|
+
|
|
17
|
+
See Terms of Use <https://www.unicode.org/copyright.html>
|
|
18
|
+
for definitions of Unicode Inc.'s Data Files and Software.
|
|
19
|
+
|
|
20
|
+
NOTICE TO USER: Carefully read the following legal agreement.
|
|
21
|
+
BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S
|
|
22
|
+
DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"),
|
|
23
|
+
YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
|
|
24
|
+
TERMS AND CONDITIONS OF THIS AGREEMENT.
|
|
25
|
+
IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE
|
|
26
|
+
THE DATA FILES OR SOFTWARE.
|
|
27
|
+
|
|
28
|
+
COPYRIGHT AND PERMISSION NOTICE
|
|
29
|
+
|
|
30
|
+
Copyright (c) 1991-2023 Unicode, Inc. All rights reserved.
|
|
31
|
+
Distributed under the Terms of Use in https://www.unicode.org/copyright.html.
|
|
32
|
+
|
|
33
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
34
|
+
a copy of the Unicode data files and any associated documentation
|
|
35
|
+
(the "Data Files") or Unicode software and any associated documentation
|
|
36
|
+
(the "Software") to deal in the Data Files or Software
|
|
37
|
+
without restriction, including without limitation the rights to use,
|
|
38
|
+
copy, modify, merge, publish, distribute, and/or sell copies of
|
|
39
|
+
the Data Files or Software, and to permit persons to whom the Data Files
|
|
40
|
+
or Software are furnished to do so, provided that either
|
|
41
|
+
(a) this copyright and permission notice appear with all copies
|
|
42
|
+
of the Data Files or Software, or
|
|
43
|
+
(b) this copyright and permission notice appear in associated
|
|
44
|
+
Documentation.
|
|
45
|
+
|
|
46
|
+
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
|
|
47
|
+
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
|
|
48
|
+
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
49
|
+
NONINFRINGEMENT OF THIRD PARTY RIGHTS.
|
|
50
|
+
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
|
|
51
|
+
NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
|
|
52
|
+
DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
|
|
53
|
+
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
|
54
|
+
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
55
|
+
PERFORMANCE OF THE DATA FILES OR SOFTWARE.
|
|
56
|
+
|
|
57
|
+
Except as contained in this notice, the name of a copyright holder
|
|
58
|
+
shall not be used in advertising or otherwise to promote the sale,
|
|
59
|
+
use or other dealings in these Data Files or Software without prior
|
|
60
|
+
written authorization of the copyright holder.
|
|
61
|
+
|
|
62
|
+
### Unicode 17.0 Diacritic data
|
|
63
|
+
|
|
64
|
+
UNICODE LICENSE V3
|
|
65
|
+
|
|
66
|
+
COPYRIGHT AND PERMISSION NOTICE
|
|
67
|
+
|
|
68
|
+
Copyright © 1991-2026 Unicode, Inc.
|
|
69
|
+
|
|
70
|
+
NOTICE TO USER: Carefully read the following legal agreement. BY
|
|
71
|
+
DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
|
|
72
|
+
SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
|
|
73
|
+
TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
|
|
74
|
+
DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
|
|
75
|
+
|
|
76
|
+
Permission is hereby granted, free of charge, to any person obtaining a
|
|
77
|
+
copy of data files and any associated documentation (the "Data Files") or
|
|
78
|
+
software and any associated documentation (the "Software") to deal in the
|
|
79
|
+
Data Files or Software without restriction, including without limitation
|
|
80
|
+
the rights to use, copy, modify, merge, publish, distribute, and/or sell
|
|
81
|
+
copies of the Data Files or Software, and to permit persons to whom the
|
|
82
|
+
Data Files or Software are furnished to do so, provided that either (a)
|
|
83
|
+
this copyright and permission notice appear with all copies of the Data
|
|
84
|
+
Files or Software, or (b) this copyright and permission notice appear in
|
|
85
|
+
associated Documentation.
|
|
86
|
+
|
|
87
|
+
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
|
|
88
|
+
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
89
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
|
|
90
|
+
THIRD PARTY RIGHTS.
|
|
91
|
+
|
|
92
|
+
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
|
|
93
|
+
BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
|
|
94
|
+
OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
|
95
|
+
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
|
|
96
|
+
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
|
|
97
|
+
FILES OR SOFTWARE.
|
|
98
|
+
|
|
99
|
+
Except as contained in this notice, the name of a copyright holder shall
|
|
100
|
+
not be used in advertising or otherwise to promote the sale, use or other
|
|
101
|
+
dealings in these Data Files or Software without prior written
|
|
102
|
+
authorization of the copyright holder.
|
|
103
|
+
|
|
5
104
|
## RE2
|
|
6
105
|
|
|
7
106
|
- Source: https://github.com/google/re2
|
package/dist/api.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import type { NativeCsvBatch } from './batches.js';
|
|
1
|
+
import type { NativeCsvBatch, NativeCsvRawRecordBatch } from './batches.js';
|
|
2
2
|
import type { CsvFileProbe } from './file-stream.js';
|
|
3
3
|
import { all, any, column, not, re } from './filter.js';
|
|
4
|
-
import
|
|
4
|
+
import { transform } from './transforms.js';
|
|
5
|
+
import type { CsvBatchesOptions, CsvColumns, CsvCountOptions, CsvParseOptions, CsvProjectedRow, CsvRawRecordBatchesOptions, CsvRowsOptions, CsvShard, CsvShardingOptions } from './types.js';
|
|
5
6
|
/**
|
|
6
7
|
* Parse one in-memory CSV buffer into materialized rows.
|
|
7
8
|
*
|
|
@@ -35,14 +36,14 @@ export declare function parse<TColumns extends CsvColumns | undefined = undefine
|
|
|
35
36
|
*/
|
|
36
37
|
export declare function rows<TColumns extends CsvColumns | undefined = undefined>(path: string, options?: CsvRowsOptions<TColumns>): AsyncGenerator<CsvProjectedRow<TColumns>[], void>;
|
|
37
38
|
export declare function iterateRows<TColumns extends CsvColumns | undefined>(path: string, options: CsvRowsOptions<TColumns>, probeFormat?: CsvFileProbe): AsyncGenerator<CsvProjectedRow<TColumns>[], void>;
|
|
39
|
+
type BatchOptions = CsvBatchesOptions | CsvRawRecordBatchesOptions;
|
|
38
40
|
/**
|
|
39
41
|
* Stream native batches with explicit lifetime control.
|
|
40
42
|
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* order. Accessors use output positions and filters use physical input indexes.
|
|
43
|
+
* Field batches provide low-allocation access to row views, byte ranges, and column data.
|
|
44
|
+
* With `output: 'raw-records'`, batches expose original decompressed bytes for the literal LF
|
|
45
|
+
* dialect. Filters use physical input indexes. Options are captured at invocation time.
|
|
46
|
+
* Use `for await (using batch of csv.batches(...))` to close each batch at the end of its iteration.
|
|
46
47
|
*
|
|
47
48
|
* @param path - Path to the CSV file.
|
|
48
49
|
* @param options - File and parser options.
|
|
@@ -50,7 +51,9 @@ export declare function iterateRows<TColumns extends CsvColumns | undefined>(pat
|
|
|
50
51
|
* @throws {Error} During iteration when the file or validation fails, or when strict validation
|
|
51
52
|
* is combined with projection or filtering.
|
|
52
53
|
*/
|
|
54
|
+
export declare function batches(path: string, options: CsvRawRecordBatchesOptions): AsyncGenerator<NativeCsvRawRecordBatch, void>;
|
|
53
55
|
export declare function batches(path: string, options?: CsvBatchesOptions): AsyncGenerator<NativeCsvBatch, void>;
|
|
56
|
+
export declare function batches(path: string, options: BatchOptions): AsyncGenerator<NativeCsvBatch | NativeCsvRawRecordBatch, void>;
|
|
54
57
|
/**
|
|
55
58
|
* Count CSV records without materializing them.
|
|
56
59
|
*
|
|
@@ -101,6 +104,8 @@ declare function findCsvSafeShards(path: string, shardCount: number, suppliedOpt
|
|
|
101
104
|
* record-safe sharding helpers in one discoverable object.
|
|
102
105
|
*/
|
|
103
106
|
export declare const csv: {
|
|
107
|
+
/** Build a reusable field transform, then bind it to physical input columns with on(). */
|
|
108
|
+
transform: typeof transform;
|
|
104
109
|
/**
|
|
105
110
|
* Combine one or more filters with logical AND semantics.
|
|
106
111
|
* @param first - First filter in the group.
|
|
@@ -164,11 +169,13 @@ export declare const csv: {
|
|
|
164
169
|
rows: typeof rows;
|
|
165
170
|
/**
|
|
166
171
|
* Stream disposable native-backed batches.
|
|
167
|
-
*
|
|
172
|
+
* By default, columns select stored fields in output order. Use `output: 'raw-records'`
|
|
173
|
+
* to access original decompressed records in the literal LF dialect.
|
|
174
|
+
* Filters address the input record.
|
|
168
175
|
* Close each yielded batch, or use `for await (using batch of ...)`.
|
|
169
176
|
* @param path - Path to the CSV file.
|
|
170
177
|
* @param options - File and parser options.
|
|
171
|
-
* @returns An async generator of
|
|
178
|
+
* @returns An async generator of disposable native batches.
|
|
172
179
|
*/
|
|
173
180
|
batches: typeof batches;
|
|
174
181
|
/**
|
package/dist/api.js
CHANGED
|
@@ -15,7 +15,10 @@ import {
|
|
|
15
15
|
not,
|
|
16
16
|
re
|
|
17
17
|
} from "./filter.js";
|
|
18
|
-
import {
|
|
18
|
+
import {
|
|
19
|
+
canUseFilteredLatin1Cleanup,
|
|
20
|
+
latin1Rows
|
|
21
|
+
} from "./latin1-rows.js";
|
|
19
22
|
import { latin1RowsParser } from "./native.js";
|
|
20
23
|
import {
|
|
21
24
|
normalizeFixedColumnsCount,
|
|
@@ -27,9 +30,11 @@ import {
|
|
|
27
30
|
countFileChunks,
|
|
28
31
|
createPreparedParser,
|
|
29
32
|
parseFileChunks,
|
|
33
|
+
parseRawRecordChunks,
|
|
30
34
|
validateRowSelection
|
|
31
35
|
} from "./parser.js";
|
|
32
36
|
import { rejectStrictSchemaUnsupported } from "./strict-schema.js";
|
|
37
|
+
import { transform } from "./transforms.js";
|
|
33
38
|
export async function parse(buffer, suppliedOptions = {}) {
|
|
34
39
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
35
40
|
if ("compression" in options && options.compression !== void 0)
|
|
@@ -41,13 +46,8 @@ export async function parse(buffer, suppliedOptions = {}) {
|
|
|
41
46
|
const columns = options.columns;
|
|
42
47
|
const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
|
|
43
48
|
const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
|
|
44
|
-
using parser = createPreparedParser(toParserOptions(options, input.parserEncoding), projected ? columns : void 0, filters);
|
|
45
|
-
|
|
46
|
-
try {
|
|
47
|
-
return materializeRows(batch, columns, projected);
|
|
48
|
-
} finally {
|
|
49
|
-
batch.close();
|
|
50
|
-
}
|
|
49
|
+
using parser = createPreparedParser(toParserOptions(options, input.parserEncoding), projected ? columns : void 0, filters, options.transform);
|
|
50
|
+
return consumeBatchRows(parser.writeBatch(input.bytes, !0), columns, projected);
|
|
51
51
|
}
|
|
52
52
|
export function rows(path, options = {}) {
|
|
53
53
|
return iterateRows(path, snapshotCsvOptions(options));
|
|
@@ -58,19 +58,19 @@ export async function* iterateRows(path, options, probeFormat) {
|
|
|
58
58
|
const columns = options.columns;
|
|
59
59
|
const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
|
|
60
60
|
await using input = await prepareCsvFileInput(path, options, "read-ahead", probeFormat);
|
|
61
|
-
const parserOptions = toParserOptions(options, input.parserEncoding, input.delimiter);
|
|
62
61
|
const reusableRows = options.reuseArrays === !0 ? [] : void 0;
|
|
63
|
-
if (options.strict !== !0 && input.parserEncoding === "latin1") {
|
|
62
|
+
if (options.strict !== !0 && input.parserEncoding === "latin1" && options.quote !== !1 && options.recordDelimiter === void 0 && (!options.transform?.length || canUseFilteredLatin1Cleanup(columns, filters, options.transform))) {
|
|
64
63
|
validateRowSelection(options);
|
|
65
64
|
const fixedColumns = normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
|
|
66
|
-
const createParser = latin1RowsParser(fixedColumns);
|
|
65
|
+
const createParser = latin1RowsParser(fixedColumns, Boolean(options.transform?.length));
|
|
67
66
|
const chunks = options.limit === 0 ? [] : input.chunks();
|
|
68
|
-
yield* latin1Rows(chunks, input.delimiter, columns, filters, createParser, reusableRows,
|
|
67
|
+
yield* latin1Rows(chunks, input.delimiter, columns, filters, createParser, reusableRows, options);
|
|
69
68
|
return;
|
|
70
69
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
70
|
+
const parserOptions = toParserOptions(options, input.parserEncoding, input.delimiter);
|
|
71
|
+
using parser = createPreparedParser(parserOptions, projected ? columns : void 0, filters, options.transform, "rows");
|
|
72
|
+
for await (const batch of parseFileChunks(input, parser, options.limit))
|
|
73
|
+
yield consumeBatchRows(batch, columns, projected, reusableRows);
|
|
74
74
|
}
|
|
75
75
|
export function batches(path, options = {}) {
|
|
76
76
|
return iterateBatches(path, snapshotCsvOptions(options));
|
|
@@ -78,11 +78,26 @@ export function batches(path, options = {}) {
|
|
|
78
78
|
async function* iterateBatches(path, options) {
|
|
79
79
|
rejectFilteredStrictSchema(options);
|
|
80
80
|
const filters = toNativeFilters(options.where);
|
|
81
|
-
const columns = options
|
|
81
|
+
const { columns, encoding: requestedEncoding, strict, transform } = options;
|
|
82
|
+
if (options.output === "raw-records") {
|
|
83
|
+
if (options.quote !== !1 || options.recordDelimiter !== `
|
|
84
|
+
`)
|
|
85
|
+
throw TypeError("raw-records output requires quote: false and recordDelimiter: LF");
|
|
86
|
+
if (columns !== void 0 || transform !== void 0 || strict === !0)
|
|
87
|
+
throw TypeError("raw-records output does not support projection, transforms, or strict CSV validation");
|
|
88
|
+
const encoding = requestedEncoding === "auto" ? void 0 : resolveInputEncoding(requestedEncoding);
|
|
89
|
+
if (typeof encoding !== "string")
|
|
90
|
+
throw TypeError("raw-records output requires a native UTF-8 or Latin-1 encoding");
|
|
91
|
+
await using input = await prepareCsvFileInput(path, { ...options, encoding });
|
|
92
|
+
yield* parseRawRecordChunks(input, toParserOptions(options, input.parserEncoding, input.delimiter), filters);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
if (options.output !== void 0 && options.output !== "fields")
|
|
96
|
+
throw TypeError("output must be fields or raw-records");
|
|
82
97
|
if (options.strict === !0 && columns !== void 0)
|
|
83
98
|
throw Error("strict CSV validation is not supported for projected batches; use csv.rows() for strict projection");
|
|
84
99
|
await using input = await prepareCsvFileInput(path, options);
|
|
85
|
-
using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), columns, filters);
|
|
100
|
+
using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), columns, filters, options.transform);
|
|
86
101
|
yield* parseFileChunks(input, parser, options.limit);
|
|
87
102
|
}
|
|
88
103
|
export async function count(path, suppliedOptions = {}) {
|
|
@@ -91,8 +106,7 @@ export async function count(path, suppliedOptions = {}) {
|
|
|
91
106
|
await using input = await prepareCsvFileInput(path, options, "count");
|
|
92
107
|
if (options.strict === !0 && filters !== void 0)
|
|
93
108
|
throw Error("strict CSV validation is not supported for count filters");
|
|
94
|
-
|
|
95
|
-
return await countFileChunks(input, parser, options);
|
|
109
|
+
return await countFileChunks(input, toParserOptions(options, input.parserEncoding, input.delimiter), filters);
|
|
96
110
|
}
|
|
97
111
|
function findCsvSafeSplitOffsets(path, shardCount, suppliedOptions = {}) {
|
|
98
112
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
@@ -105,11 +119,14 @@ function findCsvSafeShards(path, shardCount, suppliedOptions = {}) {
|
|
|
105
119
|
function shardingDelimiter(options, operation) {
|
|
106
120
|
rejectCompressedSharding(options, operation);
|
|
107
121
|
rejectAutoDelimiterSharding(options, operation);
|
|
122
|
+
if ("quote" in options && options.quote === !1 || "recordDelimiter" in options && options.recordDelimiter !== void 0)
|
|
123
|
+
throw Error(`${operation} requires the default quote and record delimiter settings`);
|
|
108
124
|
if (typeof resolveInputEncoding(options.encoding) !== "string")
|
|
109
125
|
throw Error(`${operation} requires a native UTF-8 or Latin-1 encoding because offsets refer to the source file`);
|
|
110
126
|
return options.delimiter ?? ",";
|
|
111
127
|
}
|
|
112
128
|
export const csv = {
|
|
129
|
+
transform,
|
|
113
130
|
all,
|
|
114
131
|
any,
|
|
115
132
|
column,
|
|
@@ -126,6 +143,8 @@ function toParserOptions(options, encoding, delimiter = options.delimiter) {
|
|
|
126
143
|
return {
|
|
127
144
|
delimiter,
|
|
128
145
|
encoding,
|
|
146
|
+
quote: options.quote,
|
|
147
|
+
recordDelimiter: options.recordDelimiter,
|
|
129
148
|
strict: options.strict,
|
|
130
149
|
columns: options.columns,
|
|
131
150
|
fixedColumns: options.fixedColumns,
|
|
@@ -136,7 +155,8 @@ function toParserOptions(options, encoding, delimiter = options.delimiter) {
|
|
|
136
155
|
minDataRows: options.minDataRows
|
|
137
156
|
};
|
|
138
157
|
}
|
|
139
|
-
function
|
|
158
|
+
function consumeBatchRows(nativeBatch, columns, projected, target = []) {
|
|
159
|
+
using batch = nativeBatch;
|
|
140
160
|
return batch.rowsInto(target, projected ? void 0 : columns);
|
|
141
161
|
}
|
|
142
162
|
function rejectFilteredStrictSchema(options) {
|
package/dist/batches.d.ts
CHANGED
|
@@ -286,4 +286,25 @@ export declare class NativeCsvBatch {
|
|
|
286
286
|
/** Implements `using` / explicit resource management. */
|
|
287
287
|
[Symbol.dispose](): void;
|
|
288
288
|
}
|
|
289
|
+
/**
|
|
290
|
+
* Owns a batch of original decompressed records. Consume or copy borrowed bytes
|
|
291
|
+
* before closing the batch. Each batch can be disposed independently of its iterator.
|
|
292
|
+
*/
|
|
293
|
+
export declare class NativeCsvRawRecordBatch {
|
|
294
|
+
#private;
|
|
295
|
+
/** @internal */
|
|
296
|
+
constructor(handle: NativePointer);
|
|
297
|
+
/** Whether the native storage has been released. */
|
|
298
|
+
get closed(): boolean;
|
|
299
|
+
/** Number of accepted records in this batch. */
|
|
300
|
+
get rowCount(): number;
|
|
301
|
+
/** Returns the original decompressed bytes for a zero-based row, including its LF when present. */
|
|
302
|
+
rowBytes(rowIndex: number): Uint8Array;
|
|
303
|
+
/** Returns the physical field count for a zero-based row, including empty fields. */
|
|
304
|
+
rowFieldCount(rowIndex: number): number;
|
|
305
|
+
/** Releases the native storage and invalidates borrowed bytes. Safe to call more than once. */
|
|
306
|
+
close(): void;
|
|
307
|
+
/** Releases the native storage at the end of a `using` scope. */
|
|
308
|
+
[Symbol.dispose](): void;
|
|
309
|
+
}
|
|
289
310
|
export {};
|
package/dist/batches.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { read } from "bun:ffi";
|
|
2
|
-
import {
|
|
2
|
+
import { isUtf8 } from "node:buffer";
|
|
3
|
+
import {
|
|
4
|
+
decodeMaterializedField,
|
|
5
|
+
prepareRow
|
|
6
|
+
} from "./materialize-field.js";
|
|
3
7
|
import {
|
|
4
8
|
EMPTY_BUFFER,
|
|
5
9
|
native,
|
|
@@ -12,6 +16,8 @@ import {
|
|
|
12
16
|
normalizeFilterColumn
|
|
13
17
|
} from "./normalize.js";
|
|
14
18
|
const visitBatchRows = Symbol("visitBatchRows");
|
|
19
|
+
const WINDOW_BYTES = 1024;
|
|
20
|
+
const MAX_WINDOW_FIELD_BYTES = 64;
|
|
15
21
|
|
|
16
22
|
export class NativeCsvRowView {
|
|
17
23
|
#data;
|
|
@@ -145,14 +151,13 @@ export class NativeCsvBatch {
|
|
|
145
151
|
const rowOffsetWords = this.#rowOffsetWordsView();
|
|
146
152
|
const fieldOffsetWords = this.#fieldOffsetWordsView();
|
|
147
153
|
const data = this.data();
|
|
154
|
+
const dataLength = data.byteLength;
|
|
148
155
|
target.length = rowCount;
|
|
149
156
|
if (columns !== void 0) {
|
|
150
157
|
for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
|
|
151
|
-
const fieldStart = offsetAt(rowOffsetWords, rowIndex,
|
|
152
|
-
const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1,
|
|
153
|
-
const
|
|
154
|
-
const row = existing === void 0 ? [] : existing;
|
|
155
|
-
row.length = selectedColumns.length;
|
|
158
|
+
const fieldStart = offsetAt(rowOffsetWords, rowIndex, rowIndex, totalFields);
|
|
159
|
+
const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, rowIndex, totalFields);
|
|
160
|
+
const row = prepareRow(target[rowIndex], selectedColumns.length);
|
|
156
161
|
for (let outputIndex = 0;outputIndex < selectedColumns.length; ++outputIndex) {
|
|
157
162
|
const column = selectedColumns[outputIndex] ?? 0;
|
|
158
163
|
const fieldIndex = fieldStart + column;
|
|
@@ -160,27 +165,63 @@ export class NativeCsvBatch {
|
|
|
160
165
|
row[outputIndex] = "";
|
|
161
166
|
continue;
|
|
162
167
|
}
|
|
163
|
-
const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset",
|
|
164
|
-
const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset",
|
|
168
|
+
const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", dataLength);
|
|
169
|
+
const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", dataLength);
|
|
165
170
|
row[outputIndex] = decodeMaterializedField(data, start, end, "utf8");
|
|
166
171
|
}
|
|
167
172
|
target[rowIndex] = row;
|
|
168
173
|
}
|
|
169
174
|
return target;
|
|
170
175
|
}
|
|
176
|
+
let windowStart = 0;
|
|
177
|
+
let windowEnd = 0;
|
|
178
|
+
let text = "";
|
|
179
|
+
let byteIndexed = !0;
|
|
180
|
+
let utf16Offsets;
|
|
181
|
+
const flags = native.symbols.csv_batch_quoted_rows_ptr(this.#requireHandle());
|
|
182
|
+
const quotedRows = flags === null ? void 0 : new Uint8Array(toArrayBuffer(flags, 0, rowCount));
|
|
183
|
+
let fieldStart = offsetAt(rowOffsetWords, 0, 0, totalFields);
|
|
184
|
+
let start = offsetAt(fieldOffsetWords, fieldStart, "field offset", dataLength);
|
|
171
185
|
for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
|
|
172
|
-
const
|
|
173
|
-
const
|
|
174
|
-
const
|
|
175
|
-
const
|
|
176
|
-
row.length = fieldEnd - fieldStart;
|
|
186
|
+
const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, rowIndex, totalFields);
|
|
187
|
+
const row = prepareRow(target[rowIndex], fieldEnd - fieldStart);
|
|
188
|
+
const leading = quotedRows?.[rowIndex] ?? 0;
|
|
189
|
+
const trailing = leading * 2;
|
|
177
190
|
for (let fieldIndex = fieldStart;fieldIndex < fieldEnd; ++fieldIndex) {
|
|
178
|
-
const
|
|
179
|
-
const end =
|
|
191
|
+
const rawEnd = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", dataLength);
|
|
192
|
+
const end = rawEnd - trailing;
|
|
193
|
+
start += leading;
|
|
180
194
|
const column = fieldIndex - fieldStart;
|
|
181
|
-
|
|
195
|
+
const length = end - start;
|
|
196
|
+
let value;
|
|
197
|
+
if (length > 2 && length <= MAX_WINDOW_FIELD_BYTES) {
|
|
198
|
+
if (start < windowStart || end > windowEnd) {
|
|
199
|
+
windowStart = start;
|
|
200
|
+
windowEnd = utf8WindowEnd(data, start);
|
|
201
|
+
text = decodeMaterializedField(data, start, windowEnd, "utf8");
|
|
202
|
+
byteIndexed = text.length === windowEnd - start;
|
|
203
|
+
if (!byteIndexed) {
|
|
204
|
+
utf16Offsets ??= new Int16Array(WINDOW_BYTES + 1);
|
|
205
|
+
if (!indexUtf16Boundaries(data.subarray(start, windowEnd), utf16Offsets))
|
|
206
|
+
text = "";
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const from = start - windowStart;
|
|
210
|
+
const to = end - windowStart;
|
|
211
|
+
if (byteIndexed)
|
|
212
|
+
value = text.slice(from, to);
|
|
213
|
+
else if (text.length > 0 && utf16Offsets !== void 0) {
|
|
214
|
+
const first = utf16Offsets[from] ?? -1;
|
|
215
|
+
const last = utf16Offsets[to] ?? -1;
|
|
216
|
+
if (first >= 0 && last >= 0)
|
|
217
|
+
value = text.slice(first, last);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
row[column] = value ?? decodeMaterializedField(data, start, end, "utf8");
|
|
221
|
+
start = rawEnd;
|
|
182
222
|
}
|
|
183
223
|
target[rowIndex] = row;
|
|
224
|
+
fieldStart = fieldEnd;
|
|
184
225
|
}
|
|
185
226
|
return target;
|
|
186
227
|
}
|
|
@@ -378,6 +419,68 @@ export class NativeCsvBatch {
|
|
|
378
419
|
throw RangeError(`row index out of range: ${endRow}`);
|
|
379
420
|
}
|
|
380
421
|
}
|
|
422
|
+
|
|
423
|
+
export class NativeCsvRawRecordBatch {
|
|
424
|
+
#handle;
|
|
425
|
+
#rowCount;
|
|
426
|
+
#data;
|
|
427
|
+
#byteOffsets;
|
|
428
|
+
#fieldCounts;
|
|
429
|
+
constructor(handle) {
|
|
430
|
+
this.#handle = handle;
|
|
431
|
+
}
|
|
432
|
+
get closed() {
|
|
433
|
+
return this.#handle === null;
|
|
434
|
+
}
|
|
435
|
+
get rowCount() {
|
|
436
|
+
this.#rowCount ??= u64ToSafeNumber(native.symbols.csv_batch_row_count(this.#requireHandle()), "CSV batch row count");
|
|
437
|
+
return this.#rowCount;
|
|
438
|
+
}
|
|
439
|
+
rowBytes(rowIndex) {
|
|
440
|
+
this.#validateRowIndex(rowIndex);
|
|
441
|
+
if (this.#data === void 0) {
|
|
442
|
+
const handle = this.#requireHandle();
|
|
443
|
+
this.#data = new Uint8Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_data_ptr(handle)), 0, u64ToSafeNumber(native.symbols.csv_batch_data_len(handle), "CSV batch data length")));
|
|
444
|
+
}
|
|
445
|
+
this.#byteOffsets ??= new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_field_offsets_ptr(this.#requireHandle())), 0, (this.rowCount + 1) * BigUint64Array.BYTES_PER_ELEMENT));
|
|
446
|
+
const data = this.#data;
|
|
447
|
+
const offsets = this.#byteOffsets;
|
|
448
|
+
const start = offsetAt(offsets, rowIndex, "raw row byte offset", data.length);
|
|
449
|
+
const end = offsetAt(offsets, rowIndex + 1, "raw row byte offset", data.length);
|
|
450
|
+
return data.subarray(start, end);
|
|
451
|
+
}
|
|
452
|
+
rowFieldCount(rowIndex) {
|
|
453
|
+
this.#validateRowIndex(rowIndex);
|
|
454
|
+
this.#fieldCounts ??= new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_row_offsets_ptr(this.#requireHandle())), 0, (this.rowCount + 1) * BigUint64Array.BYTES_PER_ELEMENT));
|
|
455
|
+
const offsets = this.#fieldCounts;
|
|
456
|
+
const start = offsetAt(offsets, rowIndex, "raw row field offset", Number.MAX_SAFE_INTEGER);
|
|
457
|
+
const end = offsetAt(offsets, rowIndex + 1, "raw row field offset", Number.MAX_SAFE_INTEGER);
|
|
458
|
+
return end - start;
|
|
459
|
+
}
|
|
460
|
+
close() {
|
|
461
|
+
if (this.#handle !== null) {
|
|
462
|
+
native.symbols.csv_batch_destroy(this.#handle);
|
|
463
|
+
this.#handle = null;
|
|
464
|
+
this.#rowCount = void 0;
|
|
465
|
+
this.#data = void 0;
|
|
466
|
+
this.#byteOffsets = void 0;
|
|
467
|
+
this.#fieldCounts = void 0;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
[Symbol.dispose]() {
|
|
471
|
+
this.close();
|
|
472
|
+
}
|
|
473
|
+
#validateRowIndex(rowIndex) {
|
|
474
|
+
const count = this.rowCount;
|
|
475
|
+
if (!Number.isInteger(rowIndex) || rowIndex < 0 || rowIndex >= count)
|
|
476
|
+
throw RangeError(`row index out of range: ${rowIndex}`);
|
|
477
|
+
}
|
|
478
|
+
#requireHandle() {
|
|
479
|
+
if (this.#handle === null)
|
|
480
|
+
throw Error("native CSV raw-record batch is closed");
|
|
481
|
+
return this.#handle;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
381
484
|
const UINT32_BASE = 4294967296;
|
|
382
485
|
const UINT32_BASE_BIGINT = 0x100000000n;
|
|
383
486
|
const MAX_SAFE_OFFSET_HIGH_WORD = 2097151;
|
|
@@ -385,18 +488,49 @@ const MAX_DIRECT_ROW_INDEX_EXCLUSIVE = Math.floor(2147483647 / BigUint64Array.BY
|
|
|
385
488
|
function offsetWords(offsets) {
|
|
386
489
|
return new Uint32Array(offsets.buffer, offsets.byteOffset, offsets.length * 2);
|
|
387
490
|
}
|
|
491
|
+
function utf8WindowEnd(data, start) {
|
|
492
|
+
const limit = start + WINDOW_BYTES;
|
|
493
|
+
if (limit >= data.length)
|
|
494
|
+
return data.length;
|
|
495
|
+
let end = limit;
|
|
496
|
+
while (limit - end < 3 && (data[end] & 192) === 128)
|
|
497
|
+
--end;
|
|
498
|
+
return end;
|
|
499
|
+
}
|
|
500
|
+
function indexUtf16Boundaries(bytes, offsets) {
|
|
501
|
+
if (!isUtf8(bytes))
|
|
502
|
+
return !1;
|
|
503
|
+
let units = 0;
|
|
504
|
+
for (let i = 0;i < bytes.length; ++i) {
|
|
505
|
+
const byte = bytes[i];
|
|
506
|
+
if ((byte & 192) === 128)
|
|
507
|
+
offsets[i] = -1;
|
|
508
|
+
else {
|
|
509
|
+
offsets[i] = units;
|
|
510
|
+
units += byte >= 240 ? 2 : 1;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
offsets[bytes.length] = units;
|
|
514
|
+
return !0;
|
|
515
|
+
}
|
|
388
516
|
function offsetAt(offsets, index, label, upperBound) {
|
|
389
517
|
const wordIndex = index * 2;
|
|
390
518
|
const low = offsets[wordIndex];
|
|
391
519
|
const high = offsets[wordIndex + 1];
|
|
392
|
-
if (
|
|
393
|
-
|
|
520
|
+
if (high === 0 && low !== void 0 && low <= upperBound && Number.isInteger(index))
|
|
521
|
+
return low;
|
|
522
|
+
return checkedWideOffset(low, high, index, label, upperBound);
|
|
523
|
+
}
|
|
524
|
+
function checkedWideOffset(low, high, index, label, upperBound) {
|
|
525
|
+
const description = typeof label === "number" ? `row ${label} offset` : label;
|
|
526
|
+
if (low === void 0 || high === void 0 || !Number.isInteger(index))
|
|
527
|
+
throw RangeError(`${description} index out of range: ${index}`);
|
|
394
528
|
if (high > MAX_SAFE_OFFSET_HIGH_WORD) {
|
|
395
529
|
const value = BigInt(high) * UINT32_BASE_BIGINT + BigInt(low);
|
|
396
|
-
throw RangeError(`${
|
|
530
|
+
throw RangeError(`${description} exceeds Number.MAX_SAFE_INTEGER: ${value}`);
|
|
397
531
|
}
|
|
398
532
|
const offset = low + high * UINT32_BASE;
|
|
399
533
|
if (offset > upperBound)
|
|
400
|
-
throw RangeError(`${
|
|
534
|
+
throw RangeError(`${description} exceeds backing storage: ${offset}`);
|
|
401
535
|
return offset;
|
|
402
536
|
}
|