@konstit/csv 0.5.0 → 0.6.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 +36 -3
- package/THIRD_PARTY_NOTICES.md +99 -0
- package/dist/api.d.ts +3 -0
- package/dist/api.js +34 -108
- package/dist/batches.d.ts +3 -4
- package/dist/batches.js +103 -29
- package/dist/cli-command.js +145 -75
- package/dist/cli-schema.d.ts +25 -5
- package/dist/cli-schema.js +48 -23
- package/dist/file-stream.d.ts +10 -3
- package/dist/file-stream.js +22 -17
- package/dist/files.js +32 -76
- package/dist/filter.d.ts +2 -3
- package/dist/filter.js +2 -0
- package/dist/index.d.ts +1 -1
- package/dist/inspect-file.d.ts +16 -6
- package/dist/inspect-file.js +67 -17
- package/dist/latin1-rows.d.ts +3 -3
- package/dist/latin1-rows.js +65 -15
- package/dist/materialize-field.d.ts +1 -0
- package/dist/materialize-field.js +10 -1
- package/dist/native.d.ts +47 -71
- package/dist/native.js +28 -86
- package/dist/normalize.d.ts +1 -40
- package/dist/normalize.js +25 -62
- package/dist/options-snapshot.d.ts +2 -2
- package/dist/options-snapshot.js +2 -0
- package/dist/parser.d.ts +17 -202
- package/dist/parser.js +152 -230
- package/dist/strict-schema.d.ts +1 -1
- package/dist/strict-schema.js +4 -3
- package/dist/transforms.d.ts +11 -0
- package/dist/transforms.js +192 -0
- package/dist/types.d.ts +77 -9
- package/dist/zip-reader.d.ts +2 -0
- package/dist/zip-reader.js +31 -21
- package/package.json +3 -2
- 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 +14 -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/file-stream.js
CHANGED
|
@@ -28,7 +28,8 @@ export const DELIMITER_CANDIDATES = [
|
|
|
28
28
|
{ byte: 124, delimiter: "|" },
|
|
29
29
|
{ byte: 58, delimiter: ":" },
|
|
30
30
|
{ byte: 94, delimiter: "^" },
|
|
31
|
-
{ byte: 126, delimiter: "~" }
|
|
31
|
+
{ byte: 126, delimiter: "~" },
|
|
32
|
+
{ byte: 64, delimiter: "@" }
|
|
32
33
|
];
|
|
33
34
|
const COMPRESSION_EXTENSIONS = [
|
|
34
35
|
".deflate-raw",
|
|
@@ -262,39 +263,45 @@ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
|
|
|
262
263
|
bytes = new TextEncoder().encode(text);
|
|
263
264
|
}
|
|
264
265
|
}
|
|
265
|
-
const counts = scoreDelimiters ? new Uint32Array(
|
|
266
|
-
const encodingCode = native.symbols.
|
|
266
|
+
const counts = scoreDelimiters ? new Uint32Array(DELIMITER_CANDIDATES.length + 1) : void 0;
|
|
267
|
+
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));
|
|
267
268
|
const encoding = bomEncoding ?? PROBED_BYTE_ENCODINGS[encodingCode];
|
|
268
269
|
if (encoding === void 0)
|
|
269
270
|
throw Error("NUL in encoding probe: specify the encoding explicitly");
|
|
270
|
-
return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[
|
|
271
|
+
return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[DELIMITER_CANDIDATES.length] === 0 ? [] : [counts] };
|
|
271
272
|
}
|
|
272
273
|
function requireDelimiter(path, rows) {
|
|
273
274
|
const result = selectDelimiter(path, rows);
|
|
274
|
-
if ("
|
|
275
|
-
|
|
276
|
-
|
|
275
|
+
if ("delimiter" in result)
|
|
276
|
+
return result.delimiter;
|
|
277
|
+
switch (result.reason) {
|
|
278
|
+
case "no-records":
|
|
279
|
+
throw Error(`delimiter auto-detection failed: the ${String(FILE_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`);
|
|
280
|
+
case "no-stable-separator":
|
|
281
|
+
throw Error("delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly");
|
|
282
|
+
case "ambiguous":
|
|
283
|
+
throw Error(`delimiter auto-detection is ambiguous between ${result.candidates.map((c) => JSON.stringify(c)).join(", ")}; specify delimiter explicitly`);
|
|
284
|
+
}
|
|
277
285
|
}
|
|
278
286
|
export function selectDelimiter(path, rows) {
|
|
279
287
|
if (rows.length === 0)
|
|
280
|
-
return {
|
|
281
|
-
error: `delimiter auto-detection failed: the ${String(FILE_PROBE_SIZE)}-byte probe contains no complete non-empty row; specify delimiter explicitly`
|
|
282
|
-
};
|
|
288
|
+
return { reason: "no-records" };
|
|
283
289
|
const stableCandidates = [];
|
|
290
|
+
let hasStableAtSign = !1;
|
|
284
291
|
for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
|
|
285
292
|
const separatorCount = rows[0]?.[candidateIndex] ?? 0;
|
|
286
293
|
if (separatorCount === 0)
|
|
287
294
|
continue;
|
|
288
295
|
if (rows.every((row) => row[candidateIndex] === separatorCount)) {
|
|
289
296
|
const candidate = DELIMITER_CANDIDATES[candidateIndex];
|
|
290
|
-
if (candidate
|
|
297
|
+
if (candidate?.delimiter === "@")
|
|
298
|
+
hasStableAtSign = !0;
|
|
299
|
+
else if (candidate !== void 0)
|
|
291
300
|
stableCandidates.push({ delimiter: candidate.delimiter, separatorCount });
|
|
292
301
|
}
|
|
293
302
|
}
|
|
294
303
|
if (stableCandidates.length === 0)
|
|
295
|
-
return {
|
|
296
|
-
error: "delimiter auto-detection failed: no supported delimiter has a stable positive count across the probe rows; specify delimiter explicitly"
|
|
297
|
-
};
|
|
304
|
+
return hasStableAtSign ? { delimiter: "@" } : { reason: "no-stable-separator" };
|
|
298
305
|
const extensionHint = delimiterFromExtension(path);
|
|
299
306
|
const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
|
|
300
307
|
if (confirmedHint !== void 0)
|
|
@@ -303,9 +310,7 @@ export function selectDelimiter(path, rows) {
|
|
|
303
310
|
const strongestCandidates = stableCandidates.filter((candidate) => candidate.separatorCount === maximumSeparatorCount);
|
|
304
311
|
if (strongestCandidates.length === 1)
|
|
305
312
|
return { delimiter: strongestCandidates[0]?.delimiter ?? "," };
|
|
306
|
-
return {
|
|
307
|
-
error: `delimiter auto-detection is ambiguous between ${strongestCandidates.map((candidate) => JSON.stringify(candidate.delimiter)).join(", ")}; specify delimiter explicitly`
|
|
308
|
-
};
|
|
313
|
+
return { reason: "ambiguous", candidates: strongestCandidates.map((candidate) => candidate.delimiter) };
|
|
309
314
|
}
|
|
310
315
|
export function scanDelimiterCounts(probe, sourceEnded) {
|
|
311
316
|
const rows = [];
|
package/dist/files.js
CHANGED
|
@@ -10,26 +10,22 @@ import {
|
|
|
10
10
|
import {
|
|
11
11
|
normalizeChunk,
|
|
12
12
|
prepareCsvBufferInput,
|
|
13
|
-
|
|
13
|
+
rejectSelectedColumns
|
|
14
14
|
} from "./normalize.js";
|
|
15
15
|
import { snapshotCsvOptions } from "./options-snapshot.js";
|
|
16
16
|
import {
|
|
17
|
+
countFileChunks,
|
|
17
18
|
createPreparedParser,
|
|
18
|
-
NativeCsvParser
|
|
19
|
+
NativeCsvParser,
|
|
20
|
+
parseFileChunks
|
|
19
21
|
} from "./parser.js";
|
|
20
|
-
import {
|
|
21
|
-
rejectStrictSchemaUnsupported,
|
|
22
|
-
strictSchemaValidator
|
|
23
|
-
} from "./strict-schema.js";
|
|
22
|
+
import { rejectStrictSchemaUnsupported } from "./strict-schema.js";
|
|
24
23
|
export function parseCsvBuffer(buffer, suppliedOptions = {}) {
|
|
25
24
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
26
25
|
const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
|
|
27
|
-
using parser =
|
|
28
|
-
const validator = strictSchemaValidator(options);
|
|
26
|
+
using parser = createPreparedParser({ ...options, encoding: input.parserEncoding });
|
|
29
27
|
const batch = parser.writeBatch(input.bytes, !0);
|
|
30
28
|
try {
|
|
31
|
-
validator?.validateBatch(batch);
|
|
32
|
-
validator?.finish();
|
|
33
29
|
return batch.rowsInto([], options.columns);
|
|
34
30
|
} finally {
|
|
35
31
|
batch.close();
|
|
@@ -78,81 +74,41 @@ export function parseCsvFile(path, options = {}) {
|
|
|
78
74
|
}
|
|
79
75
|
async function* iterateCsvFile(path, options) {
|
|
80
76
|
await using input = await prepareCsvFileInput(path, options);
|
|
81
|
-
using parser =
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const batch = parser.writeBatch(chunk);
|
|
85
|
-
try {
|
|
86
|
-
validator?.validateBatch(batch);
|
|
87
|
-
const rows = batch.rowsInto([], options.columns);
|
|
88
|
-
if (rows.length > 0)
|
|
89
|
-
yield rows;
|
|
90
|
-
} finally {
|
|
91
|
-
batch.close();
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
const batch = parser.endBatch();
|
|
95
|
-
try {
|
|
96
|
-
validator?.validateBatch(batch);
|
|
97
|
-
validator?.finish();
|
|
98
|
-
const rows = batch.rowsInto([], options.columns);
|
|
99
|
-
if (rows.length > 0)
|
|
100
|
-
yield rows;
|
|
101
|
-
} finally {
|
|
102
|
-
batch.close();
|
|
103
|
-
}
|
|
77
|
+
using parser = createPreparedParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
|
|
78
|
+
for await (using batch of parseFileChunks(input, parser, options.limit))
|
|
79
|
+
yield batch.rowsInto([], options.columns);
|
|
104
80
|
}
|
|
105
81
|
export function parseCsvFileProjected(path, options = {}) {
|
|
106
|
-
|
|
82
|
+
rejectSelectedColumns(options);
|
|
83
|
+
return iterateCsvFileProjected(path, snapshotCsvOptions({
|
|
84
|
+
encoding: options.encoding,
|
|
85
|
+
delimiter: options.delimiter,
|
|
86
|
+
compression: options.compression,
|
|
87
|
+
chunkSize: options.chunkSize,
|
|
88
|
+
columns: options.columns,
|
|
89
|
+
equalsFilter: options.equalsFilter,
|
|
90
|
+
filters: options.filters,
|
|
91
|
+
fixedColumns: options.fixedColumns,
|
|
92
|
+
skipRows: options.skipRows,
|
|
93
|
+
limit: options.limit,
|
|
94
|
+
strict: options.strict,
|
|
95
|
+
expectedHeaders: options.expectedHeaders,
|
|
96
|
+
requireHeader: options.requireHeader,
|
|
97
|
+
minDataRows: options.minDataRows
|
|
98
|
+
}));
|
|
107
99
|
}
|
|
108
100
|
async function* iterateCsvFileProjected(path, options) {
|
|
109
101
|
rejectStrictSchemaUnsupported(options, "projected file parsing");
|
|
110
102
|
await using input = await prepareCsvFileInput(path, options);
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
if (rows.length > 0)
|
|
117
|
-
yield rows;
|
|
118
|
-
} finally {
|
|
119
|
-
batch.close();
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
const batch = parser.endBatch();
|
|
123
|
-
try {
|
|
124
|
-
const rows = batch.rows();
|
|
125
|
-
if (rows.length > 0)
|
|
126
|
-
yield rows;
|
|
127
|
-
} finally {
|
|
128
|
-
batch.close();
|
|
129
|
-
}
|
|
103
|
+
if (options.strict === !0)
|
|
104
|
+
throw Error("strict CSV validation is not supported for projected batches");
|
|
105
|
+
using parser = new NativeCsvParser({ ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
|
|
106
|
+
for await (using batch of parseFileChunks(input, parser, options.limit))
|
|
107
|
+
yield batch.rows();
|
|
130
108
|
}
|
|
131
109
|
export async function countCsvFile(path, suppliedOptions = {}) {
|
|
132
110
|
const options = snapshotCsvOptions(suppliedOptions);
|
|
133
111
|
rejectStrictSchemaUnsupported(options, "count");
|
|
134
112
|
await using input = await prepareCsvFileInput(path, options, "count");
|
|
135
|
-
|
|
136
|
-
let rows = 0;
|
|
137
|
-
if (options.strict === !0) {
|
|
138
|
-
for await (const chunk of input.chunks()) {
|
|
139
|
-
const batch = parser.writeBatch(chunk);
|
|
140
|
-
try {
|
|
141
|
-
rows += batch.rowCount;
|
|
142
|
-
} finally {
|
|
143
|
-
batch.close();
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
const batch = parser.endBatch();
|
|
147
|
-
try {
|
|
148
|
-
rows += batch.rowCount;
|
|
149
|
-
} finally {
|
|
150
|
-
batch.close();
|
|
151
|
-
}
|
|
152
|
-
return rows;
|
|
153
|
-
}
|
|
154
|
-
for await (const chunk of input.chunks())
|
|
155
|
-
rows += parser.writeCount(chunk);
|
|
156
|
-
rows += parser.endCount();
|
|
157
|
-
return rows;
|
|
113
|
+
return await countFileChunks(input, { ...options, encoding: input.parserEncoding, delimiter: input.delimiter });
|
|
158
114
|
}
|
package/dist/filter.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type { CsvNativeFilterProgramEntry } from './
|
|
2
|
-
import type { CsvFilter, CsvFilterColumn, CsvRegex } from './types.js';
|
|
1
|
+
import type { CsvColumn, CsvFilter, CsvNativeFilterProgramEntry, CsvRegex } from './types.js';
|
|
3
2
|
/**
|
|
4
3
|
* Select a reusable zero-based physical CSV column for building native filters.
|
|
5
4
|
*
|
|
@@ -18,7 +17,7 @@ import type { CsvFilter, CsvFilterColumn, CsvRegex } from './types.js';
|
|
|
18
17
|
* const filter = state.isOneOf(['SP', 'RJ']);
|
|
19
18
|
* ```
|
|
20
19
|
*/
|
|
21
|
-
export declare function column(columnIndex: number):
|
|
20
|
+
export declare function column(columnIndex: number): CsvColumn;
|
|
22
21
|
/**
|
|
23
22
|
* Match rows for which every supplied filter matches.
|
|
24
23
|
*
|
package/dist/filter.js
CHANGED
|
@@ -3,10 +3,12 @@ import {
|
|
|
3
3
|
normalizeNativeFilterProgram,
|
|
4
4
|
validateRegex
|
|
5
5
|
} from "./normalize.js";
|
|
6
|
+
import { transformMethods } from "./transforms.js";
|
|
6
7
|
const nativeProgramByFilter = new WeakMap;
|
|
7
8
|
export function column(columnIndex) {
|
|
8
9
|
const selectedColumn = normalizeFilterColumn(columnIndex);
|
|
9
10
|
return Object.freeze({
|
|
11
|
+
...transformMethods(selectedColumn),
|
|
10
12
|
equals: (value) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, value: copyFieldValue(value, "equals value") })),
|
|
11
13
|
doesNotEqual: (value) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, notEquals: copyFieldValue(value, "doesNotEqual value") })),
|
|
12
14
|
isOneOf: (values) => createFilterFromPredicate(Object.freeze({ column: selectedColumn, values: copyFieldValues(values, "isOneOf values") })),
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { CsvApiFileOptions, CsvBatchesOptions, CsvColumnBytesCallback, CsvColumnRangeCallback, CsvColumns, CsvColumnSelection, CsvCompression, CsvCountOptions, CsvDelimiter, CsvEncoding, CsvEqualsFilter, CsvFieldRange, CsvFieldValue, CsvFileEncoding, CsvFileOptions, CsvFilter, CsvFilterColumn, CsvInFilter, CsvNativeEncoding, CsvNativeFilter, CsvNativeProjectionOptions, CsvNotEqualsFilter, CsvNotInFilter, CsvParseOptions, CsvParserOptions, CsvProjectedRow, CsvRegex, CsvRegexFilter, CsvRow, CsvRowsOptions, CsvScanColumnsCallback, CsvShard, CsvShardingOptions, CsvStartsWithFilter, CsvZipCompression, NativeCsvRowCallback, } from './types.js';
|
|
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, 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, NativeCsvRowView } from './batches.js';
|
|
4
4
|
export { countCsvFile, countTrustedNewlineRows, parseCsvBuffer, parseCsvFile, parseCsvFileProjected } from './files.js';
|
package/dist/inspect-file.d.ts
CHANGED
|
@@ -1,12 +1,22 @@
|
|
|
1
|
-
|
|
1
|
+
interface InspectionOptions {
|
|
2
|
+
readonly zipEntry?: string;
|
|
3
|
+
readonly delimiter?: string;
|
|
4
|
+
readonly encoding?: string;
|
|
5
|
+
}
|
|
2
6
|
interface FileInspection {
|
|
3
|
-
|
|
7
|
+
fileSizeBytes: number;
|
|
8
|
+
sampleBytes: number;
|
|
9
|
+
sampleReachedEof: boolean;
|
|
4
10
|
compression: Bun.CompressionFormat | 'zip' | 'none';
|
|
5
|
-
|
|
6
|
-
|
|
11
|
+
zipEntry: string | null;
|
|
12
|
+
encoding: string;
|
|
13
|
+
encodingSource: 'explicit' | 'inferred';
|
|
14
|
+
delimiter: string | null;
|
|
15
|
+
delimiterSource: 'explicit' | 'inferred' | null;
|
|
16
|
+
delimiterReason: string | null;
|
|
7
17
|
lineEnding: string;
|
|
8
|
-
firstRecordColumns: number |
|
|
18
|
+
firstRecordColumns: number | null;
|
|
9
19
|
}
|
|
10
20
|
/** Inspect a bounded sample of the CSV payload; size always refers to the file on disk. */
|
|
11
|
-
export declare function inspectCsvFile(path: string,
|
|
21
|
+
export declare function inspectCsvFile(path: string, options?: InspectionOptions): Promise<FileInspection>;
|
|
12
22
|
export {};
|
package/dist/inspect-file.js
CHANGED
|
@@ -7,42 +7,50 @@ import {
|
|
|
7
7
|
isZipSignature,
|
|
8
8
|
readCsvFileChunks,
|
|
9
9
|
scanCsvFileFormat,
|
|
10
|
+
scanDelimiterCounts,
|
|
10
11
|
selectDelimiter
|
|
11
12
|
} from "./file-stream.js";
|
|
12
|
-
|
|
13
|
+
import { resolveInputEncoding } from "./normalize.js";
|
|
14
|
+
import { NativeZipReader } from "./zip-reader.js";
|
|
15
|
+
export async function inspectCsvFile(path, options = {}) {
|
|
13
16
|
const info = await stat(path);
|
|
14
17
|
if (!info.isFile())
|
|
15
18
|
throw Error("probe requires a regular file");
|
|
16
19
|
const raw = await Bun.file(path).slice(0, FILE_PROBE_SIZE + 1).bytes();
|
|
17
20
|
const zip = isZipSignature(raw);
|
|
18
|
-
if (zipEntry !== void 0 && !zip)
|
|
21
|
+
if (options.zipEntry !== void 0 && !zip)
|
|
19
22
|
throw Error("--zip-entry requires a ZIP archive");
|
|
20
|
-
let compression = zip ?
|
|
23
|
+
let compression = zip ? "zip" : compressionFromPrefix(path, raw) ?? "none";
|
|
24
|
+
let zipEntry = null;
|
|
21
25
|
let sample = raw;
|
|
22
|
-
if (compression
|
|
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")
|
|
23
31
|
try {
|
|
24
|
-
sample = await readCompressedSample(path, compression);
|
|
32
|
+
sample = await readCompressedSample(readCsvFileChunks(path, { compression, chunkSize: FILE_PROBE_SIZE + 1 }));
|
|
25
33
|
} catch (error) {
|
|
26
34
|
if (compression !== "deflate" || compressionFromExtension(path) !== void 0 || !(error instanceof TypeError) || raw.some((b) => b < 32 && b !== 9 && b !== 10 && b !== 13))
|
|
27
35
|
throw error;
|
|
28
|
-
compression =
|
|
36
|
+
compression = "none";
|
|
29
37
|
}
|
|
30
38
|
const eof = sample.length <= FILE_PROBE_SIZE;
|
|
31
|
-
const
|
|
32
|
-
const
|
|
33
|
-
const delimiter = "delimiter" in choice ? choice.delimiter : void 0;
|
|
39
|
+
const prefix = sample.subarray(0, FILE_PROBE_SIZE);
|
|
40
|
+
const format = inspectFormat(zipEntry ?? path, prefix, eof, options.encoding ?? "auto", options.delimiter ?? "auto");
|
|
34
41
|
return {
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
42
|
+
fileSizeBytes: info.size,
|
|
43
|
+
sampleBytes: prefix.byteLength,
|
|
44
|
+
sampleReachedEof: eof,
|
|
45
|
+
compression,
|
|
46
|
+
zipEntry,
|
|
47
|
+
...format
|
|
40
48
|
};
|
|
41
49
|
}
|
|
42
|
-
async function readCompressedSample(
|
|
50
|
+
async function readCompressedSample(chunks) {
|
|
43
51
|
const sample = new Uint8Array(FILE_PROBE_SIZE + 1);
|
|
44
52
|
let length = 0;
|
|
45
|
-
for await (const chunk of
|
|
53
|
+
for await (const chunk of chunks) {
|
|
46
54
|
const take = Math.min(chunk.length, sample.length - length);
|
|
47
55
|
sample.set(chunk.subarray(0, take), length);
|
|
48
56
|
length += take;
|
|
@@ -51,6 +59,48 @@ async function readCompressedSample(path, compression) {
|
|
|
51
59
|
}
|
|
52
60
|
return sample.subarray(0, length);
|
|
53
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
|
+
}
|
|
54
104
|
function inspectRecords(bytes, eof, delimiter) {
|
|
55
105
|
const separator = delimiter?.charCodeAt(0);
|
|
56
106
|
const endings = new Set;
|
|
@@ -82,7 +132,7 @@ function inspectRecords(bytes, eof, delimiter) {
|
|
|
82
132
|
}
|
|
83
133
|
const firstComplete = !firstRecord || eof && !quoted;
|
|
84
134
|
return {
|
|
85
|
-
firstRecordColumns: firstComplete && !unknownWidth ? bytes.length === 0 ? 0 : columns :
|
|
135
|
+
firstRecordColumns: firstComplete && !unknownWidth ? bytes.length === 0 ? 0 : columns : null,
|
|
86
136
|
lineEnding: endings.size > 1 ? "mixed" : endings.values().next().value ?? (eof ? "none" : "unknown")
|
|
87
137
|
};
|
|
88
138
|
}
|
package/dist/latin1-rows.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type NativePointer } from './native.js';
|
|
2
|
-
import type { CsvNativeFilterProgramEntry } from './
|
|
3
|
-
|
|
4
|
-
export declare function latin1Rows(chunks: AsyncIterable<Uint8Array>, delimiter: CsvDelimiter, columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, createParser: (delimiter: number) => NativePointer | null, reusableRows?: CsvRow[]): AsyncGenerator<CsvRow[], void>;
|
|
2
|
+
import type { CsvColumns, CsvDelimiter, CsvNativeFilterProgramEntry, CsvParserOptions, CsvRow, CsvTransform, CsvTransformOptions } from './types.js';
|
|
3
|
+
export declare function canUseFilteredLatin1Cleanup(columns: CsvColumns | undefined, filters: readonly CsvNativeFilterProgramEntry[] | undefined, transforms: readonly CsvTransform[]): boolean;
|
|
4
|
+
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?: Pick<CsvParserOptions, 'limit' | 'skipRows'> & CsvTransformOptions): AsyncGenerator<CsvRow[], void>;
|
|
5
5
|
export declare function checkedOffset(words: Uint32Array, index: number, upperBound: number): number;
|
package/dist/latin1-rows.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import { isAscii } from "node:buffer";
|
|
1
2
|
import {
|
|
2
3
|
copyLatin1Range,
|
|
3
|
-
|
|
4
|
+
decodeMaterializedField,
|
|
5
|
+
latin1Pair,
|
|
6
|
+
prepareRow
|
|
4
7
|
} from "./materialize-field.js";
|
|
5
8
|
import {
|
|
6
9
|
EMPTY_BUFFER,
|
|
@@ -12,9 +15,29 @@ import {
|
|
|
12
15
|
import { normalizeChunk } from "./normalize.js";
|
|
13
16
|
import {
|
|
14
17
|
nativeCsvParserFinalizer,
|
|
15
|
-
prepareNativeParser
|
|
18
|
+
prepareNativeParser,
|
|
19
|
+
setRowSelection
|
|
16
20
|
} from "./parser.js";
|
|
17
|
-
|
|
21
|
+
import {
|
|
22
|
+
hasOnlyCleanupTransforms,
|
|
23
|
+
prepareTransforms
|
|
24
|
+
} from "./transforms.js";
|
|
25
|
+
const WINDOW_BYTES = 1024;
|
|
26
|
+
const MAX_WINDOW_FIELD_BYTES = 64;
|
|
27
|
+
var RowStorage;
|
|
28
|
+
((RowStorage) => {
|
|
29
|
+
RowStorage[RowStorage.QuotedSpan = 1] = "QuotedSpan";
|
|
30
|
+
RowStorage[RowStorage.PackedUtf8 = 2] = "PackedUtf8";
|
|
31
|
+
})(RowStorage ||= {});
|
|
32
|
+
export function canUseFilteredLatin1Cleanup(columns, filters, transforms) {
|
|
33
|
+
return columns === void 0 && filters !== void 0 && hasOnlyCleanupTransforms(transforms) && filters.every((entry) => {
|
|
34
|
+
if ("operator" in entry)
|
|
35
|
+
return entry.operator === "all";
|
|
36
|
+
const operand = "value" in entry ? entry.value : ("notEquals" in entry) ? entry.notEquals : void 0;
|
|
37
|
+
return typeof operand === "string" ? Buffer.byteLength(operand) === operand.length : operand !== void 0 && isAscii(operand);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export async function* latin1Rows(chunks, delimiter, columns, filters, createParser, reusableRows, options = {}) {
|
|
18
41
|
if (delimiter === "auto")
|
|
19
42
|
throw Error("automatic delimiter detection is only supported by file APIs");
|
|
20
43
|
if (delimiter.length !== 1)
|
|
@@ -25,13 +48,24 @@ export async function* latin1Rows(chunks, delimiter, columns, filters, createPar
|
|
|
25
48
|
const lifetime = {};
|
|
26
49
|
nativeCsvParserFinalizer.register(lifetime, parser, lifetime);
|
|
27
50
|
try {
|
|
51
|
+
setRowSelection(parser, options);
|
|
52
|
+
if (options.transform?.length)
|
|
53
|
+
prepareTransforms(parser, options.transform, columns);
|
|
28
54
|
const prepared = prepareNativeParser(parser, columns, filters);
|
|
55
|
+
let remaining = options.limit;
|
|
56
|
+
if (remaining === 0)
|
|
57
|
+
return;
|
|
29
58
|
for await (const chunk of chunks) {
|
|
30
59
|
const input = normalizeChunk(chunk);
|
|
31
60
|
const batch = prepared.writeBatch(input, !1);
|
|
32
61
|
const rows = consumeLatin1Batch(parser, batch, reusableRows);
|
|
33
|
-
if (rows.length > 0)
|
|
62
|
+
if (rows.length > 0) {
|
|
63
|
+
if (remaining !== void 0)
|
|
64
|
+
remaining -= rows.length;
|
|
34
65
|
yield rows;
|
|
66
|
+
if (remaining === 0)
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
35
69
|
}
|
|
36
70
|
const batch = prepared.writeBatch(EMPTY_BUFFER, !0);
|
|
37
71
|
const rows = consumeLatin1Batch(parser, batch, reusableRows);
|
|
@@ -62,13 +96,26 @@ function consumeLatin1Batch(parser, batch, reusableRows) {
|
|
|
62
96
|
rows.length = rowCount;
|
|
63
97
|
let fieldStart = checkedOffset(rowOffsets, 0, totalFields);
|
|
64
98
|
let start = checkedOffset(fieldOffsets, fieldStart, dataLength);
|
|
99
|
+
let windowStart = 0;
|
|
100
|
+
let windowEnd = 0;
|
|
101
|
+
let text = "";
|
|
65
102
|
for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
|
|
66
103
|
const fieldEnd = checkedOffset(rowOffsets, rowIndex + 1, totalFields);
|
|
67
|
-
const
|
|
68
|
-
const trailing = leading * 2;
|
|
69
|
-
const row = reusableRows?.[rowIndex] ?? [];
|
|
104
|
+
const storage = quotedRows?.[rowIndex] ?? 0;
|
|
70
105
|
const width = fieldEnd - fieldStart;
|
|
71
|
-
row
|
|
106
|
+
const row = prepareRow(reusableRows?.[rowIndex], width);
|
|
107
|
+
if (storage === 2 /* PackedUtf8 */) {
|
|
108
|
+
for (let column = 0;column < width; ++column) {
|
|
109
|
+
const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
|
|
110
|
+
row[column] = decodeMaterializedField(bytes, start, end, "utf8");
|
|
111
|
+
start = end;
|
|
112
|
+
}
|
|
113
|
+
rows[rowIndex] = row;
|
|
114
|
+
fieldStart = fieldEnd;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const leading = storage === 1 /* QuotedSpan */ ? 1 : 0;
|
|
118
|
+
const trailing = leading * 2;
|
|
72
119
|
for (let column = 0;column < width; ++column) {
|
|
73
120
|
const end = checkedOffset(fieldOffsets, fieldStart + column + 1, dataLength);
|
|
74
121
|
const payload = start + leading;
|
|
@@ -84,16 +131,19 @@ function consumeLatin1Batch(parser, batch, reusableRows) {
|
|
|
84
131
|
case 2:
|
|
85
132
|
row[column] = latin1Pair(view.getUint16(payload, !0));
|
|
86
133
|
break;
|
|
87
|
-
case 3:
|
|
88
|
-
row[column] = latin1Pair(view.getUint16(payload, !0)) + String.fromCharCode(view.getUint8(payload + 2));
|
|
89
|
-
break;
|
|
90
|
-
case 4:
|
|
91
|
-
row[column] = latin1Pair(view.getUint16(payload, !0)) + latin1Pair(view.getUint16(payload + 2, !0));
|
|
92
|
-
break;
|
|
93
134
|
default:
|
|
94
135
|
if (length < 0)
|
|
95
136
|
throw RangeError("CSV field span exceeds its backing range");
|
|
96
|
-
|
|
137
|
+
if (length > MAX_WINDOW_FIELD_BYTES) {
|
|
138
|
+
row[column] = copyLatin1Range(bytes, payload, payloadEnd);
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
if (payloadEnd > windowEnd) {
|
|
142
|
+
windowStart = payload;
|
|
143
|
+
windowEnd = Math.min(payload + WINDOW_BYTES, dataLength);
|
|
144
|
+
text = copyLatin1Range(bytes, windowStart, windowEnd);
|
|
145
|
+
}
|
|
146
|
+
row[column] = text.slice(payload - windowStart, payloadEnd - windowStart);
|
|
97
147
|
}
|
|
98
148
|
start = end;
|
|
99
149
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export declare function prepareRow(row: string[] | undefined, width: number): string[];
|
|
1
2
|
export declare function latin1Pair(key: number): string;
|
|
2
3
|
export declare function copyLatin1Range(data: Buffer, start: number, end: number): string;
|
|
3
4
|
export declare function decodeMaterializedField(data: Buffer, start: number, end: number, encoding: 'utf8' | 'latin1'): string;
|
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
const LATIN1_SINGLE = Array.from({ length: 256 }, (_, byte) => String.fromCharCode(byte));
|
|
2
2
|
const bufferPrototype = Buffer.prototype;
|
|
3
3
|
const latin1Slice = bufferPrototype.latin1Slice;
|
|
4
|
+
const utf8Slice = bufferPrototype.utf8Slice;
|
|
4
5
|
const LATIN1_PAIRS = Array.from({ length: 65536 });
|
|
6
|
+
export function prepareRow(row, width) {
|
|
7
|
+
if (row === void 0)
|
|
8
|
+
return Array(width);
|
|
9
|
+
row.length = width;
|
|
10
|
+
return row;
|
|
11
|
+
}
|
|
5
12
|
export function latin1Pair(key) {
|
|
6
13
|
const cached = LATIN1_PAIRS[key];
|
|
7
14
|
if (cached !== void 0)
|
|
@@ -27,5 +34,7 @@ export function decodeMaterializedField(data, start, end, encoding) {
|
|
|
27
34
|
if (first < 128 && second < 128)
|
|
28
35
|
return latin1Pair(first | second << 8);
|
|
29
36
|
}
|
|
30
|
-
|
|
37
|
+
if (encoding === "latin1")
|
|
38
|
+
return copyLatin1Range(data, start, end);
|
|
39
|
+
return typeof utf8Slice === "function" ? utf8Slice.call(data, start, end) : data.toString("utf8", start, end);
|
|
31
40
|
}
|