@konstit/csv 0.4.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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +554 -0
  3. package/THIRD_PARTY_NOTICES.md +365 -0
  4. package/dist/api.d.ts +81 -0
  5. package/dist/api.js +515 -0
  6. package/dist/batches.d.ts +47 -0
  7. package/dist/batches.js +348 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +605 -0
  10. package/dist/file-stream.d.ts +11 -0
  11. package/dist/file-stream.js +290 -0
  12. package/dist/files.d.ts +8 -0
  13. package/dist/files.js +150 -0
  14. package/dist/filter.d.ts +8 -0
  15. package/dist/filter.js +82 -0
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.js +19 -0
  18. package/dist/native.d.ts +199 -0
  19. package/dist/native.js +275 -0
  20. package/dist/normalize.d.ts +56 -0
  21. package/dist/normalize.js +365 -0
  22. package/dist/options.d.ts +17 -0
  23. package/dist/options.js +12 -0
  24. package/dist/parser.d.ts +32 -0
  25. package/dist/parser.js +254 -0
  26. package/dist/runtime.d.ts +5 -0
  27. package/dist/runtime.js +12 -0
  28. package/dist/strict-schema.d.ts +12 -0
  29. package/dist/strict-schema.js +90 -0
  30. package/dist/types.d.ts +181 -0
  31. package/dist/types.js +0 -0
  32. package/dist/worker-count.d.ts +2 -0
  33. package/dist/worker-count.js +96 -0
  34. package/dist/worker-factory.d.ts +3 -0
  35. package/dist/worker-factory.js +9 -0
  36. package/dist/worker-filter.d.ts +29 -0
  37. package/dist/worker-filter.js +46 -0
  38. package/dist/worker-module.d.ts +1 -0
  39. package/dist/worker-module.js +4 -0
  40. package/dist/worker-pool.d.ts +17 -0
  41. package/dist/worker-pool.js +290 -0
  42. package/dist/worker-rows.d.ts +8 -0
  43. package/dist/worker-rows.js +118 -0
  44. package/dist/workers/count.worker.d.ts +1 -0
  45. package/dist/workers/count.worker.js +49 -0
  46. package/dist/workers/rows.worker.d.ts +1 -0
  47. package/dist/workers/rows.worker.js +85 -0
  48. package/dist/zip-reader.d.ts +2 -0
  49. package/dist/zip-reader.js +89 -0
  50. package/package.json +122 -0
  51. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  52. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  53. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  54. package/prebuilds/manifest.json +48 -0
  55. package/prebuilds/provenance/darwin-arm64.json +1 -0
  56. package/prebuilds/provenance/darwin-x64.json +1 -0
  57. package/prebuilds/provenance/linux-x64.json +1 -0
@@ -0,0 +1,365 @@
1
+ import {
2
+ EMPTY_BUFFER,
3
+ EMPTY_U32,
4
+ native
5
+ } from "./native.js";
6
+ export const MAX_COLUMN_INDEX = 2024;
7
+ export const MAX_PROJECTION_LENGTH = 2024;
8
+ export const MAX_FILTER_COUNT = MAX_PROJECTION_LENGTH;
9
+ const UINT32_MAX = 4294967295;
10
+ const NATIVE_FILTER_DESCRIPTOR_LENGTH = 4;
11
+ const NATIVE_FILTER_EQUALS = 1;
12
+ const NATIVE_FILTER_IN = 2;
13
+ const NATIVE_FILTER_STARTS_WITH = 3;
14
+ const NATIVE_FILTER_REGEX = 4;
15
+ const NATIVE_FILTER_NEQ = 5;
16
+ const NATIVE_FILTER_NOIN = 6;
17
+ const NATIVE_FILTER_ALL = 7;
18
+ const NATIVE_FILTER_ANY = 8;
19
+ const NATIVE_FILTER_NOT = 9;
20
+ export const MAX_REGEX_FILTER_COUNT = 32;
21
+ export const MAX_FILTER_PROGRAM_LENGTH = 4096;
22
+ const MAX_REGEX_PATTERN_BYTES = 4096;
23
+ export function encodingCode(encoding = "utf8") {
24
+ const normalized = encoding.toLowerCase();
25
+ if (normalized === "utf8")
26
+ return 0;
27
+ if (normalized === "latin1" || normalized === "iso88591" || normalized === "iso-8859-1")
28
+ return 1;
29
+ throw Error(`unsupported encoding: ${encoding}`);
30
+ }
31
+ export function normalizeChunk(chunk) {
32
+ return chunk.byteLength === 0 ? EMPTY_BUFFER : chunk;
33
+ }
34
+ export function normalizeFixedColumnsCount(value, label) {
35
+ if (value === void 0)
36
+ return;
37
+ if (!Number.isInteger(value) || value <= 0 || value > 4294967295)
38
+ throw RangeError(`${label} out of range: ${value}`);
39
+ return value;
40
+ }
41
+ export function normalizeColumns(columns) {
42
+ if (columns === void 0)
43
+ return EMPTY_U32;
44
+ if (columns.length > MAX_PROJECTION_LENGTH)
45
+ throw RangeError(`selected column count out of range: ${columns.length}`);
46
+ const normalized = new Uint32Array(columns.length);
47
+ const seen = new Set;
48
+ for (let index = 0;index < columns.length; ++index) {
49
+ const column = columns[index] ?? NaN;
50
+ normalizeColumnIndex(column, "selected column");
51
+ if (seen.has(column))
52
+ throw RangeError(`selected column repeated: ${column}`);
53
+ seen.add(column);
54
+ normalized[index] = column;
55
+ }
56
+ return normalized.length === 0 ? EMPTY_U32 : normalized;
57
+ }
58
+ export function normalizeColumnIndex(column, label) {
59
+ if (!Number.isInteger(column) || column < 0 || column > MAX_COLUMN_INDEX)
60
+ throw RangeError(`${label} out of range: ${column}`);
61
+ return column;
62
+ }
63
+ export function normalizeEqualsFilter(filter) {
64
+ if (filter === void 0)
65
+ return {
66
+ enabled: !1,
67
+ column: 0,
68
+ value: EMPTY_BUFFER,
69
+ valueLength: 0
70
+ };
71
+ normalizeColumnIndex(filter.column, "filter column");
72
+ const value = typeof filter.value === "string" ? Buffer.from(filter.value) : filter.value;
73
+ return {
74
+ enabled: !0,
75
+ column: filter.column,
76
+ value: value.byteLength === 0 ? EMPTY_BUFFER : value,
77
+ valueLength: value.byteLength
78
+ };
79
+ }
80
+ export function normalizeFilterColumn(column) {
81
+ return normalizeColumnIndex(column, "filter column");
82
+ }
83
+ export function normalizeFilterValue(value) {
84
+ return typeof value === "string" ? Buffer.from(value) : value;
85
+ }
86
+ export function normalizeRegex(regex) {
87
+ if (typeof regex !== "object" || regex === null || typeof regex.source !== "string" || typeof regex.flags !== "string")
88
+ throw TypeError("regex must be created with csv.re()");
89
+ const unsupportedFlags = regex.flags.replace(/[imsu]/g, "");
90
+ if (unsupportedFlags.length > 0)
91
+ throw Error(`unsupported regular expression flags: ${unsupportedFlags}`);
92
+ if (new Set(regex.flags).size !== regex.flags.length)
93
+ throw Error(`duplicate regular expression flags: ${regex.flags}`);
94
+ const compatibleSource = convertJavaScriptRegexSource(regex.source, regex.flags.includes("u"));
95
+ const re2Flags = regex.flags.replace("u", "");
96
+ const source = re2Flags.length === 0 ? compatibleSource : `(?${re2Flags}:${compatibleSource})`;
97
+ const encoded = Buffer.from(source);
98
+ if (encoded.byteLength > MAX_REGEX_PATTERN_BYTES)
99
+ throw RangeError(`regular expression exceeds ${MAX_REGEX_PATTERN_BYTES} UTF-8 bytes`);
100
+ return encoded.byteLength === 0 ? EMPTY_BUFFER : encoded;
101
+ }
102
+ export function validateRegex(regex) {
103
+ const pattern = normalizeRegex(regex);
104
+ const error = native.symbols.csv_regex_validate(pattern, pattern);
105
+ if (error !== null && error.length > 0)
106
+ throw SyntaxError(error);
107
+ }
108
+ function convertJavaScriptRegexSource(source, unicode) {
109
+ let compatible = "";
110
+ for (let index = 0;index < source.length; ) {
111
+ if (source[index] !== "\\") {
112
+ compatible += source[index];
113
+ ++index;
114
+ continue;
115
+ }
116
+ const escapedCharacter = source[index + 1];
117
+ if (escapedCharacter === void 0) {
118
+ compatible += "\\";
119
+ break;
120
+ }
121
+ if (escapedCharacter === "\\") {
122
+ compatible += "\\\\";
123
+ index += 2;
124
+ continue;
125
+ }
126
+ if (escapedCharacter === "/") {
127
+ compatible += "/";
128
+ index += 2;
129
+ continue;
130
+ }
131
+ if (escapedCharacter !== "u") {
132
+ compatible += `\\${escapedCharacter}`;
133
+ index += 2;
134
+ continue;
135
+ }
136
+ if (source[index + 2] === "{") {
137
+ if (!unicode) {
138
+ compatible += "\\u";
139
+ index += 2;
140
+ continue;
141
+ }
142
+ const close = source.indexOf("}", index + 3);
143
+ const digits = close === -1 ? "" : source.slice(index + 3, close);
144
+ if (!/^[0-9a-fA-F]{1,6}$/.test(digits))
145
+ throw SyntaxError("invalid JavaScript Unicode escape in regular expression");
146
+ const codePoint = Number.parseInt(digits, 16);
147
+ if (codePoint > 1114111 || isSurrogate(codePoint))
148
+ throw SyntaxError("regular expression contains an unsupported Unicode surrogate");
149
+ compatible += `\\x{${codePoint.toString(16)}}`;
150
+ index = close + 1;
151
+ continue;
152
+ }
153
+ const digits = source.slice(index + 2, index + 6);
154
+ if (!/^[0-9a-fA-F]{4}$/.test(digits)) {
155
+ compatible += "\\u";
156
+ index += 2;
157
+ continue;
158
+ }
159
+ let codePoint = Number.parseInt(digits, 16);
160
+ index += 6;
161
+ if (codePoint >= 55296 && codePoint <= 56319) {
162
+ const lowDigits = source.slice(index + 2, index + 6);
163
+ if (source.slice(index, index + 2) !== "\\u" || !/^[0-9a-fA-F]{4}$/.test(lowDigits))
164
+ throw SyntaxError("regular expression contains an unsupported Unicode surrogate");
165
+ const low = Number.parseInt(lowDigits, 16);
166
+ if (low < 56320 || low > 57343)
167
+ throw SyntaxError("regular expression contains an unsupported Unicode surrogate");
168
+ codePoint = 65536 + (codePoint - 55296 << 10) + low - 56320;
169
+ index += 6;
170
+ } else if (codePoint >= 56320 && codePoint <= 57343)
171
+ throw SyntaxError("regular expression contains an unsupported Unicode surrogate");
172
+ compatible += `\\x{${codePoint.toString(16)}}`;
173
+ }
174
+ return compatible;
175
+ }
176
+ function isSurrogate(codePoint) {
177
+ return codePoint >= 55296 && codePoint <= 57343;
178
+ }
179
+ export function normalizeInFilter(filter) {
180
+ const column = normalizeFilterColumn(filter.column);
181
+ if (filter.values.length === 0)
182
+ throw RangeError("filter values must not be empty");
183
+ const values = filter.values.map((value) => normalizeFilterValue(value));
184
+ let valuesDataLength = 0;
185
+ for (const value of values) {
186
+ valuesDataLength += value.byteLength;
187
+ if (valuesDataLength > 4294967295)
188
+ throw RangeError("filter values exceed native offset range");
189
+ }
190
+ const valuesData = valuesDataLength === 0 ? EMPTY_BUFFER : new Uint8Array(valuesDataLength);
191
+ const offsets = new Uint32Array(values.length + 1);
192
+ let offset = 0;
193
+ for (let index = 0;index < values.length; ++index) {
194
+ const value = values[index] ?? EMPTY_BUFFER;
195
+ offsets[index] = offset;
196
+ valuesData.set(value, offset);
197
+ offset += value.byteLength;
198
+ }
199
+ offsets[values.length] = offset;
200
+ return {
201
+ column,
202
+ valuesData,
203
+ valuesDataLength,
204
+ offsets,
205
+ valueCount: values.length
206
+ };
207
+ }
208
+ export function normalizeStartsWithFilter(filter) {
209
+ const column = normalizeFilterColumn(filter.column);
210
+ const value = normalizeFilterValue(filter.prefix);
211
+ return {
212
+ column,
213
+ value: value.byteLength === 0 ? EMPTY_BUFFER : value,
214
+ valueLength: value.byteLength
215
+ };
216
+ }
217
+ export function normalizeNativeFilters(filters) {
218
+ if (filters === void 0 || filters.length === 0)
219
+ return {
220
+ descriptors: EMPTY_U32,
221
+ filterCount: 0,
222
+ valuesData: EMPTY_BUFFER,
223
+ valuesDataLength: 0,
224
+ valueOffsets: EMPTY_U32,
225
+ valueCount: 0
226
+ };
227
+ if (filters.length > MAX_FILTER_COUNT)
228
+ throw RangeError(`filter count out of range: ${filters.length}`);
229
+ const descriptors = new Uint32Array(filters.length * NATIVE_FILTER_DESCRIPTOR_LENGTH);
230
+ const values = [];
231
+ let valuesDataLength = 0;
232
+ let valueCount = 0;
233
+ let regexFilterCount = 0;
234
+ for (let filterIndex = 0;filterIndex < filters.length; ++filterIndex) {
235
+ const filter = filters[filterIndex];
236
+ if (filter === void 0)
237
+ throw TypeError(`filter missing at index ${filterIndex}`);
238
+ const column = normalizeFilterColumn(filter.column);
239
+ let kind;
240
+ let filterValues;
241
+ if ("value" in filter) {
242
+ kind = NATIVE_FILTER_EQUALS;
243
+ filterValues = [filter.value];
244
+ } else if ("values" in filter) {
245
+ kind = NATIVE_FILTER_IN;
246
+ filterValues = filter.values;
247
+ if (filterValues.length === 0)
248
+ throw RangeError("filter values must not be empty");
249
+ } else if ("notEquals" in filter) {
250
+ kind = NATIVE_FILTER_NEQ;
251
+ filterValues = [filter.notEquals];
252
+ } else if ("notIn" in filter) {
253
+ kind = NATIVE_FILTER_NOIN;
254
+ filterValues = filter.notIn;
255
+ if (filterValues.length === 0)
256
+ throw RangeError("filter values must not be empty");
257
+ } else if ("prefix" in filter) {
258
+ kind = NATIVE_FILTER_STARTS_WITH;
259
+ filterValues = [filter.prefix];
260
+ } else {
261
+ ++regexFilterCount;
262
+ if (regexFilterCount > MAX_REGEX_FILTER_COUNT)
263
+ throw RangeError(`regex filter count out of range: ${regexFilterCount}`);
264
+ kind = NATIVE_FILTER_REGEX;
265
+ filterValues = [normalizeRegex(filter.regex)];
266
+ }
267
+ if (filterValues.length > UINT32_MAX - valueCount)
268
+ throw RangeError("filter value count exceeds native offset range");
269
+ const descriptorIndex = filterIndex * NATIVE_FILTER_DESCRIPTOR_LENGTH;
270
+ descriptors[descriptorIndex] = kind;
271
+ descriptors[descriptorIndex + 1] = column;
272
+ descriptors[descriptorIndex + 2] = valueCount;
273
+ descriptors[descriptorIndex + 3] = filterValues.length;
274
+ valueCount += filterValues.length;
275
+ for (const filterValue of filterValues) {
276
+ const value = normalizeFilterValue(filterValue);
277
+ if (value.byteLength > UINT32_MAX - valuesDataLength)
278
+ throw RangeError("filter values exceed native offset range");
279
+ values.push(value);
280
+ valuesDataLength += value.byteLength;
281
+ }
282
+ }
283
+ const valuesData = valuesDataLength === 0 ? EMPTY_BUFFER : new Uint8Array(valuesDataLength);
284
+ const valueOffsets = new Uint32Array(valueCount + 1);
285
+ let valueIndex = 0;
286
+ let offset = 0;
287
+ for (const value of values) {
288
+ valueOffsets[valueIndex] = offset;
289
+ valuesData.set(value, offset);
290
+ offset += value.byteLength;
291
+ ++valueIndex;
292
+ }
293
+ valueOffsets[valueCount] = offset;
294
+ return {
295
+ descriptors,
296
+ filterCount: filters.length,
297
+ valuesData,
298
+ valuesDataLength,
299
+ valueOffsets,
300
+ valueCount
301
+ };
302
+ }
303
+ export function normalizeNativeFilterProgram(program) {
304
+ if (program.length === 0)
305
+ throw RangeError("filter program must contain at least one predicate");
306
+ if (program.length > MAX_FILTER_PROGRAM_LENGTH)
307
+ throw RangeError(`filter program length out of range: ${program.length}`);
308
+ const predicates = [];
309
+ let stackDepth = 0;
310
+ for (let index = 0;index < program.length; ++index) {
311
+ const entry = program[index];
312
+ if (entry === void 0)
313
+ throw TypeError(`filter program entry missing at index ${index}`);
314
+ if (!isNativeFilterOperator(entry)) {
315
+ predicates.push(entry);
316
+ ++stackDepth;
317
+ continue;
318
+ }
319
+ const { operandCount, operator } = entry;
320
+ if (!Number.isInteger(operandCount) || operandCount < 1)
321
+ throw RangeError(`filter ${operator} operand count out of range: ${operandCount}`);
322
+ if (operator === "not" && operandCount !== 1)
323
+ throw RangeError(`filter not operand count must be 1: ${operandCount}`);
324
+ if (operandCount > stackDepth)
325
+ throw RangeError(`filter ${operator} does not have ${operandCount} operands`);
326
+ stackDepth -= operandCount - 1;
327
+ }
328
+ if (stackDepth !== 1)
329
+ throw Error(`filter program leaves ${stackDepth} results`);
330
+ const normalized = normalizeNativeFilters(predicates);
331
+ const descriptors = new Uint32Array(program.length * NATIVE_FILTER_DESCRIPTOR_LENGTH);
332
+ let predicateIndex = 0;
333
+ for (let programIndex = 0;programIndex < program.length; ++programIndex) {
334
+ const entry = program[programIndex];
335
+ if (entry === void 0)
336
+ throw TypeError(`filter program entry missing at index ${programIndex}`);
337
+ const descriptorIndex = programIndex * NATIVE_FILTER_DESCRIPTOR_LENGTH;
338
+ if (isNativeFilterOperator(entry)) {
339
+ descriptors[descriptorIndex] = nativeFilterOperatorCode(entry.operator);
340
+ descriptors[descriptorIndex + 1] = entry.operandCount;
341
+ continue;
342
+ }
343
+ const predicateDescriptorIndex = predicateIndex * NATIVE_FILTER_DESCRIPTOR_LENGTH;
344
+ descriptors.set(normalized.descriptors.subarray(predicateDescriptorIndex, predicateDescriptorIndex + NATIVE_FILTER_DESCRIPTOR_LENGTH), descriptorIndex);
345
+ ++predicateIndex;
346
+ }
347
+ return {
348
+ ...normalized,
349
+ descriptors,
350
+ filterCount: program.length
351
+ };
352
+ }
353
+ function isNativeFilterOperator(entry) {
354
+ return "operator" in entry;
355
+ }
356
+ function nativeFilterOperatorCode(operator) {
357
+ switch (operator) {
358
+ case "all":
359
+ return NATIVE_FILTER_ALL;
360
+ case "any":
361
+ return NATIVE_FILTER_ANY;
362
+ case "not":
363
+ return NATIVE_FILTER_NOT;
364
+ }
365
+ }
@@ -0,0 +1,17 @@
1
+ import type { CsvColumnarBatchOptions, CsvColumns, CsvCountOptions, CsvRowsOptions, CsvRowViewsOptions } from './types.js';
2
+ /**
3
+ * Preserve literal inference for `csv.rows()` options.
4
+ */
5
+ export declare function defineRowsOptions<const TColumns extends CsvColumns | undefined, const TOptions extends CsvRowsOptions<TColumns>>(options: TOptions): TOptions;
6
+ /**
7
+ * Preserve literal inference for `csv.count()` options.
8
+ */
9
+ export declare function defineCountOptions<const TOptions extends CsvCountOptions>(options: TOptions): TOptions;
10
+ /**
11
+ * Preserve literal inference for `csv.withColumnarBatches()` options.
12
+ */
13
+ export declare function defineColumnarOptions<const TColumns extends CsvColumns | undefined, const TOptions extends CsvColumnarBatchOptions<TColumns>>(options: TOptions): TOptions;
14
+ /**
15
+ * Preserve literal inference for `csv.withRowViews()` options.
16
+ */
17
+ export declare function defineRowViewOptions<const TColumns extends CsvColumns | undefined, const TOptions extends CsvRowViewsOptions<TColumns>>(options: TOptions): TOptions;
@@ -0,0 +1,12 @@
1
+ export function defineRowsOptions(options) {
2
+ return options;
3
+ }
4
+ export function defineCountOptions(options) {
5
+ return options;
6
+ }
7
+ export function defineColumnarOptions(options) {
8
+ return options;
9
+ }
10
+ export function defineRowViewOptions(options) {
11
+ return options;
12
+ }
@@ -0,0 +1,32 @@
1
+ import { NativeCsvBatch } from './batches.js';
2
+ import type { CsvNativeFilterProgramEntry } from './normalize.js';
3
+ import type { CsvEqualsFilter, CsvInFilter, CsvNativeFilter, CsvNativeProjectionOptions, CsvParserOptions, CsvRow, CsvStartsWithFilter } from './types.js';
4
+ export declare class NativeCsvParser {
5
+ #private;
6
+ constructor(options?: CsvParserOptions);
7
+ get closed(): boolean;
8
+ write(chunk: NodeJS.TypedArray | DataView, final?: boolean): CsvRow[];
9
+ writeBatch(chunk: NodeJS.TypedArray | DataView, final?: boolean): NativeCsvBatch;
10
+ writeProjectedBatch(chunk: NodeJS.TypedArray | DataView, options?: CsvNativeProjectionOptions, final?: boolean): NativeCsvBatch;
11
+ end(): CsvRow[];
12
+ endBatch(): NativeCsvBatch;
13
+ endProjectedBatch(options?: CsvNativeProjectionOptions): NativeCsvBatch;
14
+ writeProjectedBatchWhere(chunk: NodeJS.TypedArray | DataView, selectedColumns: readonly number[] | undefined, program: readonly CsvNativeFilterProgramEntry[], final?: boolean): NativeCsvBatch;
15
+ endProjectedBatchWhere(selectedColumns: readonly number[] | undefined, program: readonly CsvNativeFilterProgramEntry[]): NativeCsvBatch;
16
+ writeCount(chunk: NodeJS.TypedArray | DataView, final?: boolean): number;
17
+ endCount(): number;
18
+ writeCountWhereEquals(chunk: NodeJS.TypedArray | DataView, filter: CsvEqualsFilter, final?: boolean): number;
19
+ endCountWhereEquals(filter: CsvEqualsFilter): number;
20
+ writeCountWhereIn(chunk: NodeJS.TypedArray | DataView, filter: CsvInFilter, final?: boolean): number;
21
+ endCountWhereIn(filter: CsvInFilter): number;
22
+ writeCountWhereStartsWith(chunk: NodeJS.TypedArray | DataView, filter: CsvStartsWithFilter, final?: boolean): number;
23
+ endCountWhereStartsWith(filter: CsvStartsWithFilter): number;
24
+ writeCountWhereAll(chunk: NodeJS.TypedArray | DataView, filters: readonly CsvNativeFilter[], final?: boolean): number;
25
+ endCountWhereAll(filters: readonly CsvNativeFilter[]): number;
26
+ writeCountWhere(chunk: NodeJS.TypedArray | DataView, program: readonly CsvNativeFilterProgramEntry[], final?: boolean): number;
27
+ endCountWhere(program: readonly CsvNativeFilterProgramEntry[]): number;
28
+ reset(): void;
29
+ close(): void;
30
+ dispose(): void;
31
+ [Symbol.dispose](): void;
32
+ }
package/dist/parser.js ADDED
@@ -0,0 +1,254 @@
1
+ import { NativeCsvBatch } from "./batches.js";
2
+ import {
3
+ native,
4
+ u64ToSafeNumber
5
+ } from "./native.js";
6
+ import {
7
+ encodingCode,
8
+ normalizeChunk,
9
+ normalizeColumns,
10
+ normalizeEqualsFilter,
11
+ normalizeFixedColumnsCount,
12
+ normalizeInFilter,
13
+ normalizeNativeFilterProgram,
14
+ normalizeNativeFilters,
15
+ normalizeStartsWithFilter
16
+ } from "./normalize.js";
17
+ function destroyNativeCsvParser(handle) {
18
+ native.symbols.csv_parser_destroy(handle);
19
+ }
20
+ const nativeCsvParserFinalizer = new FinalizationRegistry(destroyNativeCsvParser);
21
+
22
+ export class NativeCsvParser {
23
+ #handle;
24
+ #strict;
25
+ #fixedColumns;
26
+ constructor(options = {}) {
27
+ const delimiter = options.delimiter ?? ",";
28
+ if (delimiter === "auto")
29
+ throw Error("automatic delimiter detection is only supported by file APIs");
30
+ if (delimiter.length !== 1)
31
+ throw Error("delimiter must be one character");
32
+ this.#strict = options.strict === !0;
33
+ normalizeColumns(options.selectedColumns);
34
+ this.#fixedColumns = normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
35
+ const handle = native.symbols.csv_parser_create(encodingCode(options.encoding), delimiter.charCodeAt(0));
36
+ if (handle === null)
37
+ throw Error("failed to create native CSV parser");
38
+ this.#handle = handle;
39
+ nativeCsvParserFinalizer.register(this, handle, this);
40
+ }
41
+ get closed() {
42
+ return this.#handle === null;
43
+ }
44
+ write(chunk, final = !1) {
45
+ const batch = this.writeBatch(chunk, final);
46
+ try {
47
+ return batch.rows();
48
+ } finally {
49
+ batch.close();
50
+ }
51
+ }
52
+ writeBatch(chunk, final = !1) {
53
+ if (chunk.byteLength === 0 && final)
54
+ return this.endBatch();
55
+ const handle = this.#requireHandle();
56
+ const input = normalizeChunk(chunk);
57
+ const batch = this.#strict && this.#fixedColumns !== void 0 ? native.symbols.csv_parser_write_strict_fixed_batch(handle, input, input, final, this.#fixedColumns) : this.#strict ? native.symbols.csv_parser_write_strict_batch(handle, input, 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);
58
+ if (batch === null)
59
+ throw Error(`native CSV parser failed: ${this.#lastError()}`);
60
+ return new NativeCsvBatch(batch);
61
+ }
62
+ writeProjectedBatch(chunk, options = {}, final = !1) {
63
+ this.#rejectStrictUnsupported("projected batches");
64
+ this.#rejectProjectionFilterConflict(options);
65
+ if (chunk.byteLength === 0 && final)
66
+ return this.endProjectedBatch(options);
67
+ const handle = this.#requireHandle();
68
+ const input = normalizeChunk(chunk);
69
+ const columns = normalizeColumns(options.selectedColumns);
70
+ const filter = normalizeEqualsFilter(options.equalsFilter);
71
+ const filters = normalizeNativeFilters(options.filters);
72
+ const batch = options.filters === void 0 ? native.symbols.csv_parser_write_projected_batch(handle, input, input, final, options.selectedColumns !== void 0, columns, BigInt(options.selectedColumns?.length ?? 0), filter.enabled, filter.column, filter.value, filter.value) : native.symbols.csv_parser_write_projected_batch_where_all(handle, input, input, final, options.selectedColumns !== void 0, columns, BigInt(options.selectedColumns?.length ?? 0), filters.descriptors, BigInt(filters.filterCount), filters.valuesData, filters.valuesData, filters.valueOffsets, BigInt(filters.valueCount));
73
+ if (batch === null)
74
+ throw Error(`native CSV parser failed: ${this.#lastError()}`);
75
+ return new NativeCsvBatch(batch);
76
+ }
77
+ end() {
78
+ const batch = this.endBatch();
79
+ try {
80
+ return batch.rows();
81
+ } finally {
82
+ batch.close();
83
+ }
84
+ }
85
+ endBatch() {
86
+ const batch = this.#strict && this.#fixedColumns !== void 0 ? native.symbols.csv_parser_finish_strict_fixed_batch(this.#requireHandle(), this.#fixedColumns) : this.#strict ? native.symbols.csv_parser_finish_strict_batch(this.#requireHandle()) : this.#fixedColumns !== void 0 ? native.symbols.csv_parser_finish_fixed_batch(this.#requireHandle(), this.#fixedColumns) : native.symbols.csv_parser_finish_batch(this.#requireHandle());
87
+ if (batch === null)
88
+ throw Error(`native CSV parser failed: ${this.#lastError()}`);
89
+ return new NativeCsvBatch(batch);
90
+ }
91
+ endProjectedBatch(options = {}) {
92
+ this.#rejectStrictUnsupported("projected batches");
93
+ this.#rejectProjectionFilterConflict(options);
94
+ const columns = normalizeColumns(options.selectedColumns);
95
+ const filter = normalizeEqualsFilter(options.equalsFilter);
96
+ const filters = normalizeNativeFilters(options.filters);
97
+ const batch = options.filters === void 0 ? native.symbols.csv_parser_finish_projected_batch(this.#requireHandle(), options.selectedColumns !== void 0, columns, BigInt(options.selectedColumns?.length ?? 0), filter.enabled, filter.column, filter.value, filter.value) : native.symbols.csv_parser_finish_projected_batch_where_all(this.#requireHandle(), options.selectedColumns !== void 0, columns, BigInt(options.selectedColumns?.length ?? 0), filters.descriptors, BigInt(filters.filterCount), filters.valuesData, filters.valuesData, filters.valueOffsets, BigInt(filters.valueCount));
98
+ if (batch === null)
99
+ throw Error(`native CSV parser failed: ${this.#lastError()}`);
100
+ return new NativeCsvBatch(batch);
101
+ }
102
+ writeProjectedBatchWhere(chunk, selectedColumns, program, final = !1) {
103
+ this.#rejectStrictUnsupported("projected batches");
104
+ if (chunk.byteLength === 0 && final)
105
+ return this.endProjectedBatchWhere(selectedColumns, program);
106
+ const handle = this.#requireHandle();
107
+ const input = normalizeChunk(chunk);
108
+ const columns = normalizeColumns(selectedColumns);
109
+ const normalized = normalizeNativeFilterProgram(program);
110
+ const batch = native.symbols.csv_parser_write_projected_batch_where_all(handle, input, input, final, selectedColumns !== void 0, columns, BigInt(selectedColumns?.length ?? 0), normalized.descriptors, BigInt(normalized.filterCount), normalized.valuesData, normalized.valuesData, normalized.valueOffsets, BigInt(normalized.valueCount));
111
+ if (batch === null)
112
+ throw Error(`native CSV parser failed: ${this.#lastError()}`);
113
+ return new NativeCsvBatch(batch);
114
+ }
115
+ endProjectedBatchWhere(selectedColumns, program) {
116
+ this.#rejectStrictUnsupported("projected batches");
117
+ const columns = normalizeColumns(selectedColumns);
118
+ const normalized = normalizeNativeFilterProgram(program);
119
+ const batch = native.symbols.csv_parser_finish_projected_batch_where_all(this.#requireHandle(), selectedColumns !== void 0, columns, BigInt(selectedColumns?.length ?? 0), normalized.descriptors, BigInt(normalized.filterCount), normalized.valuesData, normalized.valuesData, normalized.valueOffsets, BigInt(normalized.valueCount));
120
+ if (batch === null)
121
+ throw Error(`native CSV parser failed: ${this.#lastError()}`);
122
+ return new NativeCsvBatch(batch);
123
+ }
124
+ writeCount(chunk, final = !1) {
125
+ this.#rejectStrictUnsupported("count");
126
+ if (chunk.byteLength === 0 && final)
127
+ return this.endCount();
128
+ const handle = this.#requireHandle();
129
+ const input = normalizeChunk(chunk);
130
+ return u64ToSafeNumber(native.symbols.csv_parser_write_count(handle, input, input, final), "CSV parsed row count");
131
+ }
132
+ endCount() {
133
+ this.#rejectStrictUnsupported("count");
134
+ return u64ToSafeNumber(native.symbols.csv_parser_finish_count(this.#requireHandle()), "CSV parsed row count");
135
+ }
136
+ writeCountWhereEquals(chunk, filter, final = !1) {
137
+ this.#rejectStrictUnsupported("count filters");
138
+ if (chunk.byteLength === 0 && final)
139
+ return this.endCountWhereEquals(filter);
140
+ const handle = this.#requireHandle();
141
+ const input = normalizeChunk(chunk);
142
+ const normalized = normalizeEqualsFilter(filter);
143
+ return u64ToSafeNumber(native.symbols.csv_parser_write_count_where_equals(handle, input, input, final, normalized.column, normalized.value, normalized.value), "CSV filtered row count");
144
+ }
145
+ endCountWhereEquals(filter) {
146
+ this.#rejectStrictUnsupported("count filters");
147
+ const normalized = normalizeEqualsFilter(filter);
148
+ return u64ToSafeNumber(native.symbols.csv_parser_finish_count_where_equals(this.#requireHandle(), normalized.column, normalized.value, normalized.value), "CSV filtered row count");
149
+ }
150
+ writeCountWhereIn(chunk, filter, final = !1) {
151
+ this.#rejectStrictUnsupported("count filters");
152
+ if (chunk.byteLength === 0 && final)
153
+ return this.endCountWhereIn(filter);
154
+ const normalized = normalizeInFilter(filter);
155
+ const handle = this.#requireHandle();
156
+ const input = normalizeChunk(chunk);
157
+ return u64ToSafeNumber(native.symbols.csv_parser_write_count_where_in(handle, input, input, final, normalized.column, normalized.valuesData, normalized.valuesData, normalized.offsets, BigInt(normalized.valueCount)), "CSV filtered row count");
158
+ }
159
+ endCountWhereIn(filter) {
160
+ this.#rejectStrictUnsupported("count filters");
161
+ const normalized = normalizeInFilter(filter);
162
+ return u64ToSafeNumber(native.symbols.csv_parser_finish_count_where_in(this.#requireHandle(), normalized.column, normalized.valuesData, normalized.valuesData, normalized.offsets, BigInt(normalized.valueCount)), "CSV filtered row count");
163
+ }
164
+ writeCountWhereStartsWith(chunk, filter, final = !1) {
165
+ this.#rejectStrictUnsupported("count filters");
166
+ if (chunk.byteLength === 0 && final)
167
+ return this.endCountWhereStartsWith(filter);
168
+ const normalized = normalizeStartsWithFilter(filter);
169
+ const handle = this.#requireHandle();
170
+ const input = normalizeChunk(chunk);
171
+ return u64ToSafeNumber(native.symbols.csv_parser_write_count_where_starts_with(handle, input, input, final, normalized.column, normalized.value, normalized.value), "CSV filtered row count");
172
+ }
173
+ endCountWhereStartsWith(filter) {
174
+ this.#rejectStrictUnsupported("count filters");
175
+ const normalized = normalizeStartsWithFilter(filter);
176
+ return u64ToSafeNumber(native.symbols.csv_parser_finish_count_where_starts_with(this.#requireHandle(), normalized.column, normalized.value, normalized.value), "CSV filtered row count");
177
+ }
178
+ writeCountWhereAll(chunk, filters, final = !1) {
179
+ this.#rejectStrictUnsupported("count filters");
180
+ if (chunk.byteLength === 0 && final)
181
+ return this.endCountWhereAll(filters);
182
+ const normalized = normalizeNativeFilters(filters);
183
+ const handle = this.#requireHandle();
184
+ const input = normalizeChunk(chunk);
185
+ const count = native.symbols.csv_parser_write_count_where_all(handle, input, input, final, normalized.descriptors, BigInt(normalized.filterCount), normalized.valuesData, normalized.valuesData, normalized.valueOffsets, BigInt(normalized.valueCount));
186
+ this.#throwIfNativeError();
187
+ return u64ToSafeNumber(count, "CSV filtered row count");
188
+ }
189
+ endCountWhereAll(filters) {
190
+ this.#rejectStrictUnsupported("count filters");
191
+ const normalized = normalizeNativeFilters(filters);
192
+ const count = native.symbols.csv_parser_finish_count_where_all(this.#requireHandle(), normalized.descriptors, BigInt(normalized.filterCount), normalized.valuesData, normalized.valuesData, normalized.valueOffsets, BigInt(normalized.valueCount));
193
+ this.#throwIfNativeError();
194
+ return u64ToSafeNumber(count, "CSV filtered row count");
195
+ }
196
+ writeCountWhere(chunk, program, final = !1) {
197
+ this.#rejectStrictUnsupported("count filters");
198
+ if (chunk.byteLength === 0 && final)
199
+ return this.endCountWhere(program);
200
+ const normalized = normalizeNativeFilterProgram(program);
201
+ const handle = this.#requireHandle();
202
+ const input = normalizeChunk(chunk);
203
+ const count = native.symbols.csv_parser_write_count_where_all(handle, input, input, final, normalized.descriptors, BigInt(normalized.filterCount), normalized.valuesData, normalized.valuesData, normalized.valueOffsets, BigInt(normalized.valueCount));
204
+ this.#throwIfNativeError();
205
+ return u64ToSafeNumber(count, "CSV filtered row count");
206
+ }
207
+ endCountWhere(program) {
208
+ this.#rejectStrictUnsupported("count filters");
209
+ const normalized = normalizeNativeFilterProgram(program);
210
+ const count = native.symbols.csv_parser_finish_count_where_all(this.#requireHandle(), normalized.descriptors, BigInt(normalized.filterCount), normalized.valuesData, normalized.valuesData, normalized.valueOffsets, BigInt(normalized.valueCount));
211
+ this.#throwIfNativeError();
212
+ return u64ToSafeNumber(count, "CSV filtered row count");
213
+ }
214
+ reset() {
215
+ native.symbols.csv_parser_reset(this.#requireHandle());
216
+ }
217
+ close() {
218
+ const handle = this.#handle;
219
+ if (handle === null)
220
+ return;
221
+ this.#handle = null;
222
+ nativeCsvParserFinalizer.unregister(this);
223
+ destroyNativeCsvParser(handle);
224
+ }
225
+ dispose() {
226
+ this.close();
227
+ }
228
+ [Symbol.dispose]() {
229
+ this.close();
230
+ }
231
+ #requireHandle() {
232
+ if (this.#handle === null)
233
+ throw Error("native CSV parser is closed");
234
+ return this.#handle;
235
+ }
236
+ #lastError() {
237
+ if (this.#handle === null)
238
+ return "parser is closed";
239
+ return native.symbols.csv_parser_last_error(this.#handle) ?? "native parser error unavailable";
240
+ }
241
+ #throwIfNativeError() {
242
+ const error = this.#lastError();
243
+ if (error.length > 0)
244
+ throw Error(`native CSV parser failed: ${error}`);
245
+ }
246
+ #rejectStrictUnsupported(operation) {
247
+ if (this.#strict)
248
+ throw Error(`strict CSV validation is not supported for ${operation}`);
249
+ }
250
+ #rejectProjectionFilterConflict(options) {
251
+ if (options.equalsFilter !== void 0 && options.filters !== void 0)
252
+ throw Error("use equalsFilter or filters, not both");
253
+ }
254
+ }