@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
package/dist/api.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import {
2
+ mappedBatchRows,
3
+ utf8BatchSlices
4
+ } from "./batches.js";
5
+ import {
6
+ detectBufferDelimiter,
2
7
  prepareCsvFileInput,
3
- rejectAutoDelimiterSharding,
4
8
  rejectCompressedSharding
5
9
  } from "./file-stream.js";
6
10
  import {
@@ -19,8 +23,12 @@ import {
19
23
  canUseFilteredLatin1Cleanup,
20
24
  latin1Rows
21
25
  } from "./latin1-rows.js";
26
+ import { sliceRowBatch } from "./materialize-field.js";
22
27
  import { latin1RowsParser } from "./native.js";
23
28
  import {
29
+ MAX_COLUMN_INDEX,
30
+ MAX_PROJECTION_LENGTH,
31
+ normalizeColumns,
24
32
  normalizeFixedColumnsCount,
25
33
  prepareCsvBufferInput,
26
34
  resolveInputEncoding
@@ -31,52 +39,177 @@ import {
31
39
  createPreparedParser,
32
40
  parseFileChunks,
33
41
  parseRawRecordChunks,
42
+ parseUtf8RowBatches,
43
+ readCsvHeader,
34
44
  validateRowSelection
35
45
  } from "./parser.js";
36
- import { rejectStrictSchemaUnsupported } from "./strict-schema.js";
46
+ import { strictSchemaValidator } from "./strict-schema.js";
37
47
  import { transform } from "./transforms.js";
38
48
  export async function parse(buffer, suppliedOptions = {}) {
39
49
  const options = snapshotCsvOptions(suppliedOptions);
40
50
  if ("compression" in options && options.compression !== void 0)
41
51
  throw Error("parse() does not support compression; pass decompressed bytes or use a file API");
42
- if (options.delimiter === "auto")
43
- throw Error("parse() does not support automatic delimiter detection; specify delimiter or use a file API");
44
- rejectFilteredStrictSchema(options);
45
52
  const filters = toNativeFilters(options.where);
46
53
  const columns = options.columns;
47
- const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
54
+ const projected = filters !== void 0 || columns !== void 0;
48
55
  const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
49
- using parser = createPreparedParser(toParserOptions(options, input.parserEncoding), projected ? columns : void 0, filters, options.transform);
50
- return consumeBatchRows(parser.writeBatch(input.bytes, !0), columns, projected);
56
+ const delimiter = options.delimiter === void 0 || options.delimiter === "auto" ? detectBufferDelimiter(input.bytes, "", !0, options) : options.delimiter;
57
+ using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, delimiter), projected ? columns : void 0, filters, options.transform);
58
+ return consumeBatchRows(parser.writeBatch(input.bytes, !0));
51
59
  }
52
60
  export function rows(path, options = {}) {
53
- return iterateRows(path, snapshotCsvOptions(options));
61
+ if (options.mapped !== void 0 && typeof options.mapped !== "boolean")
62
+ throw TypeError("mapped must be a boolean");
63
+ if (options.mapped === !0 && options.headers === void 0)
64
+ throw TypeError("mapped rows require headers");
65
+ const maxBatchRows = options.maxBatchRows;
66
+ if (maxBatchRows !== void 0) {
67
+ if (!Number.isSafeInteger(maxBatchRows) || maxBatchRows < 1)
68
+ throw RangeError("maxBatchRows must be a positive safe integer");
69
+ if (options.reuseArrays === !0)
70
+ throw TypeError("maxBatchRows requires owned rows");
71
+ }
72
+ return options.headers === void 0 ? iterateRows(path, snapshotCsvOptions(options)) : rowsWithHeaders(path, options);
73
+ }
74
+ function rowsWithHeaders(path, supplied) {
75
+ const { headers, columns, mapped, where, transform, ...fileOptions } = supplied;
76
+ if (mapped === !0 && fileOptions.reuseArrays === !0)
77
+ throw TypeError("reuseArrays requires array rows");
78
+ if (columns !== void 0 && !Array.isArray(columns))
79
+ throw TypeError("columns must be an array of header names");
80
+ if (columns !== void 0 && columns.length > MAX_PROJECTION_LENGTH)
81
+ throw RangeError(`selected column count out of range: ${columns.length}`);
82
+ const selected = columns === void 0 ? void 0 : [...columns];
83
+ if (selected !== void 0 && new Set(selected).size !== selected.length)
84
+ throw RangeError("selected header names must be unique");
85
+ if (headers === !0) {
86
+ const options = snapshotCsvOptions({
87
+ ...fileOptions,
88
+ where: typeof where === "function" ? void 0 : where,
89
+ transform: typeof transform === "function" ? void 0 : transform
90
+ });
91
+ return iterateRowsWithReadHeader(path, options, {
92
+ columns: selected,
93
+ mapped,
94
+ where: typeof where === "function" ? where : options.where,
95
+ transform: typeof transform === "function" ? transform : options.transform
96
+ });
97
+ }
98
+ const { options, layout } = bindNamedRows(fileOptions, headers, { columns: selected, mapped, where, transform });
99
+ return layout === void 0 ? iterateRows(path, options) : iterateRows(path, options, void 0, layout);
100
+ }
101
+ function bindNamedRows(fileOptions, names, { columns: selected, mapped, where, transform }) {
102
+ const resolve = headerIndexes(names);
103
+ const physicalColumns = selected?.map(resolve);
104
+ const keys = mapped === !0 ? selected ?? [...names] : void 0;
105
+ const namedColumn = (name) => column(resolve(name));
106
+ const filter = bindNamedFilter(where, namedColumn);
107
+ const transforms = typeof transform === "function" ? transform(namedColumn) : transform;
108
+ if (typeof transform === "function" && transforms === void 0)
109
+ throw TypeError("transform callback must return an array of column transforms");
110
+ const options = snapshotCsvOptions({
111
+ ...fileOptions,
112
+ columns: physicalColumns,
113
+ where: filter,
114
+ transform: transforms
115
+ });
116
+ if (keys === void 0)
117
+ return { options };
118
+ const template = keys.includes("__proto__") ? Object.fromEntries(keys.map((name) => [name, ""])) : void 0;
119
+ return { options, layout: { keys, template } };
54
120
  }
55
- export async function* iterateRows(path, options, probeFormat) {
56
- rejectFilteredStrictSchema(options);
121
+ function headerIndexes(names) {
122
+ if (!Array.isArray(names))
123
+ throw TypeError("headers must be an array of strings or true");
124
+ if (names.length > MAX_COLUMN_INDEX + 1)
125
+ throw RangeError(`header count out of range: ${names.length}`);
126
+ const indexes = new Map;
127
+ for (const [index, name] of names.entries()) {
128
+ if (typeof name !== "string")
129
+ throw TypeError(`header at index ${index} must be a string`);
130
+ if (indexes.has(name))
131
+ throw RangeError(`duplicate header: ${JSON.stringify(name)}`);
132
+ indexes.set(name, index);
133
+ }
134
+ return (name) => {
135
+ if (typeof name !== "string")
136
+ throw TypeError("column name must be a string");
137
+ const index = indexes.get(name);
138
+ if (index === void 0)
139
+ throw RangeError(`unknown header: ${JSON.stringify(name)}`);
140
+ return index;
141
+ };
142
+ }
143
+ function bindNamedFilter(where, namedColumn) {
144
+ if (typeof where !== "function")
145
+ return where;
146
+ const filter = where(namedColumn);
147
+ if (filter === void 0)
148
+ throw TypeError("where callback must return a filter");
149
+ return filter;
150
+ }
151
+ async function prepareInputWithReadHeader(path, options, mode, resources) {
152
+ validateRowSelection(options);
153
+ const input = resources.use(await prepareCsvFileInput(path, options, mode));
154
+ const { names, record } = await input.readPrefix((next) => readCsvHeader(next, toParserOptions(options, input.parserEncoding, input.delimiter)));
155
+ return { input, names, skipRows: Math.max(record, options.skipRows ?? 0) };
156
+ }
157
+ async function* iterateRowsWithReadHeader(path, fileOptions, bindings) {
158
+ await using resources = new AsyncDisposableStack;
159
+ const { input, names, skipRows } = await prepareInputWithReadHeader(path, fileOptions, "read-ahead", resources);
160
+ const { options, layout } = bindNamedRows({ ...fileOptions, skipRows }, names, bindings);
161
+ const filters = toNativeFilters(options.where);
162
+ if (options.limit === 0) {
163
+ strictSchemaValidator(options)?.finish(1);
164
+ return;
165
+ }
166
+ yield* iteratePreparedRows(input, options, filters, layout);
167
+ }
168
+ export async function* iterateRows(path, options, probeFormat, layout) {
57
169
  const filters = toNativeFilters(options.where);
58
- const columns = options.columns;
59
- const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
60
170
  await using input = await prepareCsvFileInput(path, options, "read-ahead", probeFormat);
171
+ yield* iteratePreparedRows(input, options, filters, layout);
172
+ }
173
+ async function* iteratePreparedRows(input, options, filters, layout) {
174
+ const columns = options.columns;
175
+ const projected = filters !== void 0 || columns !== void 0;
61
176
  const reusableRows = options.reuseArrays === !0 ? [] : void 0;
62
- if (options.strict !== !0 && input.parserEncoding === "latin1" && options.quote !== !1 && options.recordDelimiter === void 0 && (!options.transform?.length || canUseFilteredLatin1Cleanup(columns, filters, options.transform))) {
177
+ const transforms = options.transform;
178
+ if (input.parserEncoding === "latin1" && options.quote !== !1 && options.recordDelimiter === void 0 && (!transforms?.length || options.strict !== !0 && options.maxRecordBytes === void 0 && canUseFilteredLatin1Cleanup(columns, filters, transforms))) {
63
179
  validateRowSelection(options);
64
180
  const fixedColumns = normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
65
- const createParser = latin1RowsParser(fixedColumns, Boolean(options.transform?.length));
66
- const chunks = options.limit === 0 ? [] : input.chunks();
67
- yield* latin1Rows(chunks, input.delimiter, columns, filters, createParser, reusableRows, options);
181
+ const createParser = latin1RowsParser(fixedColumns, Boolean(transforms?.length));
182
+ if (layout === void 0)
183
+ yield* latin1Rows(input, input.delimiter, columns, filters, createParser, reusableRows, options);
184
+ else
185
+ yield* latin1Rows(input, input.delimiter, columns, filters, createParser, layout, options);
68
186
  return;
69
187
  }
70
188
  const parserOptions = toParserOptions(options, input.parserEncoding, input.delimiter);
71
- using parser = createPreparedParser(parserOptions, projected ? columns : void 0, filters, options.transform, "rows");
72
- for await (const batch of parseFileChunks(input, parser, options.limit))
73
- yield consumeBatchRows(batch, columns, projected, reusableRows);
189
+ const canPipeline = input.parserEncoding === "utf8" && input.canParseAhead !== void 0;
190
+ using parser = createPreparedParser(parserOptions, projected ? columns : void 0, filters, transforms, canPipeline ? "pipelined-rows" : "rows");
191
+ const batches = canPipeline ? parseUtf8RowBatches(input, parser, options.limit) : parseFileChunks(input, parser, options.limit);
192
+ const maxBatchRows = options.maxBatchRows;
193
+ for await (const batch of batches) {
194
+ let rows;
195
+ {
196
+ using nativeBatch = batch;
197
+ if (maxBatchRows !== void 0 && input.parserEncoding === "utf8" && nativeBatch.rowCount > maxBatchRows) {
198
+ yield* nativeBatch[utf8BatchSlices](maxBatchRows, layout);
199
+ continue;
200
+ }
201
+ rows = layout === void 0 ? nativeBatch.rowsInto(reusableRows ?? []) : nativeBatch[mappedBatchRows](layout, "utf8");
202
+ }
203
+ if (maxBatchRows !== void 0 && rows.length > maxBatchRows)
204
+ yield* sliceRowBatch(rows, maxBatchRows);
205
+ else
206
+ yield rows;
207
+ }
74
208
  }
75
209
  export function batches(path, options = {}) {
76
210
  return iterateBatches(path, snapshotCsvOptions(options));
77
211
  }
78
212
  async function* iterateBatches(path, options) {
79
- rejectFilteredStrictSchema(options);
80
213
  const filters = toNativeFilters(options.where);
81
214
  const { columns, encoding: requestedEncoding, strict, transform } = options;
82
215
  if (options.output === "raw-records") {
@@ -88,42 +221,62 @@ async function* iterateBatches(path, options) {
88
221
  const encoding = requestedEncoding === "auto" ? void 0 : resolveInputEncoding(requestedEncoding);
89
222
  if (typeof encoding !== "string")
90
223
  throw TypeError("raw-records output requires a native UTF-8 or Latin-1 encoding");
91
- await using input = await prepareCsvFileInput(path, { ...options, encoding });
224
+ await using input = await prepareCsvFileInput(path, { ...options, encoding }, "raw-records");
92
225
  yield* parseRawRecordChunks(input, toParserOptions(options, input.parserEncoding, input.delimiter), filters);
93
226
  return;
94
227
  }
95
228
  if (options.output !== void 0 && options.output !== "fields")
96
229
  throw TypeError("output must be fields or raw-records");
97
- if (options.strict === !0 && columns !== void 0)
98
- throw Error("strict CSV validation is not supported for projected batches; use csv.rows() for strict projection");
99
- await using input = await prepareCsvFileInput(path, options);
230
+ await using input = await prepareCsvFileInput(path, options, "batches");
100
231
  using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), columns, filters, options.transform);
101
232
  yield* parseFileChunks(input, parser, options.limit);
102
233
  }
103
234
  export async function count(path, suppliedOptions = {}) {
104
- const options = snapshotCsvOptions(suppliedOptions);
235
+ if (suppliedOptions.headers === !0) {
236
+ const { headers: _headers, where, ...fileOptions } = suppliedOptions;
237
+ const options = snapshotCsvOptions({ ...fileOptions, where: typeof where === "function" ? void 0 : where });
238
+ await using resources = new AsyncDisposableStack;
239
+ const { input, names, skipRows } = await prepareInputWithReadHeader(path, options, "count", resources);
240
+ const resolve = headerIndexes(names);
241
+ const filter = bindNamedFilter(where, (name) => column(resolve(name)));
242
+ const filters = toNativeFilters(filter);
243
+ if (options.limit === 0) {
244
+ normalizeColumns(options.columns);
245
+ strictSchemaValidator(options)?.finish(1);
246
+ return 0;
247
+ }
248
+ return await countFileChunks(input, toParserOptions({ ...options, skipRows }, input.parserEncoding, input.delimiter), filters);
249
+ }
250
+ let options;
251
+ if (suppliedOptions.headers === void 0)
252
+ options = snapshotCsvOptions(suppliedOptions);
253
+ else {
254
+ const { headers, where, ...fileOptions } = suppliedOptions;
255
+ const resolve = headerIndexes(headers);
256
+ options = snapshotCsvOptions({ ...fileOptions, where: bindNamedFilter(where, (name) => column(resolve(name))) });
257
+ }
105
258
  const filters = toNativeFilters(options.where);
106
259
  await using input = await prepareCsvFileInput(path, options, "count");
107
- if (options.strict === !0 && filters !== void 0)
108
- throw Error("strict CSV validation is not supported for count filters");
109
260
  return await countFileChunks(input, toParserOptions(options, input.parserEncoding, input.delimiter), filters);
110
261
  }
111
262
  function findCsvSafeSplitOffsets(path, shardCount, suppliedOptions = {}) {
112
263
  const options = snapshotCsvOptions(suppliedOptions);
113
- return findCsvSafeSplitOffsetsNative(path, shardCount, shardingDelimiter(options, "CSV split offset scanning"));
264
+ const encoding = shardingEncoding(options, "CSV split offset scanning");
265
+ return findCsvSafeSplitOffsetsNative(path, shardCount, options.delimiter, encoding);
114
266
  }
115
267
  function findCsvSafeShards(path, shardCount, suppliedOptions = {}) {
116
268
  const options = snapshotCsvOptions(suppliedOptions);
117
- return findCsvSafeShardsNative(path, shardCount, shardingDelimiter(options, "CSV shard scanning"));
269
+ const encoding = shardingEncoding(options, "CSV shard scanning");
270
+ return findCsvSafeShardsNative(path, shardCount, options.delimiter, encoding);
118
271
  }
119
- function shardingDelimiter(options, operation) {
272
+ function shardingEncoding(options, operation) {
120
273
  rejectCompressedSharding(options, operation);
121
- rejectAutoDelimiterSharding(options, operation);
122
274
  if ("quote" in options && options.quote === !1 || "recordDelimiter" in options && options.recordDelimiter !== void 0)
123
275
  throw Error(`${operation} requires the default quote and record delimiter settings`);
124
- if (typeof resolveInputEncoding(options.encoding) !== "string")
276
+ const encoding = resolveInputEncoding(options.encoding);
277
+ if (typeof encoding !== "string")
125
278
  throw Error(`${operation} requires a native UTF-8 or Latin-1 encoding because offsets refer to the source file`);
126
- return options.delimiter ?? ",";
279
+ return encoding;
127
280
  }
128
281
  export const csv = {
129
282
  transform,
@@ -148,20 +301,18 @@ function toParserOptions(options, encoding, delimiter = options.delimiter) {
148
301
  strict: options.strict,
149
302
  columns: options.columns,
150
303
  fixedColumns: options.fixedColumns,
304
+ maxRecordBytes: options.maxRecordBytes,
151
305
  skipRows: options.skipRows,
306
+ skipEmptyLines: options.skipEmptyLines,
152
307
  limit: options.limit,
153
308
  expectedHeaders: options.expectedHeaders,
154
309
  requireHeader: options.requireHeader,
155
310
  minDataRows: options.minDataRows
156
311
  };
157
312
  }
158
- function consumeBatchRows(nativeBatch, columns, projected, target = []) {
313
+ function consumeBatchRows(nativeBatch) {
159
314
  using batch = nativeBatch;
160
- return batch.rowsInto(target, projected ? void 0 : columns);
161
- }
162
- function rejectFilteredStrictSchema(options) {
163
- if (options.where !== void 0)
164
- rejectStrictSchemaUnsupported(options, "filtered rows");
315
+ return batch.rows();
165
316
  }
166
317
  function toNativeFilters(where) {
167
318
  return nativeFilterProgramFor(where);
@@ -0,0 +1,10 @@
1
+ import { type NativePointer } from './native.js';
2
+ export declare class BatchPipeline implements Disposable {
3
+ #private;
4
+ static start(parser: NativePointer, owner: object, compactOffsets?: BigUint64Array): BatchPipeline | undefined;
5
+ private constructor();
6
+ readonly recycle: (batch: NativePointer) => void;
7
+ /** Transfers ownership of each nonempty batch to the caller. */
8
+ batches(chunks: AsyncIterator<Uint8Array, void>, first: Uint8Array, remaining: number | undefined, validate: ((final: boolean) => void) | undefined, finishAtLimit: (() => void) | undefined): AsyncGenerator<NativePointer, void>;
9
+ [Symbol.dispose](): void;
10
+ }
@@ -0,0 +1,83 @@
1
+ import {
2
+ EMPTY_BUFFER,
3
+ native,
4
+ u64ToSafeNumber
5
+ } from "./native.js";
6
+ import { normalizeChunk } from "./normalize.js";
7
+ function closePipeline(lifetime) {
8
+ native.symbols.csv_parser_batch_pipeline_destroy(lifetime.handle);
9
+ lifetime.input = void 0;
10
+ }
11
+ const finalizer = new FinalizationRegistry(closePipeline);
12
+
13
+ export class BatchPipeline {
14
+ #lifetime;
15
+ #offsets;
16
+ #parser;
17
+ static start(parser, owner, compactOffsets) {
18
+ const offsets = compactOffsets ?? new BigUint64Array(1);
19
+ const handle = native.symbols.csv_parser_batch_pipeline_start(parser, compactOffsets !== void 0);
20
+ return handle === null ? void 0 : new BatchPipeline(handle, parser, owner, offsets);
21
+ }
22
+ constructor(handle, parser, owner, offsets) {
23
+ this.#lifetime = { handle, parserOwner: owner, input: void 0 };
24
+ this.#offsets = offsets;
25
+ this.#parser = parser;
26
+ finalizer.register(this, this.#lifetime, this);
27
+ }
28
+ recycle = (batch) => {
29
+ native.symbols.csv_parser_batch_pipeline_recycle(this.#lifetime.handle, batch);
30
+ };
31
+ #submit(input, final) {
32
+ const bytes = normalizeChunk(input);
33
+ if (!native.symbols.csv_parser_batch_pipeline_submit(this.#lifetime.handle, bytes, bytes, final))
34
+ throw Error("failed to submit the next native CSV batch");
35
+ this.#lifetime.input = bytes;
36
+ }
37
+ async* batches(chunks, first, remaining, validate, finishAtLimit) {
38
+ let final = !1;
39
+ this.#submit(first, final);
40
+ while (!0) {
41
+ const lastWrite = final;
42
+ const batch = native.symbols.csv_parser_batch_pipeline_take(this.#lifetime.handle, this.#offsets);
43
+ this.#lifetime.input = void 0;
44
+ if (batch === null)
45
+ throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(this.#parser) ?? "native parser error unavailable"}`);
46
+ let rowCount;
47
+ let atLimit;
48
+ try {
49
+ validate?.(lastWrite);
50
+ rowCount = u64ToSafeNumber(native.symbols.csv_batch_row_count(batch), "CSV batch row count");
51
+ atLimit = remaining === rowCount;
52
+ if (atLimit && !lastWrite)
53
+ finishAtLimit?.();
54
+ } catch (error) {
55
+ native.symbols.csv_batch_destroy(batch);
56
+ throw error;
57
+ }
58
+ let nextFailure;
59
+ if (!lastWrite && !atLimit)
60
+ try {
61
+ const next = await chunks.next();
62
+ final = next.done === !0;
63
+ this.#submit(next.done === !0 ? EMPTY_BUFFER : next.value, final);
64
+ } catch (error) {
65
+ nextFailure = { error };
66
+ }
67
+ if (rowCount > 0)
68
+ yield batch;
69
+ else
70
+ this.recycle(batch);
71
+ if (nextFailure !== void 0)
72
+ throw nextFailure.error;
73
+ if (lastWrite || atLimit)
74
+ return;
75
+ if (remaining !== void 0)
76
+ remaining -= rowCount;
77
+ }
78
+ }
79
+ [Symbol.dispose]() {
80
+ if (finalizer.unregister(this))
81
+ closePipeline(this.#lifetime);
82
+ }
83
+ }
package/dist/batches.d.ts CHANGED
@@ -1,6 +1,13 @@
1
1
  import { type NativePointer } from './native.js';
2
- import type { CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvFieldRange, CsvRow, CsvScanColumnsCallback, NativeCsvRowCallback } from './types.js';
2
+ import type { CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvFieldRange, CsvMappedRow, CsvRow, CsvScanColumnsCallback, NativeCsvRowCallback } from './types.js';
3
3
  declare const visitBatchRows: unique symbol;
4
+ export declare const mappedBatchRows: unique symbol;
5
+ export declare const utf8BatchSlices: unique symbol;
6
+ export declare const recycleBatch: unique symbol;
7
+ export interface MappedRowLayout {
8
+ readonly keys: readonly string[];
9
+ readonly template: Record<string, string> | undefined;
10
+ }
4
11
  /**
5
12
  * A reusable, low-allocation view over one row in a {@link NativeCsvBatch}.
6
13
  *
@@ -154,6 +161,9 @@ export declare class NativeCsvBatch {
154
161
  * exceeds the batch backing storage.
155
162
  */
156
163
  rowsInto(target: CsvRow[], columns?: CsvColumns): CsvRow[];
164
+ /** Borrow the batch across slices. The caller disposes it if iteration ends early. */
165
+ [utf8BatchSlices](maxBatchRows: number, layout?: MappedRowLayout): Generator<CsvRow[] | CsvMappedRow[], void>;
166
+ [mappedBatchRows](layout: MappedRowLayout, encoding: 'latin1' | 'utf8'): CsvMappedRow[];
157
167
  /**
158
168
  * Returns the concatenated field bytes as a borrowed `Buffer`.
159
169
  *
@@ -283,6 +293,7 @@ export declare class NativeCsvBatch {
283
293
  * Calling `close()` more than once is safe.
284
294
  */
285
295
  close(): void;
296
+ [recycleBatch](recycle: (batch: NativePointer) => void): void;
286
297
  /** Implements `using` / explicit resource management. */
287
298
  [Symbol.dispose](): void;
288
299
  }
@@ -292,7 +303,10 @@ export declare class NativeCsvBatch {
292
303
  */
293
304
  export declare class NativeCsvRawRecordBatch {
294
305
  #private;
295
- /** @internal */
306
+ /**
307
+ * Wraps an owned native raw-record batch handle. Get batches from `csv.batches()`.
308
+ * @internal
309
+ */
296
310
  constructor(handle: NativePointer);
297
311
  /** Whether the native storage has been released. */
298
312
  get closed(): boolean;