@konstit/csv 0.4.3 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +50 -28
  2. package/THIRD_PARTY_NOTICES.md +7 -1
  3. package/dist/api.d.ts +39 -249
  4. package/dist/api.js +56 -394
  5. package/dist/batches.d.ts +8 -57
  6. package/dist/batches.js +77 -52
  7. package/dist/cli-command.d.ts +7 -0
  8. package/dist/cli-command.js +315 -0
  9. package/dist/cli-schema.d.ts +127 -0
  10. package/dist/cli-schema.js +234 -0
  11. package/dist/cli.js +2 -604
  12. package/dist/file-stream.d.ts +62 -3
  13. package/dist/file-stream.js +242 -36
  14. package/dist/files.d.ts +11 -11
  15. package/dist/files.js +38 -79
  16. package/dist/filter.d.ts +5 -8
  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 +22 -0
  22. package/dist/inspect-file.js +138 -0
  23. package/dist/latin1-rows.d.ts +4 -3
  24. package/dist/latin1-rows.js +72 -24
  25. package/dist/materialize-field.d.ts +2 -0
  26. package/dist/materialize-field.js +20 -15
  27. package/dist/native.d.ts +50 -78
  28. package/dist/native.js +36 -112
  29. package/dist/normalize.d.ts +14 -40
  30. package/dist/normalize.js +66 -64
  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 +23 -209
  35. package/dist/parser.js +146 -261
  36. package/dist/strict-schema.d.ts +6 -4
  37. package/dist/strict-schema.js +4 -3
  38. package/dist/types.d.ts +119 -221
  39. package/dist/zip-reader.d.ts +13 -1
  40. package/dist/zip-reader.js +36 -17
  41. package/package.json +36 -33
  42. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  43. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  44. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  45. package/prebuilds/manifest.json +9 -8
  46. package/prebuilds/provenance/darwin-arm64.json +1 -1
  47. package/prebuilds/provenance/darwin-x64.json +1 -1
  48. package/prebuilds/provenance/linux-x64.json +1 -1
  49. package/dist/worker-count.d.ts +0 -34
  50. package/dist/worker-count.js +0 -101
  51. package/dist/worker-factory.d.ts +0 -3
  52. package/dist/worker-factory.js +0 -9
  53. package/dist/worker-filter.d.ts +0 -29
  54. package/dist/worker-filter.js +0 -46
  55. package/dist/worker-module.d.ts +0 -1
  56. package/dist/worker-module.js +0 -4
  57. package/dist/worker-pool.d.ts +0 -93
  58. package/dist/worker-pool.js +0 -298
  59. package/dist/worker-rows.d.ts +0 -36
  60. package/dist/worker-rows.js +0 -127
  61. package/dist/workers/count.worker.d.ts +0 -1
  62. package/dist/workers/count.worker.js +0 -36
  63. package/dist/workers/rows.worker.d.ts +0 -1
  64. package/dist/workers/rows.worker.js +0 -56
@@ -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, CsvNativeFilterOperator, CsvNativeFilterProgramEntry, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvZipCompression, NativeCsvParserOptions, 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,22 @@
1
+ interface InspectionOptions {
2
+ readonly zipEntry?: string;
3
+ readonly delimiter?: string;
4
+ readonly encoding?: string;
5
+ }
6
+ interface FileInspection {
7
+ fileSizeBytes: number;
8
+ sampleBytes: number;
9
+ sampleReachedEof: boolean;
10
+ compression: Bun.CompressionFormat | 'zip' | 'none';
11
+ zipEntry: string | null;
12
+ encoding: string;
13
+ encodingSource: 'explicit' | 'inferred';
14
+ delimiter: string | null;
15
+ delimiterSource: 'explicit' | 'inferred' | null;
16
+ delimiterReason: string | null;
17
+ lineEnding: string;
18
+ firstRecordColumns: number | null;
19
+ }
20
+ /** Inspect a bounded sample of the CSV payload; size always refers to the file on disk. */
21
+ export declare function inspectCsvFile(path: string, options?: InspectionOptions): Promise<FileInspection>;
22
+ export {};
@@ -0,0 +1,138 @@
1
+ import { stat } from "node:fs/promises";
2
+ import {
3
+ compressionFromExtension,
4
+ compressionFromPrefix,
5
+ DELIMITER_CANDIDATES,
6
+ FILE_PROBE_SIZE,
7
+ isZipSignature,
8
+ readCsvFileChunks,
9
+ scanCsvFileFormat,
10
+ scanDelimiterCounts,
11
+ selectDelimiter
12
+ } from "./file-stream.js";
13
+ import { resolveInputEncoding } from "./normalize.js";
14
+ import { NativeZipReader } from "./zip-reader.js";
15
+ export async function inspectCsvFile(path, options = {}) {
16
+ const info = await stat(path);
17
+ if (!info.isFile())
18
+ throw Error("probe requires a regular file");
19
+ const raw = await Bun.file(path).slice(0, FILE_PROBE_SIZE + 1).bytes();
20
+ const zip = isZipSignature(raw);
21
+ if (options.zipEntry !== void 0 && !zip)
22
+ throw Error("--zip-entry requires a ZIP archive");
23
+ let compression = zip ? "zip" : compressionFromPrefix(path, raw) ?? "none";
24
+ let zipEntry = null;
25
+ let sample = raw;
26
+ if (compression === "zip") {
27
+ using reader = new NativeZipReader(path, { format: "zip", entry: options.zipEntry ?? "*" });
28
+ zipEntry = reader.entryName;
29
+ sample = await readCompressedSample(reader.chunks(FILE_PROBE_SIZE + 1));
30
+ } else if (compression !== "none")
31
+ try {
32
+ sample = await readCompressedSample(readCsvFileChunks(path, { compression, chunkSize: FILE_PROBE_SIZE + 1 }));
33
+ } catch (error) {
34
+ if (compression !== "deflate" || compressionFromExtension(path) !== void 0 || !(error instanceof TypeError) || raw.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
35
+ throw error;
36
+ compression = "none";
37
+ }
38
+ const eof = sample.length <= FILE_PROBE_SIZE;
39
+ const prefix = sample.subarray(0, FILE_PROBE_SIZE);
40
+ const format = inspectFormat(zipEntry ?? path, prefix, eof, options.encoding ?? "auto", options.delimiter ?? "auto");
41
+ return {
42
+ fileSizeBytes: info.size,
43
+ sampleBytes: prefix.byteLength,
44
+ sampleReachedEof: eof,
45
+ compression,
46
+ zipEntry,
47
+ ...format
48
+ };
49
+ }
50
+ async function readCompressedSample(chunks) {
51
+ const sample = new Uint8Array(FILE_PROBE_SIZE + 1);
52
+ let length = 0;
53
+ for await (const chunk of chunks) {
54
+ const take = Math.min(chunk.length, sample.length - length);
55
+ sample.set(chunk.subarray(0, take), length);
56
+ length += take;
57
+ if (length === sample.length)
58
+ break;
59
+ }
60
+ return sample.subarray(0, length);
61
+ }
62
+ function inspectFormat(path, prefix, eof, encoding, delimiter) {
63
+ let bytes = prefix;
64
+ let counts;
65
+ const encodingSource = encoding === "auto" ? "inferred" : "explicit";
66
+ if (encoding === "auto") {
67
+ const sample = scanCsvFileFormat(prefix, eof, !0);
68
+ bytes = sample.bytes;
69
+ counts = sample.counts;
70
+ encoding = sample.encoding;
71
+ } else {
72
+ const decoder = resolveInputEncoding(encoding, delimiter);
73
+ if (typeof decoder === "string")
74
+ encoding = decoder;
75
+ else {
76
+ bytes = new TextEncoder().encode(decoder.decode(prefix, { stream: !eof }));
77
+ encoding = decoder.encoding;
78
+ }
79
+ }
80
+ const choice = delimiter === "auto" ? inspectDelimiter(path, bytes, eof, counts, prefix.length) : { delimiter, delimiterSource: "explicit", delimiterReason: null };
81
+ return { encoding, encodingSource, ...choice, ...inspectRecords(bytes, eof, choice.delimiter) };
82
+ }
83
+ function inspectDelimiter(path, bytes, eof, counts, sampleBytes) {
84
+ const rows = counts ?? scanDelimiterCounts(bytes, eof);
85
+ const choice = selectDelimiter(path, rows);
86
+ if ("delimiter" in choice)
87
+ return { delimiter: choice.delimiter, delimiterSource: "inferred", delimiterReason: null };
88
+ let reason;
89
+ switch (choice.reason) {
90
+ case "no-records":
91
+ reason = sampleBytes === 0 ? "Empty payload" : eof ? "No complete non-empty record in the payload" : "No complete non-empty record in the 64 KiB sample";
92
+ break;
93
+ case "no-stable-separator": {
94
+ const perRecord = counts === void 0 ? rows : scanDelimiterCounts(bytes, eof);
95
+ reason = perRecord.some((row) => row.some((count) => count > 0)) ? "Separator counts vary across sampled records" : "No supported separator found in sampled records";
96
+ break;
97
+ }
98
+ case "ambiguous":
99
+ reason = `Ambiguous between ${choice.candidates.map((c) => JSON.stringify(c)).join(" and ")}`;
100
+ break;
101
+ }
102
+ return { delimiter: null, delimiterSource: null, delimiterReason: reason };
103
+ }
104
+ function inspectRecords(bytes, eof, delimiter) {
105
+ const separator = delimiter?.charCodeAt(0);
106
+ const endings = new Set;
107
+ let quoted = !1;
108
+ let firstRecord = !0;
109
+ let columns = 1;
110
+ let unknownWidth = !1;
111
+ for (let i = 0;i < bytes.length; ++i) {
112
+ const byte = bytes[i];
113
+ if (byte === 34)
114
+ quoted = !quoted;
115
+ else if (!quoted) {
116
+ if (byte === 13 || byte === 10) {
117
+ firstRecord = !1;
118
+ if (byte === 13 && bytes[i + 1] === 10) {
119
+ endings.add("CRLF");
120
+ ++i;
121
+ } else if (byte === 13 && i + 1 === bytes.length && !eof)
122
+ break;
123
+ else
124
+ endings.add(byte === 10 ? "LF" : "CR");
125
+ } else if (firstRecord) {
126
+ if (byte === separator)
127
+ ++columns;
128
+ else if (separator === void 0 && DELIMITER_CANDIDATES.some((candidate) => candidate.byte === byte))
129
+ unknownWidth = !0;
130
+ }
131
+ }
132
+ }
133
+ const firstComplete = !firstRecord || eof && !quoted;
134
+ return {
135
+ firstRecordColumns: firstComplete && !unknownWidth ? bytes.length === 0 ? 0 : columns : null,
136
+ lineEnding: endings.size > 1 ? "mixed" : endings.values().next().value ?? (eof ? "none" : "unknown")
137
+ };
138
+ }
@@ -1,3 +1,4 @@
1
- import type { CsvNativeFilterProgramEntry } from './normalize.js';
2
- import type { CsvColumns, CsvDelimiter, CsvRow } from './types.js';
3
- export declare function latin1Rows(chunks: AsyncIterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined): AsyncGenerator<CsvRow[], void>;
1
+ import { type NativePointer } from './native.js';
2
+ import type { CsvColumns, CsvDelimiter, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow } from './types.js';
3
+ export declare function latin1Rows(chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, createParser: (delimiter: number) => NativePointer | null, reusableRows?: CsvRow[], options?: CsvParserOptions): AsyncGenerator<CsvRow[], void>;
4
+ export declare function checkedOffset(words: Uint32Array, index: number, upperBound: number): number;
@@ -1,46 +1,58 @@
1
- import { decodeMaterializedField } from "./materialize-field.js";
1
+ import {
2
+ copyLatin1Range,
3
+ latin1Pair
4
+ } from "./materialize-field.js";
2
5
  import {
3
6
  EMPTY_BUFFER,
4
7
  native,
5
- optionalLatin1RowsNative,
6
8
  requirePtr,
7
9
  toArrayBuffer,
8
10
  u64ToSafeNumber
9
11
  } from "./native.js";
10
12
  import { normalizeChunk } from "./normalize.js";
11
- import { prepareNativeParser } from "./parser.js";
12
- const latin1RowsParserFinalizer = new FinalizationRegistry((parser) => {
13
- native.symbols.csv_parser_destroy(parser);
14
- });
15
- export async function* latin1Rows(chunks, delimiter, columns, filters) {
13
+ import {
14
+ nativeCsvParserFinalizer,
15
+ prepareNativeParser,
16
+ setRowSelection
17
+ } from "./parser.js";
18
+ export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows, options = {}) {
16
19
  if (delimiter === "auto")
17
20
  throw Error("automatic delimiter detection is only supported by file APIs");
18
21
  if (delimiter.length !== 1)
19
22
  throw Error("delimiter must be one character");
20
- const parser = optionalLatin1RowsNative()?.symbols.csv_parser_create_latin1_rows(delimiter.charCodeAt(0));
21
- if (parser === null || parser === void 0)
23
+ const parser = createParser(delimiter.charCodeAt(0));
24
+ if (parser === null)
22
25
  throw Error("failed to create native CSV parser");
23
26
  const lifetime = {};
24
- latin1RowsParserFinalizer.register(lifetime, parser, lifetime);
27
+ nativeCsvParserFinalizer.register(lifetime, parser, lifetime);
25
28
  try {
29
+ setRowSelection(parser, options);
26
30
  const prepared = prepareNativeParser(parser, columns, filters);
31
+ let remaining = options.limit;
32
+ if (remaining === 0)
33
+ return;
27
34
  for await (const chunk of chunks) {
28
35
  const input = normalizeChunk(chunk);
29
36
  const batch = prepared.writeBatch(input, !1);
30
- const rows = consumeLatin1Batch(parser, batch);
31
- if (rows.length > 0)
37
+ const rows = consumeLatin1Batch(parser, batch, reusableRows);
38
+ if (rows.length > 0) {
39
+ if (remaining !== void 0)
40
+ remaining -= rows.length;
32
41
  yield rows;
42
+ if (remaining === 0)
43
+ return;
44
+ }
33
45
  }
34
46
  const batch = prepared.writeBatch(EMPTY_BUFFER, !0);
35
- const rows = consumeLatin1Batch(parser, batch);
47
+ const rows = consumeLatin1Batch(parser, batch, reusableRows);
36
48
  if (rows.length > 0)
37
49
  yield rows;
38
50
  } finally {
39
- latin1RowsParserFinalizer.unregister(lifetime);
51
+ nativeCsvParserFinalizer.unregister(lifetime);
40
52
  native.symbols.csv_parser_destroy(parser);
41
53
  }
42
54
  }
43
- function consumeLatin1Batch(parser, batch) {
55
+ function consumeLatin1Batch(parser, batch, reusableRows) {
44
56
  if (batch === null)
45
57
  throw Error(`native CSV parser failed: ${native.symbols.csv_parser_last_error(parser) ?? "native parser error unavailable"}`);
46
58
  try {
@@ -51,30 +63,66 @@ function consumeLatin1Batch(parser, batch) {
51
63
  const dataLength = u64ToSafeNumber(native.symbols.csv_batch_data_len(batch), "CSV batch data length");
52
64
  const data = dataLength === 0 ? EMPTY_BUFFER : new Uint8Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_data_ptr(batch)), 0, dataLength));
53
65
  const bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
66
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
54
67
  const rowOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_row_offsets_ptr(batch)), 0, (rowCount + 1) * 8));
55
68
  const fieldOffsets = new Uint32Array(toArrayBuffer(requirePtr(native.symbols.csv_batch_field_offsets_ptr(batch)), 0, (totalFields + 1) * 8));
56
- const rows = [];
69
+ const flags = native.symbols.csv_batch_quoted_rows_ptr(batch);
70
+ const quotedRows = flags === null ? void 0 : new Uint8Array(toArrayBuffer(flags, 0, rowCount));
71
+ const rows = reusableRows ?? [];
57
72
  rows.length = rowCount;
73
+ let fieldStart = checkedOffset(rowOffsets, 0, totalFields);
74
+ let start = checkedOffset(fieldOffsets, fieldStart, dataLength);
58
75
  for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
59
- const fieldStart = checkedOffset(rowOffsets, rowIndex, totalFields);
60
76
  const fieldEnd = checkedOffset(rowOffsets, rowIndex + 1, totalFields);
61
- const row = [];
62
- row.length = fieldEnd - fieldStart;
63
- for (let fieldIndex = fieldStart;fieldIndex < fieldEnd; ++fieldIndex) {
64
- const start = checkedOffset(fieldOffsets, fieldIndex, dataLength);
65
- const end = checkedOffset(fieldOffsets, fieldIndex + 1, dataLength);
66
- row[fieldIndex - fieldStart] = decodeMaterializedField(bytes, start, end, "latin1");
77
+ const leading = quotedRows?.[rowIndex] ?? 0;
78
+ const trailing = leading * 2;
79
+ const row = reusableRows?.[rowIndex] ?? [];
80
+ const width = fieldEnd - fieldStart;
81
+ row.length = width;
82
+ for (let column = 0;column < width; ++column) {
83
+ const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
84
+ const payload = start + leading;
85
+ const payloadEnd = end - trailing;
86
+ const length = payloadEnd - payload;
87
+ switch (length) {
88
+ case 0:
89
+ row[column] = "";
90
+ break;
91
+ case 1:
92
+ row[column] = String.fromCharCode(view.getUint8(payload));
93
+ break;
94
+ case 2:
95
+ row[column] = latin1Pair(view.getUint16(payload, !0));
96
+ break;
97
+ case 3:
98
+ row[column] = latin1Pair(view.getUint16(payload, !0)) + String.fromCharCode(view.getUint8(payload + 2));
99
+ break;
100
+ case 4:
101
+ row[column] = latin1Pair(view.getUint16(payload, !0)) + latin1Pair(view.getUint16(payload + 2, !0));
102
+ break;
103
+ default:
104
+ if (length < 0)
105
+ throw RangeError("CSV field span exceeds its backing range");
106
+ row[column] = copyLatin1Range(bytes, payload, payloadEnd);
107
+ }
108
+ start = end;
67
109
  }
68
110
  rows[rowIndex] = row;
111
+ fieldStart = fieldEnd;
69
112
  }
70
113
  return rows;
71
114
  } finally {
72
115
  native.symbols.csv_batch_destroy(batch);
73
116
  }
74
117
  }
75
- function checkedOffset(words, index, upperBound) {
118
+ export function checkedOffset(words, index, upperBound) {
76
119
  const low = words[index * 2];
77
120
  const high = words[index * 2 + 1];
121
+ if (low !== void 0 && high === 0 && low <= upperBound)
122
+ return low;
123
+ return checkedWideOffset(low, high, upperBound);
124
+ }
125
+ function checkedWideOffset(low, high, upperBound) {
78
126
  if (low === void 0 || high === void 0 || high > 2097151)
79
127
  throw RangeError("CSV batch offset out of range");
80
128
  const offset = low + high * 4294967296;
@@ -1 +1,3 @@
1
+ export declare function latin1Pair(key: number): string;
2
+ export declare function copyLatin1Range(data: Buffer, start: number, end: number): string;
1
3
  export declare function decodeMaterializedField(data: Buffer, start: number, end: number, encoding: 'utf8' | 'latin1'): string;
@@ -1,26 +1,31 @@
1
- const ASCII_SINGLE = Array.from({ length: 128 }, (_, byte) => String.fromCharCode(byte));
2
- const ASCII_PAIRS = Array.from({ length: 16384 });
1
+ const LATIN1_SINGLE = Array.from({ length: 256 }, (_, byte) => String.fromCharCode(byte));
2
+ const bufferPrototype = Buffer.prototype;
3
+ const latin1Slice = bufferPrototype.latin1Slice;
4
+ const LATIN1_PAIRS = Array.from({ length: 65536 });
5
+ export function latin1Pair(key) {
6
+ const cached = LATIN1_PAIRS[key];
7
+ if (cached !== void 0)
8
+ return cached;
9
+ const value = String.fromCharCode(key & 255, key >>> 8);
10
+ LATIN1_PAIRS[key] = value;
11
+ return value;
12
+ }
13
+ export function copyLatin1Range(data, start, end) {
14
+ return typeof latin1Slice === "function" ? latin1Slice.call(data, start, end) : data.toString("latin1", start, end);
15
+ }
3
16
  export function decodeMaterializedField(data, start, end, encoding) {
4
17
  const length = end - start;
5
18
  if (length === 0)
6
19
  return "";
7
20
  if (length === 1) {
8
- const first = data[start] ?? 128;
9
- if (first < 128)
10
- return ASCII_SINGLE[first] ?? "";
21
+ const first = data[start];
22
+ return first < 128 || encoding === "latin1" ? LATIN1_SINGLE[first] : "\uFFFD";
11
23
  }
12
24
  if (length === 2) {
13
25
  const first = data[start] ?? 128;
14
26
  const second = data[start + 1] ?? 128;
15
- if (first < 128 && second < 128) {
16
- const key = first << 7 | second;
17
- const cached = ASCII_PAIRS[key];
18
- if (cached !== void 0)
19
- return cached;
20
- const decoded = String.fromCharCode(first, second);
21
- ASCII_PAIRS[key] = decoded;
22
- return decoded;
23
- }
27
+ if (first < 128 && second < 128)
28
+ return latin1Pair(first | second << 8);
24
29
  }
25
- return data.toString(encoding, start, end);
30
+ return encoding === "latin1" ? copyLatin1Range(data, start, end) : data.toString("utf8", start, end);
26
31
  }
package/dist/native.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Library, type Pointer } from 'bun:ffi';
1
+ import { type Pointer } from 'bun:ffi';
2
2
  export type { Pointer } from 'bun:ffi';
3
3
  export { toArrayBuffer } from 'bun:ffi';
4
4
  /**
@@ -12,7 +12,11 @@ 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 native: Library<{
15
+ export declare const native: import("bun:ffi").Library<{
16
+ readonly csv_probe_format: {
17
+ readonly args: readonly ["buffer", "u32", "bool", "bool", "ptr"];
18
+ readonly returns: "u32";
19
+ };
16
20
  readonly csv_runtime_supports_avx2: {
17
21
  readonly args: readonly [];
18
22
  readonly returns: "int";
@@ -21,11 +25,27 @@ export declare const native: Library<{
21
25
  readonly args: readonly ["int", "u8"];
22
26
  readonly returns: "ptr";
23
27
  };
28
+ readonly csv_parser_create_prepared: {
29
+ readonly args: readonly ["int", "u8", "u32"];
30
+ readonly returns: "ptr";
31
+ };
32
+ readonly csv_parser_set_row_selection: {
33
+ readonly args: readonly ["ptr", "u64", "u64", "bool"];
34
+ readonly returns: "void";
35
+ };
36
+ readonly csv_parser_take_skipped_header: {
37
+ readonly args: readonly ["ptr"];
38
+ readonly returns: "ptr";
39
+ };
40
+ readonly csv_parser_skipped_rows: {
41
+ readonly args: readonly ["ptr"];
42
+ readonly returns: "u64";
43
+ };
24
44
  readonly csv_parser_destroy: {
25
45
  readonly args: readonly ["ptr"];
26
46
  readonly returns: "void";
27
47
  };
28
- readonly csv_parser_reset: {
48
+ readonly csv_parser_reset_stream: {
29
49
  readonly args: readonly ["ptr"];
30
50
  readonly returns: "void";
31
51
  };
@@ -33,50 +53,18 @@ export declare const native: Library<{
33
53
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
34
54
  readonly returns: "ptr";
35
55
  };
36
- readonly csv_parser_finish_batch: {
37
- readonly args: readonly ["ptr"];
38
- readonly returns: "ptr";
39
- };
40
56
  readonly csv_parser_write_strict_batch: {
41
57
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
42
58
  readonly returns: "ptr";
43
59
  };
44
- readonly csv_parser_finish_strict_batch: {
45
- readonly args: readonly ["ptr"];
46
- readonly returns: "ptr";
47
- };
48
60
  readonly csv_parser_write_fixed_batch: {
49
61
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32"];
50
62
  readonly returns: "ptr";
51
63
  };
52
- readonly csv_parser_finish_fixed_batch: {
53
- readonly args: readonly ["ptr", "u32"];
54
- readonly returns: "ptr";
55
- };
56
64
  readonly csv_parser_write_strict_fixed_batch: {
57
65
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32"];
58
66
  readonly returns: "ptr";
59
67
  };
60
- readonly csv_parser_finish_strict_fixed_batch: {
61
- readonly args: readonly ["ptr", "u32"];
62
- readonly returns: "ptr";
63
- };
64
- readonly csv_parser_write_projected_batch: {
65
- readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "bool", "buffer", "u64", "bool", "u32", "buffer", "buffer_length"];
66
- readonly returns: "ptr";
67
- };
68
- readonly csv_parser_finish_projected_batch: {
69
- readonly args: readonly ["ptr", "bool", "buffer", "u64", "bool", "u32", "buffer", "buffer_length"];
70
- readonly returns: "ptr";
71
- };
72
- readonly csv_parser_write_projected_batch_where_all: {
73
- readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "bool", "buffer", "u64", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"];
74
- readonly returns: "ptr";
75
- };
76
- readonly csv_parser_finish_projected_batch_where_all: {
77
- readonly args: readonly ["ptr", "bool", "buffer", "u64", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"];
78
- readonly returns: "ptr";
79
- };
80
68
  readonly csv_batch_destroy: {
81
69
  readonly args: readonly ["ptr"];
82
70
  readonly returns: "void";
@@ -137,42 +125,6 @@ export declare const native: Library<{
137
125
  readonly args: readonly ["ptr"];
138
126
  readonly returns: "ptr";
139
127
  };
140
- readonly csv_parser_finish_count: {
141
- readonly args: readonly ["ptr"];
142
- readonly returns: "u64";
143
- };
144
- readonly csv_parser_write_count_where_all: {
145
- readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"];
146
- readonly returns: "u64";
147
- };
148
- readonly csv_parser_finish_count_where_all: {
149
- readonly args: readonly ["ptr", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"];
150
- readonly returns: "u64";
151
- };
152
- readonly csv_parser_write_count_where_equals: {
153
- readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32", "buffer", "buffer_length"];
154
- readonly returns: "u64";
155
- };
156
- readonly csv_parser_finish_count_where_equals: {
157
- readonly args: readonly ["ptr", "u32", "buffer", "buffer_length"];
158
- readonly returns: "u64";
159
- };
160
- readonly csv_parser_write_count_where_in: {
161
- readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32", "buffer", "buffer_length", "buffer", "u64"];
162
- readonly returns: "u64";
163
- };
164
- readonly csv_parser_finish_count_where_in: {
165
- readonly args: readonly ["ptr", "u32", "buffer", "buffer_length", "buffer", "u64"];
166
- readonly returns: "u64";
167
- };
168
- readonly csv_parser_write_count_where_starts_with: {
169
- readonly args: readonly ["ptr", "buffer", "buffer_length", "bool", "u32", "buffer", "buffer_length"];
170
- readonly returns: "u64";
171
- };
172
- readonly csv_parser_finish_count_where_starts_with: {
173
- readonly args: readonly ["ptr", "u32", "buffer", "buffer_length"];
174
- readonly returns: "u64";
175
- };
176
128
  readonly csv_zip_reader_create: {
177
129
  readonly args: readonly ["cstring", "buffer", "buffer_length", "u64", "u32"];
178
130
  readonly returns: "ptr";
@@ -181,6 +133,14 @@ export declare const native: Library<{
181
133
  readonly args: readonly ["ptr"];
182
134
  readonly returns: "void";
183
135
  };
136
+ readonly csv_zip_reader_entry_name: {
137
+ readonly args: readonly ["ptr", "buffer"];
138
+ readonly returns: "ptr";
139
+ };
140
+ readonly csv_zip_reader_enable_read_ahead: {
141
+ readonly args: readonly ["ptr", "u32"];
142
+ readonly returns: "void";
143
+ };
184
144
  readonly csv_zip_reader_read: {
185
145
  readonly args: readonly ["ptr", "buffer", "buffer_length"];
186
146
  readonly returns: "u64";
@@ -197,8 +157,6 @@ export declare const native: Library<{
197
157
  readonly args: readonly ["ptr"];
198
158
  readonly returns: "cstring";
199
159
  };
200
- }>;
201
- declare const PREPARED_PARSER_SYMBOLS: {
202
160
  readonly csv_parser_prepare: {
203
161
  readonly args: readonly ["ptr", "bool", "buffer", "u64", "buffer", "u64", "buffer", "buffer_length", "buffer", "u64"];
204
162
  readonly returns: "bool";
@@ -211,15 +169,29 @@ declare const PREPARED_PARSER_SYMBOLS: {
211
169
  readonly args: readonly ["ptr", "buffer", "buffer_length", "bool"];
212
170
  readonly returns: "u64";
213
171
  };
214
- };
215
- export declare function optionalPreparedParserNative(): Library<typeof PREPARED_PARSER_SYMBOLS> | null;
216
- declare const LATIN1_ROWS_SYMBOLS: {
217
172
  readonly csv_parser_create_latin1_rows: {
218
173
  readonly args: readonly ["u8"];
219
174
  readonly returns: "ptr";
220
175
  };
221
- };
222
- export declare function optionalLatin1RowsNative(): Library<typeof LATIN1_ROWS_SYMBOLS> | null;
176
+ readonly csv_parser_create_latin1_rows_with_quoted_spans: {
177
+ readonly args: readonly ["u8"];
178
+ readonly returns: "ptr";
179
+ };
180
+ readonly csv_parser_create_latin1_quoted_rows: {
181
+ readonly args: readonly ["u8", "u32"];
182
+ readonly returns: "ptr";
183
+ };
184
+ readonly csv_batch_quoted_rows_ptr: {
185
+ readonly args: readonly ["ptr"];
186
+ readonly returns: "ptr";
187
+ };
188
+ readonly csv_parser_create_latin1_rows_with_fixed_columns: {
189
+ readonly args: readonly ["u8", "u32"];
190
+ readonly returns: "ptr";
191
+ };
192
+ }>;
193
+ export declare function latin1RowsParser(fixedColumns: number | undefined): (delimiter: number) => NativePointer | null;
194
+ export declare function resolveNativeLibraryPath(configuredPath: string | undefined): string;
223
195
  export declare function requireConfiguredNativeLibraryPath(configuredPath: string): string;
224
196
  export declare function nativeLibraryCandidates(root: string, target: string, librarySuffix: string): readonly string[];
225
197
  export declare function findNativeLibraryPath(candidates: readonly string[]): string | undefined;