@konstit/csv 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +108 -102
  2. package/THIRD_PARTY_NOTICES.md +27 -0
  3. package/dist/api.d.ts +78 -55
  4. package/dist/api.js +191 -40
  5. package/dist/batch-pipeline.d.ts +10 -0
  6. package/dist/batch-pipeline.js +83 -0
  7. package/dist/batches.d.ts +16 -2
  8. package/dist/batches.js +179 -5
  9. package/dist/cli-command.d.ts +7 -7
  10. package/dist/cli-command.js +325 -164
  11. package/dist/cli-schema.d.ts +51 -21
  12. package/dist/cli-schema.js +126 -65
  13. package/dist/cli.js +1 -1
  14. package/dist/file-stream.d.ts +62 -15
  15. package/dist/file-stream.js +494 -205
  16. package/dist/files.d.ts +17 -37
  17. package/dist/files.js +48 -21
  18. package/dist/gzip-reader.js +2 -2
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +1 -1
  21. package/dist/inspect-file.d.ts +26 -3
  22. package/dist/inspect-file.js +169 -74
  23. package/dist/inspect-zip.d.ts +26 -0
  24. package/dist/inspect-zip.js +59 -0
  25. package/dist/latin1-rows.d.ts +11 -3
  26. package/dist/latin1-rows.js +276 -75
  27. package/dist/materialize-field.d.ts +6 -0
  28. package/dist/materialize-field.js +9 -0
  29. package/dist/native.d.ts +89 -19
  30. package/dist/native.js +45 -23
  31. package/dist/normalize.d.ts +5 -0
  32. package/dist/normalize.js +42 -9
  33. package/dist/options.d.ts +27 -12
  34. package/dist/parser.d.ts +30 -13
  35. package/dist/parser.js +264 -102
  36. package/dist/strict-schema.d.ts +7 -8
  37. package/dist/strict-schema.js +45 -83
  38. package/dist/transforms.d.ts +1 -3
  39. package/dist/transforms.js +17 -16
  40. package/dist/types.d.ts +175 -77
  41. package/dist/zip-entry.d.ts +14 -0
  42. package/dist/zip-entry.js +155 -0
  43. package/dist/zip-reader.d.ts +14 -3
  44. package/dist/zip-reader.js +65 -23
  45. package/package.json +34 -23
  46. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  47. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  48. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  49. package/prebuilds/manifest.json +15 -8
  50. package/prebuilds/provenance/darwin-arm64.json +1 -1
  51. package/prebuilds/provenance/darwin-x64.json +1 -1
  52. package/prebuilds/provenance/linux-x64.json +1 -1
@@ -0,0 +1,59 @@
1
+ import { isZipSignature } from "./file-stream.js";
2
+ import {
3
+ AmbiguousZipGlobError,
4
+ isZipMember,
5
+ MAX_NESTED_ZIP_DEPTH,
6
+ openNestedZip,
7
+ withZipEntry
8
+ } from "./zip-entry.js";
9
+ import {
10
+ readZipDirectory
11
+ } from "./zip-reader.js";
12
+ export async function inspectZipArchive(path, request) {
13
+ const archive = request.entry === void 0 ? await inspectZipTree(path) : void 0;
14
+ try {
15
+ await using resources = new AsyncDisposableStack;
16
+ const selection = await withZipEntry(path, { format: "zip", entry: request.entry ?? "*" }, resources, async (reader, prefix) => {
17
+ const entry = reader.entryName;
18
+ if (archive?.zipArchives?.some((nested) => nested.path === entry && ("zipEntries" in nested)))
19
+ throw Error("Selected entry is a nested ZIP archive");
20
+ const sample = await request.readSample(reader.chunks(request.chunkSize));
21
+ if (isZipMember(entry) && isZipSignature(sample))
22
+ throw Error("Selected entry is a nested ZIP archive");
23
+ return { zipEntry: prefix + entry, sample };
24
+ });
25
+ return { archive, selection };
26
+ } catch (error) {
27
+ if (archive !== void 0)
28
+ return { archive, selection: { error } };
29
+ if (error instanceof AmbiguousZipGlobError)
30
+ return { selection: { error } };
31
+ try {
32
+ return { archive: await inspectZipTree(path), selection: { error } };
33
+ } catch {
34
+ return { selection: { error } };
35
+ }
36
+ }
37
+ }
38
+ async function inspectZipTree(source, depth = 0) {
39
+ const zipEntries = readZipDirectory(source);
40
+ const zipArchives = [];
41
+ for (const entry of new Set(zipEntries.filter(isZipMember))) {
42
+ if (depth >= MAX_NESTED_ZIP_DEPTH) {
43
+ zipArchives.push({ path: entry, error: `ZIP nesting exceeds ${MAX_NESTED_ZIP_DEPTH} levels` });
44
+ continue;
45
+ }
46
+ try {
47
+ await using resources = new AsyncDisposableStack;
48
+ const innerSource = await openNestedZip(source, { format: "zip", entry }, resources);
49
+ const tree = await inspectZipTree(innerSource, depth + 1);
50
+ zipArchives.push({ path: entry, ...tree });
51
+ } catch (error) {
52
+ zipArchives.push({ path: entry, error: nestedArchiveError(error) });
53
+ }
54
+ }
55
+ return { zipEntries, ...zipArchives.length === 0 ? {} : { zipArchives } };
56
+ }
57
+ function nestedArchiveError(error) {
58
+ return error instanceof Error && error.message.startsWith("native ZIP reader failed: ") ? error.message : "Failed to read nested ZIP archive";
59
+ }
@@ -1,5 +1,13 @@
1
+ import { type MappedRowLayout } from './batches.js';
2
+ import type { CsvFileInput } from './file-stream.js';
1
3
  import { type NativePointer } from './native.js';
2
- import type { CsvColumns, CsvDelimiter, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, CsvTransform, CsvTransformOptions } from './types.js';
4
+ import type { CsvColumns, CsvDelimiter, CsvMappedRow, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, CsvTransform, CsvTransformOptions } from './types.js';
5
+ type Latin1RowsOptions = Pick<CsvParserOptions, 'limit' | 'skipRows' | 'skipEmptyLines' | 'strict' | 'maxRecordBytes' | 'expectedHeaders' | 'requireHeader' | 'minDataRows'> & CsvTransformOptions & {
6
+ readonly maxBatchRows?: number;
7
+ };
8
+ type Latin1RowsInput = CsvFileInput | AsyncIterable<Uint8Array> | Iterable<Uint8Array>;
3
9
  export declare function canUseFilteredLatin1Cleanup(columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, transforms: readonly CsvTransform[]): boolean;
4
- export declare function latin1Rows(chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, createParser: (delimiter: number) => NativePointer | null, reusableRows?: CsvRow[], options?: Pick<CsvParserOptions, 'limit' | 'skipRows'> & CsvTransformOptions): AsyncGenerator<CsvRow[], void>;
5
- export declare function checkedOffset(words: Uint32Array, index: number, upperBound: number): number;
10
+ export declare function latin1Rows(input: Latin1RowsInput, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, createParser: (delimiter: number) => NativePointer | null, layout: MappedRowLayout, options?: Latin1RowsOptions): AsyncGenerator<CsvMappedRow[], void>;
11
+ export declare function latin1Rows(input: Latin1RowsInput, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, createParser: (delimiter: number) => NativePointer | null, reusableRows?: CsvRow[], options?: Latin1RowsOptions): AsyncGenerator<CsvRow[], void>;
12
+ export declare function checkedOffset(words: Uint32Array, index: number, upperBound: number, wordsPerOffset?: 1 | 2): number;
13
+ export {};
@@ -1,9 +1,18 @@
1
+ import { CString } from "bun:ffi";
1
2
  import { isAscii } from "node:buffer";
3
+ import { BatchPipeline } from "./batch-pipeline.js";
4
+ import {
5
+ mappedBatchRows,
6
+ NativeCsvBatch,
7
+ recycleBatch
8
+ } from "./batches.js";
2
9
  import {
3
10
  copyLatin1Range,
4
11
  decodeMaterializedField,
5
12
  latin1Pair,
6
- prepareRow
13
+ prepareRow,
14
+ RowStorage,
15
+ sliceRowBatch
7
16
  } from "./materialize-field.js";
8
17
  import {
9
18
  EMPTY_BUFFER,
@@ -12,115 +21,305 @@ import {
12
21
  toArrayBuffer,
13
22
  u64ToSafeNumber
14
23
  } from "./native.js";
15
- import { normalizeChunk } from "./normalize.js";
24
+ import {
25
+ delimiterByte,
26
+ normalizeChunk
27
+ } from "./normalize.js";
16
28
  import {
17
29
  nativeCsvParserFinalizer,
18
30
  prepareNativeParser,
31
+ prepareNativeValidation,
19
32
  setRowSelection
20
33
  } from "./parser.js";
34
+ import { strictSchemaValidator } from "./strict-schema.js";
21
35
  import {
22
- hasOnlyCleanupTransforms,
36
+ hasLatin1SpanTransforms,
23
37
  prepareTransforms
24
38
  } from "./transforms.js";
25
39
  const WINDOW_BYTES = 1024;
26
- const MAX_WINDOW_FIELD_BYTES = 64;
27
- var RowStorage;
28
- ((RowStorage) => {
29
- RowStorage[RowStorage.QuotedSpan = 1] = "QuotedSpan";
30
- RowStorage[RowStorage.PackedUtf8 = 2] = "PackedUtf8";
31
- })(RowStorage ||= {});
40
+ const MAX_FIELD_BYTES_FOR_WINDOW_REFILL = 64;
41
+ const MAX_CSTRING_FIELD_BYTES = 24;
32
42
  export function canUseFilteredLatin1Cleanup(columns, filters, transforms) {
33
- return columns === void 0 && filters !== void 0 && hasOnlyCleanupTransforms(transforms) && filters.every((entry) => {
43
+ return columns === void 0 && filters !== void 0 && hasLatin1SpanTransforms(transforms) && filters.every((entry) => {
34
44
  if ("operator" in entry)
35
45
  return entry.operator === "all";
36
46
  const operand = "value" in entry ? entry.value : ("notEquals" in entry) ? entry.notEquals : void 0;
37
47
  return typeof operand === "string" ? Buffer.byteLength(operand) === operand.length : operand !== void 0 && isAscii(operand);
38
48
  });
39
49
  }
40
- export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows, options = {}) {
50
+ export async function* latin1Rows(input, delimiter, columns, filters, createParser, output, options = {}) {
41
51
  if (delimiter === "auto")
42
52
  throw Error("automatic delimiter detection is only supported by file APIs");
43
- if (delimiter.length !== 1)
44
- throw Error("delimiter must be one character");
45
- const parser = createParser(delimiter.charCodeAt(0));
53
+ const validator = strictSchemaValidator(options);
54
+ const separator = delimiterByte(delimiter, "latin1");
55
+ const applyValidation = prepareNativeValidation(options);
56
+ const parser = createParser(separator);
46
57
  if (parser === null)
47
58
  throw Error("failed to create native CSV parser");
48
59
  const lifetime = {};
49
60
  nativeCsvParserFinalizer.register(lifetime, parser, lifetime);
61
+ const arrayOutput = output === void 0 || Array.isArray(output);
62
+ const compactOffsets = arrayOutput && columns === void 0 ? new BigUint64Array(1) : void 0;
63
+ const maxBatchRows = options.maxBatchRows;
64
+ let pipeline;
65
+ const recycle = (batch) => {
66
+ if (pipeline === void 0)
67
+ native.symbols.csv_parser_recycle_batch(parser, batch);
68
+ else
69
+ pipeline.recycle(batch);
70
+ };
71
+ const consume = arrayOutput ? (batch) => {
72
+ try {
73
+ return consumeLatin1Batch(batch, output, compactOffsets?.[0]);
74
+ } finally {
75
+ recycle(batch);
76
+ }
77
+ } : (batch) => {
78
+ const wrapper = new NativeCsvBatch(batch);
79
+ try {
80
+ return wrapper[mappedBatchRows](output, "latin1");
81
+ } finally {
82
+ wrapper[recycleBatch](recycle);
83
+ }
84
+ };
85
+ const consumeSlices = maxBatchRows !== void 0 && output === void 0 && validator === void 0 ? function* (batch, rowCount) {
86
+ const wrapper = new NativeCsvBatch(batch);
87
+ try {
88
+ const count = rowCount ?? wrapper.rowCount;
89
+ if (count === 0)
90
+ return;
91
+ yield* consumeLatin1Slices(batch, count, compactOffsets?.[0], maxBatchRows, () => wrapper[recycleBatch](recycle));
92
+ } finally {
93
+ wrapper[recycleBatch](recycle);
94
+ }
95
+ } : void 0;
50
96
  try {
51
97
  setRowSelection(parser, options);
98
+ applyValidation?.(parser);
52
99
  if (options.transform?.length)
53
100
  prepareTransforms(parser, options.transform, columns);
54
101
  const prepared = prepareNativeParser(parser, columns, filters);
102
+ const validate = validator === void 0 ? void 0 : (final) => validator.validateNative(parser, final, "latin1");
103
+ const checkBatch = (result, final) => {
104
+ const batch = requireLatin1Batch(parser, result);
105
+ try {
106
+ validate?.(final);
107
+ } catch (error) {
108
+ native.symbols.csv_batch_destroy(batch);
109
+ throw error;
110
+ }
111
+ return batch;
112
+ };
113
+ const writeBatch = (bytes, final) => checkBatch(compactOffsets === void 0 ? prepared.writeBatch(bytes, final) : native.symbols.csv_parser_write_prepared_compact_batch(parser, bytes, bytes, final, compactOffsets), final);
55
114
  let remaining = options.limit;
56
- if (remaining === 0)
115
+ if (remaining === 0 && validator === void 0)
57
116
  return;
58
- for await (const chunk of chunks) {
59
- const input = normalizeChunk(chunk);
60
- const batch = prepared.writeBatch(input, !1);
61
- const rows = consumeLatin1Batch(parser, batch, reusableRows);
62
- if (rows.length > 0) {
117
+ if (remaining !== 0) {
118
+ const source = "chunks" in input ? { file: input, cursor: input.chunks()[Symbol.asyncIterator]() } : { file: void 0, chunks: input };
119
+ const chunks = source.file === void 0 ? source.chunks : { [Symbol.asyncIterator]: () => source.cursor };
120
+ let tryPipeline = source.file !== void 0;
121
+ for await (const chunk of chunks) {
122
+ if (tryPipeline && source.file?.canParseAhead) {
123
+ tryPipeline = !1;
124
+ using ahead = BatchPipeline.start(parser, lifetime, compactOffsets);
125
+ if (ahead !== void 0) {
126
+ pipeline = ahead;
127
+ const finishAtLimit = validate === void 0 ? void 0 : () => native.symbols.csv_batch_destroy(writeBatch(EMPTY_BUFFER, !0));
128
+ for await (const batch of ahead.batches(source.cursor, chunk, remaining, validate, finishAtLimit))
129
+ if (consumeSlices !== void 0)
130
+ yield* consumeSlices(batch);
131
+ else {
132
+ const rows = consume(batch);
133
+ if (maxBatchRows !== void 0 && rows.length > maxBatchRows)
134
+ yield* sliceRowBatch(rows, maxBatchRows);
135
+ else
136
+ yield rows;
137
+ }
138
+ return;
139
+ }
140
+ }
141
+ const batch = writeBatch(normalizeChunk(chunk), !1);
142
+ if (consumeSlices !== void 0) {
143
+ if (remaining === void 0)
144
+ yield* consumeSlices(batch);
145
+ else {
146
+ let rowCount;
147
+ try {
148
+ rowCount = u64ToSafeNumber(native.symbols.csv_batch_row_count(batch), "CSV batch row count");
149
+ } catch (error) {
150
+ recycle(batch);
151
+ throw error;
152
+ }
153
+ remaining -= rowCount;
154
+ yield* consumeSlices(batch, rowCount);
155
+ if (remaining === 0)
156
+ return;
157
+ }
158
+ continue;
159
+ }
160
+ const rows = consume(batch);
161
+ if (rows.length === 0)
162
+ continue;
63
163
  if (remaining !== void 0)
64
164
  remaining -= rows.length;
65
- yield rows;
165
+ if (remaining === 0 && validator !== void 0)
166
+ native.symbols.csv_batch_destroy(writeBatch(EMPTY_BUFFER, !0));
167
+ if (maxBatchRows !== void 0 && rows.length > maxBatchRows)
168
+ yield* sliceRowBatch(rows, maxBatchRows);
169
+ else
170
+ yield rows;
66
171
  if (remaining === 0)
67
172
  return;
68
173
  }
69
174
  }
70
- const batch = prepared.writeBatch(EMPTY_BUFFER, !0);
71
- const rows = consumeLatin1Batch(parser, batch, reusableRows);
72
- if (rows.length > 0)
73
- yield rows;
175
+ const batch = writeBatch(EMPTY_BUFFER, !0);
176
+ if (consumeSlices !== void 0)
177
+ yield* consumeSlices(batch);
178
+ else {
179
+ const rows = consume(batch);
180
+ if (maxBatchRows !== void 0 && rows.length > maxBatchRows)
181
+ yield* sliceRowBatch(rows, maxBatchRows);
182
+ else if (rows.length > 0)
183
+ yield rows;
184
+ }
74
185
  } finally {
75
186
  nativeCsvParserFinalizer.unregister(lifetime);
76
187
  native.symbols.csv_parser_destroy(parser);
77
188
  }
78
189
  }
79
- function consumeLatin1Batch(parser, batch, reusableRows) {
190
+ function requireLatin1Batch(parser, batch) {
80
191
  if (batch === null)
81
192
  throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(parser) ?? "native parser error unavailable"}`);
82
- try {
83
- const rowCount = u64ToSafeNumber(native.symbols.csv_batch_row_count(batch), "CSV batch row count");
84
- if (rowCount === 0)
85
- return [];
86
- const totalFields = u64ToSafeNumber(native.symbols.csv_batch_total_fields(batch), "CSV batch field count");
87
- const dataLength = u64ToSafeNumber(native.symbols.csv_batch_data_len(batch), "CSV batch data length");
88
- const data = dataLength === 0 ? EMPTY_BUFFER : new Uint8Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_data_ptr(batch)), 0, dataLength));
89
- const bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
90
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
91
- const rowOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_row_offsets_ptr(batch)), 0, (rowCount + 1) * 8));
92
- const fieldOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_field_offsets_ptr(batch)), 0, (totalFields + 1) * 8));
93
- const flags = native.symbols.csv_batch_quoted_rows_ptr(batch);
94
- const quotedRows = flags === null ? void 0 : new Uint8Array(toArrayBuffer(flags, 0, rowCount));
95
- const rows = reusableRows ?? [];
96
- rows.length = rowCount;
97
- let fieldStart = checkedOffset(rowOffsets, 0, totalFields);
98
- let start = checkedOffset(fieldOffsets, fieldStart, dataLength);
99
- let windowStart = 0;
100
- let windowEnd = 0;
101
- let text = "";
102
- for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
193
+ return batch;
194
+ }
195
+ function consumeLatin1Batch(batch, reusableRows, compactOffsets) {
196
+ const rowCount = u64ToSafeNumber(native.symbols.csv_batch_row_count(batch), "CSV batch row count");
197
+ if (rowCount === 0)
198
+ return [];
199
+ const totalFields = u64ToSafeNumber(native.symbols.csv_batch_total_fields(batch), "CSV batch field count");
200
+ const dataLength = u64ToSafeNumber(native.symbols.csv_batch_data_len(batch), "CSV batch data length");
201
+ const dataPointer = dataLength === 0 ? null : requirePtr(native.symbols.csv_batch_data_ptr(batch));
202
+ const bytes = dataPointer === null ? Buffer.alloc(0) : Buffer.from(toArrayBuffer(dataPointer, 0, dataLength));
203
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
204
+ const rowOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_row_offsets_ptr(batch)), 0, (rowCount + 1) * 8));
205
+ const compact = compactOffsets !== void 0 && compactOffsets !== 0n;
206
+ const offsetWords = compact ? 1 : 2;
207
+ const offsetPointer = compact ? compactOffsets : requirePtr(native.symbols.csv_batch_field_offsets_ptr(batch));
208
+ const fieldOffsets = new Uint32Array(toArrayBuffer(offsetPointer, 0, (totalFields + 1) * offsetWords * 4));
209
+ const flags = native.symbols.csv_batch_quoted_rows_ptr(batch);
210
+ const quotedRows = flags === null ? void 0 : new Uint8Array(toArrayBuffer(flags, 0, rowCount));
211
+ const rows = reusableRows ?? Array(rowCount);
212
+ if (reusableRows !== void 0)
213
+ reusableRows.length = rowCount;
214
+ let fieldIndex = checkedOffset(rowOffsets, 0, totalFields);
215
+ let start = checkedOffset(fieldOffsets, fieldIndex, dataLength, offsetWords);
216
+ let windowStart = 0;
217
+ let text = "";
218
+ for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
219
+ const fieldEnd = checkedOffset(rowOffsets, rowIndex + 1, totalFields);
220
+ const storage = quotedRows?.[rowIndex] ?? 0;
221
+ const width = fieldEnd - fieldIndex;
222
+ const existing = reusableRows?.[rowIndex];
223
+ const row = existing === void 0 ? prepareRow(void 0, width) : existing;
224
+ if (row.length !== width)
225
+ row.length = width;
226
+ if (storage === RowStorage.PackedUtf8) {
227
+ for (let column = 0;column < width; ++column) {
228
+ const end = checkedOffset(fieldOffsets, ++fieldIndex, dataLength, offsetWords);
229
+ if (end < start)
230
+ throw RangeError("CSV field span exceeds its backing range");
231
+ const length = end - start;
232
+ row[column] = dataPointer !== null && length >= 3 && length <= MAX_CSTRING_FIELD_BYTES ? new CString(dataPointer, start, length) : decodeMaterializedField(bytes, start, end, "utf8");
233
+ start = end;
234
+ }
235
+ if (existing === void 0)
236
+ rows[rowIndex] = row;
237
+ continue;
238
+ }
239
+ const leading = storage === RowStorage.QuotedSpan ? 1 : 0;
240
+ const padding = leading * 3;
241
+ for (let column = 0;column < width; ++column) {
242
+ const end = checkedOffset(fieldOffsets, ++fieldIndex, dataLength, offsetWords);
243
+ const payload = start + leading;
244
+ const length = end - start - padding;
245
+ start = end;
246
+ switch (length) {
247
+ case 0:
248
+ row[column] = "";
249
+ break;
250
+ case 1:
251
+ row[column] = String.fromCharCode(view.getUint8(payload));
252
+ break;
253
+ case 2:
254
+ row[column] = latin1Pair(view.getUint16(payload, !0));
255
+ break;
256
+ default: {
257
+ if (length < 0)
258
+ throw RangeError("CSV field span exceeds its backing range");
259
+ const relative = payload - windowStart;
260
+ if (length > MAX_FIELD_BYTES_FOR_WINDOW_REFILL) {
261
+ row[column] = relative + length <= text.length ? text.slice(relative, relative + length) : copyLatin1Range(bytes, payload, payload + length);
262
+ break;
263
+ }
264
+ if (relative + length <= text.length)
265
+ row[column] = text.slice(relative, relative + length);
266
+ else {
267
+ windowStart = payload;
268
+ text = copyLatin1Range(bytes, payload, Math.min(payload + WINDOW_BYTES, dataLength));
269
+ row[column] = text.slice(0, length);
270
+ }
271
+ }
272
+ }
273
+ }
274
+ if (existing === void 0)
275
+ rows[rowIndex] = row;
276
+ }
277
+ return rows;
278
+ }
279
+ function* consumeLatin1Slices(batch, rowCount, compactOffsets, yieldRows, release) {
280
+ const totalFields = u64ToSafeNumber(native.symbols.csv_batch_total_fields(batch), "CSV batch field count");
281
+ const dataLength = u64ToSafeNumber(native.symbols.csv_batch_data_len(batch), "CSV batch data length");
282
+ const dataPointer = dataLength === 0 ? null : requirePtr(native.symbols.csv_batch_data_ptr(batch));
283
+ const bytes = dataPointer === null ? Buffer.alloc(0) : Buffer.from(toArrayBuffer(dataPointer, 0, dataLength));
284
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
285
+ const rowOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_row_offsets_ptr(batch)), 0, (rowCount + 1) * 8));
286
+ const compact = compactOffsets !== void 0 && compactOffsets !== 0n;
287
+ const offsetWords = compact ? 1 : 2;
288
+ const offsetPointer = compact ? compactOffsets : requirePtr(native.symbols.csv_batch_field_offsets_ptr(batch));
289
+ const fieldOffsets = new Uint32Array(toArrayBuffer(offsetPointer, 0, (totalFields + 1) * offsetWords * 4));
290
+ const flags = native.symbols.csv_batch_quoted_rows_ptr(batch);
291
+ const quotedRows = flags === null ? void 0 : new Uint8Array(toArrayBuffer(flags, 0, rowCount));
292
+ let fieldIndex = checkedOffset(rowOffsets, 0, totalFields);
293
+ let start = checkedOffset(fieldOffsets, fieldIndex, dataLength, offsetWords);
294
+ let windowStart = 0;
295
+ let text = "";
296
+ for (let first = 0;first < rowCount; first += yieldRows) {
297
+ const stop = Math.min(first + yieldRows, rowCount);
298
+ const rows = Array(stop - first);
299
+ for (let rowIndex = first;rowIndex < stop; ++rowIndex) {
103
300
  const fieldEnd = checkedOffset(rowOffsets, rowIndex + 1, totalFields);
104
301
  const storage = quotedRows?.[rowIndex] ?? 0;
105
- const width = fieldEnd - fieldStart;
106
- const row = prepareRow(reusableRows?.[rowIndex], width);
107
- if (storage === 2 /* PackedUtf8 */) {
302
+ const width = fieldEnd - fieldIndex;
303
+ const row = prepareRow(void 0, width);
304
+ if (storage === RowStorage.PackedUtf8) {
108
305
  for (let column = 0;column < width; ++column) {
109
- const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
110
- row[column] = decodeMaterializedField(bytes, start, end, "utf8");
306
+ const end = checkedOffset(fieldOffsets, ++fieldIndex, dataLength, offsetWords);
307
+ if (end < start)
308
+ throw RangeError("CSV field span exceeds its backing range");
309
+ const length = end - start;
310
+ row[column] = dataPointer !== null && length >= 3 && length <= MAX_CSTRING_FIELD_BYTES ? new CString(dataPointer, start, length) : decodeMaterializedField(bytes, start, end, "utf8");
111
311
  start = end;
112
312
  }
113
- rows[rowIndex] = row;
114
- fieldStart = fieldEnd;
313
+ rows[rowIndex - first] = row;
115
314
  continue;
116
315
  }
117
- const leading = storage === 1 /* QuotedSpan */ ? 1 : 0;
118
- const trailing = leading * 2;
316
+ const leading = storage === RowStorage.QuotedSpan ? 1 : 0;
317
+ const padding = leading * 3;
119
318
  for (let column = 0;column < width; ++column) {
120
- const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
319
+ const end = checkedOffset(fieldOffsets, ++fieldIndex, dataLength, offsetWords);
121
320
  const payload = start + leading;
122
- const payloadEnd = end - trailing;
123
- const length = payloadEnd - payload;
321
+ const length = end - start - padding;
322
+ start = end;
124
323
  switch (length) {
125
324
  case 0:
126
325
  row[column] = "";
@@ -131,33 +330,35 @@ function consumeLatin1Batch(parser, batch, reusableRows) {
131
330
  case 2:
132
331
  row[column] = latin1Pair(view.getUint16(payload, !0));
133
332
  break;
134
- default:
333
+ default: {
135
334
  if (length < 0)
136
335
  throw RangeError("CSV field span exceeds its backing range");
137
- if (length > MAX_WINDOW_FIELD_BYTES) {
138
- row[column] = copyLatin1Range(bytes, payload, payloadEnd);
336
+ const relative = payload - windowStart;
337
+ if (length > MAX_FIELD_BYTES_FOR_WINDOW_REFILL) {
338
+ row[column] = relative + length <= text.length ? text.slice(relative, relative + length) : copyLatin1Range(bytes, payload, payload + length);
139
339
  break;
140
340
  }
141
- if (payloadEnd > windowEnd) {
341
+ if (relative + length <= text.length)
342
+ row[column] = text.slice(relative, relative + length);
343
+ else {
142
344
  windowStart = payload;
143
- windowEnd = Math.min(payload + WINDOW_BYTES, dataLength);
144
- text = copyLatin1Range(bytes, windowStart, windowEnd);
345
+ text = copyLatin1Range(bytes, payload, Math.min(payload + WINDOW_BYTES, dataLength));
346
+ row[column] = text.slice(0, length);
145
347
  }
146
- row[column] = text.slice(payload - windowStart, payloadEnd - windowStart);
348
+ }
147
349
  }
148
- start = end;
149
350
  }
150
- rows[rowIndex] = row;
151
- fieldStart = fieldEnd;
351
+ rows[rowIndex - first] = row;
152
352
  }
153
- return rows;
154
- } finally {
155
- native.symbols.csv_batch_destroy(batch);
353
+ if (stop === rowCount)
354
+ release();
355
+ yield rows;
156
356
  }
157
357
  }
158
- export function checkedOffset(words, index, upperBound) {
159
- const low = words[index * 2];
160
- const high = words[index * 2 + 1];
358
+ export function checkedOffset(words, index, upperBound, wordsPerOffset = 2) {
359
+ const word = index * wordsPerOffset;
360
+ const low = words[word];
361
+ const high = wordsPerOffset === 1 ? 0 : words[word + 1];
161
362
  if (low !== void 0 && high === 0 && low <= upperBound)
162
363
  return low;
163
364
  return checkedWideOffset(low, high, upperBound);
@@ -1,4 +1,10 @@
1
+ import type { CsvMappedRow, CsvRow } from './types.js';
2
+ export declare enum RowStorage {
3
+ QuotedSpan = 1,
4
+ PackedUtf8 = 2
5
+ }
1
6
  export declare function prepareRow(row: string[] | undefined, width: number): string[];
7
+ export declare function sliceRowBatch(rows: CsvRow[] | CsvMappedRow[], maxBatchRows: number): Generator<CsvRow[] | CsvMappedRow[], void>;
2
8
  export declare function latin1Pair(key: number): string;
3
9
  export declare function copyLatin1Range(data: Buffer, start: number, end: number): string;
4
10
  export declare function decodeMaterializedField(data: Buffer, start: number, end: number, encoding: 'utf8' | 'latin1'): string;
@@ -3,12 +3,21 @@ const bufferPrototype = Buffer.prototype;
3
3
  const latin1Slice = bufferPrototype.latin1Slice;
4
4
  const utf8Slice = bufferPrototype.utf8Slice;
5
5
  const LATIN1_PAIRS = Array.from({ length: 65536 });
6
+ export var RowStorage;
7
+ ((RowStorage) => {
8
+ RowStorage[RowStorage.QuotedSpan = 1] = "QuotedSpan";
9
+ RowStorage[RowStorage.PackedUtf8 = 2] = "PackedUtf8";
10
+ })(RowStorage ||= {});
6
11
  export function prepareRow(row, width) {
7
12
  if (row === void 0)
8
13
  return Array(width);
9
14
  row.length = width;
10
15
  return row;
11
16
  }
17
+ export function* sliceRowBatch(rows, maxBatchRows) {
18
+ for (let first = 0;first < rows.length; first += maxBatchRows)
19
+ yield rows.slice(first, first + maxBatchRows);
20
+ }
12
21
  export function latin1Pair(key) {
13
22
  const cached = LATIN1_PAIRS[key];
14
23
  if (cached !== void 0)