@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.
- package/README.md +108 -102
- package/THIRD_PARTY_NOTICES.md +27 -0
- package/dist/api.d.ts +78 -55
- package/dist/api.js +191 -40
- package/dist/batch-pipeline.d.ts +10 -0
- package/dist/batch-pipeline.js +83 -0
- package/dist/batches.d.ts +16 -2
- package/dist/batches.js +179 -5
- package/dist/cli-command.d.ts +7 -7
- package/dist/cli-command.js +325 -164
- package/dist/cli-schema.d.ts +51 -21
- package/dist/cli-schema.js +126 -65
- package/dist/cli.js +1 -1
- package/dist/file-stream.d.ts +62 -15
- package/dist/file-stream.js +494 -205
- package/dist/files.d.ts +17 -37
- package/dist/files.js +48 -21
- package/dist/gzip-reader.js +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/inspect-file.d.ts +26 -3
- package/dist/inspect-file.js +169 -74
- package/dist/inspect-zip.d.ts +26 -0
- package/dist/inspect-zip.js +59 -0
- package/dist/latin1-rows.d.ts +11 -3
- package/dist/latin1-rows.js +276 -75
- package/dist/materialize-field.d.ts +6 -0
- package/dist/materialize-field.js +9 -0
- package/dist/native.d.ts +89 -19
- package/dist/native.js +45 -23
- package/dist/normalize.d.ts +5 -0
- package/dist/normalize.js +42 -9
- package/dist/options.d.ts +27 -12
- package/dist/parser.d.ts +30 -13
- package/dist/parser.js +264 -102
- package/dist/strict-schema.d.ts +7 -8
- package/dist/strict-schema.js +45 -83
- package/dist/transforms.d.ts +1 -3
- package/dist/transforms.js +17 -16
- package/dist/types.d.ts +175 -77
- package/dist/zip-entry.d.ts +14 -0
- package/dist/zip-entry.js +155 -0
- package/dist/zip-reader.d.ts +14 -3
- package/dist/zip-reader.js +65 -23
- package/package.json +34 -23
- 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 +15 -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/dist/parser.d.ts
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
1
1
|
import { NativeCsvBatch, NativeCsvRawRecordBatch } from './batches.js';
|
|
2
|
-
import type
|
|
2
|
+
import { type CsvFileInput } from './file-stream.js';
|
|
3
3
|
import { type NativePointer } from './native.js';
|
|
4
4
|
import type { CsvColumns, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, CsvTransform, NativeCsvParserOptions } from './types.js';
|
|
5
5
|
export declare const nativeCsvParserFinalizer: FinalizationRegistry<NativePointer>;
|
|
6
|
+
/** Read the header with the same dialect and limits used for data records. */
|
|
7
|
+
export declare function readCsvHeader(nextChunk: () => Promise<IteratorResult<Uint8Array, void>>, options: CsvParserOptions): Promise<{
|
|
8
|
+
readonly value: {
|
|
9
|
+
readonly names: CsvRow;
|
|
10
|
+
readonly record: number;
|
|
11
|
+
};
|
|
12
|
+
readonly replay: Generator<Uint8Array, void>;
|
|
13
|
+
}>;
|
|
14
|
+
type OpenParseAhead<TBatch> = (chunks: AsyncIterator<Uint8Array, void>, first: Uint8Array, limit: number | undefined) => AsyncGenerator<TBatch, void> | undefined;
|
|
6
15
|
export declare function parseFileChunks<TBatch extends NativeCsvBatch | NativeCsvRawRecordBatch>(input: CsvFileInput, parser: {
|
|
7
16
|
writeBatch(chunk: Uint8Array, final?: boolean): TBatch;
|
|
8
|
-
}, limit: number | undefined): AsyncGenerator<TBatch, void>;
|
|
17
|
+
}, limit: number | undefined, openParseAhead?: OpenParseAhead<TBatch>): AsyncGenerator<TBatch, void>;
|
|
18
|
+
export declare function parseUtf8RowBatches(input: CsvFileInput, parser: NativeCsvParser, limit: number | undefined): AsyncGenerator<NativeCsvBatch, void>;
|
|
9
19
|
export declare function parseRawRecordChunks(input: CsvFileInput, options: CsvParserOptions, program: readonly CsvNativeFilterProgramEntry[] | undefined): AsyncGenerator<NativeCsvRawRecordBatch, void>;
|
|
10
20
|
export declare function countFileChunks(input: CsvFileInput, options: CsvParserOptions, filters?: readonly CsvNativeFilterProgramEntry[]): Promise<number>;
|
|
11
|
-
export declare function createPreparedParser(options: CsvParserOptions, columns?: CsvColumns, program?: readonly CsvNativeFilterProgramEntry[], transform?: readonly CsvTransform[], output?: 'batches' | 'rows'): NativeCsvParser;
|
|
21
|
+
export declare function createPreparedParser(options: CsvParserOptions, columns?: CsvColumns, program?: readonly CsvNativeFilterProgramEntry[], transform?: readonly CsvTransform[], output?: 'batches' | 'rows' | 'pipelined-rows'): NativeCsvParser;
|
|
12
22
|
interface PreparedNativeWriter {
|
|
13
23
|
writeBatch(input: NodeJS.TypedArray | DataView, final: boolean): NativePointer | null;
|
|
14
24
|
writeCount(input: NodeJS.TypedArray | DataView, final: boolean): bigint | number;
|
|
@@ -28,9 +38,12 @@ interface PreparedNativeWriter {
|
|
|
28
38
|
* @throws {Error} If the native library rejects the configuration.
|
|
29
39
|
*/
|
|
30
40
|
export declare function prepareNativeParser(handle: NativePointer, columns: CsvColumns | undefined, program: readonly CsvNativeFilterProgramEntry[] | undefined): PreparedNativeWriter;
|
|
31
|
-
export declare function validateRowSelection({ skipRows, limit }: Pick<CsvParserOptions, 'skipRows' | 'limit'>): void;
|
|
32
|
-
export declare function setRowSelection(handle: NativePointer, options: CsvParserOptions
|
|
41
|
+
export declare function validateRowSelection({ skipRows, skipEmptyLines, limit }: Pick<CsvParserOptions, 'skipRows' | 'skipEmptyLines' | 'limit'>): void;
|
|
42
|
+
export declare function setRowSelection(handle: NativePointer, options: CsvParserOptions): void;
|
|
43
|
+
export declare function prepareNativeValidation({ strict, expectedHeaders, maxRecordBytes }: Pick<CsvParserOptions, 'strict' | 'expectedHeaders' | 'maxRecordBytes'>): ((handle: NativePointer) => void) | undefined;
|
|
33
44
|
declare const createSchemaParser: unique symbol;
|
|
45
|
+
declare const physicalRows: unique symbol;
|
|
46
|
+
declare const openPipeline: unique symbol;
|
|
34
47
|
/**
|
|
35
48
|
* Incrementally parses caller-owned CSV chunks through the native parser.
|
|
36
49
|
*
|
|
@@ -39,6 +52,8 @@ declare const createSchemaParser: unique symbol;
|
|
|
39
52
|
* for the next write. Every returned batch owns native memory and must be
|
|
40
53
|
* closed or disposed. `write()` and `end()` are convenience methods that
|
|
41
54
|
* materialize rows and close their temporary batches automatically.
|
|
55
|
+
* With automatic delimiter detection, writes emit no rows until the input
|
|
56
|
+
* exceeds 64 KiB or ends. Supply a delimiter to parse each chunk as it arrives.
|
|
42
57
|
*
|
|
43
58
|
* The constructor captures the projection and filters for the lifetime of the parser.
|
|
44
59
|
* Filters use physical column indexes. Batches emit fields in projection order.
|
|
@@ -54,18 +69,17 @@ declare const createSchemaParser: unique symbol;
|
|
|
54
69
|
*/
|
|
55
70
|
export declare class NativeCsvParser {
|
|
56
71
|
#private;
|
|
57
|
-
static [createSchemaParser](options: NativeCsvParserOptions, output: 'batches' | 'rows'): NativeCsvParser;
|
|
72
|
+
static [createSchemaParser](options: NativeCsvParserOptions, output: 'batches' | 'rows' | 'pipelined-rows'): NativeCsvParser;
|
|
58
73
|
/**
|
|
59
74
|
* Creates an open parser.
|
|
60
75
|
*
|
|
61
76
|
* @param options Parser settings, output columns and predicates. The delimiter defaults
|
|
62
|
-
* to
|
|
63
|
-
* APIs handle schema metadata such as `expectedHeaders`.
|
|
77
|
+
* to automatic detection. Strict validation checks physical records before projection and filtering.
|
|
64
78
|
* @throws {Error} If the delimiter is not one character or native parser
|
|
65
79
|
* creation fails.
|
|
66
80
|
* @throws {RangeError} If selected or fixed column settings are out of range.
|
|
67
81
|
*/
|
|
68
|
-
constructor(
|
|
82
|
+
constructor(supplied?: NativeCsvParserOptions);
|
|
69
83
|
/** Whether the native parser handle has been released. */
|
|
70
84
|
get closed(): boolean;
|
|
71
85
|
/**
|
|
@@ -88,6 +102,8 @@ export declare class NativeCsvParser {
|
|
|
88
102
|
* Call `batch.close()` or use `using` for the returned batch. The parser may
|
|
89
103
|
* retain an incomplete row between calls. `final: true` marks the input end
|
|
90
104
|
* and flushes that row.
|
|
105
|
+
* Switch between count and materialized writes at record boundaries after any
|
|
106
|
+
* delimiter probe bytes have been parsed.
|
|
91
107
|
*
|
|
92
108
|
* @param chunk Input bytes.
|
|
93
109
|
* @param final Whether this is the final input chunk.
|
|
@@ -95,6 +111,7 @@ export declare class NativeCsvParser {
|
|
|
95
111
|
* @throws {Error} If the parser is closed or native parsing fails.
|
|
96
112
|
*/
|
|
97
113
|
writeBatch(chunk: NodeJS.TypedArray | DataView, final?: boolean): NativeCsvBatch;
|
|
114
|
+
[openPipeline](chunks: AsyncIterator<Uint8Array, void>, first: Uint8Array, limit: number | undefined): AsyncGenerator<NativeCsvBatch, void> | undefined;
|
|
98
115
|
/**
|
|
99
116
|
* Flushes the parser and materializes its final rows.
|
|
100
117
|
*
|
|
@@ -121,22 +138,21 @@ export declare class NativeCsvParser {
|
|
|
121
138
|
* @param chunk Input bytes.
|
|
122
139
|
* @param final Whether this is the final input chunk.
|
|
123
140
|
* @returns The number of rows emitted by this call.
|
|
124
|
-
* @throws {Error}
|
|
125
|
-
* or if the parser is closed/native parsing fails.
|
|
141
|
+
* @throws {Error} If the parser is closed or a consumed record fails validation.
|
|
126
142
|
*/
|
|
127
143
|
writeCount(chunk: NodeJS.TypedArray | DataView, final?: boolean): number;
|
|
128
144
|
/**
|
|
129
145
|
* Flushes buffered state and returns the number of matching final records.
|
|
130
146
|
*
|
|
131
147
|
* @returns The number of rows emitted while finishing the stream.
|
|
132
|
-
* @throws {Error} If
|
|
133
|
-
* parsing fails.
|
|
148
|
+
* @throws {Error} If the parser is closed or the final record fails validation.
|
|
134
149
|
*/
|
|
135
150
|
endCount(): number;
|
|
136
151
|
/**
|
|
137
152
|
* Discards buffered row state and parser errors while keeping this parser open.
|
|
138
153
|
*
|
|
139
154
|
* Row skipping and limiting restart with the constructor's values. Projection and filters stay active.
|
|
155
|
+
* Automatic delimiter detection runs again on the next input.
|
|
140
156
|
*
|
|
141
157
|
* @throws {Error} If the parser is already closed.
|
|
142
158
|
*/
|
|
@@ -151,5 +167,6 @@ export declare class NativeCsvParser {
|
|
|
151
167
|
close(): void;
|
|
152
168
|
/** Implements `using` / explicit resource management. */
|
|
153
169
|
[Symbol.dispose](): void;
|
|
170
|
+
[physicalRows](): number;
|
|
154
171
|
}
|
|
155
172
|
export {};
|
package/dist/parser.js
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
|
+
import { BatchPipeline } from "./batch-pipeline.js";
|
|
1
2
|
import {
|
|
2
3
|
NativeCsvBatch,
|
|
3
4
|
NativeCsvRawRecordBatch
|
|
4
5
|
} from "./batches.js";
|
|
6
|
+
import {
|
|
7
|
+
detectBufferDelimiter,
|
|
8
|
+
FILE_PROBE_SIZE
|
|
9
|
+
} from "./file-stream.js";
|
|
5
10
|
import {
|
|
6
11
|
EMPTY_BUFFER,
|
|
7
12
|
native,
|
|
8
13
|
u64ToSafeNumber
|
|
9
14
|
} from "./native.js";
|
|
10
15
|
import {
|
|
16
|
+
delimiterByte,
|
|
11
17
|
encodingCode,
|
|
12
18
|
normalizeChunk,
|
|
13
19
|
normalizeColumns,
|
|
@@ -23,38 +29,109 @@ import {
|
|
|
23
29
|
} from "./strict-schema.js";
|
|
24
30
|
import {
|
|
25
31
|
prepareTransforms,
|
|
26
|
-
selectTransforms,
|
|
27
32
|
snapshotTransforms
|
|
28
33
|
} from "./transforms.js";
|
|
29
34
|
function destroyNativeCsvParser(handle) {
|
|
30
35
|
native.symbols.csv_parser_destroy(handle);
|
|
31
36
|
}
|
|
32
37
|
export const nativeCsvParserFinalizer = new FinalizationRegistry(destroyNativeCsvParser);
|
|
33
|
-
export async function
|
|
38
|
+
export async function readCsvHeader(nextChunk, options) {
|
|
39
|
+
using parser = createPreparedParser({
|
|
40
|
+
...options,
|
|
41
|
+
columns: void 0,
|
|
42
|
+
skipRows: void 0,
|
|
43
|
+
limit: 1,
|
|
44
|
+
minDataRows: void 0
|
|
45
|
+
});
|
|
46
|
+
const pending = [];
|
|
47
|
+
let blankRecords = 0;
|
|
48
|
+
let endsWithCr = !1;
|
|
49
|
+
let names;
|
|
50
|
+
while (names === void 0) {
|
|
51
|
+
const next = await nextChunk();
|
|
52
|
+
if (next.done === !0) {
|
|
53
|
+
[names] = parser.end();
|
|
54
|
+
if (names === void 0)
|
|
55
|
+
throw Error("CSV input is missing a header record");
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
const chunk = next.value;
|
|
59
|
+
if (chunk.length === 0)
|
|
60
|
+
continue;
|
|
61
|
+
[names] = parser.write(chunk);
|
|
62
|
+
if (names !== void 0) {
|
|
63
|
+
pending.push(chunk);
|
|
64
|
+
break;
|
|
65
|
+
}
|
|
66
|
+
if (pending.length === 0 && options.skipEmptyLines === !0 && chunk.every((byte) => byte === 10 || options.recordDelimiter === void 0 && byte === 13)) {
|
|
67
|
+
blankRecords = parser[physicalRows]();
|
|
68
|
+
endsWithCr = chunk.at(-1) === 13;
|
|
69
|
+
} else
|
|
70
|
+
pending.push(new Uint8Array(chunk));
|
|
71
|
+
}
|
|
72
|
+
function* prefix() {
|
|
73
|
+
let lines = blankRecords - Number(endsWithCr);
|
|
74
|
+
if (lines > 0) {
|
|
75
|
+
const buffer = new Uint8Array(Math.min(65536, lines)).fill(10);
|
|
76
|
+
while (lines > 0) {
|
|
77
|
+
const length = Math.min(lines, buffer.length);
|
|
78
|
+
yield buffer.subarray(0, length);
|
|
79
|
+
lines -= length;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (endsWithCr)
|
|
83
|
+
yield Uint8Array.of(13);
|
|
84
|
+
yield* pending;
|
|
85
|
+
pending.length = 0;
|
|
86
|
+
}
|
|
87
|
+
return { value: { names, record: parser[physicalRows]() }, replay: prefix() };
|
|
88
|
+
}
|
|
89
|
+
export async function* parseFileChunks(input, parser, limit, openParseAhead) {
|
|
34
90
|
let remaining = limit;
|
|
35
|
-
if (remaining !== 0)
|
|
36
|
-
|
|
91
|
+
if (remaining !== 0) {
|
|
92
|
+
const cursor = input.chunks()[Symbol.asyncIterator]();
|
|
93
|
+
for await (const chunk of { [Symbol.asyncIterator]: () => cursor }) {
|
|
94
|
+
if (openParseAhead !== void 0 && input.canParseAhead) {
|
|
95
|
+
const ahead = openParseAhead(cursor, chunk, remaining);
|
|
96
|
+
openParseAhead = void 0;
|
|
97
|
+
if (ahead !== void 0) {
|
|
98
|
+
yield* ahead;
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
37
102
|
const batch = parser.writeBatch(chunk);
|
|
38
103
|
const count = batch.rowCount;
|
|
104
|
+
if (remaining !== void 0) {
|
|
105
|
+
remaining -= count;
|
|
106
|
+
if (remaining === 0) {
|
|
107
|
+
try {
|
|
108
|
+
parser.writeBatch(EMPTY_BUFFER, !0).close();
|
|
109
|
+
} catch (error) {
|
|
110
|
+
batch.close();
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
yield batch;
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
39
117
|
if (count > 0)
|
|
40
118
|
yield batch;
|
|
41
119
|
else
|
|
42
120
|
batch.close();
|
|
43
|
-
if (remaining !== void 0) {
|
|
44
|
-
remaining -= count;
|
|
45
|
-
if (remaining === 0)
|
|
46
|
-
break;
|
|
47
|
-
}
|
|
48
121
|
}
|
|
122
|
+
}
|
|
49
123
|
const final = parser.writeBatch(EMPTY_BUFFER, !0);
|
|
50
124
|
if (final.rowCount > 0)
|
|
51
125
|
yield final;
|
|
52
126
|
else
|
|
53
127
|
final.close();
|
|
54
128
|
}
|
|
129
|
+
export function parseUtf8RowBatches(input, parser, limit) {
|
|
130
|
+
return parseFileChunks(input, parser, limit, (chunks, first, remaining) => parser[openPipeline](chunks, first, remaining));
|
|
131
|
+
}
|
|
55
132
|
export async function* parseRawRecordChunks(input, options, program) {
|
|
56
133
|
normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
|
|
57
|
-
const handle = createNativeCsvParser(options, !0);
|
|
134
|
+
const handle = createNativeCsvParser(options, input.delimiter, !0);
|
|
58
135
|
const parser = {
|
|
59
136
|
writeBatch(chunk, final = !1) {
|
|
60
137
|
const bytes = normalizeChunk(chunk);
|
|
@@ -77,11 +154,6 @@ export async function countFileChunks(input, options, filters) {
|
|
|
77
154
|
const columns = options.fixedColumns !== void 0 && options.strict !== !0 && filters === void 0 ? [] : void 0;
|
|
78
155
|
using parser = createPreparedParser(options, columns, filters);
|
|
79
156
|
let total = 0;
|
|
80
|
-
if (options.strict === !0) {
|
|
81
|
-
for await (using batch of parseFileChunks(input, parser, options.limit))
|
|
82
|
-
total += batch.rowCount;
|
|
83
|
-
return total;
|
|
84
|
-
}
|
|
85
157
|
if (options.limit !== 0)
|
|
86
158
|
for await (const chunk of input.chunks()) {
|
|
87
159
|
total += parser.writeCount(chunk);
|
|
@@ -99,110 +171,143 @@ export function createPreparedParser(options, columns, program, transform, outpu
|
|
|
99
171
|
quote: options.quote,
|
|
100
172
|
recordDelimiter: options.recordDelimiter,
|
|
101
173
|
fixedColumns: options.fixedColumns,
|
|
174
|
+
maxRecordBytes: options.maxRecordBytes,
|
|
102
175
|
strict: options.strict,
|
|
103
176
|
skipRows: options.skipRows,
|
|
177
|
+
skipEmptyLines: options.skipEmptyLines,
|
|
104
178
|
limit: options.limit,
|
|
105
179
|
expectedHeaders: options.expectedHeaders,
|
|
106
180
|
requireHeader: options.requireHeader,
|
|
107
181
|
minDataRows: options.minDataRows,
|
|
108
182
|
columns,
|
|
109
183
|
filterProgram: program,
|
|
110
|
-
transform
|
|
184
|
+
transform
|
|
111
185
|
}, output);
|
|
112
186
|
}
|
|
113
187
|
export function prepareNativeParser(handle, columns, program) {
|
|
188
|
+
return configureNativeWriter(columns, program)(handle);
|
|
189
|
+
}
|
|
190
|
+
function configureNativeWriter(columns, program) {
|
|
114
191
|
const normalizedColumns = normalizeColumns(columns);
|
|
115
192
|
const hasProjection = columns !== void 0;
|
|
116
193
|
const columnCount = BigInt(normalizedColumns.length);
|
|
117
194
|
const normalized = program === void 0 ? normalizeNativeFilters(void 0) : normalizeNativeFilterProgram(program);
|
|
118
195
|
const filterCount = BigInt(normalized.filterCount);
|
|
119
196
|
const valueCount = BigInt(normalized.valueCount);
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
197
|
+
return (handle) => {
|
|
198
|
+
if (!native.symbols.csv_parser_prepare(handle, hasProjection, normalizedColumns, columnCount, normalized.descriptors, filterCount, normalized.valuesData, normalized.valuesData, normalized.valueOffsets, valueCount))
|
|
199
|
+
throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(handle) ?? "native parser error unavailable"}`);
|
|
200
|
+
return {
|
|
201
|
+
writeBatch: (input, final) => native.symbols.csv_parser_write_prepared_batch(handle, input, input, final),
|
|
202
|
+
writeCount: (input, final) => {
|
|
203
|
+
const count = native.symbols.csv_parser_write_prepared_count(handle, input, input, final);
|
|
204
|
+
if (count === 0xffffffffffffffffn)
|
|
205
|
+
throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(handle) ?? "native parser error unavailable"}`);
|
|
206
|
+
return count;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
130
209
|
};
|
|
131
210
|
}
|
|
132
|
-
export function validateRowSelection({ skipRows, limit }) {
|
|
211
|
+
export function validateRowSelection({ skipRows, skipEmptyLines, limit }) {
|
|
133
212
|
if (skipRows !== void 0 && (!Number.isSafeInteger(skipRows) || skipRows < 0))
|
|
134
213
|
throw RangeError("skipRows must be a non-negative safe integer");
|
|
214
|
+
if (skipEmptyLines !== void 0 && typeof skipEmptyLines !== "boolean")
|
|
215
|
+
throw TypeError("skipEmptyLines must be a boolean");
|
|
135
216
|
if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0))
|
|
136
217
|
throw RangeError("limit must be a non-negative safe integer");
|
|
137
218
|
}
|
|
138
|
-
export function setRowSelection(handle, options
|
|
219
|
+
export function setRowSelection(handle, options) {
|
|
220
|
+
if (options.skipEmptyLines === !0)
|
|
221
|
+
native.symbols.csv_parser_set_skip_empty_lines(handle);
|
|
139
222
|
if (options.skipRows !== void 0 || options.limit !== void 0)
|
|
140
|
-
native.symbols.csv_parser_set_row_selection(handle, BigInt(options.skipRows ?? 0), options.limit === void 0 ? 0xffffffffffffffffn : BigInt(options.limit),
|
|
223
|
+
native.symbols.csv_parser_set_row_selection(handle, BigInt(options.skipRows ?? 0), options.limit === void 0 ? 0xffffffffffffffffn : BigInt(options.limit), !1);
|
|
141
224
|
}
|
|
142
|
-
function
|
|
143
|
-
|
|
144
|
-
|
|
225
|
+
export function prepareNativeValidation({ strict, expectedHeaders, maxRecordBytes }) {
|
|
226
|
+
if (maxRecordBytes !== void 0 && (!Number.isSafeInteger(maxRecordBytes) || maxRecordBytes <= 0))
|
|
227
|
+
throw RangeError("maxRecordBytes must be a positive safe integer");
|
|
228
|
+
if (strict !== !0 && maxRecordBytes === void 0)
|
|
229
|
+
return;
|
|
230
|
+
const captureHeader = strict === !0 && expectedHeaders !== void 0;
|
|
231
|
+
const limit = BigInt(maxRecordBytes ?? 0);
|
|
232
|
+
return (handle) => native.symbols.csv_parser_set_validation(handle, strict === !0, captureHeader, limit);
|
|
233
|
+
}
|
|
234
|
+
function createNativeCsvParser(options, delimiter, prepared) {
|
|
235
|
+
const { quote, recordDelimiter } = options;
|
|
236
|
+
validateRowSelection(options);
|
|
145
237
|
validateCsvDialect(options);
|
|
146
|
-
const delimiter = options.delimiter ?? ",";
|
|
147
|
-
if (delimiter === "auto")
|
|
148
|
-
throw Error("automatic delimiter detection is only supported by file APIs");
|
|
149
|
-
if (delimiter.length !== 1)
|
|
150
|
-
throw Error("delimiter must be one character");
|
|
151
238
|
const encoding = encodingCode(options.encoding);
|
|
152
|
-
const
|
|
153
|
-
|
|
239
|
+
const separator = delimiterByte(delimiter, encoding === 1 ? "latin1" : "utf8");
|
|
240
|
+
const applyValidation = prepareNativeValidation(options);
|
|
241
|
+
const handle = quote === !1 || recordDelimiter !== void 0 ? native.symbols.csv_parser_create_dialect(encoding, separator, options.fixedColumns ?? 0, quote ?? !0, recordDelimiter === `
|
|
242
|
+
`) : prepared ? native.symbols.csv_parser_create_prepared(encoding, separator, options.fixedColumns ?? 0) : native.symbols.csv_parser_create(encoding, separator);
|
|
154
243
|
if (handle === null)
|
|
155
244
|
throw Error("failed to create native CSV parser");
|
|
156
|
-
setRowSelection(handle,
|
|
245
|
+
setRowSelection(handle, options);
|
|
246
|
+
applyValidation?.(handle);
|
|
157
247
|
return handle;
|
|
158
248
|
}
|
|
159
249
|
const createSchemaParser = Symbol("createSchemaParser");
|
|
250
|
+
const physicalRows = Symbol("physicalRows");
|
|
251
|
+
const prepareForPipeline = Symbol("prepareForPipeline");
|
|
252
|
+
const openPipeline = Symbol("openPipeline");
|
|
160
253
|
|
|
161
254
|
export class NativeCsvParser {
|
|
162
255
|
#handle;
|
|
163
|
-
#
|
|
256
|
+
#writeMode;
|
|
257
|
+
#schemaFailure;
|
|
164
258
|
#fixedColumns;
|
|
165
259
|
#writer;
|
|
166
|
-
#
|
|
260
|
+
#detection;
|
|
167
261
|
#validator;
|
|
168
|
-
#captureSkippedHeader = !1;
|
|
169
262
|
static [createSchemaParser](options, output) {
|
|
170
|
-
const
|
|
171
|
-
const parser = new NativeCsvParser(
|
|
172
|
-
if (output
|
|
263
|
+
const settings = output === "pipelined-rows" ? { ...options, [prepareForPipeline]: !0 } : options;
|
|
264
|
+
const parser = new NativeCsvParser(settings);
|
|
265
|
+
if (output !== "batches" && !options.strict && options.transform?.length)
|
|
173
266
|
native.symbols.csv_parser_enable_transformed_quoted_spans(parser.#requireHandle());
|
|
174
|
-
parser.#validator = validator;
|
|
175
|
-
if (validator !== void 0 && (options.skipRows ?? 0) > 0) {
|
|
176
|
-
parser.#captureSkippedHeader = !0;
|
|
177
|
-
setRowSelection(parser.#requireHandle(), options, !0);
|
|
178
|
-
}
|
|
179
267
|
return parser;
|
|
180
268
|
}
|
|
181
|
-
constructor(
|
|
182
|
-
rejectSelectedColumns(
|
|
183
|
-
|
|
269
|
+
constructor(supplied = {}) {
|
|
270
|
+
rejectSelectedColumns(supplied);
|
|
271
|
+
const automatic = supplied.delimiter === void 0 || supplied.delimiter === "auto";
|
|
272
|
+
const options = automatic ? { ...supplied } : supplied;
|
|
273
|
+
const strict = options.strict === !0;
|
|
274
|
+
this.#validator = strictSchemaValidator(options);
|
|
184
275
|
this.#fixedColumns = normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
|
|
185
276
|
const { columns, filterProgram } = options;
|
|
186
277
|
if (filterProgram !== void 0 && (options.equalsFilter !== void 0 || options.filters !== void 0))
|
|
187
278
|
throw Error("filterProgram cannot be combined with equalsFilter or filters");
|
|
188
279
|
const program = filterProgram === void 0 ? projectionFilterProgram(options) : filterProgram;
|
|
189
|
-
if (this.#strict && (columns !== void 0 || program !== void 0))
|
|
190
|
-
throw Error("strict CSV validation is not supported for projected batches or filters");
|
|
191
280
|
const transforms = snapshotTransforms(options.transform);
|
|
192
281
|
const customDialect = options.quote === !1 || options.recordDelimiter !== void 0;
|
|
193
|
-
if (customDialect &&
|
|
282
|
+
if (customDialect && strict)
|
|
194
283
|
throw Error("strict CSV validation requires the default quote and record delimiter settings");
|
|
195
|
-
const prepared = customDialect || columns !== void 0 || program !== void 0 ||
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
284
|
+
const prepared = strict || options.maxRecordBytes !== void 0 || customDialect || columns !== void 0 || program !== void 0 || Boolean(transforms?.length) || prepareForPipeline in options;
|
|
285
|
+
const configure = prepared ? configureNativeWriter(columns, program) : void 0;
|
|
286
|
+
const transformColumns = automatic && columns !== void 0 ? [...columns] : columns;
|
|
287
|
+
const open = (delimiter) => {
|
|
288
|
+
const handle = createNativeCsvParser(options, delimiter, prepared);
|
|
289
|
+
try {
|
|
290
|
+
if (transforms?.length)
|
|
291
|
+
prepareTransforms(handle, transforms, transformColumns);
|
|
292
|
+
return { handle, writer: configure?.(handle) };
|
|
293
|
+
} catch (error) {
|
|
294
|
+
destroyNativeCsvParser(handle);
|
|
295
|
+
throw error;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
const delimiter = automatic ? "," : supplied.delimiter;
|
|
299
|
+
const { handle, writer } = open(delimiter);
|
|
300
|
+
if (automatic)
|
|
301
|
+
this.#detection = {
|
|
302
|
+
open,
|
|
303
|
+
dialect: options,
|
|
304
|
+
delimiter,
|
|
305
|
+
selected: !1,
|
|
306
|
+
prefix: void 0,
|
|
307
|
+
length: 0
|
|
308
|
+
};
|
|
205
309
|
this.#handle = handle;
|
|
310
|
+
this.#writer = writer;
|
|
206
311
|
nativeCsvParserFinalizer.register(this, handle, this);
|
|
207
312
|
}
|
|
208
313
|
get closed() {
|
|
@@ -217,19 +322,35 @@ export class NativeCsvParser {
|
|
|
217
322
|
}
|
|
218
323
|
}
|
|
219
324
|
writeBatch(chunk, final = !1) {
|
|
220
|
-
|
|
221
|
-
const input =
|
|
222
|
-
const batch = this.#
|
|
325
|
+
this.#requireWritableHandle("materialize");
|
|
326
|
+
const input = this.#detectDelimiter(chunk, final);
|
|
327
|
+
const batch = this.#writeBatch(this.#requireHandle(), input, final);
|
|
328
|
+
this.#writeMode = "materialize";
|
|
329
|
+
return batch;
|
|
330
|
+
}
|
|
331
|
+
#writeBatch(handle, input, final) {
|
|
332
|
+
const batch = this.#writer !== void 0 ? this.#writer.writeBatch(input, final) : this.#fixedColumns !== void 0 ? native.symbols.csv_parser_write_fixed_batch(handle, input, input, final, this.#fixedColumns) : native.symbols.csv_parser_write_batch(handle, input, input, final);
|
|
223
333
|
if (batch === null)
|
|
224
334
|
throw Error(`native CSV parser failed: ${this.#lastError()}`);
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
335
|
+
const result = new NativeCsvBatch(batch);
|
|
336
|
+
try {
|
|
337
|
+
this.#validateSchema(final);
|
|
338
|
+
return result;
|
|
339
|
+
} catch (error) {
|
|
340
|
+
result.close();
|
|
341
|
+
throw error;
|
|
231
342
|
}
|
|
232
|
-
|
|
343
|
+
}
|
|
344
|
+
[openPipeline](chunks, first, limit) {
|
|
345
|
+
const pipeline = BatchPipeline.start(this.#requireHandle(), this);
|
|
346
|
+
return pipeline === void 0 ? void 0 : this.#readPipeline(pipeline, chunks, first, limit);
|
|
347
|
+
}
|
|
348
|
+
async* #readPipeline(ahead, chunks, first, limit) {
|
|
349
|
+
using pipeline = ahead;
|
|
350
|
+
const validate = this.#validator === void 0 ? void 0 : (final) => this.#validateSchema(final);
|
|
351
|
+
const finishAtLimit = () => this.writeBatch(EMPTY_BUFFER, !0).close();
|
|
352
|
+
for await (const batch of pipeline.batches(chunks, first, limit, validate, finishAtLimit))
|
|
353
|
+
yield new NativeCsvBatch(batch);
|
|
233
354
|
}
|
|
234
355
|
end() {
|
|
235
356
|
const batch = this.endBatch();
|
|
@@ -243,27 +364,37 @@ export class NativeCsvParser {
|
|
|
243
364
|
return this.writeBatch(EMPTY_BUFFER, !0);
|
|
244
365
|
}
|
|
245
366
|
writeCount(chunk, final = !1) {
|
|
246
|
-
|
|
247
|
-
|
|
367
|
+
this.#requireWritableHandle("count");
|
|
368
|
+
const input = this.#detectDelimiter(chunk, final);
|
|
369
|
+
const handle = this.#requireHandle();
|
|
248
370
|
if (this.#writer === void 0 && this.#fixedColumns !== void 0) {
|
|
249
|
-
using batch = this
|
|
371
|
+
using batch = this.#writeBatch(handle, input, final);
|
|
372
|
+
this.#writeMode = "count";
|
|
250
373
|
return batch.rowCount;
|
|
251
374
|
}
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
|
|
375
|
+
const count = u64ToSafeNumber(this.#writer === void 0 ? native.symbols.csv_parser_write_count(handle, input, input, final) : this.#writer.writeCount(input, final), "CSV parsed row count");
|
|
376
|
+
this.#validateSchema(final);
|
|
377
|
+
this.#writeMode = "count";
|
|
378
|
+
return count;
|
|
255
379
|
}
|
|
256
380
|
endCount() {
|
|
257
381
|
return this.writeCount(EMPTY_BUFFER, !0);
|
|
258
382
|
}
|
|
259
383
|
reset() {
|
|
260
384
|
native.symbols.csv_parser_reset_stream(this.#requireHandle());
|
|
385
|
+
if (this.#detection !== void 0) {
|
|
386
|
+
this.#detection.selected = !1;
|
|
387
|
+
this.#detection.length = 0;
|
|
388
|
+
}
|
|
389
|
+
this.#writeMode = void 0;
|
|
390
|
+
this.#schemaFailure = void 0;
|
|
261
391
|
}
|
|
262
392
|
close() {
|
|
263
393
|
const handle = this.#handle;
|
|
264
394
|
if (handle === null)
|
|
265
395
|
return;
|
|
266
396
|
this.#handle = null;
|
|
397
|
+
this.#detection = void 0;
|
|
267
398
|
nativeCsvParserFinalizer.unregister(this);
|
|
268
399
|
destroyNativeCsvParser(handle);
|
|
269
400
|
}
|
|
@@ -275,30 +406,61 @@ export class NativeCsvParser {
|
|
|
275
406
|
throw Error("native CSV parser is closed");
|
|
276
407
|
return this.#handle;
|
|
277
408
|
}
|
|
409
|
+
[physicalRows]() {
|
|
410
|
+
return u64ToSafeNumber(native.symbols.csv_parser_physical_rows(this.#requireHandle()), "CSV physical record count");
|
|
411
|
+
}
|
|
278
412
|
#lastError() {
|
|
279
413
|
return native.symbols.csv_parser_last_error(this.#requireHandle()) ?? "native parser error unavailable";
|
|
280
414
|
}
|
|
281
|
-
#
|
|
282
|
-
const
|
|
283
|
-
if (this.#
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
415
|
+
#requireWritableHandle(mode) {
|
|
416
|
+
const handle = this.#requireHandle();
|
|
417
|
+
if (this.#schemaFailure !== void 0)
|
|
418
|
+
throw this.#schemaFailure.error;
|
|
419
|
+
const previous = this.#writeMode;
|
|
420
|
+
if (previous !== void 0 && previous !== mode && ((this.#detection?.length ?? 0) > 0 || native.symbols.csv_parser_has_pending_record(handle))) {
|
|
421
|
+
const pending = previous === "count" ? "count record" : "materialized record";
|
|
422
|
+
throw Error(`cannot switch CSV write modes while a ${pending} is pending`);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
#detectDelimiter(chunk, final) {
|
|
426
|
+
const input = normalizeChunk(chunk);
|
|
427
|
+
const detection = this.#detection;
|
|
428
|
+
if (detection === void 0 || detection.selected)
|
|
429
|
+
return input;
|
|
430
|
+
const bytes = new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
|
|
431
|
+
if (!final && detection.length + bytes.length <= FILE_PROBE_SIZE) {
|
|
432
|
+
if (bytes.length > 0) {
|
|
433
|
+
detection.prefix ??= new Uint8Array(FILE_PROBE_SIZE);
|
|
434
|
+
detection.prefix.set(bytes, detection.length);
|
|
435
|
+
detection.length += bytes.length;
|
|
298
436
|
}
|
|
299
|
-
return
|
|
437
|
+
return EMPTY_BUFFER;
|
|
438
|
+
}
|
|
439
|
+
const buffered = detection.prefix === void 0 ? bytes : Buffer.concat([detection.prefix.subarray(0, detection.length), bytes]);
|
|
440
|
+
const delimiter = detectBufferDelimiter(buffered, "", final, detection.dialect);
|
|
441
|
+
if (delimiter !== detection.delimiter) {
|
|
442
|
+
const previous = this.#requireHandle();
|
|
443
|
+
const { handle, writer } = detection.open(delimiter);
|
|
444
|
+
nativeCsvParserFinalizer.unregister(this);
|
|
445
|
+
this.#handle = handle;
|
|
446
|
+
this.#writer = writer;
|
|
447
|
+
nativeCsvParserFinalizer.register(this, handle, this);
|
|
448
|
+
destroyNativeCsvParser(previous);
|
|
449
|
+
detection.delimiter = delimiter;
|
|
450
|
+
}
|
|
451
|
+
detection.selected = !0;
|
|
452
|
+
detection.length = 0;
|
|
453
|
+
detection.prefix = void 0;
|
|
454
|
+
return buffered;
|
|
455
|
+
}
|
|
456
|
+
#validateSchema(final) {
|
|
457
|
+
if (!this.#validator)
|
|
458
|
+
return;
|
|
459
|
+
const handle = this.#requireHandle();
|
|
460
|
+
try {
|
|
461
|
+
this.#validator.validateNative(handle, final);
|
|
300
462
|
} catch (error) {
|
|
301
|
-
|
|
463
|
+
this.#schemaFailure = { error };
|
|
302
464
|
throw error;
|
|
303
465
|
}
|
|
304
466
|
}
|