@konstit/csv 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +34 -1
  2. package/THIRD_PARTY_NOTICES.md +99 -0
  3. package/dist/api.d.ts +16 -9
  4. package/dist/api.js +40 -20
  5. package/dist/batches.d.ts +21 -0
  6. package/dist/batches.js +154 -20
  7. package/dist/cli-command.js +107 -2
  8. package/dist/cli-schema.d.ts +4 -0
  9. package/dist/cli-schema.js +11 -1
  10. package/dist/file-stream.d.ts +10 -6
  11. package/dist/file-stream.js +97 -47
  12. package/dist/files.js +3 -2
  13. package/dist/filter.d.ts +2 -2
  14. package/dist/filter.js +2 -0
  15. package/dist/gzip-reader.d.ts +2 -0
  16. package/dist/gzip-reader.js +37 -0
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.js +1 -1
  19. package/dist/latin1-rows.d.ts +3 -2
  20. package/dist/latin1-rows.js +52 -12
  21. package/dist/materialize-field.d.ts +1 -0
  22. package/dist/materialize-field.js +10 -1
  23. package/dist/native.d.ts +55 -3
  24. package/dist/native.js +27 -3
  25. package/dist/normalize.d.ts +2 -1
  26. package/dist/normalize.js +7 -0
  27. package/dist/options-snapshot.d.ts +2 -2
  28. package/dist/options-snapshot.js +2 -0
  29. package/dist/parser.d.ts +9 -6
  30. package/dist/parser.js +64 -11
  31. package/dist/transforms.d.ts +11 -0
  32. package/dist/transforms.js +192 -0
  33. package/dist/types.d.ts +64 -9
  34. package/package.json +1 -1
  35. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  36. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  37. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  38. package/prebuilds/manifest.json +17 -8
  39. package/prebuilds/provenance/darwin-arm64.json +1 -1
  40. package/prebuilds/provenance/darwin-x64.json +1 -1
  41. package/prebuilds/provenance/linux-x64.json +1 -1
@@ -1,6 +1,9 @@
1
+ import { isAscii } from "node:buffer";
1
2
  import {
2
3
  copyLatin1Range,
3
- latin1Pair
4
+ decodeMaterializedField,
5
+ latin1Pair,
6
+ prepareRow
4
7
  } from "./materialize-field.js";
5
8
  import {
6
9
  EMPTY_BUFFER,
@@ -15,6 +18,25 @@ import {
15
18
  prepareNativeParser,
16
19
  setRowSelection
17
20
  } from "./parser.js";
21
+ import {
22
+ hasOnlyCleanupTransforms,
23
+ prepareTransforms
24
+ } from "./transforms.js";
25
+ 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 ||= {});
32
+ export function canUseFilteredLatin1Cleanup(columns, filters, transforms) {
33
+ return columns === void 0 && filters !== void 0 && hasOnlyCleanupTransforms(transforms) && filters.every((entry) => {
34
+ if ("operator" in entry)
35
+ return entry.operator === "all";
36
+ const operand = "value" in entry ? entry.value : ("notEquals" in entry) ? entry.notEquals : void 0;
37
+ return typeof operand === "string" ? Buffer.byteLength(operand) === operand.length : operand !== void 0 && isAscii(operand);
38
+ });
39
+ }
18
40
  export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows, options = {}) {
19
41
  if (delimiter === "auto")
20
42
  throw Error("automatic delimiter detection is only supported by file APIs");
@@ -27,6 +49,8 @@ export async function* latin1Rows(chunks, delimiter, columns, filters, createPar
27
49
  nativeCsvParserFinalizer.register(lifetime, parser, lifetime);
28
50
  try {
29
51
  setRowSelection(parser, options);
52
+ if (options.transform?.length)
53
+ prepareTransforms(parser, options.transform, columns);
30
54
  const prepared = prepareNativeParser(parser, columns, filters);
31
55
  let remaining = options.limit;
32
56
  if (remaining === 0)
@@ -72,13 +96,26 @@ function consumeLatin1Batch(parser, batch, reusableRows) {
72
96
  rows.length = rowCount;
73
97
  let fieldStart = checkedOffset(rowOffsets, 0, totalFields);
74
98
  let start = checkedOffset(fieldOffsets, fieldStart, dataLength);
99
+ let windowStart = 0;
100
+ let windowEnd = 0;
101
+ let text = "";
75
102
  for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
76
103
  const fieldEnd = checkedOffset(rowOffsets, rowIndex + 1, totalFields);
77
- const leading = quotedRows?.[rowIndex] ?? 0;
78
- const trailing = leading * 2;
79
- const row = reusableRows?.[rowIndex] ?? [];
104
+ const storage = quotedRows?.[rowIndex] ?? 0;
80
105
  const width = fieldEnd - fieldStart;
81
- row.length = width;
106
+ const row = prepareRow(reusableRows?.[rowIndex], width);
107
+ if (storage === 2 /* PackedUtf8 */) {
108
+ for (let column = 0;column < width; ++column) {
109
+ const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
110
+ row[column] = decodeMaterializedField(bytes, start, end, "utf8");
111
+ start = end;
112
+ }
113
+ rows[rowIndex] = row;
114
+ fieldStart = fieldEnd;
115
+ continue;
116
+ }
117
+ const leading = storage === 1 /* QuotedSpan */ ? 1 : 0;
118
+ const trailing = leading * 2;
82
119
  for (let column = 0;column < width; ++column) {
83
120
  const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
84
121
  const payload = start + leading;
@@ -94,16 +131,19 @@ function consumeLatin1Batch(parser, batch, reusableRows) {
94
131
  case 2:
95
132
  row[column] = latin1Pair(view.getUint16(payload, !0));
96
133
  break;
97
- case 3:
98
- row[column] = latin1Pair(view.getUint16(payload, !0)) + String.fromCharCode(view.getUint8(payload + 2));
99
- break;
100
- case 4:
101
- row[column] = latin1Pair(view.getUint16(payload, !0)) + latin1Pair(view.getUint16(payload + 2, !0));
102
- break;
103
134
  default:
104
135
  if (length < 0)
105
136
  throw RangeError("CSV field span exceeds its backing range");
106
- row[column] = copyLatin1Range(bytes, payload, payloadEnd);
137
+ if (length > MAX_WINDOW_FIELD_BYTES) {
138
+ row[column] = copyLatin1Range(bytes, payload, payloadEnd);
139
+ break;
140
+ }
141
+ if (payloadEnd > windowEnd) {
142
+ windowStart = payload;
143
+ windowEnd = Math.min(payload + WINDOW_BYTES, dataLength);
144
+ text = copyLatin1Range(bytes, windowStart, windowEnd);
145
+ }
146
+ row[column] = text.slice(payload - windowStart, payloadEnd - windowStart);
107
147
  }
108
148
  start = end;
109
149
  }
@@ -1,3 +1,4 @@
1
+ export declare function prepareRow(row: string[] | undefined, width: number): string[];
1
2
  export declare function latin1Pair(key: number): string;
2
3
  export declare function copyLatin1Range(data: Buffer, start: number, end: number): string;
3
4
  export declare function decodeMaterializedField(data: Buffer, start: number, end: number, encoding: 'utf8' | 'latin1'): string;
@@ -1,7 +1,14 @@
1
1
  const LATIN1_SINGLE = Array.from({ length: 256 }, (_, byte) => String.fromCharCode(byte));
2
2
  const bufferPrototype = Buffer.prototype;
3
3
  const latin1Slice = bufferPrototype.latin1Slice;
4
+ const utf8Slice = bufferPrototype.utf8Slice;
4
5
  const LATIN1_PAIRS = Array.from({ length: 65536 });
6
+ export function prepareRow(row, width) {
7
+ if (row === void 0)
8
+ return Array(width);
9
+ row.length = width;
10
+ return row;
11
+ }
5
12
  export function latin1Pair(key) {
6
13
  const cached = LATIN1_PAIRS[key];
7
14
  if (cached !== void 0)
@@ -27,5 +34,7 @@ export function decodeMaterializedField(data, start, end, encoding) {
27
34
  if (first < 128 && second < 128)
28
35
  return latin1Pair(first | second << 8);
29
36
  }
30
- return encoding === "latin1" ? copyLatin1Range(data, start, end) : data.toString("utf8", start, end);
37
+ if (encoding === "latin1")
38
+ return copyLatin1Range(data, start, end);
39
+ return typeof utf8Slice === "function" ? utf8Slice.call(data, start, end) : data.toString("utf8", start, end);
31
40
  }
package/dist/native.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Pointer } from 'bun:ffi';
1
+ import { FFIType, type Pointer } from 'bun:ffi';
2
2
  export type { Pointer } from 'bun:ffi';
3
3
  export { toArrayBuffer } from 'bun:ffi';
4
4
  /**
@@ -13,7 +13,23 @@ export declare const EMPTY_BUFFER: Uint8Array<ArrayBuffer>;
13
13
  export declare const EMPTY_U32: Uint32Array<ArrayBuffer>;
14
14
  export declare const DEFAULT_CHUNK_SIZE: number;
15
15
  export declare const native: import("bun:ffi").Library<{
16
- readonly csv_probe_format: {
16
+ readonly csv_parser_add_transform: {
17
+ readonly args: readonly ["ptr", "u32", "u32"];
18
+ readonly returns: "bool";
19
+ };
20
+ readonly csv_parser_add_transform_with_default: {
21
+ readonly args: readonly ["ptr", "u32", "u32", "buffer", "buffer_length"];
22
+ readonly returns: "bool";
23
+ };
24
+ readonly csv_parser_transform_pair: {
25
+ readonly args: readonly ["ptr", "u32", "buffer", "buffer_length", "buffer", "buffer_length"];
26
+ readonly returns: "bool";
27
+ };
28
+ readonly csv_parser_transform_validated_batch: {
29
+ readonly args: readonly ["ptr", "ptr"];
30
+ readonly returns: "ptr";
31
+ };
32
+ readonly csv_probe_format_v2: {
17
33
  readonly args: readonly ["buffer", "u32", "bool", "bool", "ptr"];
18
34
  readonly returns: "u32";
19
35
  };
@@ -29,6 +45,18 @@ export declare const native: import("bun:ffi").Library<{
29
45
  readonly args: readonly ["int", "u8", "u32"];
30
46
  readonly returns: "ptr";
31
47
  };
48
+ readonly csv_parser_create_dialect: {
49
+ readonly args: readonly ["int", "u8", "u32", "bool", "bool"];
50
+ readonly returns: "ptr";
51
+ };
52
+ readonly csv_parser_write_raw_records: {
53
+ readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
54
+ readonly returns: "ptr";
55
+ };
56
+ readonly csv_parser_enable_transformed_quoted_spans: {
57
+ readonly args: readonly ["ptr"];
58
+ readonly returns: "void";
59
+ };
32
60
  readonly csv_parser_set_row_selection: {
33
61
  readonly args: readonly ["ptr", "u64", "u64", "bool"];
34
62
  readonly returns: "void";
@@ -125,6 +153,26 @@ export declare const native: import("bun:ffi").Library<{
125
153
  readonly args: readonly ["ptr"];
126
154
  readonly returns: "ptr";
127
155
  };
156
+ readonly csv_gzip_reader_create: {
157
+ readonly args: readonly ["i32"];
158
+ readonly returns: "ptr";
159
+ };
160
+ readonly csv_gzip_reader_destroy: {
161
+ readonly args: readonly ["ptr"];
162
+ readonly returns: "void";
163
+ };
164
+ readonly csv_gzip_reader_enable_read_ahead: {
165
+ readonly args: readonly ["ptr", "u32"];
166
+ readonly returns: "void";
167
+ };
168
+ readonly csv_gzip_reader_read: {
169
+ readonly args: readonly ["ptr", "buffer", "buffer_length"];
170
+ readonly returns: FFIType.i64_fast;
171
+ };
172
+ readonly csv_gzip_reader_last_error: {
173
+ readonly args: readonly ["ptr"];
174
+ readonly returns: "cstring";
175
+ };
128
176
  readonly csv_zip_reader_create: {
129
177
  readonly args: readonly ["cstring", "buffer", "buffer_length", "u64", "u32"];
130
178
  readonly returns: "ptr";
@@ -181,6 +229,10 @@ export declare const native: import("bun:ffi").Library<{
181
229
  readonly args: readonly ["u8", "u32"];
182
230
  readonly returns: "ptr";
183
231
  };
232
+ readonly csv_parser_create_latin1_cleanup_rows: {
233
+ readonly args: readonly ["u8", "u32"];
234
+ readonly returns: "ptr";
235
+ };
184
236
  readonly csv_batch_quoted_rows_ptr: {
185
237
  readonly args: readonly ["ptr"];
186
238
  readonly returns: "ptr";
@@ -190,7 +242,7 @@ export declare const native: import("bun:ffi").Library<{
190
242
  readonly returns: "ptr";
191
243
  };
192
244
  }>;
193
- export declare function latin1RowsParser(fixedColumns: number | undefined): (delimiter: number) => NativePointer | null;
245
+ export declare function latin1RowsParser(fixedColumns: number | undefined, cleanup?: boolean): (delimiter: number) => NativePointer | null;
194
246
  export declare function resolveNativeLibraryPath(configuredPath: string | undefined): string;
195
247
  export declare function requireConfiguredNativeLibraryPath(configuredPath: string): string;
196
248
  export declare function nativeLibraryCandidates(root: string, target: string, librarySuffix: string): readonly string[];
package/dist/native.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  dlopen,
3
+ FFIType,
3
4
  suffix
4
5
  } from "bun:ffi";
5
6
  import {
@@ -19,7 +20,20 @@ export const EMPTY_BUFFER = EMPTY_BUFFER_STORAGE.subarray(0, 0);
19
20
  export const EMPTY_U32 = new Uint32Array(1);
20
21
  export const DEFAULT_CHUNK_SIZE = 1048576;
21
22
  const CSV_SYMBOLS = {
22
- csv_probe_format: {
23
+ csv_parser_add_transform: { args: ["ptr", "u32", "u32"], returns: "bool" },
24
+ csv_parser_add_transform_with_default: {
25
+ args: [
26
+ "ptr",
27
+ "u32",
28
+ "u32",
29
+ "buffer",
30
+ "buffer_length"
31
+ ],
32
+ returns: "bool"
33
+ },
34
+ csv_parser_transform_pair: { args: ["ptr", "u32", "buffer", "buffer_length", "buffer", "buffer_length"], returns: "bool" },
35
+ csv_parser_transform_validated_batch: { args: ["ptr", "ptr"], returns: "ptr" },
36
+ csv_probe_format_v2: {
23
37
  args: [
24
38
  "buffer",
25
39
  "u32",
@@ -38,6 +52,9 @@ const CSV_SYMBOLS = {
38
52
  returns: "ptr"
39
53
  },
40
54
  csv_parser_create_prepared: { args: ["int", "u8", "u32"], returns: "ptr" },
55
+ csv_parser_create_dialect: { args: ["int", "u8", "u32", "bool", "bool"], returns: "ptr" },
56
+ csv_parser_write_raw_records: { args: ["ptr", "buffer", "buffer_length", "bool"], returns: "ptr" },
57
+ csv_parser_enable_transformed_quoted_spans: { args: ["ptr"], returns: "void" },
41
58
  csv_parser_set_row_selection: { args: ["ptr", "u64", "u64", "bool"], returns: "void" },
42
59
  csv_parser_take_skipped_header: { args: ["ptr"], returns: "ptr" },
43
60
  csv_parser_skipped_rows: { args: ["ptr"], returns: "u64" },
@@ -125,6 +142,11 @@ const CSV_SYMBOLS = {
125
142
  args: ["ptr"],
126
143
  returns: "ptr"
127
144
  },
145
+ csv_gzip_reader_create: { args: ["i32"], returns: "ptr" },
146
+ csv_gzip_reader_destroy: { args: ["ptr"], returns: "void" },
147
+ csv_gzip_reader_enable_read_ahead: { args: ["ptr", "u32"], returns: "void" },
148
+ csv_gzip_reader_read: { args: ["ptr", "buffer", "buffer_length"], returns: FFIType.i64_fast },
149
+ csv_gzip_reader_last_error: { args: ["ptr"], returns: "cstring" },
128
150
  csv_zip_reader_create: {
129
151
  args: ["cstring", "buffer", "buffer_length", "u64", "u32"],
130
152
  returns: "ptr"
@@ -175,6 +197,7 @@ const CSV_SYMBOLS = {
175
197
  },
176
198
  csv_parser_create_latin1_rows_with_quoted_spans: { args: ["u8"], returns: "ptr" },
177
199
  csv_parser_create_latin1_quoted_rows: { args: ["u8", "u32"], returns: "ptr" },
200
+ csv_parser_create_latin1_cleanup_rows: { args: ["u8", "u32"], returns: "ptr" },
178
201
  csv_batch_quoted_rows_ptr: { args: ["ptr"], returns: "ptr" },
179
202
  csv_parser_create_latin1_rows_with_fixed_columns: {
180
203
  args: ["u8", "u32"],
@@ -182,8 +205,9 @@ const CSV_SYMBOLS = {
182
205
  }
183
206
  };
184
207
  export const native = dlopen(resolveNativeLibraryPath(process.env.CSV_NATIVE_LIBRARY_PATH), CSV_SYMBOLS);
185
- export function latin1RowsParser(fixedColumns) {
186
- return (delimiter) => native.symbols.csv_parser_create_latin1_quoted_rows(delimiter, fixedColumns ?? 0);
208
+ export function latin1RowsParser(fixedColumns, cleanup = !1) {
209
+ const create = cleanup ? native.symbols.csv_parser_create_latin1_cleanup_rows : native.symbols.csv_parser_create_latin1_quoted_rows;
210
+ return (delimiter) => create(delimiter, fixedColumns ?? 0);
187
211
  }
188
212
  export function resolveNativeLibraryPath(configuredPath) {
189
213
  const root = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -1,4 +1,4 @@
1
- import type { CsvColumns, CsvEncoding, CsvFieldValue, CsvNativeEncoding, CsvNativeFilter, CsvNativeFilterProgramEntry, CsvNativeProjectionOptions, CsvRegex } from './types.js';
1
+ import type { CsvColumns, CsvEncoding, CsvFieldValue, CsvNativeEncoding, CsvNativeFilter, CsvNativeFilterProgramEntry, CsvNativeProjectionOptions, CsvParserOptions, CsvRegex } from './types.js';
2
2
  interface PreparedCsvBufferInput {
3
3
  readonly bytes: NodeJS.TypedArray | DataView;
4
4
  readonly parserEncoding: 'utf8' | 'latin1';
@@ -18,6 +18,7 @@ export declare function resolveInputEncoding(encoding?: string, delimiter?: stri
18
18
  /** Converts a complete buffer to bytes accepted by the native parser. */
19
19
  export declare function prepareCsvBufferInput(buffer: NodeJS.TypedArray | DataView, encoding?: CsvEncoding, delimiter?: string): PreparedCsvBufferInput;
20
20
  export declare function normalizeChunk(chunk: NodeJS.TypedArray | DataView): NodeJS.TypedArray | DataView;
21
+ export declare function validateCsvDialect({ quote, recordDelimiter }: Pick<CsvParserOptions, 'quote' | 'recordDelimiter'>): void;
21
22
  export declare function normalizeFixedColumnsCount(value: number | undefined, label: string): number | undefined;
22
23
  /** Reject stale JavaScript options before a requested projection can silently return all fields. */
23
24
  export declare function rejectSelectedColumns(options: object): void;
package/dist/normalize.js CHANGED
@@ -83,6 +83,13 @@ export function prepareCsvBufferInput(buffer, encoding, delimiter) {
83
83
  export function normalizeChunk(chunk) {
84
84
  return chunk.byteLength === 0 ? EMPTY_BUFFER : chunk;
85
85
  }
86
+ export function validateCsvDialect({ quote, recordDelimiter }) {
87
+ if (quote !== void 0 && typeof quote !== "boolean")
88
+ throw TypeError("quote must be a boolean");
89
+ if (recordDelimiter !== void 0 && recordDelimiter !== `
90
+ `)
91
+ throw TypeError("recordDelimiter must be LF");
92
+ }
86
93
  export function normalizeFixedColumnsCount(value, label) {
87
94
  if (value === void 0)
88
95
  return;
@@ -1,3 +1,3 @@
1
- import type { CsvApiFileOptions, CsvNativeProjectionOptions } from './types.js';
1
+ import type { CsvApiFileOptions, CsvNativeProjectionOptions, CsvTransformOptions } from './types.js';
2
2
  /** Own the mutable option values while retaining opaque immutable filter handles. */
3
- export declare function snapshotCsvOptions<TOptions extends CsvApiFileOptions & CsvNativeProjectionOptions>(options: TOptions): TOptions;
3
+ export declare function snapshotCsvOptions<TOptions extends CsvApiFileOptions & CsvNativeProjectionOptions & CsvTransformOptions>(options: TOptions): TOptions;
@@ -3,6 +3,7 @@ import {
3
3
  MAX_PROJECTION_LENGTH,
4
4
  rejectSelectedColumns
5
5
  } from "./normalize.js";
6
+ import { snapshotTransforms } from "./transforms.js";
6
7
  const snapshots = new WeakSet;
7
8
  export function snapshotCsvOptions(options) {
8
9
  if (snapshots.has(options))
@@ -13,6 +14,7 @@ export function snapshotCsvOptions(options) {
13
14
  throw RangeError(`filter count out of range: ${captured.filters.length}`);
14
15
  const snapshot = Object.freeze({
15
16
  ...captured,
17
+ transform: snapshotTransforms(captured.transform),
16
18
  columns: snapshotColumns(captured.columns),
17
19
  expectedHeaders: captured.expectedHeaders === void 0 ? void 0 : Object.freeze([...captured.expectedHeaders]),
18
20
  compression: typeof captured.compression === "object" && captured.compression !== null ? Object.freeze({ ...captured.compression }) : captured.compression,
package/dist/parser.d.ts CHANGED
@@ -1,11 +1,14 @@
1
- import { NativeCsvBatch } from './batches.js';
1
+ import { NativeCsvBatch, NativeCsvRawRecordBatch } from './batches.js';
2
2
  import type { CsvFileInput } from './file-stream.js';
3
3
  import { type NativePointer } from './native.js';
4
- import type { CsvColumns, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, NativeCsvParserOptions } from './types.js';
4
+ import type { CsvColumns, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, CsvTransform, NativeCsvParserOptions } from './types.js';
5
5
  export declare const nativeCsvParserFinalizer: FinalizationRegistry<NativePointer>;
6
- export declare function parseFileChunks(input: CsvFileInput, parser: NativeCsvParser, limit: number | undefined): AsyncGenerator<NativeCsvBatch, void>;
7
- export declare function countFileChunks(input: CsvFileInput, parser: NativeCsvParser, options: Pick<CsvParserOptions, 'limit' | 'strict'>): Promise<number>;
8
- export declare function createPreparedParser(options: CsvParserOptions, columns?: CsvColumns, program?: readonly CsvNativeFilterProgramEntry[]): NativeCsvParser;
6
+ export declare function parseFileChunks<TBatch extends NativeCsvBatch | NativeCsvRawRecordBatch>(input: CsvFileInput, parser: {
7
+ writeBatch(chunk: Uint8Array, final?: boolean): TBatch;
8
+ }, limit: number | undefined): AsyncGenerator<TBatch, void>;
9
+ export declare function parseRawRecordChunks(input: CsvFileInput, options: CsvParserOptions, program: readonly CsvNativeFilterProgramEntry[] | undefined): AsyncGenerator<NativeCsvRawRecordBatch, void>;
10
+ 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;
9
12
  interface PreparedNativeWriter {
10
13
  writeBatch(input: NodeJS.TypedArray | DataView, final: boolean): NativePointer | null;
11
14
  writeCount(input: NodeJS.TypedArray | DataView, final: boolean): bigint | number;
@@ -51,7 +54,7 @@ declare const createSchemaParser: unique symbol;
51
54
  */
52
55
  export declare class NativeCsvParser {
53
56
  #private;
54
- static [createSchemaParser](options: NativeCsvParserOptions): NativeCsvParser;
57
+ static [createSchemaParser](options: NativeCsvParserOptions, output: 'batches' | 'rows'): NativeCsvParser;
55
58
  /**
56
59
  * Creates an open parser.
57
60
  *
package/dist/parser.js CHANGED
@@ -1,4 +1,7 @@
1
- import { NativeCsvBatch } from "./batches.js";
1
+ import {
2
+ NativeCsvBatch,
3
+ NativeCsvRawRecordBatch
4
+ } from "./batches.js";
2
5
  import {
3
6
  EMPTY_BUFFER,
4
7
  native,
@@ -12,11 +15,17 @@ import {
12
15
  normalizeNativeFilterProgram,
13
16
  normalizeNativeFilters,
14
17
  projectionFilterProgram,
15
- rejectSelectedColumns
18
+ rejectSelectedColumns,
19
+ validateCsvDialect
16
20
  } from "./normalize.js";
17
21
  import {
18
22
  strictSchemaValidator
19
23
  } from "./strict-schema.js";
24
+ import {
25
+ prepareTransforms,
26
+ selectTransforms,
27
+ snapshotTransforms
28
+ } from "./transforms.js";
20
29
  function destroyNativeCsvParser(handle) {
21
30
  native.symbols.csv_parser_destroy(handle);
22
31
  }
@@ -37,13 +46,36 @@ export async function* parseFileChunks(input, parser, limit) {
37
46
  break;
38
47
  }
39
48
  }
40
- const final = parser.endBatch();
49
+ const final = parser.writeBatch(EMPTY_BUFFER, !0);
41
50
  if (final.rowCount > 0)
42
51
  yield final;
43
52
  else
44
53
  final.close();
45
54
  }
46
- export async function countFileChunks(input, parser, options) {
55
+ export async function* parseRawRecordChunks(input, options, program) {
56
+ normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
57
+ const handle = createNativeCsvParser(options, !0);
58
+ const parser = {
59
+ writeBatch(chunk, final = !1) {
60
+ const bytes = normalizeChunk(chunk);
61
+ const batch = native.symbols.csv_parser_write_raw_records(handle, bytes, bytes, final);
62
+ if (batch === null)
63
+ throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(handle) ?? "native parser error unavailable"}`);
64
+ return new NativeCsvRawRecordBatch(batch);
65
+ }
66
+ };
67
+ nativeCsvParserFinalizer.register(parser, handle, parser);
68
+ try {
69
+ prepareNativeParser(handle, void 0, program);
70
+ yield* parseFileChunks(input, parser, options.limit);
71
+ } finally {
72
+ nativeCsvParserFinalizer.unregister(parser);
73
+ destroyNativeCsvParser(handle);
74
+ }
75
+ }
76
+ export async function countFileChunks(input, options, filters) {
77
+ const columns = options.fixedColumns !== void 0 && options.strict !== !0 && filters === void 0 ? [] : void 0;
78
+ using parser = createPreparedParser(options, columns, filters);
47
79
  let total = 0;
48
80
  if (options.strict === !0) {
49
81
  for await (using batch of parseFileChunks(input, parser, options.limit))
@@ -58,12 +90,14 @@ export async function countFileChunks(input, parser, options) {
58
90
  }
59
91
  return total + parser.endCount();
60
92
  }
61
- export function createPreparedParser(options, columns, program) {
93
+ export function createPreparedParser(options, columns, program, transform, output = "batches") {
62
94
  if (options.columns !== columns)
63
95
  normalizeColumns(options.columns);
64
96
  return NativeCsvParser[createSchemaParser]({
65
97
  encoding: options.encoding,
66
98
  delimiter: options.delimiter,
99
+ quote: options.quote,
100
+ recordDelimiter: options.recordDelimiter,
67
101
  fixedColumns: options.fixedColumns,
68
102
  strict: options.strict,
69
103
  skipRows: options.skipRows,
@@ -72,8 +106,9 @@ export function createPreparedParser(options, columns, program) {
72
106
  requireHeader: options.requireHeader,
73
107
  minDataRows: options.minDataRows,
74
108
  columns,
75
- filterProgram: program
76
- });
109
+ filterProgram: program,
110
+ transform: options.strict && options.columns && transform ? selectTransforms(transform, options.columns) : transform
111
+ }, output);
77
112
  }
78
113
  export function prepareNativeParser(handle, columns, program) {
79
114
  const normalizedColumns = normalizeColumns(columns);
@@ -105,15 +140,17 @@ export function setRowSelection(handle, options, captureHeader = !1) {
105
140
  native.symbols.csv_parser_set_row_selection(handle, BigInt(options.skipRows ?? 0), options.limit === void 0 ? 0xffffffffffffffffn : BigInt(options.limit), captureHeader);
106
141
  }
107
142
  function createNativeCsvParser(options, prepared = !1) {
108
- const { skipRows, limit } = options;
143
+ const { skipRows, limit, quote, recordDelimiter } = options;
109
144
  validateRowSelection({ skipRows, limit });
145
+ validateCsvDialect(options);
110
146
  const delimiter = options.delimiter ?? ",";
111
147
  if (delimiter === "auto")
112
148
  throw Error("automatic delimiter detection is only supported by file APIs");
113
149
  if (delimiter.length !== 1)
114
150
  throw Error("delimiter must be one character");
115
151
  const encoding = encodingCode(options.encoding);
116
- const handle = prepared ? native.symbols.csv_parser_create_prepared(encoding, delimiter.charCodeAt(0), options.fixedColumns ?? 0) : native.symbols.csv_parser_create(encoding, delimiter.charCodeAt(0));
152
+ const handle = quote === !1 || recordDelimiter !== void 0 ? native.symbols.csv_parser_create_dialect(encoding, delimiter.charCodeAt(0), options.fixedColumns ?? 0, quote ?? !0, recordDelimiter === `
153
+ `) : prepared ? native.symbols.csv_parser_create_prepared(encoding, delimiter.charCodeAt(0), options.fixedColumns ?? 0) : native.symbols.csv_parser_create(encoding, delimiter.charCodeAt(0));
117
154
  if (handle === null)
118
155
  throw Error("failed to create native CSV parser");
119
156
  setRowSelection(handle, { skipRows, limit });
@@ -126,11 +163,14 @@ export class NativeCsvParser {
126
163
  #strict;
127
164
  #fixedColumns;
128
165
  #writer;
166
+ #transformStrictBatch;
129
167
  #validator;
130
168
  #captureSkippedHeader = !1;
131
- static [createSchemaParser](options) {
169
+ static [createSchemaParser](options, output) {
132
170
  const validator = strictSchemaValidator(options);
133
171
  const parser = new NativeCsvParser(options);
172
+ if (output === "rows" && !parser.#strict && options.transform?.length)
173
+ native.symbols.csv_parser_enable_transformed_quoted_spans(parser.#requireHandle());
134
174
  parser.#validator = validator;
135
175
  if (validator !== void 0 && (options.skipRows ?? 0) > 0) {
136
176
  parser.#captureSkippedHeader = !0;
@@ -148,9 +188,15 @@ export class NativeCsvParser {
148
188
  const program = filterProgram === void 0 ? projectionFilterProgram(options) : filterProgram;
149
189
  if (this.#strict && (columns !== void 0 || program !== void 0))
150
190
  throw Error("strict CSV validation is not supported for projected batches or filters");
151
- const prepared = columns !== void 0 || program !== void 0;
191
+ const transforms = snapshotTransforms(options.transform);
192
+ const customDialect = options.quote === !1 || options.recordDelimiter !== void 0;
193
+ if (customDialect && this.#strict)
194
+ throw Error("strict CSV validation requires the default quote and record delimiter settings");
195
+ const prepared = customDialect || columns !== void 0 || program !== void 0 || !this.#strict && Boolean(transforms?.length);
152
196
  const handle = createNativeCsvParser(options, prepared);
153
197
  try {
198
+ const active = transforms?.length ? prepareTransforms(handle, transforms, columns) : !1;
199
+ this.#transformStrictBatch = this.#strict && active;
154
200
  this.#writer = prepared ? prepareNativeParser(handle, columns, program) : void 0;
155
201
  } catch (error) {
156
202
  destroyNativeCsvParser(handle);
@@ -176,6 +222,13 @@ export class NativeCsvParser {
176
222
  const batch = this.#writer !== void 0 ? this.#writer.writeBatch(input, final) : 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);
177
223
  if (batch === null)
178
224
  throw Error(`native CSV parser failed: ${this.#lastError()}`);
225
+ if (this.#transformStrictBatch) {
226
+ using _original = this.#validatedBatch(batch, final);
227
+ const result = native.symbols.csv_parser_transform_validated_batch(handle, batch);
228
+ if (!result)
229
+ throw Error(`native CSV parser failed: ${this.#lastError()}`);
230
+ return new NativeCsvBatch(result);
231
+ }
179
232
  return this.#validatedBatch(batch, final);
180
233
  }
181
234
  end() {
@@ -0,0 +1,11 @@
1
+ import { type NativePointer } from './native.js';
2
+ import type { CsvColumns, CsvTransform, CsvTransformChain, CsvTransformMethods } from './types.js';
3
+ /** Start a reusable chain. Choose physical columns after defining its steps. */
4
+ export declare function transform(): CsvTransformMethods<CsvTransformChain>;
5
+ export declare function transformMethods(column: number): CsvTransformMethods;
6
+ export declare function snapshotTransforms(transforms: readonly CsvTransform[] | undefined): readonly CsvTransform[] | undefined;
7
+ export declare function hasOnlyCleanupTransforms(tokens: readonly CsvTransform[]): boolean;
8
+ /** Strict row projection happens after full-width validation and transformation. */
9
+ export declare function selectTransforms(tokens: readonly CsvTransform[], columns: CsvColumns): readonly CsvTransform[];
10
+ /** Copy each selected chain into its parser. Native writes never reference caller-owned data. */
11
+ export declare function prepareTransforms(handle: NativePointer, tokens: readonly CsvTransform[], selected: CsvColumns | undefined): boolean;