@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/native.d.ts CHANGED
@@ -12,6 +12,7 @@ export type NativePointer = Pointer | bigint;
12
12
  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
+ export declare const MAX_CHUNK_SIZE: number;
15
16
  export declare const native: import("bun:ffi").Library<{
16
17
  readonly csv_parser_add_transform: {
17
18
  readonly args: readonly ["ptr", "u32", "u32"];
@@ -25,11 +26,7 @@ export declare const native: import("bun:ffi").Library<{
25
26
  readonly args: readonly ["ptr", "u32", "buffer", "buffer_length", "buffer", "buffer_length"];
26
27
  readonly returns: "bool";
27
28
  };
28
- readonly csv_parser_transform_validated_batch: {
29
- readonly args: readonly ["ptr", "ptr"];
30
- readonly returns: "ptr";
31
- };
32
- readonly csv_probe_format_v2: {
29
+ readonly csv_probe_format_v3: {
33
30
  readonly args: readonly ["buffer", "u32", "bool", "bool", "ptr"];
34
31
  readonly returns: "u32";
35
32
  };
@@ -61,14 +58,34 @@ export declare const native: import("bun:ffi").Library<{
61
58
  readonly args: readonly ["ptr", "u64", "u64", "bool"];
62
59
  readonly returns: "void";
63
60
  };
64
- readonly csv_parser_take_skipped_header: {
61
+ readonly csv_parser_set_validation: {
62
+ readonly args: readonly ["ptr", "bool", "bool", "u64"];
63
+ readonly returns: "void";
64
+ };
65
+ readonly csv_parser_physical_rows: {
65
66
  readonly args: readonly ["ptr"];
66
- readonly returns: "ptr";
67
+ readonly returns: "u64";
67
68
  };
68
- readonly csv_parser_skipped_rows: {
69
+ readonly csv_parser_set_skip_empty_lines: {
70
+ readonly args: readonly ["ptr"];
71
+ readonly returns: "void";
72
+ };
73
+ readonly csv_parser_schema_rows: {
74
+ readonly args: readonly ["ptr"];
75
+ readonly returns: "u64";
76
+ };
77
+ readonly csv_parser_header_record: {
69
78
  readonly args: readonly ["ptr"];
70
79
  readonly returns: "u64";
71
80
  };
81
+ readonly csv_parser_has_pending_record: {
82
+ readonly args: readonly ["ptr"];
83
+ readonly returns: "bool";
84
+ };
85
+ readonly csv_parser_take_skipped_header: {
86
+ readonly args: readonly ["ptr"];
87
+ readonly returns: "ptr";
88
+ };
72
89
  readonly csv_parser_destroy: {
73
90
  readonly args: readonly ["ptr"];
74
91
  readonly returns: "void";
@@ -89,10 +106,6 @@ export declare const native: import("bun:ffi").Library<{
89
106
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32"];
90
107
  readonly returns: "ptr";
91
108
  };
92
- readonly csv_parser_write_strict_fixed_batch: {
93
- readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32"];
94
- readonly returns: "ptr";
95
- };
96
109
  readonly csv_batch_destroy: {
97
110
  readonly args: readonly ["ptr"];
98
111
  readonly returns: "void";
@@ -129,16 +142,12 @@ export declare const native: import("bun:ffi").Library<{
129
142
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
130
143
  readonly returns: "u64";
131
144
  };
132
- readonly csv_parser_count_trusted_newlines: {
133
- readonly args: readonly ["buffer", "buffer_length"];
134
- readonly returns: "u64";
135
- };
136
145
  readonly csv_regex_validate: {
137
146
  readonly args: readonly ["buffer", "buffer_length"];
138
147
  readonly returns: "cstring";
139
148
  };
140
- readonly csv_parser_find_split_offsets: {
141
- readonly args: readonly ["cstring", "u64", "u8"];
149
+ readonly csv_parser_find_split_offsets_v2: {
150
+ readonly args: readonly ["cstring", "u64", "u8", "bool"];
142
151
  readonly returns: "ptr";
143
152
  };
144
153
  readonly csv_split_offsets_batch_destroy: {
@@ -177,6 +186,18 @@ export declare const native: import("bun:ffi").Library<{
177
186
  readonly args: readonly ["cstring", "buffer", "buffer_length", "u64", "u32"];
178
187
  readonly returns: "ptr";
179
188
  };
189
+ readonly csv_zip_reader_verify_stored_archive: {
190
+ readonly args: readonly ["ptr"];
191
+ readonly returns: "bool";
192
+ };
193
+ readonly csv_zip_reader_verify_nested_archive: {
194
+ readonly args: readonly ["ptr"];
195
+ readonly returns: "int";
196
+ };
197
+ readonly csv_zip_reader_create_nested: {
198
+ readonly args: readonly ["ptr", "buffer", "buffer_length", "u64", "u32"];
199
+ readonly returns: "ptr";
200
+ };
180
201
  readonly csv_zip_reader_destroy: {
181
202
  readonly args: readonly ["ptr"];
182
203
  readonly returns: "void";
@@ -185,10 +206,30 @@ export declare const native: import("bun:ffi").Library<{
185
206
  readonly args: readonly ["ptr", "buffer"];
186
207
  readonly returns: "ptr";
187
208
  };
209
+ readonly csv_zip_directory_open: {
210
+ readonly args: readonly ["cstring"];
211
+ readonly returns: "ptr";
212
+ };
213
+ readonly csv_zip_directory_open_nested: {
214
+ readonly args: readonly ["ptr"];
215
+ readonly returns: "ptr";
216
+ };
217
+ readonly csv_zip_directory_next: {
218
+ readonly args: readonly ["ptr", "buffer"];
219
+ readonly returns: "ptr";
220
+ };
188
221
  readonly csv_zip_reader_enable_read_ahead: {
189
222
  readonly args: readonly ["ptr", "u32"];
190
223
  readonly returns: "void";
191
224
  };
225
+ readonly csv_zip_reader_can_read_parallel: {
226
+ readonly args: readonly ["ptr", "u32"];
227
+ readonly returns: "bool";
228
+ };
229
+ readonly csv_zip_reader_start_parallel: {
230
+ readonly args: readonly ["ptr", "buffer", "buffer", "buffer", "u32"];
231
+ readonly returns: "bool";
232
+ };
192
233
  readonly csv_zip_reader_read: {
193
234
  readonly args: readonly ["ptr", "buffer", "buffer_length"];
194
235
  readonly returns: "u64";
@@ -213,6 +254,34 @@ export declare const native: import("bun:ffi").Library<{
213
254
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
214
255
  readonly returns: "ptr";
215
256
  };
257
+ readonly csv_parser_write_prepared_compact_batch: {
258
+ readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "buffer"];
259
+ readonly returns: "ptr";
260
+ };
261
+ readonly csv_parser_recycle_batch: {
262
+ readonly args: readonly ["ptr", "ptr"];
263
+ readonly returns: "bool";
264
+ };
265
+ readonly csv_parser_batch_pipeline_start: {
266
+ readonly args: readonly ["ptr", "bool"];
267
+ readonly returns: "ptr";
268
+ };
269
+ readonly csv_parser_batch_pipeline_submit: {
270
+ readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
271
+ readonly returns: "bool";
272
+ };
273
+ readonly csv_parser_batch_pipeline_take: {
274
+ readonly args: readonly ["ptr", "buffer"];
275
+ readonly returns: "ptr";
276
+ };
277
+ readonly csv_parser_batch_pipeline_recycle: {
278
+ readonly args: readonly ["ptr", "ptr"];
279
+ readonly returns: "void";
280
+ };
281
+ readonly csv_parser_batch_pipeline_destroy: {
282
+ readonly args: readonly ["ptr"];
283
+ readonly returns: "void";
284
+ };
216
285
  readonly csv_parser_write_prepared_count: {
217
286
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
218
287
  readonly returns: "u64";
@@ -243,7 +312,8 @@ export declare const native: import("bun:ffi").Library<{
243
312
  };
244
313
  }>;
245
314
  export declare function latin1RowsParser(fixedColumns: number | undefined, cleanup?: boolean): (delimiter: number) => NativePointer | null;
246
- export declare function resolveNativeLibraryPath(configuredPath: string | undefined): string;
315
+ /** A null configuration requires the prebuild shipped in the package. */
316
+ export declare function resolveNativeLibraryPath(configuredPath: string | null | undefined, root?: string): string;
247
317
  export declare function requireConfiguredNativeLibraryPath(configuredPath: string): string;
248
318
  export declare function nativeLibraryCandidates(root: string, target: string, librarySuffix: string): readonly string[];
249
319
  export declare function findNativeLibraryPath(candidates: readonly string[]): string | undefined;
package/dist/native.js CHANGED
@@ -16,9 +16,7 @@ import {
16
16
  import { fileURLToPath } from "node:url";
17
17
  export { toArrayBuffer } from "bun:ffi";
18
18
  const EMPTY_BUFFER_STORAGE = new Uint8Array(1);
19
- export const EMPTY_BUFFER = EMPTY_BUFFER_STORAGE.subarray(0, 0);
20
- export const EMPTY_U32 = new Uint32Array(1);
21
- export const DEFAULT_CHUNK_SIZE = 1048576;
19
+ export const EMPTY_BUFFER = EMPTY_BUFFER_STORAGE.subarray(0, 0), EMPTY_U32 = new Uint32Array(1), DEFAULT_CHUNK_SIZE = 1048576, MAX_CHUNK_SIZE = 67108864;
22
20
  const CSV_SYMBOLS = {
23
21
  csv_parser_add_transform: { args: ["ptr", "u32", "u32"], returns: "bool" },
24
22
  csv_parser_add_transform_with_default: {
@@ -32,8 +30,7 @@ const CSV_SYMBOLS = {
32
30
  returns: "bool"
33
31
  },
34
32
  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: {
33
+ csv_probe_format_v3: {
37
34
  args: [
38
35
  "buffer",
39
36
  "u32",
@@ -56,8 +53,13 @@ const CSV_SYMBOLS = {
56
53
  csv_parser_write_raw_records: { args: ["ptr", "buffer", "buffer_length", "bool"], returns: "ptr" },
57
54
  csv_parser_enable_transformed_quoted_spans: { args: ["ptr"], returns: "void" },
58
55
  csv_parser_set_row_selection: { args: ["ptr", "u64", "u64", "bool"], returns: "void" },
56
+ csv_parser_set_validation: { args: ["ptr", "bool", "bool", "u64"], returns: "void" },
57
+ csv_parser_physical_rows: { args: ["ptr"], returns: "u64" },
58
+ csv_parser_set_skip_empty_lines: { args: ["ptr"], returns: "void" },
59
+ csv_parser_schema_rows: { args: ["ptr"], returns: "u64" },
60
+ csv_parser_header_record: { args: ["ptr"], returns: "u64" },
61
+ csv_parser_has_pending_record: { args: ["ptr"], returns: "bool" },
59
62
  csv_parser_take_skipped_header: { args: ["ptr"], returns: "ptr" },
60
- csv_parser_skipped_rows: { args: ["ptr"], returns: "u64" },
61
63
  csv_parser_destroy: {
62
64
  args: ["ptr"],
63
65
  returns: "void"
@@ -78,10 +80,6 @@ const CSV_SYMBOLS = {
78
80
  args: ["ptr", "buffer", "buffer_length", "bool", "u32"],
79
81
  returns: "ptr"
80
82
  },
81
- csv_parser_write_strict_fixed_batch: {
82
- args: ["ptr", "buffer", "buffer_length", "bool", "u32"],
83
- returns: "ptr"
84
- },
85
83
  csv_batch_destroy: {
86
84
  args: ["ptr"],
87
85
  returns: "void"
@@ -118,16 +116,12 @@ const CSV_SYMBOLS = {
118
116
  args: ["ptr", "buffer", "buffer_length", "bool"],
119
117
  returns: "u64"
120
118
  },
121
- csv_parser_count_trusted_newlines: {
122
- args: ["buffer", "buffer_length"],
123
- returns: "u64"
124
- },
125
119
  csv_regex_validate: {
126
120
  args: ["buffer", "buffer_length"],
127
121
  returns: "cstring"
128
122
  },
129
- csv_parser_find_split_offsets: {
130
- args: ["cstring", "u64", "u8"],
123
+ csv_parser_find_split_offsets_v2: {
124
+ args: ["cstring", "u64", "u8", "bool"],
131
125
  returns: "ptr"
132
126
  },
133
127
  csv_split_offsets_batch_destroy: {
@@ -151,6 +145,12 @@ const CSV_SYMBOLS = {
151
145
  args: ["cstring", "buffer", "buffer_length", "u64", "u32"],
152
146
  returns: "ptr"
153
147
  },
148
+ csv_zip_reader_verify_stored_archive: { args: ["ptr"], returns: "bool" },
149
+ csv_zip_reader_verify_nested_archive: { args: ["ptr"], returns: "int" },
150
+ csv_zip_reader_create_nested: {
151
+ args: ["ptr", "buffer", "buffer_length", "u64", "u32"],
152
+ returns: "ptr"
153
+ },
154
154
  csv_zip_reader_destroy: {
155
155
  args: ["ptr"],
156
156
  returns: "void"
@@ -159,10 +159,18 @@ const CSV_SYMBOLS = {
159
159
  args: ["ptr", "buffer"],
160
160
  returns: "ptr"
161
161
  },
162
+ csv_zip_directory_open: { args: ["cstring"], returns: "ptr" },
163
+ csv_zip_directory_open_nested: { args: ["ptr"], returns: "ptr" },
164
+ csv_zip_directory_next: { args: ["ptr", "buffer"], returns: "ptr" },
162
165
  csv_zip_reader_enable_read_ahead: {
163
166
  args: ["ptr", "u32"],
164
167
  returns: "void"
165
168
  },
169
+ csv_zip_reader_can_read_parallel: { args: ["ptr", "u32"], returns: "bool" },
170
+ csv_zip_reader_start_parallel: {
171
+ args: ["ptr", "buffer", "buffer", "buffer", "u32"],
172
+ returns: "bool"
173
+ },
166
174
  csv_zip_reader_read: {
167
175
  args: ["ptr", "buffer", "buffer_length"],
168
176
  returns: "u64"
@@ -187,6 +195,13 @@ const CSV_SYMBOLS = {
187
195
  args: ["ptr", "buffer", "buffer_length", "bool"],
188
196
  returns: "ptr"
189
197
  },
198
+ csv_parser_write_prepared_compact_batch: { args: ["ptr", "buffer", "buffer_length", "bool", "buffer"], returns: "ptr" },
199
+ csv_parser_recycle_batch: { args: ["ptr", "ptr"], returns: "bool" },
200
+ csv_parser_batch_pipeline_start: { args: ["ptr", "bool"], returns: "ptr" },
201
+ csv_parser_batch_pipeline_submit: { args: ["ptr", "buffer", "buffer_length", "bool"], returns: "bool" },
202
+ csv_parser_batch_pipeline_take: { args: ["ptr", "buffer"], returns: "ptr" },
203
+ csv_parser_batch_pipeline_recycle: { args: ["ptr", "ptr"], returns: "void" },
204
+ csv_parser_batch_pipeline_destroy: { args: ["ptr"], returns: "void" },
190
205
  csv_parser_write_prepared_count: {
191
206
  args: ["ptr", "buffer", "buffer_length", "bool"],
192
207
  returns: "u64"
@@ -203,16 +218,20 @@ const CSV_SYMBOLS = {
203
218
  args: ["u8", "u32"],
204
219
  returns: "ptr"
205
220
  }
206
- };
207
- export const native = dlopen(resolveNativeLibraryPath(process.env.CSV_NATIVE_LIBRARY_PATH), CSV_SYMBOLS);
221
+ }, nativeLibraryRoot = dirname(dirname(fileURLToPath(import.meta.url))), nativeTarget = `${process.platform}-${process.arch}`, configuredNativeLibraryPath = null;
222
+ export const native = dlopen(resolveNativeLibraryPath(configuredNativeLibraryPath), CSV_SYMBOLS);
208
223
  export function latin1RowsParser(fixedColumns, cleanup = !1) {
209
224
  const create = cleanup ? native.symbols.csv_parser_create_latin1_cleanup_rows : native.symbols.csv_parser_create_latin1_quoted_rows;
210
225
  return (delimiter) => create(delimiter, fixedColumns ?? 0);
211
226
  }
212
- export function resolveNativeLibraryPath(configuredPath) {
213
- const root = dirname(dirname(fileURLToPath(import.meta.url)));
214
- const target = `${process.platform}-${process.arch}`;
215
- const libraryPath = configuredPath === void 0 ? requireNativeLibraryPath(nativeLibraryCandidates(root, target, suffix)) : requireConfiguredNativeLibraryPath(configuredPath);
227
+ export function resolveNativeLibraryPath(configuredPath, root = nativeLibraryRoot) {
228
+ if (configuredPath === null) {
229
+ const libraryPath = bundledNativeLibraryPath(root, nativeTarget, suffix);
230
+ if (!statSync(libraryPath, { throwIfNoEntry: !1 })?.isFile())
231
+ throw Error(`bundled native library not found for ${nativeTarget}`);
232
+ return resolve(libraryPath);
233
+ }
234
+ const libraryPath = configuredPath === void 0 ? requireNativeLibraryPath(nativeLibraryCandidates(root, nativeTarget, suffix)) : requireConfiguredNativeLibraryPath(configuredPath);
216
235
  return resolve(libraryPath);
217
236
  }
218
237
  export function requireConfiguredNativeLibraryPath(configuredPath) {
@@ -230,7 +249,7 @@ export function requireConfiguredNativeLibraryPath(configuredPath) {
230
249
  }
231
250
  export function nativeLibraryCandidates(root, target, librarySuffix) {
232
251
  return [
233
- join(root, "prebuilds", target, `libcsv_native.${librarySuffix}`),
252
+ bundledNativeLibraryPath(root, target, librarySuffix),
234
253
  join(root, "build", target, `libcsv_native.${librarySuffix}`),
235
254
  join(root, "build", target, "Release", `libcsv_native.${librarySuffix}`),
236
255
  join(root, "build", `libcsv_native.${librarySuffix}`),
@@ -238,6 +257,9 @@ export function nativeLibraryCandidates(root, target, librarySuffix) {
238
257
  join(root, `libcsv_native.${librarySuffix}`)
239
258
  ];
240
259
  }
260
+ function bundledNativeLibraryPath(root, target, librarySuffix) {
261
+ return join(root, "prebuilds", target, `libcsv_native.${librarySuffix}`);
262
+ }
241
263
  export function findNativeLibraryPath(candidates) {
242
264
  return candidates.find((candidate) => existsSync(candidate));
243
265
  }
@@ -8,16 +8,21 @@ export declare const MAX_PROJECTION_LENGTH = 2024;
8
8
  export declare const MAX_FILTER_COUNT = 2024;
9
9
  export declare const MAX_REGEX_FILTER_COUNT = 32;
10
10
  export declare const MAX_FILTER_PROGRAM_LENGTH = 4096;
11
+ export declare const MAX_FILTER_NESTING = 128;
11
12
  export declare function projectionFilterProgram(options: CsvNativeProjectionOptions): readonly CsvNativeFilterProgramEntry[] | undefined;
12
13
  export declare function encodingCode(encoding?: CsvNativeEncoding): number;
14
+ export declare function delimiterByte(delimiter: string, encoding: 'utf8' | 'latin1'): number;
13
15
  /**
14
16
  * Selects the byte encoding used by the native parser or a decoder for the input.
15
17
  * The three Latin-1 labels map bytes 0x80–0x9f directly to Unicode control characters.
16
18
  */
17
19
  export declare function resolveInputEncoding(encoding?: string, delimiter?: string): 'utf8' | 'latin1' | TextDecoder;
20
+ export declare const UTF8_BOM: readonly [239, 187, 191];
21
+ export declare function hasUtf8Bom(bytes: Uint8Array): boolean;
18
22
  /** Converts a complete buffer to bytes accepted by the native parser. */
19
23
  export declare function prepareCsvBufferInput(buffer: NodeJS.TypedArray | DataView, encoding?: CsvEncoding, delimiter?: string): PreparedCsvBufferInput;
20
24
  export declare function normalizeChunk(chunk: NodeJS.TypedArray | DataView): NodeJS.TypedArray | DataView;
25
+ export declare function validateChunkSize(chunkSize: number): void;
21
26
  export declare function validateCsvDialect({ quote, recordDelimiter }: Pick<CsvParserOptions, 'quote' | 'recordDelimiter'>): void;
22
27
  export declare function normalizeFixedColumnsCount(value: number | undefined, label: string): number | undefined;
23
28
  /** Reject stale JavaScript options before a requested projection can silently return all fields. */
package/dist/normalize.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  EMPTY_BUFFER,
3
3
  EMPTY_U32,
4
+ MAX_CHUNK_SIZE,
4
5
  native
5
6
  } from "./native.js";
6
7
  const LATIN1_ENCODINGS = new Set(["latin1", "iso88591", "iso-8859-1"]);
@@ -21,6 +22,7 @@ const NATIVE_FILTER_ANY = 8;
21
22
  const NATIVE_FILTER_NOT = 9;
22
23
  export const MAX_REGEX_FILTER_COUNT = 32;
23
24
  export const MAX_FILTER_PROGRAM_LENGTH = 4096;
25
+ export const MAX_FILTER_NESTING = 128;
24
26
  const MAX_REGEX_PATTERN_BYTES = 4096;
25
27
  export function projectionFilterProgram(options) {
26
28
  if (options.equalsFilter !== void 0 && options.filters !== void 0)
@@ -46,6 +48,14 @@ export function encodingCode(encoding = "utf8") {
46
48
  return 1;
47
49
  throw Error(`unsupported encoding: ${encoding}`);
48
50
  }
51
+ export function delimiterByte(delimiter, encoding) {
52
+ if (typeof delimiter !== "string" || delimiter.length !== 1)
53
+ throw Error("delimiter must be one character");
54
+ const byte = delimiter.charCodeAt(0);
55
+ if (byte > (encoding === "latin1" ? 255 : 127))
56
+ throw RangeError(`delimiter must fit in one ${encoding} byte`);
57
+ return byte;
58
+ }
49
59
  export function resolveInputEncoding(encoding = "utf8", delimiter) {
50
60
  if (encoding === "auto")
51
61
  throw Error("automatic encoding detection is only supported by file parsing APIs; specify encoding explicitly");
@@ -55,9 +65,11 @@ export function resolveInputEncoding(encoding = "utf8", delimiter) {
55
65
  return "latin1";
56
66
  if (typeof encoding !== "string")
57
67
  throw TypeError("encoding must be a string");
68
+ const normalizedLabel = encoding.trim().toLowerCase();
69
+ const decoderLabel = normalizedLabel === "cp949" ? "windows-949" : encoding;
58
70
  let decoder;
59
71
  try {
60
- decoder = new TextDecoder(encoding);
72
+ decoder = new TextDecoder(decoderLabel);
61
73
  } catch (cause) {
62
74
  if (cause instanceof RangeError)
63
75
  throw Error(`unsupported encoding: ${encoding}`, { cause });
@@ -65,15 +77,23 @@ export function resolveInputEncoding(encoding = "utf8", delimiter) {
65
77
  }
66
78
  if (decoder.encoding === "utf-8")
67
79
  return "utf8";
68
- if (decoder.encoding === "windows-1252" && LATIN1_ENCODINGS.has(encoding.trim().toLowerCase()))
80
+ if (decoder.encoding === "windows-1252" && LATIN1_ENCODINGS.has(normalizedLabel))
69
81
  return "latin1";
70
82
  if (delimiter !== void 0 && delimiter.charCodeAt(0) > 127)
71
83
  throw Error(`encoding ${decoder.encoding} requires an ASCII delimiter`);
72
84
  return decoder;
73
85
  }
86
+ export const UTF8_BOM = [239, 187, 191];
87
+ export function hasUtf8Bom(bytes) {
88
+ return bytes[0] === UTF8_BOM[0] && bytes[1] === UTF8_BOM[1] && bytes[2] === UTF8_BOM[2];
89
+ }
74
90
  export function prepareCsvBufferInput(buffer, encoding, delimiter) {
75
91
  const resolved = resolveInputEncoding(encoding, delimiter);
76
- if (typeof resolved === "string")
92
+ if (resolved === "utf8") {
93
+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
94
+ return { bytes: hasUtf8Bom(bytes) ? bytes.subarray(UTF8_BOM.length) : buffer, parserEncoding: resolved };
95
+ }
96
+ if (resolved === "latin1")
77
97
  return { bytes: buffer, parserEncoding: resolved };
78
98
  return {
79
99
  bytes: new TextEncoder().encode(resolved.decode(buffer)),
@@ -83,6 +103,12 @@ export function prepareCsvBufferInput(buffer, encoding, delimiter) {
83
103
  export function normalizeChunk(chunk) {
84
104
  return chunk.byteLength === 0 ? EMPTY_BUFFER : chunk;
85
105
  }
106
+ export function validateChunkSize(chunkSize) {
107
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0)
108
+ throw RangeError("chunkSize must be a positive safe integer");
109
+ if (chunkSize > MAX_CHUNK_SIZE)
110
+ throw RangeError("chunkSize must be at most 64 MiB");
111
+ }
86
112
  export function validateCsvDialect({ quote, recordDelimiter }) {
87
113
  if (quote !== void 0 && typeof quote !== "boolean")
88
114
  throw TypeError("quote must be a boolean");
@@ -321,7 +347,7 @@ export function normalizeNativeFilterProgram(program) {
321
347
  if (program.length > MAX_FILTER_PROGRAM_LENGTH)
322
348
  throw RangeError(`filter program length out of range: ${program.length}`);
323
349
  const predicates = [];
324
- let stackDepth = 0;
350
+ const depths = [];
325
351
  for (let index = 0;index < program.length; ++index) {
326
352
  const entry = program[index];
327
353
  if (entry === void 0)
@@ -330,7 +356,7 @@ export function normalizeNativeFilterProgram(program) {
330
356
  throw TypeError(`invalid filter program entry at index ${index}`);
331
357
  if (!isNativeFilterOperator(entry)) {
332
358
  predicates.push(entry);
333
- ++stackDepth;
359
+ depths.push(0);
334
360
  continue;
335
361
  }
336
362
  const { operandCount, operator } = entry;
@@ -338,12 +364,19 @@ export function normalizeNativeFilterProgram(program) {
338
364
  throw RangeError(`filter ${operator} operand count out of range: ${operandCount}`);
339
365
  if (operator === "not" && operandCount !== 1)
340
366
  throw RangeError(`filter not operand count must be 1: ${operandCount}`);
341
- if (operandCount > stackDepth)
367
+ if (operandCount > depths.length)
342
368
  throw RangeError(`filter ${operator} does not have ${operandCount} operands`);
343
- stackDepth -= operandCount - 1;
369
+ const firstOperand = depths.length - operandCount;
370
+ let maxOperandDepth = 0;
371
+ for (let operand = firstOperand;operand < depths.length; ++operand)
372
+ maxOperandDepth = Math.max(maxOperandDepth, depths[operand] ?? 0);
373
+ if (maxOperandDepth >= MAX_FILTER_NESTING)
374
+ throw RangeError(`filter nesting exceeds ${MAX_FILTER_NESTING}`);
375
+ depths.length = firstOperand;
376
+ depths.push(maxOperandDepth + 1);
344
377
  }
345
- if (stackDepth !== 1)
346
- throw Error(`filter program leaves ${stackDepth} results`);
378
+ if (depths.length !== 1)
379
+ throw Error(`filter program leaves ${depths.length} results`);
347
380
  const normalized = normalizeNativeFilters(predicates);
348
381
  const descriptors = new Uint32Array(program.length * NATIVE_FILTER_DESCRIPTOR_LENGTH);
349
382
  let predicateIndex = 0;
package/dist/options.d.ts CHANGED
@@ -1,32 +1,47 @@
1
- import type { CsvColumns, CsvCountOptions, CsvRowsOptions } from './types.js';
1
+ import type { CsvColumns, CsvColumnSelection, CsvCountBaseOptions, CsvCountOptions, CsvDialectOptions, CsvHeaderName, CsvHeaderSource, CsvIndexedRowsBaseOptions, CsvNamedCountBaseOptions, CsvNamedRowsBaseOptions, CsvOperationDialect, CsvParserOptions, CsvRowsOptions } from './types.js';
2
+ type OptionKeys<TOptions> = TOptions extends unknown ? keyof TOptions : never;
3
+ type InvalidDialectKey<TOptions> = TOptions extends unknown ? Pick<TOptions, keyof TOptions & keyof CsvOperationDialect> extends CsvOperationDialect ? never : 'strict' : never;
4
+ type DefinedOptions<TOptions, TBase> = TOptions & TBase & CsvDialectOptions & Pick<CsvParserOptions, 'strict'> & Record<Exclude<OptionKeys<TOptions>, keyof TBase | keyof CsvOperationDialect>, never> & Record<InvalidDialectKey<TOptions>, never>;
2
5
  /**
3
- * Preserve literal column inference for `csv.rows()` options.
6
+ * Check named options for `csv.rows()` and preserve literal projections and object keys.
4
7
  *
5
- * This identity helper is useful when options are declared separately from the call site. It
6
- * checks projection and strict validation options while retaining tuple literals for projected row
7
- * types. Each operation snapshots caller-owned option values when invoked.
8
+ * Use this identity helper when options are declared separately from the call site.
9
+ * Each parsing operation snapshots option values at invocation.
8
10
  *
9
- * @typeParam TColumns - Literal selected column indexes, when supplied.
11
+ * @typeParam THeaders - Names supplied by the caller, or `true` to read them from input.
12
+ * @typeParam TMapped - Whether to emit objects keyed by header name.
10
13
  * @typeParam TOptions - The complete rows option object to preserve.
11
14
  * @param options - Type-checked rows options.
12
15
  * @returns The same options object, with its literal type preserved.
13
16
  *
14
17
  * @example
15
18
  * ```ts
16
- * const options = defineRowsOptions({ columns: [0, 2] as const });
19
+ * const options = defineRowsOptions({ headers: true, columns: ['name'], mapped: true });
17
20
  * for await (const rows of csv.rows('data.csv', options)) {
18
- * const firstField = rows[0]?.[0];
21
+ * const firstName = rows[0]?.name;
19
22
  * }
20
23
  * ```
21
24
  */
22
- export declare function defineRowsOptions<const TColumns extends CsvColumns | undefined, const TOptions extends CsvRowsOptions<TColumns>>(options: TOptions): TOptions;
25
+ export declare function defineRowsOptions<const THeaders extends CsvHeaderSource, const TMapped extends boolean | undefined, const TOptions extends object>(options: DefinedOptions<TOptions, CsvNamedRowsBaseOptions<THeaders, readonly NoInfer<CsvHeaderName<THeaders>>[] | undefined, TMapped>>): TOptions;
23
26
  /**
24
- * Preserve literal inference for `csv.count()` options.
27
+ * Check indexed options for `csv.rows()` and return the same object with literal column indexes preserved.
28
+ * @param options - Options for streaming array rows using zero-based column indexes.
29
+ */
30
+ export declare function defineRowsOptions<const TColumns extends CsvColumns | undefined, const TOptions extends CsvRowsOptions<TColumns>>(options: DefinedOptions<TOptions, CsvIndexedRowsBaseOptions & CsvColumnSelection<TColumns>>): TOptions;
31
+ /**
32
+ * Check named options for `csv.count()` and preserve literal header names.
25
33
  *
26
- * The helper checks that strict counts use unfiltered input and returns the original object.
34
+ * The helper checks counting, filtering, and validation options and returns the original object.
27
35
  *
36
+ * @typeParam THeaders - Names supplied by the caller, or `true` to read them from input.
28
37
  * @typeParam TOptions - The complete count option object to preserve.
29
38
  * @param options - Type-checked count options.
30
39
  * @returns The same options object, with its literal type preserved.
31
40
  */
32
- export declare function defineCountOptions<const TOptions extends CsvCountOptions>(options: TOptions): TOptions;
41
+ export declare function defineCountOptions<const THeaders extends CsvHeaderSource, const TOptions extends object>(options: DefinedOptions<TOptions, CsvNamedCountBaseOptions<THeaders>>): TOptions;
42
+ /**
43
+ * Check indexed options for `csv.count()` and return the same object with its literal type preserved.
44
+ * @param options - Count options with predicates on zero-based input columns.
45
+ */
46
+ export declare function defineCountOptions<const TOptions extends CsvCountOptions>(options: DefinedOptions<TOptions, CsvCountBaseOptions>): TOptions;
47
+ export {};