@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.
- package/README.md +108 -102
- package/THIRD_PARTY_NOTICES.md +27 -0
- package/dist/api.d.ts +78 -55
- package/dist/api.js +191 -40
- package/dist/batch-pipeline.d.ts +10 -0
- package/dist/batch-pipeline.js +83 -0
- package/dist/batches.d.ts +16 -2
- package/dist/batches.js +179 -5
- package/dist/cli-command.d.ts +7 -7
- package/dist/cli-command.js +325 -164
- package/dist/cli-schema.d.ts +51 -21
- package/dist/cli-schema.js +126 -65
- package/dist/cli.js +1 -1
- package/dist/file-stream.d.ts +62 -15
- package/dist/file-stream.js +494 -205
- package/dist/files.d.ts +17 -37
- package/dist/files.js +48 -21
- package/dist/gzip-reader.js +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/inspect-file.d.ts +26 -3
- package/dist/inspect-file.js +169 -74
- package/dist/inspect-zip.d.ts +26 -0
- package/dist/inspect-zip.js +59 -0
- package/dist/latin1-rows.d.ts +11 -3
- package/dist/latin1-rows.js +276 -75
- package/dist/materialize-field.d.ts +6 -0
- package/dist/materialize-field.js +9 -0
- package/dist/native.d.ts +89 -19
- package/dist/native.js +45 -23
- package/dist/normalize.d.ts +5 -0
- package/dist/normalize.js +42 -9
- package/dist/options.d.ts +27 -12
- package/dist/parser.d.ts +30 -13
- package/dist/parser.js +264 -102
- package/dist/strict-schema.d.ts +7 -8
- package/dist/strict-schema.js +45 -83
- package/dist/transforms.d.ts +1 -3
- package/dist/transforms.js +17 -16
- package/dist/types.d.ts +175 -77
- package/dist/zip-entry.d.ts +14 -0
- package/dist/zip-entry.js +155 -0
- package/dist/zip-reader.d.ts +14 -3
- package/dist/zip-reader.js +65 -23
- package/package.json +34 -23
- package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
- package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
- package/prebuilds/linux-x64/libcsv_native.so +0 -0
- package/prebuilds/manifest.json +15 -8
- package/prebuilds/provenance/darwin-arm64.json +1 -1
- package/prebuilds/provenance/darwin-x64.json +1 -1
- package/prebuilds/provenance/linux-x64.json +1 -1
package/dist/files.d.ts
CHANGED
|
@@ -8,8 +8,7 @@ import type { CsvEncoding, CsvFileOptions, CsvNativeProjectionOptions, CsvParser
|
|
|
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
|
-
*
|
|
12
|
-
* Use an explicit one-character delimiter for in-memory input.
|
|
11
|
+
* The delimiter is detected by default. Supply uncompressed bytes with a known encoding.
|
|
13
12
|
*
|
|
14
13
|
* @param buffer Complete CSV bytes to parse.
|
|
15
14
|
* @param suppliedOptions Parser, projection, and strict-schema options.
|
|
@@ -25,37 +24,22 @@ import type { CsvEncoding, CsvFileOptions, CsvNativeProjectionOptions, CsvParser
|
|
|
25
24
|
* ```
|
|
26
25
|
*/
|
|
27
26
|
export declare function parseCsvBuffer(buffer: NodeJS.TypedArray | DataView, suppliedOptions?: CsvParserOptions<CsvEncoding>): CsvRow[];
|
|
28
|
-
/**
|
|
29
|
-
* Count rows in bytes known to contain one record per physical line.
|
|
30
|
-
*
|
|
31
|
-
* This is a structural newline counter rather than a CSV parser: newlines in
|
|
32
|
-
* quoted fields are counted as row boundaries. The native counter counts each
|
|
33
|
-
* LF byte; a final byte other than LF or CR adds one unterminated row. Thus a
|
|
34
|
-
* CRLF ending counts once through its LF, while a standalone CR is not a row
|
|
35
|
-
* separator. Use it only for trusted newline-delimited data.
|
|
36
|
-
*
|
|
37
|
-
* @param buffer Newline-delimited bytes. Typed-array views are counted from their visible byte range.
|
|
38
|
-
* @returns The number of physical lines, represented as a safe JavaScript number.
|
|
39
|
-
* @throws If the count cannot be represented safely as a JavaScript number.
|
|
40
|
-
*/
|
|
41
|
-
export declare function countTrustedNewlineRows(buffer: NodeJS.TypedArray | DataView): number;
|
|
42
27
|
/**
|
|
43
28
|
* Find byte offsets at which a CSV file can be split without breaking a record.
|
|
44
29
|
*
|
|
45
30
|
* Returned offsets include `0` and the file byte length. Intermediate offsets
|
|
46
31
|
* are chosen at record boundaries, including records containing quoted
|
|
47
|
-
* newlines, and approximate the requested number of shards. The
|
|
48
|
-
*
|
|
49
|
-
* one-character delimiter.
|
|
32
|
+
* newlines, and approximate the requested number of shards. The delimiter
|
|
33
|
+
* is detected from a prefix of the raw file bytes by default.
|
|
50
34
|
*
|
|
51
35
|
* @param path Path to the uncompressed CSV file.
|
|
52
|
-
* @param shardCount Desired number of shards. It must be a positive integer.
|
|
53
|
-
* @param delimiter One-byte CSV delimiter
|
|
36
|
+
* @param shardCount Desired number of shards. It must be a positive safe integer.
|
|
37
|
+
* @param delimiter One-byte CSV delimiter or `'auto'` (the default).
|
|
54
38
|
* @returns Nondecreasing byte offsets suitable as half-open shard starts and ends.
|
|
55
|
-
* @throws {RangeError} If `shardCount` is not a positive integer.
|
|
56
|
-
* @throws If
|
|
39
|
+
* @throws {RangeError} If `shardCount` is not a positive safe integer.
|
|
40
|
+
* @throws If the delimiter cannot be resolved or the native scan fails.
|
|
57
41
|
*/
|
|
58
|
-
export declare function findCsvSafeSplitOffsets(path: string, shardCount: number, delimiter?: string): number[];
|
|
42
|
+
export declare function findCsvSafeSplitOffsets(path: string, shardCount: number, delimiter?: string, encoding?: 'utf8' | 'latin1'): number[];
|
|
59
43
|
/**
|
|
60
44
|
* Return inclusive byte ranges that can each be read as complete CSV records.
|
|
61
45
|
*
|
|
@@ -65,13 +49,13 @@ export declare function findCsvSafeSplitOffsets(path: string, shardCount: number
|
|
|
65
49
|
* are inclusive.
|
|
66
50
|
*
|
|
67
51
|
* @param path Path to the uncompressed CSV file.
|
|
68
|
-
* @param shardCount Desired number of shards. It must be a positive integer.
|
|
69
|
-
* @param delimiter One-byte CSV delimiter
|
|
52
|
+
* @param shardCount Desired number of shards. It must be a positive safe integer.
|
|
53
|
+
* @param delimiter One-byte CSV delimiter or `'auto'` (the default).
|
|
70
54
|
* @returns Non-empty, record-safe ranges in file order.
|
|
71
|
-
* @throws {RangeError} If `shardCount` is not a positive integer.
|
|
72
|
-
* @throws If
|
|
55
|
+
* @throws {RangeError} If `shardCount` is not a positive safe integer.
|
|
56
|
+
* @throws If the delimiter cannot be resolved or the native scan fails.
|
|
73
57
|
*/
|
|
74
|
-
export declare function findCsvSafeShards(path: string, shardCount: number, delimiter?: string): CsvShard[];
|
|
58
|
+
export declare function findCsvSafeShards(path: string, shardCount: number, delimiter?: string, encoding?: 'utf8' | 'latin1'): CsvShard[];
|
|
75
59
|
/**
|
|
76
60
|
* Stream materialized row arrays from a CSV file.
|
|
77
61
|
*
|
|
@@ -108,14 +92,12 @@ export declare function parseCsvFile(path: string, options?: CsvFileOptions): As
|
|
|
108
92
|
* physical columns before materialization. Options are snapshotted at call
|
|
109
93
|
* time, including nested filter values.
|
|
110
94
|
*
|
|
111
|
-
* Strict
|
|
112
|
-
* quote parsing and strict schema metadata. Use `parseCsvFile` when strict
|
|
113
|
-
* validation is required.
|
|
95
|
+
* Strict validation uses the physical fields before projection or filtering.
|
|
114
96
|
*
|
|
115
97
|
* @param path Path to the CSV file (or compressed/ZIP input selected by `options.compression`).
|
|
116
98
|
* @param options Native projection/filter and file parser options.
|
|
117
99
|
* @returns An async generator of non-empty projected row batches.
|
|
118
|
-
* @throws When
|
|
100
|
+
* @throws When I/O, decompression, validation, or parsing fails during iteration.
|
|
119
101
|
*
|
|
120
102
|
* @example
|
|
121
103
|
* ```ts
|
|
@@ -135,14 +117,12 @@ export declare function parseCsvFileProjected(path: string, options?: CsvFileOpt
|
|
|
135
117
|
*
|
|
136
118
|
* The parser honors quoted newlines and supports the same compression and
|
|
137
119
|
* delimiter options as file parsing. With `strict: true`, quote syntax
|
|
138
|
-
*
|
|
139
|
-
* supported by this counting path; use row parsing when headers or minimum
|
|
140
|
-
* data-row constraints must be checked.
|
|
120
|
+
* and physical widths are validated while counting. Schema options apply to the consumed records.
|
|
141
121
|
*
|
|
142
122
|
* @param path Path to the CSV file (or compressed/ZIP input selected by `suppliedOptions.compression`).
|
|
143
123
|
* @param suppliedOptions File and parser options.
|
|
144
124
|
* @returns A promise for the logical CSV record count.
|
|
145
|
-
* @throws When
|
|
125
|
+
* @throws When reading, decompression, parsing, or validation fails, or the count exceeds the safe integer range.
|
|
146
126
|
*
|
|
147
127
|
* @example
|
|
148
128
|
* ```ts
|
package/dist/files.js
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
closeSync,
|
|
3
|
+
constants,
|
|
4
|
+
fstatSync,
|
|
5
|
+
openSync,
|
|
6
|
+
readSync
|
|
7
|
+
} from "node:fs";
|
|
8
|
+
import {
|
|
9
|
+
detectBufferDelimiter,
|
|
10
|
+
FILE_PROBE_SIZE,
|
|
11
|
+
prepareCsvFileInput
|
|
12
|
+
} from "./file-stream.js";
|
|
2
13
|
import {
|
|
3
14
|
native,
|
|
4
15
|
u64ToSafeNumber
|
|
@@ -8,7 +19,7 @@ import {
|
|
|
8
19
|
toArrayBuffer
|
|
9
20
|
} from "./native.js";
|
|
10
21
|
import {
|
|
11
|
-
|
|
22
|
+
delimiterByte,
|
|
12
23
|
prepareCsvBufferInput,
|
|
13
24
|
rejectSelectedColumns
|
|
14
25
|
} from "./normalize.js";
|
|
@@ -19,11 +30,11 @@ import {
|
|
|
19
30
|
NativeCsvParser,
|
|
20
31
|
parseFileChunks
|
|
21
32
|
} from "./parser.js";
|
|
22
|
-
import { rejectStrictSchemaUnsupported } from "./strict-schema.js";
|
|
23
33
|
export function parseCsvBuffer(buffer, suppliedOptions = {}) {
|
|
24
34
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
25
35
|
const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
|
|
26
|
-
|
|
36
|
+
const delimiter = options.delimiter === void 0 || options.delimiter === "auto" ? detectBufferDelimiter(input.bytes, "", !0, options) : options.delimiter;
|
|
37
|
+
using parser = createPreparedParser({ ...options, encoding: input.parserEncoding, delimiter });
|
|
27
38
|
const batch = parser.writeBatch(input.bytes, !0);
|
|
28
39
|
try {
|
|
29
40
|
return batch.rowsInto([], options.columns);
|
|
@@ -31,18 +42,13 @@ export function parseCsvBuffer(buffer, suppliedOptions = {}) {
|
|
|
31
42
|
batch.close();
|
|
32
43
|
}
|
|
33
44
|
}
|
|
34
|
-
export function
|
|
35
|
-
if (
|
|
36
|
-
return 0;
|
|
37
|
-
const input = normalizeChunk(buffer);
|
|
38
|
-
return u64ToSafeNumber(native.symbols.csv_parser_count_trusted_newlines(input, input), "CSV newline row count");
|
|
39
|
-
}
|
|
40
|
-
export function findCsvSafeSplitOffsets(path, shardCount, delimiter = ",") {
|
|
41
|
-
if (!Number.isInteger(shardCount) || shardCount <= 0)
|
|
45
|
+
export function findCsvSafeSplitOffsets(path, shardCount, delimiter = "auto", encoding = "utf8") {
|
|
46
|
+
if (!Number.isSafeInteger(shardCount) || shardCount <= 0)
|
|
42
47
|
throw RangeError(`invalid shard count: ${shardCount}`);
|
|
43
|
-
if (
|
|
44
|
-
throw
|
|
45
|
-
const
|
|
48
|
+
if (path.includes("\x00"))
|
|
49
|
+
throw TypeError("CSV path must not contain a null byte");
|
|
50
|
+
const resolved = delimiter === "auto" ? detectBufferDelimiter(readShardingPrefix(path), path, !0, void 0, encoding === "utf8") : delimiter;
|
|
51
|
+
const batch = native.symbols.csv_parser_find_split_offsets_v2(Buffer.from(`${path}\x00`), BigInt(shardCount), delimiterByte(resolved, encoding), encoding === "utf8");
|
|
46
52
|
if (batch === null)
|
|
47
53
|
throw Error(`native CSV split offset scan failed: ${path}`);
|
|
48
54
|
try {
|
|
@@ -54,8 +60,31 @@ export function findCsvSafeSplitOffsets(path, shardCount, delimiter = ",") {
|
|
|
54
60
|
native.symbols.csv_split_offsets_batch_destroy(batch);
|
|
55
61
|
}
|
|
56
62
|
}
|
|
57
|
-
|
|
58
|
-
|
|
63
|
+
function readShardingPrefix(path) {
|
|
64
|
+
try {
|
|
65
|
+
const file = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
66
|
+
try {
|
|
67
|
+
const stats = fstatSync(file);
|
|
68
|
+
if (!stats.isFile())
|
|
69
|
+
throw Error("CSV shard input must be a regular file");
|
|
70
|
+
const prefix = Buffer.allocUnsafe(FILE_PROBE_SIZE + 1);
|
|
71
|
+
let length = 0;
|
|
72
|
+
while (length < prefix.length) {
|
|
73
|
+
const bytesRead = readSync(file, prefix, length, prefix.length - length, length);
|
|
74
|
+
if (bytesRead === 0)
|
|
75
|
+
break;
|
|
76
|
+
length += bytesRead;
|
|
77
|
+
}
|
|
78
|
+
return prefix.subarray(0, length);
|
|
79
|
+
} finally {
|
|
80
|
+
closeSync(file);
|
|
81
|
+
}
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw Error(`native CSV split offset scan failed: ${path}`, { cause: error });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
export function findCsvSafeShards(path, shardCount, delimiter = "auto", encoding = "utf8") {
|
|
87
|
+
const offsets = findCsvSafeSplitOffsets(path, shardCount, delimiter, encoding);
|
|
59
88
|
const shards = [];
|
|
60
89
|
for (let index = 0;index < offsets.length - 1; ++index) {
|
|
61
90
|
const start = offsets[index] ?? 0;
|
|
@@ -91,7 +120,9 @@ export function parseCsvFileProjected(path, options = {}) {
|
|
|
91
120
|
equalsFilter: options.equalsFilter,
|
|
92
121
|
filters: options.filters,
|
|
93
122
|
fixedColumns: options.fixedColumns,
|
|
123
|
+
maxRecordBytes: options.maxRecordBytes,
|
|
94
124
|
skipRows: options.skipRows,
|
|
125
|
+
skipEmptyLines: options.skipEmptyLines,
|
|
95
126
|
limit: options.limit,
|
|
96
127
|
strict: options.strict,
|
|
97
128
|
expectedHeaders: options.expectedHeaders,
|
|
@@ -100,17 +131,13 @@ export function parseCsvFileProjected(path, options = {}) {
|
|
|
100
131
|
}));
|
|
101
132
|
}
|
|
102
133
|
async function* iterateCsvFileProjected(path, options) {
|
|
103
|
-
rejectStrictSchemaUnsupported(options, "projected file parsing");
|
|
104
134
|
await using input = await prepareCsvFileInput(path, options);
|
|
105
|
-
if (options.strict === !0)
|
|
106
|
-
throw Error("strict CSV validation is not supported for projected batches");
|
|
107
135
|
using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
|
|
108
136
|
for await (using batch of parseFileChunks(input, parser, options.limit))
|
|
109
137
|
yield batch.rows();
|
|
110
138
|
}
|
|
111
139
|
export async function countCsvFile(path, suppliedOptions = {}) {
|
|
112
140
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
113
|
-
rejectStrictSchemaUnsupported(options, "count");
|
|
114
141
|
await using input = await prepareCsvFileInput(path, options, "count");
|
|
115
142
|
return await countFileChunks(input, { ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
|
|
116
143
|
}
|
package/dist/gzip-reader.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
native
|
|
3
3
|
} from "./native.js";
|
|
4
|
+
import { validateChunkSize } from "./normalize.js";
|
|
4
5
|
const gzipReaderFinalizer = new FinalizationRegistry(native.symbols.csv_gzip_reader_destroy);
|
|
5
6
|
export function* readGzipFileChunks(fd, chunkSize, reuseBuffer, readAhead = !0) {
|
|
6
|
-
|
|
7
|
-
throw RangeError("gzip chunkSize must be a positive integer no larger than 4294967295");
|
|
7
|
+
validateChunkSize(chunkSize);
|
|
8
8
|
const handle = native.symbols.csv_gzip_reader_create(fd);
|
|
9
9
|
if (handle === null)
|
|
10
10
|
throw Error("failed to create native gzip reader");
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumn, 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, CsvRawRecordBatchesOptions, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvTransform, CsvTransformChain, CsvTransformMethods, CsvTransformOptions, CsvZipCompression, NativeCsvParserOptions, NativeCsvRowCallback, } from './types.js';
|
|
1
|
+
export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumn, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileEncoding, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvHeaderColumn, CsvHeaderSource, CsvInFilter, CsvInput, CsvMappedRow, CsvNamedCountOptions, CsvNamedRowsOptions, CsvNativeEncoding, CsvNativeFilter, CsvNativeFilterOperator, CsvNativeFilterProgramEntry, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRawRecordBatchesOptions, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvTransform, CsvTransformChain, CsvTransformMethods, CsvTransformOptions, CsvZipCompression, NativeCsvParserOptions, NativeCsvRowCallback, } from './types.js';
|
|
2
2
|
export { csv } from './api.js';
|
|
3
3
|
export { NativeCsvBatch, NativeCsvRawRecordBatch, NativeCsvRowView } from './batches.js';
|
|
4
|
-
export { countCsvFile,
|
|
4
|
+
export { countCsvFile, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from './files.js';
|
|
5
5
|
export { defineCountOptions, defineRowsOptions } from './options.js';
|
|
6
6
|
export { NativeCsvParser } from './parser.js';
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,6 @@ import { requireBunRuntime } from "./runtime.js";
|
|
|
2
2
|
requireBunRuntime();
|
|
3
3
|
export { csv } from "./api.js";
|
|
4
4
|
export { NativeCsvBatch, NativeCsvRawRecordBatch, NativeCsvRowView } from "./batches.js";
|
|
5
|
-
export { countCsvFile,
|
|
5
|
+
export { countCsvFile, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from "./files.js";
|
|
6
6
|
export { defineCountOptions, defineRowsOptions } from "./options.js";
|
|
7
7
|
export { NativeCsvParser } from "./parser.js";
|
package/dist/inspect-file.d.ts
CHANGED
|
@@ -1,21 +1,44 @@
|
|
|
1
|
+
import { type ResolvedCompression } from './file-stream.js';
|
|
2
|
+
import { type NestedZipArchive, type ZipTree } from './inspect-zip.js';
|
|
3
|
+
export declare const MAX_INSPECTION_SAMPLE_SIZE: number;
|
|
4
|
+
type FormatSource = 'explicit' | 'inferred';
|
|
1
5
|
interface InspectionOptions {
|
|
2
6
|
readonly zipEntry?: string;
|
|
3
7
|
readonly delimiter?: string;
|
|
4
8
|
readonly encoding?: string;
|
|
9
|
+
readonly compression?: ResolvedCompression | 'auto';
|
|
10
|
+
readonly sampleSize?: number;
|
|
11
|
+
readonly explain?: boolean;
|
|
12
|
+
}
|
|
13
|
+
interface InspectionExplanation {
|
|
14
|
+
encoding: string;
|
|
15
|
+
delimiter: string;
|
|
5
16
|
}
|
|
6
17
|
interface FileInspection {
|
|
7
18
|
fileSizeBytes: number;
|
|
8
19
|
sampleBytes: number;
|
|
9
20
|
sampleReachedEof: boolean;
|
|
10
|
-
compression:
|
|
21
|
+
compression: ResolvedCompression;
|
|
22
|
+
compressionSource: FormatSource;
|
|
11
23
|
zipEntry: string | null;
|
|
24
|
+
zipEntries?: readonly string[];
|
|
25
|
+
zipArchives?: readonly NestedZipArchive[];
|
|
12
26
|
encoding: string;
|
|
13
|
-
encodingSource:
|
|
27
|
+
encodingSource: FormatSource;
|
|
14
28
|
delimiter: string | null;
|
|
15
|
-
delimiterSource:
|
|
29
|
+
delimiterSource: FormatSource | null;
|
|
16
30
|
delimiterReason: string | null;
|
|
17
31
|
lineEnding: string;
|
|
18
32
|
firstRecordColumns: number | null;
|
|
33
|
+
sampledRecords: number | null;
|
|
34
|
+
minRecordColumns: number | null;
|
|
35
|
+
maxRecordColumns: number | null;
|
|
36
|
+
explanation?: InspectionExplanation;
|
|
37
|
+
}
|
|
38
|
+
export declare class ZipProbeError extends Error {
|
|
39
|
+
readonly fileSizeBytes: number;
|
|
40
|
+
readonly archive: ZipTree;
|
|
41
|
+
constructor(cause: Error, fileSizeBytes: number, archive: ZipTree);
|
|
19
42
|
}
|
|
20
43
|
/** Inspect a bounded sample of the CSV payload; size always refers to the file on disk. */
|
|
21
44
|
export declare function inspectCsvFile(path: string, options?: InspectionOptions): Promise<FileInspection>;
|
package/dist/inspect-file.js
CHANGED
|
@@ -1,54 +1,89 @@
|
|
|
1
1
|
import { stat } from "node:fs/promises";
|
|
2
2
|
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
DELIMITER_CANDIDATES,
|
|
3
|
+
COMPRESSION_PROBE_SIZE,
|
|
4
|
+
delimiterAmbiguityError,
|
|
6
5
|
FILE_PROBE_SIZE,
|
|
7
|
-
|
|
6
|
+
isDelimiterCandidate,
|
|
7
|
+
probeCompression,
|
|
8
8
|
readCsvFileChunks,
|
|
9
9
|
scanCsvFileFormat,
|
|
10
|
-
|
|
10
|
+
scanDelimiterScores,
|
|
11
11
|
selectDelimiter
|
|
12
12
|
} from "./file-stream.js";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
13
|
+
import { formatBytes } from "./format-bytes.js";
|
|
14
|
+
import {
|
|
15
|
+
inspectZipArchive
|
|
16
|
+
} from "./inspect-zip.js";
|
|
17
|
+
import {
|
|
18
|
+
delimiterByte,
|
|
19
|
+
hasUtf8Bom,
|
|
20
|
+
resolveInputEncoding,
|
|
21
|
+
UTF8_BOM
|
|
22
|
+
} from "./normalize.js";
|
|
23
|
+
export const MAX_INSPECTION_SAMPLE_SIZE = 1048576;
|
|
24
|
+
|
|
25
|
+
export class ZipProbeError extends Error {
|
|
26
|
+
fileSizeBytes;
|
|
27
|
+
archive;
|
|
28
|
+
constructor(cause, fileSizeBytes, archive) {
|
|
29
|
+
super(cause.message, { cause });
|
|
30
|
+
this.fileSizeBytes = fileSizeBytes;
|
|
31
|
+
this.archive = archive;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
15
34
|
export async function inspectCsvFile(path, options = {}) {
|
|
35
|
+
const sampleSize = options.sampleSize ?? FILE_PROBE_SIZE;
|
|
36
|
+
if (!Number.isSafeInteger(sampleSize) || sampleSize < 1 || sampleSize > MAX_INSPECTION_SAMPLE_SIZE)
|
|
37
|
+
throw RangeError("sample size must be between 1 byte and 1 MiB");
|
|
16
38
|
const info = await stat(path);
|
|
17
39
|
if (!info.isFile())
|
|
18
40
|
throw Error("probe requires a regular file");
|
|
19
|
-
const
|
|
20
|
-
const
|
|
21
|
-
|
|
41
|
+
const configuredCompression = options.compression ?? "auto";
|
|
42
|
+
const compressionSource = configuredCompression === "auto" ? "inferred" : "explicit";
|
|
43
|
+
const readSize = sampleSize + 1;
|
|
44
|
+
const chunkSize = Math.max(COMPRESSION_PROBE_SIZE, Math.min(readSize, FILE_PROBE_SIZE + 1));
|
|
45
|
+
const raw = configuredCompression === "auto" || configuredCompression === "none" ? await Bun.file(path).slice(0, configuredCompression === "auto" ? Math.max(COMPRESSION_PROBE_SIZE, readSize) : readSize).bytes() : new Uint8Array(0);
|
|
46
|
+
const compression = configuredCompression === "auto" ? probeCompression(raw, !0, { kind: "inspection", path }) : configuredCompression;
|
|
47
|
+
if (options.zipEntry !== void 0 && compression !== "zip")
|
|
22
48
|
throw Error("--zip-entry requires a ZIP archive");
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
if (
|
|
35
|
-
throw error;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
+
const zipInspection = compression === "zip" ? await inspectZipArchive(path, {
|
|
50
|
+
entry: options.zipEntry,
|
|
51
|
+
chunkSize,
|
|
52
|
+
readSample: (chunks) => readCompressedSample(chunks, readSize)
|
|
53
|
+
}) : void 0;
|
|
54
|
+
const archive = zipInspection?.archive;
|
|
55
|
+
try {
|
|
56
|
+
let zipEntry = null;
|
|
57
|
+
let sample = raw.subarray(0, readSize);
|
|
58
|
+
if (zipInspection !== void 0) {
|
|
59
|
+
const selection = zipInspection.selection;
|
|
60
|
+
if ("error" in selection)
|
|
61
|
+
throw selection.error;
|
|
62
|
+
zipEntry = selection.zipEntry;
|
|
63
|
+
sample = selection.sample;
|
|
64
|
+
} else if (compression !== "none" && compression !== "zip")
|
|
65
|
+
sample = await readCompressedSample(readCsvFileChunks(path, { compression, chunkSize }), readSize);
|
|
66
|
+
const eof = sample.length <= sampleSize;
|
|
67
|
+
const prefix = sample.subarray(0, sampleSize);
|
|
68
|
+
const format = inspectFormat(zipEntry ?? path, prefix, eof, options);
|
|
69
|
+
return {
|
|
70
|
+
fileSizeBytes: info.size,
|
|
71
|
+
sampleBytes: prefix.byteLength,
|
|
72
|
+
sampleReachedEof: eof,
|
|
73
|
+
compression,
|
|
74
|
+
compressionSource,
|
|
75
|
+
zipEntry,
|
|
76
|
+
...archive !== void 0 && (archive.zipArchives !== void 0 || archive.zipEntries.length > 1 || archive.zipEntries.some((entry) => entry.includes("/"))) ? archive : {},
|
|
77
|
+
...format
|
|
78
|
+
};
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (archive !== void 0 && archive.zipEntries.length > 0 && error instanceof Error)
|
|
81
|
+
throw new ZipProbeError(error, info.size, archive);
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
49
84
|
}
|
|
50
|
-
async function readCompressedSample(chunks) {
|
|
51
|
-
const sample = new Uint8Array(
|
|
85
|
+
async function readCompressedSample(chunks, readSize) {
|
|
86
|
+
const sample = new Uint8Array(readSize);
|
|
52
87
|
let length = 0;
|
|
53
88
|
for await (const chunk of chunks) {
|
|
54
89
|
const take = Math.min(chunk.length, sample.length - length);
|
|
@@ -59,80 +94,140 @@ async function readCompressedSample(chunks) {
|
|
|
59
94
|
}
|
|
60
95
|
return sample.subarray(0, length);
|
|
61
96
|
}
|
|
62
|
-
function inspectFormat(path, prefix, eof,
|
|
97
|
+
function inspectFormat(path, prefix, eof, options) {
|
|
63
98
|
let bytes = prefix;
|
|
64
|
-
let
|
|
99
|
+
let scores;
|
|
100
|
+
let hasBom = !1;
|
|
101
|
+
let encoding = options.encoding ?? "auto";
|
|
102
|
+
const delimiter = options.delimiter ?? "auto";
|
|
65
103
|
const encodingSource = encoding === "auto" ? "inferred" : "explicit";
|
|
66
104
|
if (encoding === "auto") {
|
|
67
105
|
const sample = scanCsvFileFormat(prefix, eof, !0);
|
|
68
106
|
bytes = sample.bytes;
|
|
69
|
-
|
|
107
|
+
scores = sample.scores;
|
|
70
108
|
encoding = sample.encoding;
|
|
109
|
+
hasBom = sample.hasBom;
|
|
71
110
|
} else {
|
|
72
111
|
const decoder = resolveInputEncoding(encoding, delimiter);
|
|
73
|
-
if (typeof decoder === "string")
|
|
112
|
+
if (typeof decoder === "string") {
|
|
74
113
|
encoding = decoder;
|
|
75
|
-
|
|
114
|
+
if (encoding === "utf8" && hasUtf8Bom(bytes))
|
|
115
|
+
bytes = bytes.subarray(UTF8_BOM.length);
|
|
116
|
+
} else {
|
|
76
117
|
bytes = new TextEncoder().encode(decoder.decode(prefix, { stream: !eof }));
|
|
77
118
|
encoding = decoder.encoding;
|
|
78
119
|
}
|
|
79
120
|
}
|
|
80
|
-
|
|
81
|
-
|
|
121
|
+
if (delimiter !== "auto")
|
|
122
|
+
delimiterByte(delimiter, encoding === "latin1" ? "latin1" : "utf8");
|
|
123
|
+
const choice = delimiter === "auto" ? inspectDelimiter(path, scores ?? scanDelimiterScores(bytes, eof), eof, prefix.length, options.explain) : { delimiter, delimiterSource: "explicit", delimiterReason: null, detail: "Set by --delimiter" };
|
|
124
|
+
const { detail, ...delimiterReport } = choice;
|
|
125
|
+
const explanation = options.explain ? { encoding: explainEncoding(prefix, encoding, encodingSource, hasBom), delimiter: detail } : void 0;
|
|
126
|
+
return {
|
|
127
|
+
encoding,
|
|
128
|
+
encodingSource,
|
|
129
|
+
...delimiterReport,
|
|
130
|
+
...inspectRecords(bytes, eof, choice.delimiter),
|
|
131
|
+
...explanation === void 0 ? {} : { explanation }
|
|
132
|
+
};
|
|
82
133
|
}
|
|
83
|
-
function
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (
|
|
87
|
-
return
|
|
134
|
+
function explainEncoding(prefix, encoding, source, hasBom) {
|
|
135
|
+
if (source === "explicit")
|
|
136
|
+
return "Set by --encoding";
|
|
137
|
+
if (hasBom)
|
|
138
|
+
return "Identified by a byte-order mark (BOM)";
|
|
139
|
+
if (prefix.length === 0)
|
|
140
|
+
return "Using UTF-8 for an empty sample";
|
|
141
|
+
if (encoding === "utf8")
|
|
142
|
+
return prefix.every((byte) => byte < 128) ? "ASCII-only sample fits UTF-8, Latin-1, and Windows-1252. Using UTF-8." : "Sample bytes are consistent with UTF-8";
|
|
143
|
+
return encoding === "windows-1252" ? "Sample is invalid UTF-8 and contains bytes in the range 0x80\u20130x9F" : "Sample is invalid UTF-8 and contains no bytes in the range 0x80\u20130x9F";
|
|
144
|
+
}
|
|
145
|
+
function inspectDelimiter(path, scores, eof, sampleBytes, explain) {
|
|
146
|
+
const choice = selectDelimiter(path, scores);
|
|
147
|
+
if ("delimiter" in choice) {
|
|
148
|
+
let detail = "Separator count is consistent across the records used for detection";
|
|
149
|
+
if (explain && choice.extensionHint !== void 0)
|
|
150
|
+
detail = choice.extensionBrokeTie ? `The ${choice.extensionHint} filename hint resolved a tie in quoting evidence` : `Stable separator counts and quoting evidence support the ${choice.extensionHint} filename hint`;
|
|
151
|
+
return { delimiter: choice.delimiter, delimiterSource: "inferred", delimiterReason: null, detail };
|
|
152
|
+
}
|
|
88
153
|
let reason;
|
|
89
154
|
switch (choice.reason) {
|
|
90
155
|
case "no-records":
|
|
91
|
-
reason = sampleBytes === 0 ? "Empty payload" : eof ? "No complete non-empty record in the payload" :
|
|
156
|
+
reason = sampleBytes === 0 ? "Empty payload" : eof ? "No complete non-empty record in the payload" : `No complete non-empty record in the ${formatBytes(sampleBytes)} sample`;
|
|
92
157
|
break;
|
|
93
158
|
case "no-stable-separator": {
|
|
94
|
-
|
|
95
|
-
reason = perRecord.some((row) => row.some((count) => count > 0)) ? "Separator counts vary across sampled records" : "No supported separator found in sampled records";
|
|
159
|
+
reason = scores.hasSeparator ? "Separator counts vary across sampled records" : "No supported separator found in sampled records";
|
|
96
160
|
break;
|
|
97
161
|
}
|
|
98
162
|
case "ambiguous":
|
|
163
|
+
if (choice.conflictingHint)
|
|
164
|
+
throw delimiterAmbiguityError(choice.candidates);
|
|
99
165
|
reason = `Ambiguous between ${choice.candidates.map((c) => JSON.stringify(c)).join(" and ")}`;
|
|
100
166
|
break;
|
|
167
|
+
case "weak-separator":
|
|
168
|
+
reason = `Could not confirm ${JSON.stringify(choice.candidate)} from one separator per record without stronger quoting evidence`;
|
|
169
|
+
break;
|
|
101
170
|
}
|
|
102
|
-
return { delimiter: null, delimiterSource: null, delimiterReason: reason };
|
|
171
|
+
return { delimiter: null, delimiterSource: null, delimiterReason: reason, detail: reason };
|
|
103
172
|
}
|
|
104
173
|
function inspectRecords(bytes, eof, delimiter) {
|
|
105
174
|
const separator = delimiter?.charCodeAt(0);
|
|
106
175
|
const endings = new Set;
|
|
107
176
|
let quoted = !1;
|
|
108
|
-
let
|
|
177
|
+
let atFieldStart = !0;
|
|
178
|
+
let recordStart = 0;
|
|
109
179
|
let columns = 1;
|
|
180
|
+
let count = 0;
|
|
181
|
+
let firstRecordColumns = bytes.length === 0 ? 0 : null;
|
|
182
|
+
let minColumns = 1 / 0;
|
|
183
|
+
let maxColumns = 0;
|
|
110
184
|
let unknownWidth = !1;
|
|
185
|
+
function finishRecord() {
|
|
186
|
+
if (count === 0 && !unknownWidth)
|
|
187
|
+
firstRecordColumns = columns;
|
|
188
|
+
++count;
|
|
189
|
+
minColumns = Math.min(minColumns, columns);
|
|
190
|
+
maxColumns = Math.max(maxColumns, columns);
|
|
191
|
+
columns = 1;
|
|
192
|
+
}
|
|
111
193
|
for (let i = 0;i < bytes.length; ++i) {
|
|
112
194
|
const byte = bytes[i];
|
|
113
|
-
if (
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
if (byte === 13 || byte === 10) {
|
|
117
|
-
firstRecord = !1;
|
|
118
|
-
if (byte === 13 && bytes[i + 1] === 10) {
|
|
119
|
-
endings.add("CRLF");
|
|
195
|
+
if (quoted) {
|
|
196
|
+
if (byte === 34)
|
|
197
|
+
if (bytes[i + 1] === 34)
|
|
120
198
|
++i;
|
|
121
|
-
} else if (byte === 13 && i + 1 === bytes.length && !eof)
|
|
122
|
-
break;
|
|
123
199
|
else
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
200
|
+
quoted = !1;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (byte === 13 || byte === 10) {
|
|
204
|
+
finishRecord();
|
|
205
|
+
atFieldStart = !0;
|
|
206
|
+
if (byte === 13 && bytes[i + 1] === 10) {
|
|
207
|
+
endings.add("CRLF");
|
|
208
|
+
++i;
|
|
209
|
+
} else if (byte === 13 && i + 1 === bytes.length && !eof)
|
|
210
|
+
break;
|
|
211
|
+
else
|
|
212
|
+
endings.add(byte === 10 ? "LF" : "CR");
|
|
213
|
+
recordStart = i + 1;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (byte === 34 && atFieldStart)
|
|
217
|
+
quoted = !0;
|
|
218
|
+
atFieldStart = separator === void 0 ? isDelimiterCandidate(byte) : byte === separator;
|
|
219
|
+
if (atFieldStart) {
|
|
220
|
+
++columns;
|
|
221
|
+
unknownWidth ||= separator === void 0;
|
|
131
222
|
}
|
|
132
223
|
}
|
|
133
|
-
|
|
224
|
+
if (eof && !quoted && recordStart < bytes.length)
|
|
225
|
+
finishRecord();
|
|
134
226
|
return {
|
|
135
|
-
firstRecordColumns
|
|
136
|
-
lineEnding: endings.size > 1 ? "mixed" : endings.values().next().value ?? (eof ? "none" : "unknown")
|
|
227
|
+
firstRecordColumns,
|
|
228
|
+
lineEnding: endings.size > 1 ? "mixed" : endings.values().next().value ?? (eof ? "none" : "unknown"),
|
|
229
|
+
sampledRecords: unknownWidth ? null : count,
|
|
230
|
+
minRecordColumns: unknownWidth || count === 0 ? null : minColumns,
|
|
231
|
+
maxRecordColumns: unknownWidth || count === 0 ? null : maxColumns
|
|
137
232
|
};
|
|
138
233
|
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export interface ZipTree {
|
|
2
|
+
readonly zipEntries: readonly string[];
|
|
3
|
+
readonly zipArchives?: readonly NestedZipArchive[];
|
|
4
|
+
}
|
|
5
|
+
export type NestedZipArchive = {
|
|
6
|
+
readonly path: string;
|
|
7
|
+
} & (ZipTree | {
|
|
8
|
+
readonly error: string;
|
|
9
|
+
});
|
|
10
|
+
interface ZipEntrySample {
|
|
11
|
+
readonly zipEntry: string;
|
|
12
|
+
readonly sample: Uint8Array<ArrayBuffer>;
|
|
13
|
+
}
|
|
14
|
+
interface ZipEntryRequest {
|
|
15
|
+
readonly entry?: string;
|
|
16
|
+
readonly chunkSize: number;
|
|
17
|
+
readonly readSample: (chunks: Iterable<Uint8Array>) => Promise<Uint8Array<ArrayBuffer>>;
|
|
18
|
+
}
|
|
19
|
+
interface ZipInspection {
|
|
20
|
+
readonly archive?: ZipTree;
|
|
21
|
+
readonly selection: ZipEntrySample | {
|
|
22
|
+
readonly error: unknown;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export declare function inspectZipArchive(path: string, request: ZipEntryRequest): Promise<ZipInspection>;
|
|
26
|
+
export {};
|