@konstit/csv 0.6.0 → 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 (53) hide show
  1. package/README.md +113 -101
  2. package/THIRD_PARTY_NOTICES.md +27 -0
  3. package/dist/api.d.ts +84 -57
  4. package/dist/api.js +211 -40
  5. package/dist/batch-pipeline.d.ts +10 -0
  6. package/dist/batch-pipeline.js +83 -0
  7. package/dist/batches.d.ts +36 -1
  8. package/dist/batches.js +241 -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 +66 -18
  15. package/dist/file-stream.js +534 -199
  16. package/dist/files.d.ts +17 -37
  17. package/dist/files.js +50 -21
  18. package/dist/gzip-reader.d.ts +2 -0
  19. package/dist/gzip-reader.js +37 -0
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +2 -2
  22. package/dist/inspect-file.d.ts +26 -3
  23. package/dist/inspect-file.js +169 -74
  24. package/dist/inspect-zip.d.ts +26 -0
  25. package/dist/inspect-zip.js +59 -0
  26. package/dist/latin1-rows.d.ts +11 -3
  27. package/dist/latin1-rows.js +276 -75
  28. package/dist/materialize-field.d.ts +6 -0
  29. package/dist/materialize-field.js +9 -0
  30. package/dist/native.d.ts +118 -20
  31. package/dist/native.js +53 -23
  32. package/dist/normalize.d.ts +7 -1
  33. package/dist/normalize.js +49 -9
  34. package/dist/options.d.ts +27 -12
  35. package/dist/parser.d.ts +34 -14
  36. package/dist/parser.js +296 -102
  37. package/dist/strict-schema.d.ts +7 -8
  38. package/dist/strict-schema.js +45 -83
  39. package/dist/transforms.d.ts +1 -3
  40. package/dist/transforms.js +17 -16
  41. package/dist/types.d.ts +192 -75
  42. package/dist/zip-entry.d.ts +14 -0
  43. package/dist/zip-entry.js +155 -0
  44. package/dist/zip-reader.d.ts +14 -3
  45. package/dist/zip-reader.js +65 -23
  46. package/package.json +34 -23
  47. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  48. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  49. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  50. package/prebuilds/manifest.json +18 -8
  51. package/prebuilds/provenance/darwin-arm64.json +1 -1
  52. package/prebuilds/provenance/darwin-x64.json +1 -1
  53. package/prebuilds/provenance/linux-x64.json +1 -1
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
  /**
@@ -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
  };
@@ -45,6 +42,14 @@ export declare const native: import("bun:ffi").Library<{
45
42
  readonly args: readonly ["int", "u8", "u32"];
46
43
  readonly returns: "ptr";
47
44
  };
45
+ readonly csv_parser_create_dialect: {
46
+ readonly args: readonly ["int", "u8", "u32", "bool", "bool"];
47
+ readonly returns: "ptr";
48
+ };
49
+ readonly csv_parser_write_raw_records: {
50
+ readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
51
+ readonly returns: "ptr";
52
+ };
48
53
  readonly csv_parser_enable_transformed_quoted_spans: {
49
54
  readonly args: readonly ["ptr"];
50
55
  readonly returns: "void";
@@ -53,14 +58,34 @@ export declare const native: import("bun:ffi").Library<{
53
58
  readonly args: readonly ["ptr", "u64", "u64", "bool"];
54
59
  readonly returns: "void";
55
60
  };
56
- 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: {
57
66
  readonly args: readonly ["ptr"];
58
- readonly returns: "ptr";
67
+ readonly returns: "u64";
68
+ };
69
+ readonly csv_parser_set_skip_empty_lines: {
70
+ readonly args: readonly ["ptr"];
71
+ readonly returns: "void";
59
72
  };
60
- readonly csv_parser_skipped_rows: {
73
+ readonly csv_parser_schema_rows: {
61
74
  readonly args: readonly ["ptr"];
62
75
  readonly returns: "u64";
63
76
  };
77
+ readonly csv_parser_header_record: {
78
+ readonly args: readonly ["ptr"];
79
+ readonly returns: "u64";
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
+ };
64
89
  readonly csv_parser_destroy: {
65
90
  readonly args: readonly ["ptr"];
66
91
  readonly returns: "void";
@@ -81,10 +106,6 @@ export declare const native: import("bun:ffi").Library<{
81
106
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32"];
82
107
  readonly returns: "ptr";
83
108
  };
84
- readonly csv_parser_write_strict_fixed_batch: {
85
- readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32"];
86
- readonly returns: "ptr";
87
- };
88
109
  readonly csv_batch_destroy: {
89
110
  readonly args: readonly ["ptr"];
90
111
  readonly returns: "void";
@@ -121,16 +142,12 @@ export declare const native: import("bun:ffi").Library<{
121
142
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
122
143
  readonly returns: "u64";
123
144
  };
124
- readonly csv_parser_count_trusted_newlines: {
125
- readonly args: readonly ["buffer", "buffer_length"];
126
- readonly returns: "u64";
127
- };
128
145
  readonly csv_regex_validate: {
129
146
  readonly args: readonly ["buffer", "buffer_length"];
130
147
  readonly returns: "cstring";
131
148
  };
132
- readonly csv_parser_find_split_offsets: {
133
- readonly args: readonly ["cstring", "u64", "u8"];
149
+ readonly csv_parser_find_split_offsets_v2: {
150
+ readonly args: readonly ["cstring", "u64", "u8", "bool"];
134
151
  readonly returns: "ptr";
135
152
  };
136
153
  readonly csv_split_offsets_batch_destroy: {
@@ -145,10 +162,42 @@ export declare const native: import("bun:ffi").Library<{
145
162
  readonly args: readonly ["ptr"];
146
163
  readonly returns: "ptr";
147
164
  };
165
+ readonly csv_gzip_reader_create: {
166
+ readonly args: readonly ["i32"];
167
+ readonly returns: "ptr";
168
+ };
169
+ readonly csv_gzip_reader_destroy: {
170
+ readonly args: readonly ["ptr"];
171
+ readonly returns: "void";
172
+ };
173
+ readonly csv_gzip_reader_enable_read_ahead: {
174
+ readonly args: readonly ["ptr", "u32"];
175
+ readonly returns: "void";
176
+ };
177
+ readonly csv_gzip_reader_read: {
178
+ readonly args: readonly ["ptr", "buffer", "buffer_length"];
179
+ readonly returns: FFIType.i64_fast;
180
+ };
181
+ readonly csv_gzip_reader_last_error: {
182
+ readonly args: readonly ["ptr"];
183
+ readonly returns: "cstring";
184
+ };
148
185
  readonly csv_zip_reader_create: {
149
186
  readonly args: readonly ["cstring", "buffer", "buffer_length", "u64", "u32"];
150
187
  readonly returns: "ptr";
151
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
+ };
152
201
  readonly csv_zip_reader_destroy: {
153
202
  readonly args: readonly ["ptr"];
154
203
  readonly returns: "void";
@@ -157,10 +206,30 @@ export declare const native: import("bun:ffi").Library<{
157
206
  readonly args: readonly ["ptr", "buffer"];
158
207
  readonly returns: "ptr";
159
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
+ };
160
221
  readonly csv_zip_reader_enable_read_ahead: {
161
222
  readonly args: readonly ["ptr", "u32"];
162
223
  readonly returns: "void";
163
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
+ };
164
233
  readonly csv_zip_reader_read: {
165
234
  readonly args: readonly ["ptr", "buffer", "buffer_length"];
166
235
  readonly returns: "u64";
@@ -185,6 +254,34 @@ export declare const native: import("bun:ffi").Library<{
185
254
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
186
255
  readonly returns: "ptr";
187
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
+ };
188
285
  readonly csv_parser_write_prepared_count: {
189
286
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
190
287
  readonly returns: "u64";
@@ -215,7 +312,8 @@ export declare const native: import("bun:ffi").Library<{
215
312
  };
216
313
  }>;
217
314
  export declare function latin1RowsParser(fixedColumns: number | undefined, cleanup?: boolean): (delimiter: number) => NativePointer | null;
218
- 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;
219
317
  export declare function requireConfiguredNativeLibraryPath(configuredPath: string): string;
220
318
  export declare function nativeLibraryCandidates(root: string, target: string, librarySuffix: string): readonly string[];
221
319
  export declare function findNativeLibraryPath(candidates: readonly string[]): string | undefined;
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 {
@@ -15,9 +16,7 @@ import {
15
16
  import { fileURLToPath } from "node:url";
16
17
  export { toArrayBuffer } from "bun:ffi";
17
18
  const EMPTY_BUFFER_STORAGE = new Uint8Array(1);
18
- export const EMPTY_BUFFER = EMPTY_BUFFER_STORAGE.subarray(0, 0);
19
- export const EMPTY_U32 = new Uint32Array(1);
20
- 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;
21
20
  const CSV_SYMBOLS = {
22
21
  csv_parser_add_transform: { args: ["ptr", "u32", "u32"], returns: "bool" },
23
22
  csv_parser_add_transform_with_default: {
@@ -31,8 +30,7 @@ const CSV_SYMBOLS = {
31
30
  returns: "bool"
32
31
  },
33
32
  csv_parser_transform_pair: { args: ["ptr", "u32", "buffer", "buffer_length", "buffer", "buffer_length"], returns: "bool" },
34
- csv_parser_transform_validated_batch: { args: ["ptr", "ptr"], returns: "ptr" },
35
- csv_probe_format_v2: {
33
+ csv_probe_format_v3: {
36
34
  args: [
37
35
  "buffer",
38
36
  "u32",
@@ -51,10 +49,17 @@ const CSV_SYMBOLS = {
51
49
  returns: "ptr"
52
50
  },
53
51
  csv_parser_create_prepared: { args: ["int", "u8", "u32"], returns: "ptr" },
52
+ csv_parser_create_dialect: { args: ["int", "u8", "u32", "bool", "bool"], returns: "ptr" },
53
+ csv_parser_write_raw_records: { args: ["ptr", "buffer", "buffer_length", "bool"], returns: "ptr" },
54
54
  csv_parser_enable_transformed_quoted_spans: { args: ["ptr"], returns: "void" },
55
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" },
56
62
  csv_parser_take_skipped_header: { args: ["ptr"], returns: "ptr" },
57
- csv_parser_skipped_rows: { args: ["ptr"], returns: "u64" },
58
63
  csv_parser_destroy: {
59
64
  args: ["ptr"],
60
65
  returns: "void"
@@ -75,10 +80,6 @@ const CSV_SYMBOLS = {
75
80
  args: ["ptr", "buffer", "buffer_length", "bool", "u32"],
76
81
  returns: "ptr"
77
82
  },
78
- csv_parser_write_strict_fixed_batch: {
79
- args: ["ptr", "buffer", "buffer_length", "bool", "u32"],
80
- returns: "ptr"
81
- },
82
83
  csv_batch_destroy: {
83
84
  args: ["ptr"],
84
85
  returns: "void"
@@ -115,16 +116,12 @@ const CSV_SYMBOLS = {
115
116
  args: ["ptr", "buffer", "buffer_length", "bool"],
116
117
  returns: "u64"
117
118
  },
118
- csv_parser_count_trusted_newlines: {
119
- args: ["buffer", "buffer_length"],
120
- returns: "u64"
121
- },
122
119
  csv_regex_validate: {
123
120
  args: ["buffer", "buffer_length"],
124
121
  returns: "cstring"
125
122
  },
126
- csv_parser_find_split_offsets: {
127
- args: ["cstring", "u64", "u8"],
123
+ csv_parser_find_split_offsets_v2: {
124
+ args: ["cstring", "u64", "u8", "bool"],
128
125
  returns: "ptr"
129
126
  },
130
127
  csv_split_offsets_batch_destroy: {
@@ -139,10 +136,21 @@ const CSV_SYMBOLS = {
139
136
  args: ["ptr"],
140
137
  returns: "ptr"
141
138
  },
139
+ csv_gzip_reader_create: { args: ["i32"], returns: "ptr" },
140
+ csv_gzip_reader_destroy: { args: ["ptr"], returns: "void" },
141
+ csv_gzip_reader_enable_read_ahead: { args: ["ptr", "u32"], returns: "void" },
142
+ csv_gzip_reader_read: { args: ["ptr", "buffer", "buffer_length"], returns: FFIType.i64_fast },
143
+ csv_gzip_reader_last_error: { args: ["ptr"], returns: "cstring" },
142
144
  csv_zip_reader_create: {
143
145
  args: ["cstring", "buffer", "buffer_length", "u64", "u32"],
144
146
  returns: "ptr"
145
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
+ },
146
154
  csv_zip_reader_destroy: {
147
155
  args: ["ptr"],
148
156
  returns: "void"
@@ -151,10 +159,18 @@ const CSV_SYMBOLS = {
151
159
  args: ["ptr", "buffer"],
152
160
  returns: "ptr"
153
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" },
154
165
  csv_zip_reader_enable_read_ahead: {
155
166
  args: ["ptr", "u32"],
156
167
  returns: "void"
157
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
+ },
158
174
  csv_zip_reader_read: {
159
175
  args: ["ptr", "buffer", "buffer_length"],
160
176
  returns: "u64"
@@ -179,6 +195,13 @@ const CSV_SYMBOLS = {
179
195
  args: ["ptr", "buffer", "buffer_length", "bool"],
180
196
  returns: "ptr"
181
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" },
182
205
  csv_parser_write_prepared_count: {
183
206
  args: ["ptr", "buffer", "buffer_length", "bool"],
184
207
  returns: "u64"
@@ -195,16 +218,20 @@ const CSV_SYMBOLS = {
195
218
  args: ["u8", "u32"],
196
219
  returns: "ptr"
197
220
  }
198
- };
199
- 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);
200
223
  export function latin1RowsParser(fixedColumns, cleanup = !1) {
201
224
  const create = cleanup ? native.symbols.csv_parser_create_latin1_cleanup_rows : native.symbols.csv_parser_create_latin1_quoted_rows;
202
225
  return (delimiter) => create(delimiter, fixedColumns ?? 0);
203
226
  }
204
- export function resolveNativeLibraryPath(configuredPath) {
205
- const root = dirname(dirname(fileURLToPath(import.meta.url)));
206
- const target = `${process.platform}-${process.arch}`;
207
- 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);
208
235
  return resolve(libraryPath);
209
236
  }
210
237
  export function requireConfiguredNativeLibraryPath(configuredPath) {
@@ -222,7 +249,7 @@ export function requireConfiguredNativeLibraryPath(configuredPath) {
222
249
  }
223
250
  export function nativeLibraryCandidates(root, target, librarySuffix) {
224
251
  return [
225
- join(root, "prebuilds", target, `libcsv_native.${librarySuffix}`),
252
+ bundledNativeLibraryPath(root, target, librarySuffix),
226
253
  join(root, "build", target, `libcsv_native.${librarySuffix}`),
227
254
  join(root, "build", target, "Release", `libcsv_native.${librarySuffix}`),
228
255
  join(root, "build", `libcsv_native.${librarySuffix}`),
@@ -230,6 +257,9 @@ export function nativeLibraryCandidates(root, target, librarySuffix) {
230
257
  join(root, `libcsv_native.${librarySuffix}`)
231
258
  ];
232
259
  }
260
+ function bundledNativeLibraryPath(root, target, librarySuffix) {
261
+ return join(root, "prebuilds", target, `libcsv_native.${librarySuffix}`);
262
+ }
233
263
  export function findNativeLibraryPath(candidates) {
234
264
  return candidates.find((candidate) => existsSync(candidate));
235
265
  }
@@ -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';
@@ -8,16 +8,22 @@ 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;
26
+ export declare function validateCsvDialect({ quote, recordDelimiter }: Pick<CsvParserOptions, 'quote' | 'recordDelimiter'>): void;
21
27
  export declare function normalizeFixedColumnsCount(value: number | undefined, label: string): number | undefined;
22
28
  /** Reject stale JavaScript options before a requested projection can silently return all fields. */
23
29
  export declare function rejectSelectedColumns(options: object): void;
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,19 @@ 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
+ }
112
+ export function validateCsvDialect({ quote, recordDelimiter }) {
113
+ if (quote !== void 0 && typeof quote !== "boolean")
114
+ throw TypeError("quote must be a boolean");
115
+ if (recordDelimiter !== void 0 && recordDelimiter !== `
116
+ `)
117
+ throw TypeError("recordDelimiter must be LF");
118
+ }
86
119
  export function normalizeFixedColumnsCount(value, label) {
87
120
  if (value === void 0)
88
121
  return;
@@ -314,7 +347,7 @@ export function normalizeNativeFilterProgram(program) {
314
347
  if (program.length > MAX_FILTER_PROGRAM_LENGTH)
315
348
  throw RangeError(`filter program length out of range: ${program.length}`);
316
349
  const predicates = [];
317
- let stackDepth = 0;
350
+ const depths = [];
318
351
  for (let index = 0;index < program.length; ++index) {
319
352
  const entry = program[index];
320
353
  if (entry === void 0)
@@ -323,7 +356,7 @@ export function normalizeNativeFilterProgram(program) {
323
356
  throw TypeError(`invalid filter program entry at index ${index}`);
324
357
  if (!isNativeFilterOperator(entry)) {
325
358
  predicates.push(entry);
326
- ++stackDepth;
359
+ depths.push(0);
327
360
  continue;
328
361
  }
329
362
  const { operandCount, operator } = entry;
@@ -331,12 +364,19 @@ export function normalizeNativeFilterProgram(program) {
331
364
  throw RangeError(`filter ${operator} operand count out of range: ${operandCount}`);
332
365
  if (operator === "not" && operandCount !== 1)
333
366
  throw RangeError(`filter not operand count must be 1: ${operandCount}`);
334
- if (operandCount > stackDepth)
367
+ if (operandCount > depths.length)
335
368
  throw RangeError(`filter ${operator} does not have ${operandCount} operands`);
336
- 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);
337
377
  }
338
- if (stackDepth !== 1)
339
- throw Error(`filter program leaves ${stackDepth} results`);
378
+ if (depths.length !== 1)
379
+ throw Error(`filter program leaves ${depths.length} results`);
340
380
  const normalized = normalizeNativeFilters(predicates);
341
381
  const descriptors = new Uint32Array(program.length * NATIVE_FILTER_DESCRIPTOR_LENGTH);
342
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 {};