@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
@@ -1,5 +1,7 @@
1
1
  import { ptr } from "bun:ffi";
2
- import { createReadStream } from "node:fs";
2
+ import {
3
+ createReadStream
4
+ } from "node:fs";
3
5
  import {
4
6
  open,
5
7
  stat
@@ -17,12 +19,20 @@ import {
17
19
  native
18
20
  } from "./native.js";
19
21
  import {
22
+ delimiterByte,
23
+ hasUtf8Bom,
20
24
  resolveInputEncoding,
25
+ UTF8_BOM,
26
+ validateChunkSize,
21
27
  validateCsvDialect
22
28
  } from "./normalize.js";
23
29
  import { snapshotCsvOptions } from "./options-snapshot.js";
24
- import { readZipEntryChunks } from "./zip-reader.js";
30
+ import { readZipEntryChunks } from "./zip-entry.js";
25
31
  export const FILE_PROBE_SIZE = 65536;
32
+ export const COMPRESSION_PROBE_SIZE = 64;
33
+ const SMALL_PLAIN_FILE_MAX_BYTES = 65536;
34
+ const MIN_PARSE_AHEAD_FILE_BYTES = 33554432;
35
+ const MIN_PARSE_AHEAD_CHUNK_BYTES = 262144;
26
36
  const PROBED_BYTE_ENCODINGS = ["utf8", "latin1", "windows-1252"];
27
37
  const MAX_DELIMITER_PROBE_ROWS = 128;
28
38
  export const DELIMITER_CANDIDATES = [
@@ -46,36 +56,39 @@ const COMPRESSION_EXTENSIONS = [
46
56
  ".gz",
47
57
  ".zz"
48
58
  ];
59
+ function usesPlainFileReadAhead(mode) {
60
+ return mode === "read-ahead" || mode === "count";
61
+ }
62
+ function usesSmallPlainFileRead(mode) {
63
+ return mode === "read-ahead" || mode === "batches";
64
+ }
49
65
  export async function prepareCsvFileInput(path, suppliedOptions, readMode = "parse", probeFormat = probeCsvFileFormat) {
50
66
  const options = snapshotCsvOptions(suppliedOptions);
51
67
  validateCsvDialect(options);
68
+ const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
69
+ validateChunkSize(chunkSize);
70
+ const configuredDelimiter = options.delimiter ?? "auto";
52
71
  const autoEncoding = options.encoding === void 0 || options.encoding === "auto";
53
- const inputEncoding = autoEncoding ? "utf8" : resolveInputEncoding(options.encoding, options.delimiter);
72
+ const inputEncoding = autoEncoding ? "utf8" : resolveInputEncoding(options.encoding, configuredDelimiter);
54
73
  const parserEncoding = typeof inputEncoding === "string" ? inputEncoding : "utf8";
74
+ const readAhead = readMode === "read-ahead" && typeof path === "string" && typeof inputEncoding === "string" && chunkSize >= MIN_PARSE_AHEAD_CHUNK_BYTES ? { minimumParseAheadBytes: Math.max(MIN_PARSE_AHEAD_FILE_BYTES, 2 * chunkSize), canParseAhead: !1 } : void 0;
75
+ let hint = typeof path === "string" ? path : "";
76
+ const onZipEntryName = configuredDelimiter === "auto" && isZipCompression(options.compression ?? "auto") ? (entry) => {
77
+ hint = entry;
78
+ } : void 0;
55
79
  const source = () => {
56
- const chunks = readCsvFileChunks(path, options, readMode);
80
+ const chunks = typeof path === "string" ? readCsvFileChunks(path, options, readMode, onZipEntryName, readAhead) : readCsvByteStream(path, options, chunkSize);
81
+ if (!autoEncoding && inputEncoding === "utf8" && readMode !== "raw-records")
82
+ return stripUtf8StreamBom(chunks);
57
83
  return typeof inputEncoding === "string" ? chunks : transcodeCsvChunks(chunks, inputEncoding);
58
84
  };
59
- const configuredDelimiter = options.delimiter ?? ",";
60
85
  if (!autoEncoding && configuredDelimiter !== "auto") {
61
- let opened = !1;
62
- return {
63
- delimiter: configuredDelimiter,
64
- parserEncoding,
65
- chunks() {
66
- if (opened)
67
- throw Error("CSV file input can only be read once");
68
- opened = !0;
69
- return source();
70
- },
71
- [Symbol.asyncDispose]() {
72
- return Promise.resolve();
73
- }
74
- };
86
+ delimiterByte(configuredDelimiter, parserEncoding);
87
+ return new PreparedCsvFileInput(configuredDelimiter, parserEncoding, () => source()[Symbol.asyncIterator](), readAhead);
75
88
  }
76
89
  const iterator = source()[Symbol.asyncIterator]();
77
90
  const compression = options.compression ?? "auto";
78
- const reusesReadBuffer = typeof inputEncoding === "string" && (readMode !== "stream" && (compression === "auto" || compression === "gzip") || readMode === "read-ahead" && compression === "none" || isZipCompression(compression) && useZipReadAhead(readMode, options.chunkSize ?? DEFAULT_CHUNK_SIZE));
91
+ const reusesReadBuffer = typeof inputEncoding === "string" && (typeof path !== "string" || readMode !== "stream" && (compression === "auto" || compression === "gzip") || usesPlainFileReadAhead(readMode) && compression === "none" || isZipCompression(compression) && useZipReadAhead(readMode, chunkSize));
79
92
  const bufferedChunks = [];
80
93
  let bufferedByteLength = 0;
81
94
  let sourceEnded = !1;
@@ -95,10 +108,10 @@ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "par
95
108
  bufferedChunks.push(reusesReadBuffer && bufferedByteLength < bytesNeeded ? new Uint8Array(result.value) : result.value);
96
109
  }
97
110
  const probe = copyProbePrefix(bufferedChunks, bufferedByteLength);
98
- const hint = delimiterHintPath(path, options.compression);
99
111
  const format = autoEncoding ? probeFormat(hint, probe, sourceEnded, configuredDelimiter, options) : void 0;
100
112
  const delimiter = format?.delimiter ?? detectDelimiter(hint, probe, sourceEnded, options);
101
113
  const replayEncoding = format === void 0 ? parserEncoding : resolveInputEncoding(format.encoding, delimiter);
114
+ delimiterByte(delimiter, typeof replayEncoding === "string" ? replayEncoding : "utf8");
102
115
  let skip = format?.skipBytes ?? 0;
103
116
  if (skip > 0)
104
117
  for (const [i, chunk] of bufferedChunks.entries()) {
@@ -108,37 +121,126 @@ export async function prepareCsvFileInput(path, suppliedOptions, readMode = "par
108
121
  if (skip === 0)
109
122
  break;
110
123
  }
111
- let opened = !1;
124
+ const replay = replayCsvFileChunks(bufferedChunks, iterator);
125
+ return typeof replayEncoding === "string" ? new PreparedCsvFileInput(delimiter, replayEncoding, replay, readAhead, iterator) : new PreparedCsvFileInput(delimiter, "utf8", transcodeCsvChunks(replay, replayEncoding), void 0, iterator);
126
+ } catch (error) {
127
+ await closeCsvFileIterator(iterator);
128
+ throw error;
129
+ }
130
+ }
131
+
132
+ class PreparedCsvFileInput {
133
+ delimiter;
134
+ parserEncoding;
135
+ #state;
136
+ #readAhead;
137
+ constructor(delimiter, parserEncoding, source, readAhead, probedSource) {
138
+ this.delimiter = delimiter;
139
+ this.parserEncoding = parserEncoding;
140
+ this.#state = { phase: "ready", source, probedSource, replay: void 0 };
141
+ this.#readAhead = readAhead;
142
+ }
143
+ get canParseAhead() {
144
+ return this.#readAhead?.canParseAhead;
145
+ }
146
+ async readPrefix(inspect) {
147
+ const state = this.#ready();
148
+ if (state.replay !== void 0)
149
+ throw Error("CSV input prefix has already been read");
150
+ state.phase = "reading-prefix";
151
+ try {
152
+ const { value, replay } = await inspect(() => this.#nextChunk());
153
+ if (this.#state.phase === "closed")
154
+ throw Error("CSV file input is closed");
155
+ state.replay = replay;
156
+ state.phase = "ready";
157
+ return value;
158
+ } catch (error) {
159
+ await this[Symbol.asyncDispose]();
160
+ throw error;
161
+ }
162
+ }
163
+ chunks() {
164
+ this.#ready().phase = "reading";
112
165
  return {
113
- delimiter,
114
- parserEncoding: typeof replayEncoding === "string" ? replayEncoding : "utf8",
115
- chunks() {
116
- if (opened)
117
- throw Error("CSV file input can only be read once");
118
- opened = !0;
119
- const replay = replayCsvFileChunks(bufferedChunks, iterator);
120
- return typeof replayEncoding === "string" ? replay : transcodeCsvChunks(replay, replayEncoding);
166
+ [Symbol.asyncIterator]() {
167
+ return this;
168
+ },
169
+ next: async () => {
170
+ try {
171
+ const result = await this.#nextChunk();
172
+ if (result.done !== !0 && this.#state.phase !== "closed")
173
+ return result;
174
+ } catch (error) {
175
+ await this[Symbol.asyncDispose]();
176
+ throw error;
177
+ }
178
+ await this[Symbol.asyncDispose]();
179
+ return { done: !0, value: void 0 };
121
180
  },
122
- [Symbol.asyncDispose]() {
123
- return closeCsvFileIterator(iterator);
181
+ return: async () => {
182
+ await this.#close();
183
+ return { done: !0, value: void 0 };
124
184
  }
125
185
  };
126
- } catch (error) {
127
- await closeCsvFileIterator(iterator);
128
- throw error;
186
+ }
187
+ async[Symbol.asyncDispose]() {
188
+ try {
189
+ await this.#close();
190
+ } catch {}
191
+ }
192
+ #ready() {
193
+ const state = this.#state;
194
+ if (state.phase !== "ready")
195
+ throw Error("CSV file input can only be read once");
196
+ return state;
197
+ }
198
+ #nextChunk() {
199
+ const state = this.#state;
200
+ if (state.phase === "closed")
201
+ return Promise.resolve({ done: !0, value: void 0 });
202
+ if (state.replay !== void 0) {
203
+ const result = state.replay.next();
204
+ if (result.done !== !0)
205
+ return Promise.resolve(result);
206
+ state.replay = void 0;
207
+ }
208
+ if (typeof state.source === "function")
209
+ state.source = state.source();
210
+ return state.source.next();
211
+ }
212
+ #close() {
213
+ if (this.#state.phase === "closed")
214
+ return this.#state.closing;
215
+ const { source, probedSource } = this.#state;
216
+ const closing = Promise.resolve().then(async () => {
217
+ try {
218
+ if (typeof source !== "function")
219
+ await source.return?.();
220
+ } finally {
221
+ if (probedSource !== void 0)
222
+ await closeCsvFileIterator(probedSource);
223
+ }
224
+ });
225
+ this.#state = { phase: "closed", closing };
226
+ return closing;
129
227
  }
130
228
  }
131
- async function* readAheadFileChunks(path, chunkSize) {
132
- validateReadAheadChunkSize(chunkSize);
229
+ async function* readPlainFileChunks(path, chunkSize, mode, readAhead) {
133
230
  await using file = await open(path, "r");
134
- yield* readAheadOpenFileChunks(file, chunkSize, (await file.stat()).isFile());
135
- }
136
- function validateReadAheadChunkSize(chunkSize) {
137
- if (!Number.isSafeInteger(chunkSize) || chunkSize <= 0)
138
- throw RangeError("chunkSize must be a positive safe integer");
231
+ const stats = await file.stat();
232
+ const smallRead = usesSmallPlainFileRead(mode) ? readSmallRegularFile(file, stats, chunkSize) : void 0;
233
+ if (smallRead !== void 0) {
234
+ const bytes = await smallRead;
235
+ if (bytes.length <= stats.size) {
236
+ yield* closeWhileYielding(file, bytes);
237
+ return;
238
+ }
239
+ }
240
+ yield* smallRead === void 0 && usesPlainFileReadAhead(mode) ? readAheadOpenFileChunks(file, chunkSize, stats, readAhead) : file.createReadStream({ highWaterMark: chunkSize, autoClose: !1, start: smallRead === void 0 ? void 0 : 0 });
139
241
  }
140
- async function* readAheadOpenFileChunks(file, chunkSize, regularFile) {
141
- if (!regularFile) {
242
+ async function* readAheadOpenFileChunks(file, chunkSize, stats, readAhead) {
243
+ if (!stats.isFile()) {
142
244
  const buffer = Buffer.allocUnsafe(chunkSize);
143
245
  let { bytesRead } = await file.read(buffer);
144
246
  while (bytesRead > 0) {
@@ -147,6 +249,8 @@ async function* readAheadOpenFileChunks(file, chunkSize, regularFile) {
147
249
  }
148
250
  return;
149
251
  }
252
+ if (readAhead !== void 0)
253
+ readAhead.canParseAhead = stats.size >= readAhead.minimumParseAheadBytes;
150
254
  let current = Buffer.allocUnsafe(chunkSize);
151
255
  let spare = Buffer.allocUnsafe(chunkSize);
152
256
  let { bytesRead } = await file.read(current);
@@ -158,17 +262,18 @@ async function* readAheadOpenFileChunks(file, chunkSize, regularFile) {
158
262
  [current, spare] = [spare, current];
159
263
  }
160
264
  }
161
- export function readCsvFileChunks(path, suppliedOptions, readMode = "stream") {
265
+ export function readCsvFileChunks(path, suppliedOptions, readMode = "stream", onZipEntryName, readAhead) {
162
266
  const options = snapshotCsvOptions(suppliedOptions);
163
267
  const chunkSize = options.chunkSize ?? DEFAULT_CHUNK_SIZE;
268
+ validateChunkSize(chunkSize);
164
269
  const compression = options.compression ?? "auto";
165
270
  const zipReadAhead = useZipReadAhead(readMode, chunkSize);
166
271
  if (isZipCompression(compression))
167
- return readZipEntryChunks(path, compression, chunkSize, zipReadAhead);
272
+ return readZipFileChunks(path, compression, chunkSize, zipReadAhead, readAhead, onZipEntryName);
168
273
  if (compression === "auto")
169
- return readAutoDetectedCsvFileChunks(path, chunkSize, readMode, zipReadAhead);
274
+ return readAutoDetectedCsvFileChunks(path, chunkSize, readMode, zipReadAhead, readAhead);
170
275
  if (compression === "none")
171
- return readMode === "read-ahead" ? readAheadFileChunks(path, chunkSize) : createReadStream(path, { highWaterMark: chunkSize });
276
+ return usesPlainFileReadAhead(readMode) || usesSmallPlainFileRead(readMode) ? readPlainFileChunks(path, chunkSize, readMode, readAhead) : createReadStream(path, { highWaterMark: chunkSize });
172
277
  if (compression === "gzip")
173
278
  return readGzipPathChunks(path, chunkSize, readMode !== "stream");
174
279
  return decompressedCsvFileChunks(path, compression, chunkSize);
@@ -176,31 +281,95 @@ export function readCsvFileChunks(path, suppliedOptions, readMode = "stream") {
176
281
  function isZipCompression(compression) {
177
282
  return typeof compression === "object" && compression.format === "zip";
178
283
  }
284
+ async function* readCsvByteStream(input, options, chunkSize) {
285
+ const compression = options.compression ?? "auto";
286
+ if (isZipCompression(compression))
287
+ throw Error("ZIP input requires a regular file");
288
+ async function* bytes() {
289
+ const iterator = input[Symbol.asyncIterator]();
290
+ try {
291
+ while (!0) {
292
+ const next = await iterator.next();
293
+ if (next.done)
294
+ return;
295
+ if (!(next.value instanceof Uint8Array))
296
+ throw TypeError("CSV stream chunks must be Uint8Array values");
297
+ yield next.value;
298
+ }
299
+ } finally {
300
+ await closeCsvFileIterator(iterator);
301
+ }
302
+ }
303
+ if (compression !== "auto") {
304
+ yield* compression === "none" ? bytes() : decompressByteStream(bytes(), compression, chunkSize);
305
+ return;
306
+ }
307
+ const iterator = bytes();
308
+ try {
309
+ const buffered = [];
310
+ const detected = await probeStreamCompression(iterator, buffered, !0, { kind: "stream" });
311
+ if (detected === "zip")
312
+ throw Error("ZIP input requires a regular file");
313
+ const replay = replayCsvFileChunks(buffered, iterator);
314
+ yield* detected === "none" ? replay : decompressByteStream(replay, detected, chunkSize);
315
+ } finally {
316
+ await closeCsvFileIterator(iterator);
317
+ }
318
+ }
319
+ function decompressByteStream(input, format, chunkSize) {
320
+ return decompressChunks(copyChunks(input), format, Math.max(64, Math.min(chunkSize, DEFAULT_CHUNK_SIZE)));
321
+ }
322
+ async function probeStreamCompression(iterator, buffered, reusesBuffer, source) {
323
+ const prefix = new Uint8Array(COMPRESSION_PROBE_SIZE);
324
+ let length = 0;
325
+ while (!0) {
326
+ const next = await iterator.next();
327
+ if (next.done === !0)
328
+ return probeCompression(prefix.subarray(0, length), !0, source);
329
+ const chunk = next.value;
330
+ if (chunk.length === 0)
331
+ continue;
332
+ const take = Math.min(prefix.length - length, chunk.length);
333
+ prefix.set(chunk.subarray(0, take), length);
334
+ length += take;
335
+ const result = probeCompression(prefix.subarray(0, length), !1, source);
336
+ const needsMore = result === "need-more";
337
+ buffered.push(reusesBuffer && needsMore ? new Uint8Array(chunk) : chunk);
338
+ if (!needsMore)
339
+ return result;
340
+ }
341
+ }
179
342
  function useZipReadAhead(mode, chunkSize) {
180
343
  return mode === "count" || mode !== "stream" && chunkSize >= 65536;
181
344
  }
182
- function delimiterHintPath(path, compression) {
183
- return compression !== void 0 && isZipCompression(compression) ? compression.entry : path;
345
+ async function* readZipFileChunks(path, compression, chunkSize, zipReadAhead, readAhead, onZipEntryName) {
346
+ const chunks = readZipEntryChunks(path, compression, chunkSize, zipReadAhead, onZipEntryName, readAhead !== void 0);
347
+ if (readAhead === void 0) {
348
+ yield* chunks;
349
+ return;
350
+ }
351
+ let bytesUntilParseAhead = readAhead.minimumParseAheadBytes;
352
+ for await (const chunk of chunks) {
353
+ if (bytesUntilParseAhead > 0) {
354
+ bytesUntilParseAhead -= chunk.byteLength;
355
+ if (bytesUntilParseAhead <= 0)
356
+ readAhead.canParseAhead = !0;
357
+ }
358
+ yield chunk;
359
+ }
184
360
  }
185
361
  export function rejectCompressedSharding(options, operation) {
186
362
  if (options.compression !== void 0)
187
363
  throw Error(`${operation} does not support compressed input because compressed byte offsets cannot be sharded`);
188
364
  }
189
- export function rejectAutoDelimiterSharding(options, operation) {
190
- if (options.delimiter === "auto")
191
- throw Error(`${operation} does not support automatic delimiter detection because byte offsets are resolved first`);
192
- }
193
365
  async function* replayCsvFileChunks(bufferedChunks, iterator) {
194
- try {
195
- yield* bufferedChunks;
196
- while (!0) {
197
- const result = await iterator.next();
198
- if (result.done === !0)
199
- return;
200
- yield result.value;
201
- }
202
- } finally {
203
- await closeCsvFileIterator(iterator);
366
+ yield* bufferedChunks;
367
+ bufferedChunks.length = 0;
368
+ while (!0) {
369
+ const result = await iterator.next();
370
+ if (result.done === !0)
371
+ return;
372
+ yield result.value;
204
373
  }
205
374
  }
206
375
  async function* transcodeCsvChunks(source, decoder) {
@@ -214,6 +383,34 @@ async function* transcodeCsvChunks(source, decoder) {
214
383
  if (text.length > 0)
215
384
  yield encoder.encode(text);
216
385
  }
386
+ async function* stripUtf8StreamBom(chunks) {
387
+ let checked = !1;
388
+ let matched = 0;
389
+ for await (const chunk of chunks) {
390
+ if (checked) {
391
+ yield chunk;
392
+ continue;
393
+ }
394
+ let offset = 0;
395
+ while (offset < chunk.length && matched < UTF8_BOM.length && chunk[offset] === UTF8_BOM[matched]) {
396
+ ++offset;
397
+ ++matched;
398
+ }
399
+ if (matched === UTF8_BOM.length) {
400
+ checked = !0;
401
+ if (offset < chunk.length)
402
+ yield chunk.subarray(offset);
403
+ } else if (offset < chunk.length) {
404
+ checked = !0;
405
+ const preceding = matched - offset;
406
+ if (preceding > 0)
407
+ yield Uint8Array.from(UTF8_BOM.slice(0, preceding));
408
+ yield chunk;
409
+ }
410
+ }
411
+ if (!checked && matched > 0)
412
+ yield Uint8Array.from(UTF8_BOM.slice(0, matched));
413
+ }
217
414
  async function closeCsvFileIterator(iterator) {
218
415
  try {
219
416
  await iterator.return?.();
@@ -247,11 +444,16 @@ function copyProbePrefix(chunks, totalByteLength) {
247
444
  return probe;
248
445
  }
249
446
  export function detectDelimiter(path, probe, sourceEnded, dialect) {
250
- return requireDelimiter(path, scanDelimiterCounts(probe, sourceEnded, dialect));
447
+ return requireDelimiter(path, scanDelimiterScores(probe, sourceEnded, dialect), probe, sourceEnded, dialect);
448
+ }
449
+ export function detectBufferDelimiter(input, path, final, dialect, stripBom = !1) {
450
+ const prefix = new Uint8Array(input.buffer, input.byteOffset, Math.min(input.byteLength, FILE_PROBE_SIZE));
451
+ const probe = stripBom && hasUtf8Bom(prefix) ? prefix.subarray(UTF8_BOM.length) : prefix;
452
+ return detectDelimiter(path, probe, final && input.byteLength <= FILE_PROBE_SIZE, dialect);
251
453
  }
252
454
  export const probeCsvFileFormat = (path, prefix, sourceEnded, delimiter, dialect) => {
253
- const { encoding, skipBytes, counts } = scanCsvFileFormat(prefix, sourceEnded, delimiter === "auto", dialect);
254
- return { encoding, delimiter: delimiter === "auto" ? requireDelimiter(path, counts) : delimiter, skipBytes };
455
+ const { bytes, encoding, skipBytes, scores } = scanCsvFileFormat(prefix, sourceEnded, delimiter === "auto", dialect);
456
+ return { encoding, delimiter: scores === void 0 ? delimiter : requireDelimiter(path, scores, bytes, sourceEnded, dialect), skipBytes };
255
457
  };
256
458
  export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters, dialect) {
257
459
  let bytes = prefix;
@@ -259,9 +461,9 @@ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters, dialect)
259
461
  let skipBytes = 0;
260
462
  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)
261
463
  throw Error("automatic encoding detection does not support UTF-32; transcode the input to UTF-8");
262
- if (bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) {
464
+ if (hasUtf8Bom(bytes)) {
263
465
  bomEncoding = "utf8";
264
- skipBytes = 3;
466
+ skipBytes = UTF8_BOM.length;
265
467
  bytes = bytes.subarray(skipBytes);
266
468
  } else if (bytes[0] === 255 && bytes[1] === 254)
267
469
  bomEncoding = "utf-16le";
@@ -269,105 +471,157 @@ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters, dialect)
269
471
  bomEncoding = "utf-16be";
270
472
  if (bomEncoding !== void 0) {
271
473
  if (!scoreDelimiters)
272
- return { bytes, encoding: bomEncoding, skipBytes, counts: [] };
474
+ return { bytes, encoding: bomEncoding, hasBom: !0, skipBytes };
273
475
  if (bomEncoding !== "utf8") {
274
476
  const text = new TextDecoder(bomEncoding).decode(bytes, { stream: !sourceEnded });
275
477
  bytes = new TextEncoder().encode(text);
276
478
  }
277
479
  }
278
480
  const customDialect = scoreDelimiters && (dialect?.quote === !1 || dialect?.recordDelimiter !== void 0);
279
- const counts = scoreDelimiters && !customDialect ? new Uint32Array(DELIMITER_CANDIDATES.length + 1) : void 0;
280
- const encodingCode = native.symbols.csv_probe_format_v2(bytes.length === 0 ? EMPTY_BUFFER : bytes, bytes.length, sourceEnded, bomEncoding === void 0, counts === void 0 ? null : ptr(counts));
481
+ const candidateCount = DELIMITER_CANDIDATES.length;
482
+ const counts = scoreDelimiters && !customDialect ? new Uint32Array(2 * candidateCount + 2) : void 0;
483
+ const encodingCode = native.symbols.csv_probe_format_v3(bytes.length === 0 ? EMPTY_BUFFER : bytes, bytes.length, sourceEnded, bomEncoding === void 0, counts === void 0 ? null : ptr(counts));
281
484
  const encoding = bomEncoding ?? PROBED_BYTE_ENCODINGS[encodingCode];
282
485
  if (encoding === void 0)
283
486
  throw Error("NUL in encoding probe: specify the encoding explicitly");
487
+ const hasBom = bomEncoding !== void 0;
284
488
  if (customDialect)
285
- return { bytes, encoding, skipBytes, counts: scanDelimiterCounts(bytes, sourceEnded, dialect) };
286
- return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[DELIMITER_CANDIDATES.length] === 0 ? [] : [counts] };
489
+ return { bytes, encoding, hasBom, skipBytes, scores: scanDelimiterScores(bytes, sourceEnded, dialect) };
490
+ const scores = counts === void 0 ? void 0 : {
491
+ stableCounts: counts.subarray(0, candidateCount),
492
+ quotedFields: counts.subarray(candidateCount, 2 * candidateCount),
493
+ hasCompleteRecords: (counts[2 * candidateCount] ?? 0) > 0,
494
+ hasSeparator: counts[2 * candidateCount + 1] === 1
495
+ };
496
+ return { bytes, encoding, hasBom, skipBytes, scores };
287
497
  }
288
- function requireDelimiter(path, rows) {
289
- const result = selectDelimiter(path, rows);
498
+ function requireDelimiter(path, scores, sample, sourceEnded, dialect) {
499
+ const result = selectDelimiter(path, scores);
290
500
  if ("delimiter" in result)
291
501
  return result.delimiter;
502
+ if (sourceEnded && !scores.hasSeparator) {
503
+ if (sample.every((byte) => byte === 10 || byte === 13))
504
+ return ",";
505
+ const fullScores = scanDelimiterScores(sample, !0, dialect, 1 / 0);
506
+ if (fullScores.hasCompleteRecords && !fullScores.hasSeparator)
507
+ return ",";
508
+ }
292
509
  switch (result.reason) {
293
510
  case "no-records":
294
511
  throw Error(`delimiter auto-detection failed: the ${String(FILE_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`);
295
512
  case "no-stable-separator":
296
513
  throw Error("delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly");
297
514
  case "ambiguous":
298
- throw Error(`delimiter auto-detection is ambiguous between ${result.candidates.map((c) => JSON.stringify(c)).join(", ")}; specify delimiter explicitly`);
515
+ throw delimiterAmbiguityError(result.candidates);
516
+ case "weak-separator":
517
+ throw Error(`delimiter auto-detection could not confirm ${JSON.stringify(result.candidate)}; specify delimiter explicitly`);
299
518
  }
300
519
  }
301
- export function selectDelimiter(path, rows) {
302
- if (rows.length === 0)
520
+ export function delimiterAmbiguityError(candidates) {
521
+ return Error(`delimiter auto-detection is ambiguous between ${candidates.map((candidate) => JSON.stringify(candidate)).join(", ")}; specify delimiter explicitly`);
522
+ }
523
+ export function selectDelimiter(path, scores) {
524
+ if (!scores.hasCompleteRecords)
303
525
  return { reason: "no-records" };
304
526
  const stableCandidates = [];
305
- let hasStableAtSign = !1;
306
- for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
307
- const separatorCount = rows[0]?.[candidateIndex] ?? 0;
527
+ for (const [candidateIndex, candidate] of DELIMITER_CANDIDATES.entries()) {
528
+ const separatorCount = scores.stableCounts[candidateIndex] ?? 0;
308
529
  if (separatorCount === 0)
309
530
  continue;
310
- if (rows.every((row) => row[candidateIndex] === separatorCount)) {
311
- const candidate = DELIMITER_CANDIDATES[candidateIndex];
312
- if (candidate?.delimiter === "@")
313
- hasStableAtSign = !0;
314
- else if (candidate !== void 0)
315
- stableCandidates.push({ delimiter: candidate.delimiter, separatorCount });
316
- }
531
+ stableCandidates.push({ delimiter: candidate.delimiter, separatorCount, quotedFields: scores.quotedFields[candidateIndex] ?? 0 });
317
532
  }
318
533
  if (stableCandidates.length === 0)
319
- return hasStableAtSign ? { delimiter: "@" } : { reason: "no-stable-separator" };
320
- const extensionHint = delimiterFromExtension(path);
534
+ return { reason: "no-stable-separator" };
535
+ const bestQuoteCount = Math.max(...stableCandidates.map((candidate) => candidate.quotedFields));
536
+ const bestQuotedCandidates = stableCandidates.filter((candidate) => candidate.quotedFields === bestQuoteCount);
537
+ const extension = extname(stripCompressionExtension(path.toLowerCase()));
538
+ const extensionHint = delimiterFromExtension(extension);
321
539
  const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
322
- if (confirmedHint !== void 0)
323
- return { delimiter: confirmedHint.delimiter };
324
- const maximumSeparatorCount = Math.max(...stableCandidates.map((candidate) => candidate.separatorCount));
325
- const strongestCandidates = stableCandidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
326
- if (strongestCandidates.length === 1)
327
- return { delimiter: strongestCandidates[0]?.delimiter ?? "," };
540
+ if (confirmedHint !== void 0) {
541
+ if (confirmedHint.quotedFields === bestQuoteCount)
542
+ return {
543
+ delimiter: confirmedHint.delimiter,
544
+ extensionHint: extension,
545
+ ...bestQuotedCandidates.length > 1 ? { extensionBrokeTie: !0 } : {}
546
+ };
547
+ return {
548
+ reason: "ambiguous",
549
+ candidates: [confirmedHint.delimiter, ...bestQuotedCandidates.map((candidate) => candidate.delimiter)],
550
+ conflictingHint: !0
551
+ };
552
+ }
553
+ const preferredCandidates = bestQuotedCandidates.filter((candidate) => candidate.delimiter !== "@");
554
+ const candidates = preferredCandidates.length === 0 ? bestQuotedCandidates : preferredCandidates;
555
+ const maximumSeparatorCount = Math.max(...candidates.map((candidate) => candidate.separatorCount));
556
+ const strongestCandidates = candidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
557
+ const [strongest] = strongestCandidates;
558
+ if (strongest !== void 0 && strongestCandidates.length === 1) {
559
+ const { delimiter, quotedFields, separatorCount } = strongest;
560
+ if (separatorCount === 1 && (delimiter === "@" || delimiter === ":" || delimiter === "^" || delimiter === "~") && DELIMITER_CANDIDATES.some((candidate, index) => candidate.delimiter !== delimiter && (scores.quotedFields[index] ?? 0) >= quotedFields))
561
+ return { reason: "weak-separator", candidate: delimiter };
562
+ return { delimiter };
563
+ }
328
564
  return { reason: "ambiguous", candidates: strongestCandidates.map((candidate) => candidate.delimiter) };
329
565
  }
330
- export function scanDelimiterCounts(probe, sourceEnded, { quote = !0, recordDelimiter } = {}) {
331
- const rows = [];
332
- let counts = Array.from({ length: DELIMITER_CANDIDATES.length }, () => 0);
333
- let inQuotes = !1;
334
- let rowHasContent = !1;
335
- for (let index = 0;index < probe.byteLength; ++index) {
336
- const byte = probe[index];
337
- if (quote && byte === 34) {
338
- rowHasContent = !0;
339
- if (inQuotes && probe[index + 1] === 34) {
340
- ++index;
341
- continue;
342
- }
343
- inQuotes = !inQuotes;
344
- continue;
345
- }
346
- if (!inQuotes && (byte === 10 || recordDelimiter === void 0 && byte === 13)) {
347
- if (rowHasContent) {
348
- rows.push(counts);
349
- if (rows.length === MAX_DELIMITER_PROBE_ROWS)
350
- return rows;
566
+ export function scanDelimiterScores(probe, sourceEnded, { quote = !0, recordDelimiter } = {}, maxRows = MAX_DELIMITER_PROBE_ROWS) {
567
+ const stableCounts = new Uint32Array(DELIMITER_CANDIDATES.length);
568
+ const quotedFields = new Uint32Array(DELIMITER_CANDIDATES.length);
569
+ let hasCompleteRecords = !1;
570
+ let hasSeparator = !1;
571
+ for (const [candidateIndex, { byte: delimiter }] of DELIMITER_CANDIDATES.entries()) {
572
+ let finishRecord = function() {
573
+ if (rows === 0)
574
+ stableCounts[candidateIndex] = separators;
575
+ else if (stableCounts[candidateIndex] !== separators)
576
+ stableCounts[candidateIndex] = 0;
577
+ ++rows;
578
+ hasCompleteRecords = !0;
579
+ hasSeparator ||= separators > 0;
580
+ quotedFields[candidateIndex] = (quotedFields[candidateIndex] ?? 0) + completeQuotes;
581
+ separators = 0;
582
+ completeQuotes = 0;
583
+ };
584
+ let rows = 0;
585
+ let rowStart = 0;
586
+ let separators = 0;
587
+ let completeQuotes = 0;
588
+ let quoted = !1;
589
+ for (let index = 0;index < probe.byteLength; ++index) {
590
+ const byte = probe[index];
591
+ if (quote && byte === 34) {
592
+ if (quoted) {
593
+ const next = probe[index + 1];
594
+ if (next === 34)
595
+ ++index;
596
+ else {
597
+ quoted = !1;
598
+ if (next === delimiter || next === 10 || recordDelimiter === void 0 && next === 13 || next === void 0 && sourceEnded)
599
+ ++completeQuotes;
600
+ }
601
+ } else if (index === rowStart || probe[index - 1] === delimiter)
602
+ quoted = !0;
603
+ } else if (!quoted) {
604
+ if (byte === delimiter)
605
+ ++separators;
606
+ else if (byte === 10 || recordDelimiter === void 0 && byte === 13) {
607
+ if (index > rowStart) {
608
+ finishRecord();
609
+ if (rows === maxRows)
610
+ break;
611
+ }
612
+ rowStart = index + 1;
613
+ }
351
614
  }
352
- counts = Array.from({ length: DELIMITER_CANDIDATES.length }, () => 0);
353
- rowHasContent = !1;
354
- if (byte === 13 && probe[index + 1] === 10)
355
- ++index;
356
- continue;
357
- }
358
- rowHasContent = !0;
359
- if (!inQuotes) {
360
- for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex)
361
- if (byte === DELIMITER_CANDIDATES[candidateIndex]?.byte)
362
- counts[candidateIndex] = (counts[candidateIndex] ?? 0) + 1;
363
615
  }
616
+ if (sourceEnded && !quoted && rowStart < probe.byteLength && rows < maxRows)
617
+ finishRecord();
364
618
  }
365
- if (sourceEnded && !inQuotes && rowHasContent && rows.length < MAX_DELIMITER_PROBE_ROWS)
366
- rows.push(counts);
367
- return rows;
619
+ return { stableCounts, quotedFields, hasCompleteRecords, hasSeparator };
368
620
  }
369
- function delimiterFromExtension(path) {
370
- const extension = extname(stripCompressionExtension(path.toLowerCase()));
621
+ export function isDelimiterCandidate(byte) {
622
+ return DELIMITER_CANDIDATES.some((candidate) => candidate.byte === byte);
623
+ }
624
+ function delimiterFromExtension(extension) {
371
625
  switch (extension) {
372
626
  case ".csv":
373
627
  return ",";
@@ -386,78 +640,90 @@ function stripCompressionExtension(path) {
386
640
  return path.slice(0, -extension.length);
387
641
  return path;
388
642
  }
389
- async function* readAutoDetectedCsvFileChunks(path, chunkSize, readMode, zipReadAhead) {
643
+ async function* readAutoDetectedCsvFileChunks(path, chunkSize, readMode, zipReadAhead, readAhead) {
390
644
  const reusesBuffer = readMode === "read-ahead";
391
- if (reusesBuffer)
392
- validateReadAheadChunkSize(chunkSize);
393
645
  await using file = await open(path, "r");
394
- const regularFile = (await file.stat()).isFile();
395
- const raw = () => reusesBuffer ? readAheadOpenFileChunks(file, chunkSize, regularFile) : file.createReadStream({ highWaterMark: chunkSize, autoClose: !1 });
646
+ const stats = await file.stat();
647
+ const regularFile = stats.isFile();
648
+ const smallRead = usesSmallPlainFileRead(readMode) ? readSmallRegularFile(file, stats, chunkSize) : void 0;
649
+ const raw = (plainReadAhead) => reusesBuffer && smallRead === void 0 ? readAheadOpenFileChunks(file, chunkSize, stats, plainReadAhead) : file.createReadStream({ highWaterMark: chunkSize, autoClose: !1, start: smallRead === void 0 ? void 0 : 0 });
396
650
  const iterator = regularFile ? void 0 : raw()[Symbol.asyncIterator]();
397
651
  const buffered = [];
398
- const prefix = new Uint8Array(64);
399
- let length = 0;
400
652
  try {
401
- if (iterator === void 0)
402
- while (length < prefix.length) {
403
- const { bytesRead } = await file.read(prefix, length, prefix.length - length, length);
404
- if (bytesRead === 0)
405
- break;
406
- length += bytesRead;
407
- }
408
- else {
409
- let needed = 4;
410
- while (length < needed) {
411
- const next = await iterator.next();
412
- if (next.done === !0)
413
- break;
414
- const chunk = next.value;
415
- const take = Math.min(prefix.length - length, chunk.length);
416
- prefix.set(chunk.subarray(0, take), length);
417
- length += take;
418
- if (length >= 4 && isZlibHeader(prefix) && isPrintableZlibHeader(prefix))
419
- needed = prefix.length;
420
- buffered.push(reusesBuffer && length < needed ? new Uint8Array(chunk) : chunk);
421
- }
422
- }
423
- const sample = prefix.subarray(0, length);
424
- if (isZipSignature(sample)) {
653
+ const bytes = smallRead === void 0 ? void 0 : await smallRead;
654
+ const smallFile = bytes !== void 0 && bytes.length <= stats.size ? bytes : void 0;
655
+ const probeSource = { kind: "file", path };
656
+ const compression = iterator === void 0 ? probeCompression(smallFile ?? await readRegularFilePrefix(file, COMPRESSION_PROBE_SIZE), !0, probeSource) : await probeStreamCompression(iterator, buffered, reusesBuffer, probeSource);
657
+ if (compression === "zip") {
425
658
  if (!regularFile || !(await stat(path)).isFile())
426
659
  throw Error("ZIP input requires a regular file; save the archive before reading it");
427
660
  await file.close();
428
- yield* readZipEntryChunks(path, { format: "zip", entry: "*" }, chunkSize, zipReadAhead);
661
+ yield* readZipFileChunks(path, { format: "zip", entry: "*" }, chunkSize, zipReadAhead, readAhead);
429
662
  return;
430
663
  }
431
- const compression = compressionFromPrefix(path, sample);
432
664
  if (compression === "gzip" && regularFile) {
433
665
  yield* readGzipFileChunks(file.fd, chunkSize, readMode !== "stream");
434
666
  return;
435
667
  }
436
- if (compression === void 0 && !isPlainCsvFile(path))
668
+ if (compression === "none" && !isPlainCsvFile(path))
437
669
  throw Error("compression auto-detection failed: no supported signature or extension and no delimited-text MIME type; specify compression explicitly (none for plain input)");
438
- const source = iterator === void 0 ? raw() : replayCsvFileChunks(buffered, iterator);
439
- if (compression === void 0) {
670
+ if (compression === "none" && regularFile && readMode === "count") {
671
+ yield* readAheadOpenFileChunks(file, chunkSize, stats);
672
+ return;
673
+ }
674
+ if (compression === "none" && smallFile !== void 0) {
675
+ yield* closeWhileYielding(file, smallFile);
676
+ return;
677
+ }
678
+ const source = iterator === void 0 ? raw(compression === "none" ? readAhead : void 0) : replayCsvFileChunks(buffered, iterator);
679
+ if (compression === "none") {
440
680
  yield* source;
441
681
  return;
442
682
  }
443
- yield* decompressFileStream(reusesBuffer ? copyFileChunks(source) : source, compression, chunkSize);
683
+ yield* decompressChunks(reusesBuffer ? copyChunks(source) : source, compression, chunkSize);
444
684
  } finally {
445
685
  if (iterator !== void 0)
446
686
  await closeCsvFileIterator(iterator);
447
687
  }
448
688
  }
689
+ function readSmallRegularFile(file, stats, chunkSize) {
690
+ if (!stats.isFile() || stats.size === 0 || stats.size > Math.min(SMALL_PLAIN_FILE_MAX_BYTES, chunkSize))
691
+ return;
692
+ return Bun.file(file.fd).slice(0, stats.size + 1).bytes();
693
+ }
694
+ async function* closeWhileYielding(file, bytes) {
695
+ const closing = file.close();
696
+ void closing.catch(() => {});
697
+ try {
698
+ if (bytes.length > 0)
699
+ yield bytes;
700
+ } finally {
701
+ await closing;
702
+ }
703
+ }
704
+ async function readRegularFilePrefix(file, capacity) {
705
+ const bytes = new Uint8Array(capacity);
706
+ let length = 0;
707
+ while (length < capacity) {
708
+ const { bytesRead } = await file.read(bytes, length, capacity - length, length);
709
+ if (bytesRead === 0)
710
+ break;
711
+ length += bytesRead;
712
+ }
713
+ return bytes.subarray(0, length);
714
+ }
449
715
  async function* readGzipPathChunks(path, chunkSize, reuseBuffer) {
450
716
  await using file = await open(path, "r");
451
717
  if ((await file.stat()).isFile()) {
452
718
  yield* readGzipFileChunks(file.fd, chunkSize, reuseBuffer);
453
719
  return;
454
720
  }
455
- yield* decompressFileStream(file.createReadStream({ highWaterMark: chunkSize, autoClose: !1 }), "gzip", chunkSize);
721
+ yield* decompressChunks(file.createReadStream({ highWaterMark: chunkSize, autoClose: !1 }), "gzip", chunkSize);
456
722
  }
457
- function decompressFileStream(source, compression, chunkSize) {
723
+ function decompressChunks(source, compression, chunkSize) {
458
724
  return WebReadableStream.from(source).pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
459
725
  }
460
- async function* copyFileChunks(chunks) {
726
+ async function* copyChunks(chunks) {
461
727
  for await (const chunk of chunks)
462
728
  yield new Uint8Array(chunk);
463
729
  }
@@ -466,7 +732,7 @@ function isPlainCsvFile(path) {
466
732
  return mime === "text/csv" || mime === "text/tab-separated-values" || mime === "text/plain" || mime === "application/octet-stream" && /\.(?:psv|ssv|tab)$/i.test(path);
467
733
  }
468
734
  export function isZipSignature(prefix) {
469
- return prefix[0] === 80 && prefix[1] === 75 && (prefix[2] === 3 && prefix[3] === 4 || prefix[2] === 5 && prefix[3] === 6);
735
+ return compressionSignature(prefix) === "zip";
470
736
  }
471
737
  function isPrintableZlibHeader(prefix) {
472
738
  const first = prefix[0] ?? 0;
@@ -476,15 +742,22 @@ function isPrintableZlibHeader(prefix) {
476
742
  function decompressedCsvFileChunks(path, compression, chunkSize) {
477
743
  return Bun.file(path).stream().pipeThrough(new DecompressionStream(compression, { highWaterMark: chunkSize }));
478
744
  }
479
- export function compressionFromPrefix(path, prefix) {
480
- const extensionHint = compressionFromExtension(path);
481
- const strongSignature = compressionFromStrongSignature(prefix);
482
- if (strongSignature !== void 0) {
483
- if (extensionHint !== void 0 && extensionHint.format !== strongSignature)
484
- throw Error(`compression auto-detection mismatch: extension ${extensionHint.extension} indicates ${extensionHint.format}, but the file signature indicates ${strongSignature}`);
485
- return strongSignature;
745
+ export function probeCompression(prefix, sourceEnded, source) {
746
+ const sample = prefix.length > COMPRESSION_PROBE_SIZE ? prefix.subarray(0, COMPRESSION_PROBE_SIZE) : prefix;
747
+ const signature = compressionSignature(sample);
748
+ const hasZlibHeader = isZlibHeader(sample);
749
+ const printableZlib = hasZlibHeader && isPrintableZlibHeader(sample);
750
+ if (!sourceEnded && (sample.length === 0 || signature === "partial" || sample.length === 1 && isZlibMethod(sample[0]) || sample.length < COMPRESSION_PROBE_SIZE && printableZlib))
751
+ return "need-more";
752
+ if (signature === "zip")
753
+ return "zip";
754
+ const path = source.kind === "stream" ? void 0 : source.path;
755
+ const extensionHint = path === void 0 ? void 0 : compressionFromExtension(path);
756
+ if (signature === "gzip" || signature === "zstd") {
757
+ if (extensionHint !== void 0 && extensionHint.format !== signature)
758
+ throw Error(`compression auto-detection mismatch: extension ${extensionHint.extension} indicates ${extensionHint.format}, but the file signature indicates ${signature}`);
759
+ return signature;
486
760
  }
487
- const hasZlibHeader = isZlibHeader(prefix);
488
761
  if (extensionHint !== void 0) {
489
762
  if (extensionHint.signatureRequired) {
490
763
  if (extensionHint.format === "deflate" && hasZlibHeader)
@@ -495,21 +768,19 @@ export function compressionFromPrefix(path, prefix) {
495
768
  }
496
769
  return extensionHint.format;
497
770
  }
498
- if (hasZlibHeader) {
499
- const sample = prefix.subarray(0, 64);
500
- if (isPrintableZlibHeader(sample) && isPlainCsvFile(path) && !sample.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
501
- try {
502
- inflateSync(sample, { finishFlush: sample.length < 64 ? constants.Z_FINISH : constants.Z_SYNC_FLUSH });
503
- } catch (error) {
504
- if (error instanceof Error && "code" in error && (error.code === "Z_DATA_ERROR" || error.code === "Z_NEED_DICT" || error.code === "Z_BUF_ERROR"))
505
- return;
506
- throw error;
507
- }
508
- return "deflate";
509
- }
510
- return;
771
+ if (!hasZlibHeader)
772
+ return "none";
773
+ if (printableZlib && (path === void 0 || isPlainCsvFile(path)) || source.kind === "inspection" && !sample.some((byte) => byte < 32 && byte !== 9 && byte !== 10 && byte !== 13))
774
+ try {
775
+ inflateSync(sample, { finishFlush: sample.length < COMPRESSION_PROBE_SIZE ? constants.Z_FINISH : constants.Z_SYNC_FLUSH });
776
+ } catch (error) {
777
+ if (error instanceof Error && "code" in error && (error.code === "Z_DATA_ERROR" || error.code === "Z_NEED_DICT" || error.code === "Z_BUF_ERROR"))
778
+ return "none";
779
+ throw error;
780
+ }
781
+ return "deflate";
511
782
  }
512
- export function compressionFromExtension(path) {
783
+ function compressionFromExtension(path) {
513
784
  const lowerPath = path.toLowerCase();
514
785
  if (lowerPath.endsWith(".deflate-raw"))
515
786
  return { extension: ".deflate-raw", format: "deflate-raw", signatureRequired: !1 };
@@ -531,19 +802,37 @@ export function compressionFromExtension(path) {
531
802
  return;
532
803
  }
533
804
  }
534
- function compressionFromStrongSignature(prefix) {
535
- if (prefix[0] === 31 && prefix[1] === 139)
536
- return "gzip";
537
- if (prefix[0] === 40 && prefix[1] === 181 && prefix[2] === 47 && prefix[3] === 253)
538
- return "zstd";
539
- if (prefix[0] !== void 0 && prefix[0] >= 80 && prefix[0] <= 95 && prefix[1] === 42 && prefix[2] === 77 && prefix[3] === 24)
540
- return "zstd";
805
+ const COMPRESSION_SIGNATURES = [
806
+ { format: "gzip", bytes: [31, 139], firstByteMask: 255 },
807
+ { format: "zstd", bytes: [40, 181, 47, 253], firstByteMask: 255 },
808
+ { format: "zstd", bytes: [80, 42, 77, 24], firstByteMask: 240 },
809
+ { format: "zip", bytes: [80, 75, 3, 4], firstByteMask: 255 },
810
+ { format: "zip", bytes: [80, 75, 5, 6], firstByteMask: 255 }
811
+ ];
812
+ function compressionSignature(prefix) {
813
+ const first = prefix[0];
814
+ if (first === void 0)
815
+ return;
816
+ for (const { format, bytes, firstByteMask } of COMPRESSION_SIGNATURES) {
817
+ if ((first & firstByteMask) !== bytes[0])
818
+ continue;
819
+ let matched = 1;
820
+ while (matched < bytes.length && prefix[matched] === bytes[matched])
821
+ ++matched;
822
+ if (matched === bytes.length)
823
+ return format;
824
+ if (matched === prefix.length)
825
+ return "partial";
826
+ }
541
827
  return;
542
828
  }
829
+ function isZlibMethod(byte = 0) {
830
+ return (byte & 15) === 8 && byte >> 4 <= 7;
831
+ }
543
832
  function isZlibHeader(prefix) {
544
833
  const compressionMethodAndFlags = prefix[0];
545
834
  const flags = prefix[1];
546
835
  if (compressionMethodAndFlags === void 0 || flags === void 0)
547
836
  return !1;
548
- return (compressionMethodAndFlags & 15) === 8 && compressionMethodAndFlags >> 4 <= 7 && (compressionMethodAndFlags << 8 | flags) % 31 === 0;
837
+ return isZlibMethod(compressionMethodAndFlags) && (compressionMethodAndFlags << 8 | flags) % 31 === 0;
549
838
  }