@konstit/csv 0.4.3 → 0.5.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 (63) hide show
  1. package/README.md +42 -26
  2. package/THIRD_PARTY_NOTICES.md +7 -1
  3. package/dist/api.d.ts +39 -249
  4. package/dist/api.js +40 -304
  5. package/dist/batches.d.ts +5 -53
  6. package/dist/batches.js +66 -43
  7. package/dist/cli-command.d.ts +7 -0
  8. package/dist/cli-command.js +350 -0
  9. package/dist/cli-schema.d.ts +111 -0
  10. package/dist/cli-schema.js +219 -0
  11. package/dist/cli.js +2 -604
  12. package/dist/file-stream.d.ts +57 -2
  13. package/dist/file-stream.js +241 -36
  14. package/dist/files.d.ts +11 -11
  15. package/dist/files.js +11 -9
  16. package/dist/filter.d.ts +4 -6
  17. package/dist/format-bytes.d.ts +1 -0
  18. package/dist/format-bytes.js +11 -0
  19. package/dist/index.d.ts +3 -3
  20. package/dist/index.js +2 -14
  21. package/dist/inspect-file.d.ts +12 -0
  22. package/dist/inspect-file.js +88 -0
  23. package/dist/latin1-rows.d.ts +3 -1
  24. package/dist/latin1-rows.js +61 -23
  25. package/dist/materialize-field.d.ts +2 -0
  26. package/dist/materialize-field.js +20 -15
  27. package/dist/native.d.ts +29 -9
  28. package/dist/native.js +27 -29
  29. package/dist/normalize.d.ts +15 -2
  30. package/dist/normalize.js +41 -2
  31. package/dist/options-snapshot.js +3 -2
  32. package/dist/options.d.ts +4 -30
  33. package/dist/options.js +0 -6
  34. package/dist/parser.d.ts +14 -15
  35. package/dist/parser.js +38 -54
  36. package/dist/strict-schema.d.ts +5 -3
  37. package/dist/types.d.ts +88 -222
  38. package/dist/zip-reader.d.ts +11 -1
  39. package/dist/zip-reader.js +12 -3
  40. package/package.json +34 -32
  41. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  42. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  43. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  44. package/prebuilds/manifest.json +9 -8
  45. package/prebuilds/provenance/darwin-arm64.json +1 -1
  46. package/prebuilds/provenance/darwin-x64.json +1 -1
  47. package/prebuilds/provenance/linux-x64.json +1 -1
  48. package/dist/worker-count.d.ts +0 -34
  49. package/dist/worker-count.js +0 -101
  50. package/dist/worker-factory.d.ts +0 -3
  51. package/dist/worker-factory.js +0 -9
  52. package/dist/worker-filter.d.ts +0 -29
  53. package/dist/worker-filter.js +0 -46
  54. package/dist/worker-module.d.ts +0 -1
  55. package/dist/worker-module.js +0 -4
  56. package/dist/worker-pool.d.ts +0 -93
  57. package/dist/worker-pool.js +0 -298
  58. package/dist/worker-rows.d.ts +0 -36
  59. package/dist/worker-rows.js +0 -127
  60. package/dist/workers/count.worker.d.ts +0 -1
  61. package/dist/workers/count.worker.js +0 -36
  62. package/dist/workers/rows.worker.d.ts +0 -1
  63. package/dist/workers/rows.worker.js +0 -56
@@ -1,11 +1,27 @@
1
+ import { ptr } from "bun:ffi";
1
2
  import { createReadStream } from "node:fs";
3
+ import {
4
+ open,
5
+ stat
6
+ } from "node:fs/promises";
2
7
  import { extname } from "node:path";
3
- import { DEFAULT_CHUNK_SIZE } from "./native.js";
8
+ import { ReadableStream as WebReadableStream } from "node:stream/web";
9
+ import {
10
+ constants,
11
+ inflateSync
12
+ } from "node:zlib";
13
+ import {
14
+ DEFAULT_CHUNK_SIZE,
15
+ EMPTY_BUFFER,
16
+ native
17
+ } from "./native.js";
18
+ import { resolveInputEncoding } from "./normalize.js";
4
19
  import { snapshotCsvOptions } from "./options-snapshot.js";
5
20
  import { readZipEntryChunks } from "./zip-reader.js";
6
- const DELIMITER_PROBE_SIZE = 65536;
21
+ export const FILE_PROBE_SIZE = 65536;
22
+ const PROBED_BYTE_ENCODINGS = ["utf8", "latin1", "windows-1252"];
7
23
  const MAX_DELIMITER_PROBE_ROWS = 128;
8
- const DELIMITER_CANDIDATES = [
24
+ export const DELIMITER_CANDIDATES = [
9
25
  { byte: 44, delimiter: "," },
10
26
  { byte: 9, delimiter: "\t" },
11
27
  { byte: 59, delimiter: ";" },
@@ -25,30 +41,41 @@ const COMPRESSION_EXTENSIONS = [
25
41
  ".gz",
26
42
  ".zz"
27
43
  ];
28
- export async function prepareCsvFileInput(path, suppliedOptions) {
44
+ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "parse", probeFormat = probeCsvFileFormat) {
29
45
  const options = snapshotCsvOptions(suppliedOptions);
46
+ const autoEncoding = options.encoding === void 0 || options.encoding === "auto";
47
+ const inputEncoding = autoEncoding ? "utf8" : resolveInputEncoding(options.encoding, options.delimiter);
48
+ const parserEncoding = typeof inputEncoding === "string" ? inputEncoding : "utf8";
49
+ const source = () => {
50
+ const chunks = readCsvFileChunks(path, options, readMode);
51
+ return typeof inputEncoding === "string" ? chunks : transcodeCsvChunks(chunks, inputEncoding);
52
+ };
30
53
  const configuredDelimiter = options.delimiter ?? ",";
31
- if (configuredDelimiter !== "auto") {
54
+ if (!autoEncoding && configuredDelimiter !== "auto") {
32
55
  let opened = !1;
33
56
  return {
34
57
  delimiter: configuredDelimiter,
58
+ parserEncoding,
35
59
  chunks() {
36
60
  if (opened)
37
61
  throw Error("CSV file input can only be read once");
38
62
  opened = !0;
39
- return readCsvFileChunks(path, options);
63
+ return source();
40
64
  },
41
65
  [Symbol.asyncDispose]() {
42
66
  return Promise.resolve();
43
67
  }
44
68
  };
45
69
  }
46
- const iterator = readCsvFileChunks(path, options)[Symbol.asyncIterator]();
70
+ const iterator = source()[Symbol.asyncIterator]();
71
+ const compression = options.compression ?? "auto";
72
+ const reusesReadBuffer = typeof inputEncoding === "string" && (readMode === "read-ahead" && (compression === "auto" || compression === "none") || (compression === "auto" || isZipCompression(compression)) && useZipReadAhead(readMode, options.chunkSize ?? DEFAULT_CHUNK_SIZE));
47
73
  const bufferedChunks = [];
48
74
  let bufferedByteLength = 0;
49
75
  let sourceEnded = !1;
76
+ let bytesNeeded = FILE_PROBE_SIZE;
50
77
  try {
51
- while (bufferedByteLength < DELIMITER_PROBE_SIZE) {
78
+ while (bufferedByteLength < bytesNeeded) {
52
79
  const result = await iterator.next();
53
80
  if (result.done === !0) {
54
81
  sourceEnded = !0;
@@ -56,19 +83,35 @@ export async function prepareCsvFileInput(path, suppliedOptions) {
56
83
  }
57
84
  if (result.value.byteLength === 0)
58
85
  continue;
59
- bufferedChunks.push(result.value);
60
86
  bufferedByteLength += result.value.byteLength;
87
+ if (bufferedByteLength === FILE_PROBE_SIZE && (configuredDelimiter === "auto" || autoEncoding && mayEndInPartialUtf8(result.value)))
88
+ ++bytesNeeded;
89
+ bufferedChunks.push(reusesReadBuffer && bufferedByteLength < bytesNeeded ? new Uint8Array(result.value) : result.value);
61
90
  }
62
91
  const probe = copyProbePrefix(bufferedChunks, bufferedByteLength);
63
- const delimiter = detectDelimiter(delimiterHintPath(path, options.compression), probe, sourceEnded);
92
+ const hint = delimiterHintPath(path, options.compression);
93
+ const format = autoEncoding ? probeFormat(hint, probe, sourceEnded, configuredDelimiter) : void 0;
94
+ const delimiter = format?.delimiter ?? detectDelimiter(hint, probe, sourceEnded);
95
+ const replayEncoding = format === void 0 ? parserEncoding : resolveInputEncoding(format.encoding, delimiter);
96
+ let skip = format?.skipBytes ?? 0;
97
+ if (skip > 0)
98
+ for (const [i, chunk] of bufferedChunks.entries()) {
99
+ const length = Math.min(skip, chunk.length);
100
+ bufferedChunks[i] = chunk.subarray(length);
101
+ skip -= length;
102
+ if (skip === 0)
103
+ break;
104
+ }
64
105
  let opened = !1;
65
106
  return {
66
107
  delimiter,
108
+ parserEncoding: typeof replayEncoding === "string" ? replayEncoding : "utf8",
67
109
  chunks() {
68
110
  if (opened)
69
111
  throw Error("CSV file input can only be read once");
70
112
  opened = !0;
71
- return replayCsvFileChunks(bufferedChunks, iterator);
113
+ const replay = replayCsvFileChunks(bufferedChunks, iterator);
114
+ return typeof replayEncoding === "string" ? replay : transcodeCsvChunks(replay, replayEncoding);
72
115
  },
73
116
  [Symbol.asyncDispose]() {
74
117
  return closeCsvFileIterator(iterator);
@@ -79,20 +122,50 @@ export async function prepareCsvFileInput(path, suppliedOptions) {
79
122
  throw error;
80
123
  }
81
124
  }
82
- export function readCsvFileChunks(path, suppliedOptions) {
125
+ async function* readAheadFileChunks(path, chunkSize) {
126
+ if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0)
127
+ throw RangeError("chunkSize must be a positive safe integer");
128
+ await using file = await open(path, "r");
129
+ if (!(await file.stat()).isFile()) {
130
+ const buffer = Buffer.allocUnsafe(chunkSize);
131
+ let { bytesRead } = await file.read(buffer);
132
+ while (bytesRead > 0) {
133
+ yield buffer.subarray(0, bytesRead);
134
+ bytesRead = (await file.read(buffer)).bytesRead;
135
+ }
136
+ return;
137
+ }
138
+ let current = Buffer.allocUnsafe(chunkSize);
139
+ let spare = Buffer.allocUnsafe(chunkSize);
140
+ let { bytesRead } = await file.read(current);
141
+ while (bytesRead > 0) {
142
+ const pending = file.read(spare);
143
+ void pending.catch(() => {});
144
+ yield bytesRead === current.length ? current : current.subarray(0, bytesRead);
145
+ bytesRead = (await pending).bytesRead;
146
+ [current, spare] = [spare, current];
147
+ }
148
+ }
149
+ export function readCsvFileChunks(path, suppliedOptions, readMode = "stream") {
83
150
  const options = snapshotCsvOptions(suppliedOptions);
84
151
  const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
85
- if (options.compression === void 0)
86
- return createReadStream(path, { highWaterMark: chunkSize });
87
- if (isZipCompression(options.compression))
88
- return readZipEntryChunks(path, options.compression, chunkSize);
89
- if (options.compression === "auto")
90
- return readAutoDetectedCsvFileChunks(path, chunkSize);
91
- return decompressedCsvFileChunks(path, options.compression, chunkSize);
152
+ const compression = options.compression ?? "auto";
153
+ const zipReadAhead = useZipReadAhead(readMode, chunkSize);
154
+ if (isZipCompression(compression))
155
+ return readZipEntryChunks(path, compression, chunkSize, zipReadAhead);
156
+ if (compression === "auto" || compression === "none") {
157
+ const readAhead = readMode === "read-ahead";
158
+ const raw = readAhead ? readAheadFileChunks(path, chunkSize) : createReadStream(path, { highWaterMark: chunkSize });
159
+ return compression === "none" ? raw : readAutoDetectedCsvFileChunks(path, raw, chunkSize, readAhead, zipReadAhead);
160
+ }
161
+ return decompressedCsvFileChunks(path, compression, chunkSize);
92
162
  }
93
163
  function isZipCompression(compression) {
94
164
  return typeof compression === "object" && compression.format === "zip";
95
165
  }
166
+ function useZipReadAhead(mode, chunkSize) {
167
+ return mode === "count" || mode !== "stream" && chunkSize >= 65536;
168
+ }
96
169
  function delimiterHintPath(path, compression) {
97
170
  return compression !== void 0 && isZipCompression(compression) ? compression.entry : path;
98
171
  }
@@ -117,13 +190,38 @@ async function* replayCsvFileChunks(bufferedChunks, iterator) {
117
190
  await closeCsvFileIterator(iterator);
118
191
  }
119
192
  }
193
+ async function* transcodeCsvChunks(source, decoder) {
194
+ const encoder = new TextEncoder;
195
+ for await (const chunk of source) {
196
+ const text = decoder.decode(chunk, { stream: !0 });
197
+ if (text.length > 0)
198
+ yield encoder.encode(text);
199
+ }
200
+ const text = decoder.decode();
201
+ if (text.length > 0)
202
+ yield encoder.encode(text);
203
+ }
120
204
  async function closeCsvFileIterator(iterator) {
121
205
  try {
122
206
  await iterator.return?.();
123
207
  } catch {}
124
208
  }
209
+ function mayEndInPartialUtf8(chunk) {
210
+ let index = chunk.length - 1;
211
+ while (index >= 0 && chunk.length - index < 4 && ((chunk[index] ?? 0) & 192) === 128)
212
+ --index;
213
+ const length = chunk.length - index;
214
+ if (length >= 4)
215
+ return !1;
216
+ if (index < 0)
217
+ return !0;
218
+ const lead = chunk[index] ?? 0;
219
+ if (lead < 194 || lead > 244)
220
+ return !1;
221
+ return length < (lead < 224 ? 2 : lead < 240 ? 3 : 4);
222
+ }
125
223
  function copyProbePrefix(chunks, totalByteLength) {
126
- const probe = new Uint8Array(Math.min(totalByteLength, DELIMITER_PROBE_SIZE));
224
+ const probe = new Uint8Array(Math.min(totalByteLength, FILE_PROBE_SIZE));
127
225
  let offset = 0;
128
226
  for (const chunk of chunks) {
129
227
  if (offset === probe.byteLength)
@@ -135,10 +233,53 @@ function copyProbePrefix(chunks, totalByteLength) {
135
233
  }
136
234
  return probe;
137
235
  }
138
- function detectDelimiter(path, probe, sourceEnded) {
139
- const rows = scanDelimiterCounts(probe, sourceEnded);
236
+ export function detectDelimiter(path, probe, sourceEnded) {
237
+ return requireDelimiter(path, scanDelimiterCounts(probe, sourceEnded));
238
+ }
239
+ export const probeCsvFileFormat = (path, prefix, sourceEnded, delimiter) => {
240
+ const { encoding, skipBytes, counts } = scanCsvFileFormat(prefix, sourceEnded, delimiter === "auto");
241
+ return { encoding, delimiter: delimiter === "auto" ? requireDelimiter(path, counts) : delimiter, skipBytes };
242
+ };
243
+ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
244
+ let bytes = prefix;
245
+ let bomEncoding;
246
+ let skipBytes = 0;
247
+ if (bytes[0] === 255 && bytes[1] === 254 && bytes[2] === 0 && bytes[3] === 0 || bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 254 && bytes[3] === 255)
248
+ throw Error("automatic encoding detection does not support UTF-32; transcode the input to UTF-8");
249
+ if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) {
250
+ bomEncoding = "utf8";
251
+ skipBytes = 3;
252
+ bytes = bytes.subarray(skipBytes);
253
+ } else if (bytes[0] === 255 && bytes[1] === 254)
254
+ bomEncoding = "utf-16le";
255
+ else if (bytes[0] === 254 && bytes[1] === 255)
256
+ bomEncoding = "utf-16be";
257
+ if (bomEncoding !== void 0) {
258
+ if (!scoreDelimiters)
259
+ return { bytes, encoding: bomEncoding, skipBytes, counts: [] };
260
+ if (bomEncoding !== "utf8") {
261
+ const text = new TextDecoder(bomEncoding).decode(bytes, { stream: !sourceEnded });
262
+ bytes = new TextEncoder().encode(text);
263
+ }
264
+ }
265
+ const counts = scoreDelimiters ? new Uint32Array(8) : void 0;
266
+ const encodingCode = native.symbols.csv_probe_format(bytes.length === 0 ? EMPTY_BUFFER : bytes, bytes.length, sourceEnded, bomEncoding === void 0, counts === void 0 ? null : ptr(counts));
267
+ const encoding = bomEncoding ?? PROBED_BYTE_ENCODINGS[encodingCode];
268
+ if (encoding === void 0)
269
+ throw Error("NUL in encoding probe: specify the encoding explicitly");
270
+ return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[7] === 0 ? [] : [counts] };
271
+ }
272
+ function requireDelimiter(path, rows) {
273
+ const result = selectDelimiter(path, rows);
274
+ if ("error" in result)
275
+ throw Error(result.error);
276
+ return result.delimiter;
277
+ }
278
+ export function selectDelimiter(path, rows) {
140
279
  if (rows.length === 0)
141
- throw Error(`delimiter auto-detection failed: the ${String(DELIMITER_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`);
280
+ return {
281
+ error: `delimiter auto-detection failed: the ${String(FILE_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`
282
+ };
142
283
  const stableCandidates = [];
143
284
  for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
144
285
  const separatorCount = rows[0]?.[candidateIndex] ?? 0;
@@ -151,16 +292,20 @@ function detectDelimiter(path, probe, sourceEnded) {
151
292
  }
152
293
  }
153
294
  if (stableCandidates.length === 0)
154
- throw Error("delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly");
295
+ return {
296
+ error: "delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly"
297
+ };
155
298
  const extensionHint = delimiterFromExtension(path);
156
299
  const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
157
300
  if (confirmedHint !== void 0)
158
- return confirmedHint.delimiter;
301
+ return { delimiter: confirmedHint.delimiter };
159
302
  const maximumSeparatorCount = Math.max(...stableCandidates.map((candidate) => candidate.separatorCount));
160
303
  const strongestCandidates = stableCandidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
161
304
  if (strongestCandidates.length === 1)
162
- return strongestCandidates[0]?.delimiter ?? ",";
163
- throw Error(`delimiter auto-detection is ambiguous between ${strongestCandidates.map((candidate) => JSON.stringify(candidate.delimiter)).join(", ")}; specify delimiter explicitly`);
305
+ return { delimiter: strongestCandidates[0]?.delimiter ?? "," };
306
+ return {
307
+ error: `delimiter auto-detection is ambiguous between ${strongestCandidates.map((candidate) => JSON.stringify(candidate.delimiter)).join(", ")}; specify delimiter explicitly`
308
+ };
164
309
  }
165
310
  export function scanDelimiterCounts(probe, sourceEnded) {
166
311
  const rows = [];
@@ -221,16 +366,66 @@ function stripCompressionExtension(path) {
221
366
  return path.slice(0, -extension.length);
222
367
  return path;
223
368
  }
224
- async function* readAutoDetectedCsvFileChunks(path, chunkSize) {
225
- const compression = await detectCompression(path);
226
- for await (const chunk of decompressedCsvFileChunks(path, compression, chunkSize))
227
- yield chunk;
369
+ async function* readAutoDetectedCsvFileChunks(path, raw, chunkSize, reusesBuffer, zipReadAhead) {
370
+ const iterator = raw[Symbol.asyncIterator]();
371
+ const buffered = [];
372
+ const prefix = new Uint8Array(64);
373
+ let length = 0;
374
+ let needed = 4;
375
+ try {
376
+ while (length < needed) {
377
+ const next = await iterator.next();
378
+ if (next.done === !0)
379
+ break;
380
+ const chunk = next.value;
381
+ const take = Math.min(prefix.length - length, chunk.length);
382
+ prefix.set(chunk.subarray(0, take), length);
383
+ length += take;
384
+ if (length >= 4 && isZlibHeader(prefix) && isPrintableZlibHeader(prefix))
385
+ needed = prefix.length;
386
+ buffered.push(reusesBuffer && length < needed ? new Uint8Array(chunk) : chunk);
387
+ }
388
+ const sample = prefix.subarray(0, length);
389
+ if (isZipSignature(sample)) {
390
+ if (!(await stat(path)).isFile())
391
+ throw Error("ZIP input requires a regular file; save the archive before reading it");
392
+ await closeCsvFileIterator(iterator);
393
+ yield* readZipEntryChunks(path, { format: "zip", entry: "*" }, chunkSize, zipReadAhead);
394
+ return;
395
+ }
396
+ const compression = compressionFromPrefix(path, sample);
397
+ const replay = replayCsvFileChunks(buffered, iterator);
398
+ if (compression === void 0) {
399
+ if (!isPlainCsvFile(path))
400
+ throw Error("compression auto-detection failed: no supported signature or extension and no delimited-text MIME type; specify compression explicitly (none for plain input)");
401
+ yield* replay;
402
+ return;
403
+ }
404
+ yield* WebReadableStream.from(reusesBuffer ? copyFileChunks(replay) : replay).pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
405
+ } finally {
406
+ await closeCsvFileIterator(iterator);
407
+ }
408
+ }
409
+ async function* copyFileChunks(chunks) {
410
+ for await (const chunk of chunks)
411
+ yield new Uint8Array(chunk);
412
+ }
413
+ function isPlainCsvFile(path) {
414
+ const mime = Bun.file(path).type.split(";", 1)[0];
415
+ return mime === "text/csv" || mime === "text/tab-separated-values" || mime === "text/plain" || mime === "application/octet-stream" && /\.(?:psv|ssv|tab)$/i.test(path);
416
+ }
417
+ export function isZipSignature(prefix) {
418
+ return prefix[0] === 80 && prefix[1] === 75 && (prefix[2] === 3 && prefix[3] === 4 || prefix[2] === 5 && prefix[3] === 6);
419
+ }
420
+ function isPrintableZlibHeader(prefix) {
421
+ const first = prefix[0] ?? 0;
422
+ const second = prefix[1] ?? 0;
423
+ return first >= 32 && first < 127 && second >= 32 && second < 127;
228
424
  }
229
425
  function decompressedCsvFileChunks(path, compression, chunkSize) {
230
426
  return Bun.file(path).stream().pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
231
427
  }
232
- async function detectCompression(path) {
233
- const prefix = await Bun.file(path).slice(0, 4).bytes();
428
+ export function compressionFromPrefix(path, prefix) {
234
429
  const extensionHint = compressionFromExtension(path);
235
430
  const strongSignature = compressionFromStrongSignature(prefix);
236
431
  if (strongSignature !== void 0) {
@@ -249,11 +444,21 @@ async function detectCompression(path) {
249
444
  }
250
445
  return extensionHint.format;
251
446
  }
252
- if (hasZlibHeader)
447
+ if (hasZlibHeader) {
448
+ const sample = prefix.subarray(0, 64);
449
+ if (isPrintableZlibHeader(sample) && isPlainCsvFile(path) && !sample.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
450
+ try {
451
+ inflateSync(sample, { finishFlush: sample.length < 64 ? constants.Z_FINISH : constants.Z_SYNC_FLUSH });
452
+ } catch (error) {
453
+ if (error instanceof Error && "code" in error && (error.code === "Z_DATA_ERROR" || error.code === "Z_NEED_DICT" || error.code === "Z_BUF_ERROR"))
454
+ return;
455
+ throw error;
456
+ }
253
457
  return "deflate";
254
- throw Error("compression auto-detection failed: no supported signature or extension; specify compression as 'brotli' or 'deflate-raw' when applicable");
458
+ }
459
+ return;
255
460
  }
256
- function compressionFromExtension(path) {
461
+ export function compressionFromExtension(path) {
257
462
  const lowerPath = path.toLowerCase();
258
463
  if (lowerPath.endsWith(".deflate-raw"))
259
464
  return { extension: ".deflate-raw", format: "deflate-raw", signatureRequired: !1 };
package/dist/files.d.ts CHANGED
@@ -1,14 +1,14 @@
1
- import type { CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvRow, CsvShard } from './types.js';
1
+ import type { CsvEncoding, CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvRow, CsvShard } from './types.js';
2
2
  /**
3
3
  * Parse one complete in-memory CSV buffer into materialized rows.
4
4
  *
5
5
  * The buffer is treated as the complete input, so quoted records may span the
6
- * buffer but parser state is not retained after this call. `selectedColumns`
6
+ * buffer but parser state is not retained after this call. `columns`
7
7
  * projects zero-based physical columns in the returned rows. The supplied
8
8
  * options are captured when the function is called; changing an options array
9
9
  * while parsing cannot change the operation.
10
10
  *
11
- * Automatic delimiter detection and file compression are file-only features.
11
+ * Automatic delimiter and encoding detection and compression are file-only features.
12
12
  * Use an explicit one-character delimiter for in-memory input.
13
13
  *
14
14
  * @param buffer Complete CSV bytes to parse.
@@ -24,7 +24,7 @@ import type { CsvFileOptions, CsvNativeProjectionOptions, CsvParserOptions, CsvR
24
24
  * // rows[0] is ['id', 'name']
25
25
  * ```
26
26
  */
27
- export declare function parseCsvBuffer(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParserOptions): CsvRow[];
27
+ export declare function parseCsvBuffer(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParserOptions<CsvEncoding>): CsvRow[];
28
28
  /**
29
29
  * Count rows in bytes known to contain one record per physical line.
30
30
  *
@@ -57,7 +57,7 @@ export declare function countTrustedNewlineRows(buffer: NodeJS.TypedArray | Data
57
57
  */
58
58
  export declare function findCsvSafeSplitOffsets(path: string, shardCount: number, delimiter?: string): number[];
59
59
  /**
60
- * Return inclusive, record-safe byte ranges for parallel CSV processing.
60
+ * Return inclusive byte ranges that can each be read as complete CSV records.
61
61
  *
62
62
  * The ranges are derived from {@link findCsvSafeSplitOffsets}. Empty ranges
63
63
  * are omitted, so a small file can produce fewer ranges than `shardCount`.
@@ -77,7 +77,7 @@ export declare function findCsvSafeShards(path: string, shardCount: number, deli
77
77
  *
78
78
  * Each yielded value contains the rows parsed from one input chunk. Rows are
79
79
  * ordinary strings and remain usable after the next batch is yielded. File
80
- * compression and automatic delimiter detection are supported by
80
+ * compression and automatic delimiter and encoding detection are supported by
81
81
  * `CsvFileOptions`.
82
82
  *
83
83
  * Options are snapshotted when this function is called, before iteration
@@ -85,7 +85,7 @@ export declare function findCsvSafeShards(path: string, shardCount: number, deli
85
85
  * generator to reconfigure the stream.
86
86
  *
87
87
  * @param path Path to the CSV file (or compressed/ZIP input selected by `options.compression`).
88
- * @param options File and parser options. `selectedColumns` selects physical columns for each row.
88
+ * @param options File and parser options. `columns` selects physical columns for each row.
89
89
  * @returns An async generator of non-empty row batches.
90
90
  * @throws When iteration encounters an I/O, decompression, parsing, or strict-schema error.
91
91
  *
@@ -93,7 +93,7 @@ export declare function findCsvSafeShards(path: string, shardCount: number, deli
93
93
  * ```ts
94
94
  * import { parseCsvFile } from '@konstit/csv';
95
95
  *
96
- * for await (const rows of parseCsvFile('data.csv', { selectedColumns: [0, 2] })) {
96
+ * for await (const rows of parseCsvFile('data.csv', { columns: [0, 2] })) {
97
97
  * for (const row of rows) console.log(row);
98
98
  * }
99
99
  * ```
@@ -103,7 +103,7 @@ export declare function parseCsvFile(path: string, options?: CsvFileOptions): As
103
103
  * Stream rows using native projection and native filter evaluation.
104
104
  *
105
105
  * This lower-level file API is useful when the selected columns or native
106
- * filter descriptors are already prepared. `selectedColumns` is the returned
106
+ * filter descriptors are already prepared. `columns` is the returned
107
107
  * projection, while `equalsFilter` and `filters` are evaluated against
108
108
  * physical columns before materialization. Options are snapshotted at call
109
109
  * time, including nested filter values.
@@ -122,7 +122,7 @@ export declare function parseCsvFile(path: string, options?: CsvFileOptions): As
122
122
  * import { parseCsvFileProjected } from '@konstit/csv';
123
123
  *
124
124
  * for await (const rows of parseCsvFileProjected('data.csv', {
125
- * selectedColumns: [2, 0],
125
+ * columns: [2, 0],
126
126
  * equalsFilter: { column: 1, value: 'active' },
127
127
  * })) {
128
128
  * console.log(rows);
@@ -134,7 +134,7 @@ export declare function parseCsvFileProjected(path: string, options?: CsvFileOpt
134
134
  * Count logical CSV records in a file without materializing row strings.
135
135
  *
136
136
  * The parser honors quoted newlines and supports the same compression and
137
- * delimiter options as serial file parsing. With `strict: true`, quote syntax
137
+ * delimiter options as file parsing. With `strict: true`, quote syntax
138
138
  * is validated while counting. Strict schema metadata is intentionally not
139
139
  * supported by this counting path; use row parsing when headers or minimum
140
140
  * data-row constraints must be checked.
package/dist/files.js CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  } from "./native.js";
10
10
  import {
11
11
  normalizeChunk,
12
+ prepareCsvBufferInput,
12
13
  projectionFilterProgram
13
14
  } from "./normalize.js";
14
15
  import { snapshotCsvOptions } from "./options-snapshot.js";
@@ -22,13 +23,14 @@ import {
22
23
  } from "./strict-schema.js";
23
24
  export function parseCsvBuffer(buffer, suppliedOptions = {}) {
24
25
  const options = snapshotCsvOptions(suppliedOptions);
25
- using parser = new NativeCsvParser(options);
26
+ const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
27
+ using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding });
26
28
  const validator = strictSchemaValidator(options);
27
- const batch = parser.writeBatch(buffer, !0);
29
+ const batch = parser.writeBatch(input.bytes, !0);
28
30
  try {
29
31
  validator?.validateBatch(batch);
30
32
  validator?.finish();
31
- return batch.rowsInto([], options.selectedColumns);
33
+ return batch.rowsInto([], options.columns);
32
34
  } finally {
33
35
  batch.close();
34
36
  }
@@ -76,13 +78,13 @@ export function parseCsvFile(path, options = {}) {
76
78
  }
77
79
  async function* iterateCsvFile(path, options) {
78
80
  await using input = await prepareCsvFileInput(path, options);
79
- using parser = new NativeCsvParser({ ...options, delimiter: input.delimiter });
81
+ using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
80
82
  const validator = strictSchemaValidator(options);
81
83
  for await (const chunk of input.chunks()) {
82
84
  const batch = parser.writeBatch(chunk);
83
85
  try {
84
86
  validator?.validateBatch(batch);
85
- const rows = batch.rowsInto([], options.selectedColumns);
87
+ const rows = batch.rowsInto([], options.columns);
86
88
  if (rows.length > 0)
87
89
  yield rows;
88
90
  } finally {
@@ -93,7 +95,7 @@ async function* iterateCsvFile(path, options) {
93
95
  try {
94
96
  validator?.validateBatch(batch);
95
97
  validator?.finish();
96
- const rows = batch.rowsInto([], options.selectedColumns);
98
+ const rows = batch.rowsInto([], options.columns);
97
99
  if (rows.length > 0)
98
100
  yield rows;
99
101
  } finally {
@@ -106,7 +108,7 @@ export function parseCsvFileProjected(path, options = {}) {
106
108
  async function* iterateCsvFileProjected(path, options) {
107
109
  rejectStrictSchemaUnsupported(options, "projected file parsing");
108
110
  await using input = await prepareCsvFileInput(path, options);
109
- using parser = createPreparedParser({ ...options, delimiter: input.delimiter }, options.selectedColumns, projectionFilterProgram(options), !0);
111
+ using parser = createPreparedParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter }, options.columns, projectionFilterProgram(options), !0);
110
112
  for await (const chunk of input.chunks()) {
111
113
  const batch = parser.writeBatch(chunk);
112
114
  try {
@@ -129,8 +131,8 @@ async function* iterateCsvFileProjected(path, options) {
129
131
  export async function countCsvFile(path, suppliedOptions = {}) {
130
132
  const options = snapshotCsvOptions(suppliedOptions);
131
133
  rejectStrictSchemaUnsupported(options, "count");
132
- await using input = await prepareCsvFileInput(path, options);
133
- using parser = new NativeCsvParser({ ...options, delimiter: input.delimiter });
134
+ await using input = await prepareCsvFileInput(path, options, "count");
135
+ using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
134
136
  let rows = 0;
135
137
  if (options.strict === !0) {
136
138
  for await (const chunk of input.chunks()) {
package/dist/filter.d.ts CHANGED
@@ -22,9 +22,8 @@ export declare function column(columnIndex: number): CsvFilterColumn;
22
22
  /**
23
23
  * Match rows for which every supplied filter matches.
24
24
  *
25
- * Groups can be nested, and the resulting filter can be reused across row, count, and worker
26
- * operations. A missing physical column remains unknown rather than becoming a match through
27
- * negation; the native evaluator applies the CSV filter's three-valued semantics.
25
+ * Groups can be nested, and the resulting filter can be reused for both rows and counts.
26
+ * A missing physical column remains unknown under negation.
28
27
  *
29
28
  * @param first - First filter in the group.
30
29
  * @param rest - Additional filters that must also match.
@@ -36,9 +35,8 @@ export declare function all(first: CsvFilter, ...rest: readonly CsvFilter[]): Cs
36
35
  /**
37
36
  * Match rows for which at least one supplied filter matches.
38
37
  *
39
- * Groups can be nested, and the resulting filter can be reused across row, count, and worker
40
- * operations. A missing column does not match by itself, but another matching child can still make
41
- * the group match.
38
+ * Groups can be nested, and the resulting filter can be reused for both rows and counts.
39
+ * Another matching child can satisfy the group when one child's column is missing.
42
40
  *
43
41
  * @param first - First filter in the group.
44
42
  * @param rest - Additional filters, any one of which may match.
@@ -0,0 +1 @@
1
+ export declare function formatBytes(bytes: number): string;
@@ -0,0 +1,11 @@
1
+ export function formatBytes(bytes) {
2
+ const units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
3
+ let value = bytes;
4
+ let unitIndex = 0;
5
+ while (unitIndex < units.length - 1 && value >= 1024) {
6
+ value /= 1024;
7
+ ++unitIndex;
8
+ }
9
+ const unit = units[unitIndex] ?? "B";
10
+ return `${value.toFixed(value >= 10 || unit === "B" ? 0 : 1)} ${unit}`;
11
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumnarBatchCallback, CsvColumnarBatchOptions, CsvColumnarBatchView, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvInFilter, CsvNativeFilter, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParallelCountOptions, CsvParallelRowsOptions, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvRowView, CsvRowViewCallback, CsvRowViewsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvSingleThreadRowsOptions, CsvStartsWithFilter, CsvWorkerPoolOptions, CsvZipCompression, NativeCsvRowCallback, } from './types.js';
2
- export { csv, CsvWorkerPool, findCsvSafeShards, findCsvSafeSplitOffsets, forEachColumnarBatches, forEachRowViews, parallelCount, parallelRows, withColumnarBatches, withRowViews, workerPool, } from './api.js';
1
+ export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileEncoding, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvInFilter, CsvNativeEncoding, CsvNativeFilter, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvZipCompression, NativeCsvRowCallback, } from './types.js';
2
+ export { csv } from './api.js';
3
3
  export { NativeCsvBatch, NativeCsvRowView } from './batches.js';
4
4
  export { countCsvFile, countTrustedNewlineRows, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from './files.js';
5
- export { defineColumnarOptions, defineCountOptions, defineRowsOptions, defineRowViewOptions } from './options.js';
5
+ export { defineCountOptions, defineRowsOptions } from './options.js';
6
6
  export { NativeCsvParser } from './parser.js';
package/dist/index.js CHANGED
@@ -1,19 +1,7 @@
1
1
  import { requireBunRuntime } from "./runtime.js";
2
2
  requireBunRuntime();
3
- export {
4
- csv,
5
- CsvWorkerPool,
6
- findCsvSafeShards,
7
- findCsvSafeSplitOffsets,
8
- forEachColumnarBatches,
9
- forEachRowViews,
10
- parallelCount,
11
- parallelRows,
12
- withColumnarBatches,
13
- withRowViews,
14
- workerPool
15
- } from "./api.js";
3
+ export { csv } from "./api.js";
16
4
  export { NativeCsvBatch, NativeCsvRowView } from "./batches.js";
17
5
  export { countCsvFile, countTrustedNewlineRows, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from "./files.js";
18
- export { defineColumnarOptions, defineCountOptions, defineRowsOptions, defineRowViewOptions } from "./options.js";
6
+ export { defineCountOptions, defineRowsOptions } from "./options.js";
19
7
  export { NativeCsvParser } from "./parser.js";
@@ -0,0 +1,12 @@
1
+ import type { CsvFileProbe } from './file-stream.js';
2
+ interface FileInspection {
3
+ size: number;
4
+ compression: Bun.CompressionFormat | 'zip' | 'none';
5
+ encoding: ReturnType<CsvFileProbe>['encoding'];
6
+ delimiter: string | undefined;
7
+ lineEnding: string;
8
+ firstRecordColumns: number | undefined;
9
+ }
10
+ /** Inspect a bounded sample of the CSV payload; size always refers to the file on disk. */
11
+ export declare function inspectCsvFile(path: string, zipEntry?: string): Promise<FileInspection>;
12
+ export {};