@konstit/csv 0.4.3 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -26
- package/THIRD_PARTY_NOTICES.md +7 -1
- package/dist/api.d.ts +39 -249
- package/dist/api.js +40 -304
- package/dist/batches.d.ts +5 -53
- package/dist/batches.js +66 -43
- package/dist/cli-command.d.ts +7 -0
- package/dist/cli-command.js +350 -0
- package/dist/cli-schema.d.ts +111 -0
- package/dist/cli-schema.js +219 -0
- package/dist/cli.js +2 -604
- package/dist/file-stream.d.ts +57 -2
- package/dist/file-stream.js +241 -36
- package/dist/files.d.ts +11 -11
- package/dist/files.js +11 -9
- package/dist/filter.d.ts +4 -6
- package/dist/format-bytes.d.ts +1 -0
- package/dist/format-bytes.js +11 -0
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -14
- package/dist/inspect-file.d.ts +12 -0
- package/dist/inspect-file.js +88 -0
- package/dist/latin1-rows.d.ts +3 -1
- package/dist/latin1-rows.js +61 -23
- package/dist/materialize-field.d.ts +2 -0
- package/dist/materialize-field.js +20 -15
- package/dist/native.d.ts +29 -9
- package/dist/native.js +27 -29
- package/dist/normalize.d.ts +15 -2
- package/dist/normalize.js +41 -2
- package/dist/options-snapshot.js +3 -2
- package/dist/options.d.ts +4 -30
- package/dist/options.js +0 -6
- package/dist/parser.d.ts +14 -15
- package/dist/parser.js +38 -54
- package/dist/strict-schema.d.ts +5 -3
- package/dist/types.d.ts +88 -222
- package/dist/zip-reader.d.ts +11 -1
- package/dist/zip-reader.js +12 -3
- package/package.json +34 -32
- 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 +9 -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/worker-count.d.ts +0 -34
- package/dist/worker-count.js +0 -101
- package/dist/worker-factory.d.ts +0 -3
- package/dist/worker-factory.js +0 -9
- package/dist/worker-filter.d.ts +0 -29
- package/dist/worker-filter.js +0 -46
- package/dist/worker-module.d.ts +0 -1
- package/dist/worker-module.js +0 -4
- package/dist/worker-pool.d.ts +0 -93
- package/dist/worker-pool.js +0 -298
- package/dist/worker-rows.d.ts +0 -36
- package/dist/worker-rows.js +0 -127
- package/dist/workers/count.worker.d.ts +0 -1
- package/dist/workers/count.worker.js +0 -36
- package/dist/workers/rows.worker.d.ts +0 -1
- package/dist/workers/rows.worker.js +0 -56
package/dist/batches.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { read } from "bun:ffi";
|
|
1
2
|
import { decodeMaterializedField } from "./materialize-field.js";
|
|
2
3
|
import {
|
|
3
4
|
EMPTY_BUFFER,
|
|
@@ -10,6 +11,7 @@ import {
|
|
|
10
11
|
normalizeColumns,
|
|
11
12
|
normalizeFilterColumn
|
|
12
13
|
} from "./normalize.js";
|
|
14
|
+
const visitBatchRows = Symbol("visitBatchRows");
|
|
13
15
|
|
|
14
16
|
export class NativeCsvRowView {
|
|
15
17
|
#data;
|
|
@@ -17,6 +19,7 @@ export class NativeCsvRowView {
|
|
|
17
19
|
#fieldOffsets;
|
|
18
20
|
#fieldOffsetWords;
|
|
19
21
|
#rowIndex;
|
|
22
|
+
#owner;
|
|
20
23
|
constructor(data, rowOffsets, fieldOffsets, rowIndex = 0) {
|
|
21
24
|
this.#data = data;
|
|
22
25
|
this.#rowOffsetWords = offsetWords(rowOffsets);
|
|
@@ -25,6 +28,7 @@ export class NativeCsvRowView {
|
|
|
25
28
|
this.#rowIndex = rowIndex;
|
|
26
29
|
}
|
|
27
30
|
get rowIndex() {
|
|
31
|
+
this.#requireActive();
|
|
28
32
|
return this.#rowIndex;
|
|
29
33
|
}
|
|
30
34
|
get fieldCount() {
|
|
@@ -36,7 +40,7 @@ export class NativeCsvRowView {
|
|
|
36
40
|
this.#rowIndex = rowIndex;
|
|
37
41
|
return this;
|
|
38
42
|
}
|
|
39
|
-
|
|
43
|
+
range(columnIndex) {
|
|
40
44
|
const [rowStart, rowEnd] = this.#rowRange(this.#rowIndex);
|
|
41
45
|
const fieldIndex = rowStart + columnIndex;
|
|
42
46
|
if (fieldIndex < rowStart || fieldIndex >= rowEnd)
|
|
@@ -46,50 +50,31 @@ export class NativeCsvRowView {
|
|
|
46
50
|
end: offsetAt(this.#fieldOffsetWords, fieldIndex + 1, "field offset", this.#data.byteLength)
|
|
47
51
|
};
|
|
48
52
|
}
|
|
49
|
-
range(columnIndex) {
|
|
50
|
-
return this.fieldRange(columnIndex);
|
|
51
|
-
}
|
|
52
|
-
fieldBytes(columnIndex) {
|
|
53
|
-
const range = this.fieldRange(columnIndex);
|
|
54
|
-
if (range === null)
|
|
55
|
-
return null;
|
|
56
|
-
return this.#data.subarray(range.start, range.end);
|
|
57
|
-
}
|
|
58
53
|
bytes(columnIndex) {
|
|
59
|
-
return this.
|
|
54
|
+
return this.buffer(columnIndex);
|
|
60
55
|
}
|
|
61
|
-
|
|
62
|
-
const range = this.
|
|
56
|
+
buffer(columnIndex) {
|
|
57
|
+
const range = this.range(columnIndex);
|
|
63
58
|
if (range === null)
|
|
64
59
|
return null;
|
|
65
60
|
return this.#data.subarray(range.start, range.end);
|
|
66
61
|
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
fieldString(columnIndex) {
|
|
71
|
-
const range = this.fieldRange(columnIndex);
|
|
62
|
+
get(columnIndex) {
|
|
63
|
+
const range = this.range(columnIndex);
|
|
72
64
|
if (range === null)
|
|
73
65
|
return null;
|
|
74
66
|
return this.#data.toString("utf8", range.start, range.end);
|
|
75
67
|
}
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
79
|
-
get(columnIndex) {
|
|
80
|
-
return this.getPhysical(columnIndex);
|
|
81
|
-
}
|
|
82
|
-
pickPhysical(columns) {
|
|
68
|
+
pick(columns) {
|
|
69
|
+
this.#requireActive();
|
|
83
70
|
const values = [];
|
|
84
71
|
values.length = columns.length;
|
|
85
72
|
for (let index = 0;index < columns.length; ++index)
|
|
86
|
-
values[index] = this.
|
|
73
|
+
values[index] = this.get(columns[index] ?? 0) ?? "";
|
|
87
74
|
return values;
|
|
88
75
|
}
|
|
89
|
-
pick(columns) {
|
|
90
|
-
return this.pickPhysical(columns);
|
|
91
|
-
}
|
|
92
76
|
#rowRange(rowIndex) {
|
|
77
|
+
this.#requireActive();
|
|
93
78
|
const maxFieldIndex = this.#fieldOffsets.length - 1;
|
|
94
79
|
const rowStart = offsetAt(this.#rowOffsetWords, rowIndex, `row ${rowIndex} offset`, maxFieldIndex);
|
|
95
80
|
const rowEnd = offsetAt(this.#rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, maxFieldIndex);
|
|
@@ -97,12 +82,36 @@ export class NativeCsvRowView {
|
|
|
97
82
|
throw RangeError(`row ${rowIndex} offsets are not monotonic`);
|
|
98
83
|
return [rowStart, rowEnd];
|
|
99
84
|
}
|
|
85
|
+
#requireActive() {
|
|
86
|
+
if (this.#owner === null)
|
|
87
|
+
throw Error("row view is only valid during row view callback");
|
|
88
|
+
if (this.#owner?.closed)
|
|
89
|
+
throw Error("native CSV batch is closed");
|
|
90
|
+
}
|
|
91
|
+
static [visitBatchRows](batch, callback) {
|
|
92
|
+
const rowCount = batch.rowCount;
|
|
93
|
+
const view = new NativeCsvRowView(batch.data(), batch.rowOffsets(), batch.fieldOffsets());
|
|
94
|
+
for (let index = 0;index < rowCount; ++index) {
|
|
95
|
+
view.#owner = batch;
|
|
96
|
+
let result;
|
|
97
|
+
try {
|
|
98
|
+
result = callback(view.moveTo(index), index);
|
|
99
|
+
} finally {
|
|
100
|
+
view.#owner = null;
|
|
101
|
+
}
|
|
102
|
+
if (result !== null && (typeof result === "object" || typeof result === "function") && "then" in result && typeof result.then === "function") {
|
|
103
|
+
void Promise.resolve(result).catch(() => {});
|
|
104
|
+
throw TypeError("row view callback must be synchronous");
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
100
108
|
}
|
|
101
109
|
|
|
102
110
|
export class NativeCsvBatch {
|
|
103
111
|
#handle;
|
|
104
112
|
#data;
|
|
105
113
|
#dataView;
|
|
114
|
+
#rowOffsetLimit;
|
|
106
115
|
#rowOffsets;
|
|
107
116
|
#rowOffsetWords;
|
|
108
117
|
#fieldOffsets;
|
|
@@ -126,10 +135,7 @@ export class NativeCsvBatch {
|
|
|
126
135
|
return this.rowsInto([]);
|
|
127
136
|
}
|
|
128
137
|
forEachRow(callback) {
|
|
129
|
-
|
|
130
|
-
const rowView = new NativeCsvRowView(this.data(), this.rowOffsets(), this.fieldOffsets());
|
|
131
|
-
for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex)
|
|
132
|
-
callback(rowView.moveTo(rowIndex), rowIndex);
|
|
138
|
+
NativeCsvRowView[visitBatchRows](this, callback);
|
|
133
139
|
}
|
|
134
140
|
rowsInto(target, columns) {
|
|
135
141
|
normalizeColumns(columns);
|
|
@@ -197,10 +203,7 @@ export class NativeCsvBatch {
|
|
|
197
203
|
if (this.#rowOffsets !== void 0)
|
|
198
204
|
return this.#rowOffsets;
|
|
199
205
|
const rowCount = this.rowCount;
|
|
200
|
-
|
|
201
|
-
if (ptr === null)
|
|
202
|
-
throw Error("native CSV batch row offsets are null");
|
|
203
|
-
this.#rowOffsets = new BigUint64Array(toArrayBuffer(ptr, 0, (rowCount + 1) * BigUint64Array.BYTES_PER_ELEMENT));
|
|
206
|
+
this.#rowOffsets = new BigUint64Array(toArrayBuffer(this.#rowOffsetsPointer(), 0, (rowCount + 1) * BigUint64Array.BYTES_PER_ELEMENT));
|
|
204
207
|
return this.#rowOffsets;
|
|
205
208
|
}
|
|
206
209
|
fieldOffsets() {
|
|
@@ -214,9 +217,22 @@ export class NativeCsvBatch {
|
|
|
214
217
|
return this.#fieldOffsets;
|
|
215
218
|
}
|
|
216
219
|
rowFieldCount(rowIndex) {
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
const
|
|
220
|
+
const firstLookupWithoutView = this.#rowOffsetLimit === void 0 && this.#rowOffsets === void 0;
|
|
221
|
+
this.#rowOffsetLimit ??= this.totalFields;
|
|
222
|
+
const totalFields = this.#rowOffsetLimit;
|
|
223
|
+
if (!Number.isInteger(rowIndex) || rowIndex < 0)
|
|
224
|
+
throw RangeError(`row ${rowIndex} offset index out of range: ${rowIndex}`);
|
|
225
|
+
if (firstLookupWithoutView && rowIndex < MAX_DIRECT_ROW_INDEX_EXCLUSIVE && rowIndex < native.symbols.csv_batch_row_count(this.#requireHandle())) {
|
|
226
|
+
const ptr = this.#rowOffsetsPointer();
|
|
227
|
+
const byteOffset = rowIndex * BigUint64Array.BYTES_PER_ELEMENT;
|
|
228
|
+
const start = Number(read.u64(ptr, byteOffset));
|
|
229
|
+
const end = Number(read.u64(ptr, byteOffset + BigUint64Array.BYTES_PER_ELEMENT));
|
|
230
|
+
if (start <= totalFields && end <= totalFields)
|
|
231
|
+
return end - start;
|
|
232
|
+
}
|
|
233
|
+
const rowOffsetWords = this.#rowOffsetWords ?? this.#rowOffsetWordsView();
|
|
234
|
+
const start = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
|
|
235
|
+
const end = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
|
|
220
236
|
return end - start;
|
|
221
237
|
}
|
|
222
238
|
fieldRange(rowIndex, columnIndex) {
|
|
@@ -260,6 +276,7 @@ export class NativeCsvBatch {
|
|
|
260
276
|
const resolvedEndRow = this.#resolveEndRow(endRow);
|
|
261
277
|
this.#validateRowRange(startRow, resolvedEndRow);
|
|
262
278
|
for (let rowIndex = startRow;rowIndex < resolvedEndRow; ++rowIndex) {
|
|
279
|
+
this.#requireHandle();
|
|
263
280
|
const rowStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
|
|
264
281
|
const rowEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
|
|
265
282
|
const fieldIndex = rowStart + columnIndex;
|
|
@@ -283,6 +300,7 @@ export class NativeCsvBatch {
|
|
|
283
300
|
const totalFields = this.totalFields;
|
|
284
301
|
const ranges = new Float64Array(columns.length * 2);
|
|
285
302
|
for (let rowIndex = startRow;rowIndex < resolvedEndRow; ++rowIndex) {
|
|
303
|
+
this.#requireHandle();
|
|
286
304
|
const rowStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
|
|
287
305
|
const rowEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
|
|
288
306
|
for (let columnOffset = 0;columnOffset < columns.length; ++columnOffset) {
|
|
@@ -312,15 +330,13 @@ export class NativeCsvBatch {
|
|
|
312
330
|
this.#handle = null;
|
|
313
331
|
this.#data = void 0;
|
|
314
332
|
this.#dataView = void 0;
|
|
333
|
+
this.#rowOffsetLimit = void 0;
|
|
315
334
|
this.#rowOffsets = void 0;
|
|
316
335
|
this.#rowOffsetWords = void 0;
|
|
317
336
|
this.#fieldOffsets = void 0;
|
|
318
337
|
this.#fieldOffsetWords = void 0;
|
|
319
338
|
}
|
|
320
339
|
}
|
|
321
|
-
dispose() {
|
|
322
|
-
this.close();
|
|
323
|
-
}
|
|
324
340
|
[Symbol.dispose]() {
|
|
325
341
|
this.close();
|
|
326
342
|
}
|
|
@@ -335,6 +351,12 @@ export class NativeCsvBatch {
|
|
|
335
351
|
this.#rowOffsetWords = offsetWords(rowOffsets);
|
|
336
352
|
return this.#rowOffsetWords;
|
|
337
353
|
}
|
|
354
|
+
#rowOffsetsPointer() {
|
|
355
|
+
const ptr = native.symbols.csv_batch_row_offsets_ptr(this.#requireHandle());
|
|
356
|
+
if (ptr === null)
|
|
357
|
+
throw Error("native CSV batch row offsets are null");
|
|
358
|
+
return ptr;
|
|
359
|
+
}
|
|
338
360
|
#fieldOffsetWordsView() {
|
|
339
361
|
const fieldOffsets = this.fieldOffsets();
|
|
340
362
|
if (this.#fieldOffsetWords === void 0)
|
|
@@ -357,6 +379,7 @@ export class NativeCsvBatch {
|
|
|
357
379
|
const UINT32_BASE = 4294967296;
|
|
358
380
|
const UINT32_BASE_BIGINT = 0x100000000n;
|
|
359
381
|
const MAX_SAFE_OFFSET_HIGH_WORD = 2097151;
|
|
382
|
+
const MAX_DIRECT_ROW_INDEX_EXCLUSIVE = Math.floor(2147483647 / BigUint64Array.BYTES_PER_ELEMENT);
|
|
360
383
|
function offsetWords(offsets) {
|
|
361
384
|
return new Uint32Array(offsets.buffer, offsets.byteOffset, offsets.length * 2);
|
|
362
385
|
}
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import { csv } from "./api.js";
|
|
2
|
+
import {
|
|
3
|
+
csvCommand
|
|
4
|
+
} from "./cli-schema.js";
|
|
5
|
+
import { formatBytes } from "./format-bytes.js";
|
|
6
|
+
import { inspectCsvFile } from "./inspect-file.js";
|
|
7
|
+
import {
|
|
8
|
+
normalizeColumns,
|
|
9
|
+
normalizeFilterColumn
|
|
10
|
+
} from "./normalize.js";
|
|
11
|
+
const MAX_FILTER_NESTING = 128;
|
|
12
|
+
const OUTPUT_BUFFER_SIZE = 65536;
|
|
13
|
+
export async function runCli(arguments_, customOutput) {
|
|
14
|
+
const result = csvCommand.tryParse(arguments_);
|
|
15
|
+
if (result.type === "display")
|
|
16
|
+
return csvCommand.runParsed(result, customOutput && { stdout: (text) => customOutput.log(text.trimEnd()) });
|
|
17
|
+
const output = customOutput ?? {
|
|
18
|
+
log: console.log,
|
|
19
|
+
error: console.error,
|
|
20
|
+
write: (chunk) => Bun.write(Bun.stdout, chunk)
|
|
21
|
+
};
|
|
22
|
+
if (result.type === "error")
|
|
23
|
+
return usageError(output, result.error.message, `${result.error.commandPath.join(" ")} --help`);
|
|
24
|
+
const { subcommand } = result.value;
|
|
25
|
+
switch (subcommand.name) {
|
|
26
|
+
case "count":
|
|
27
|
+
return runCount(subcommand.args, output);
|
|
28
|
+
case "lines":
|
|
29
|
+
return runLines(subcommand.args, output);
|
|
30
|
+
case "probe":
|
|
31
|
+
return runProbe(subcommand.args.path, subcommand.args["zip-entry"], output);
|
|
32
|
+
case "completion":
|
|
33
|
+
return runCompletion(subcommand.args.shell, output);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
async function runCompletion(shell, output) {
|
|
37
|
+
const { generateCompletion } = await import("@konstit/cli/completion");
|
|
38
|
+
output.log(generateCompletion(csvCommand, shell).trimEnd());
|
|
39
|
+
return 0;
|
|
40
|
+
}
|
|
41
|
+
async function runProbe(path, entry, output) {
|
|
42
|
+
try {
|
|
43
|
+
const result = await inspectCsvFile(path, entry);
|
|
44
|
+
output.log([
|
|
45
|
+
`File size: ${formatBytes(result.size)}`,
|
|
46
|
+
`Encoding: ${result.encoding}`,
|
|
47
|
+
`Delimiter: ${result.delimiter === void 0 ? "undetermined" : JSON.stringify(result.delimiter)}`,
|
|
48
|
+
`Line endings: ${result.lineEnding}`,
|
|
49
|
+
`Compression: ${result.compression}`,
|
|
50
|
+
`First record columns: ${String(result.firstRecordColumns ?? "unknown")}`
|
|
51
|
+
].join(`
|
|
52
|
+
`));
|
|
53
|
+
return 0;
|
|
54
|
+
} catch (error) {
|
|
55
|
+
output.error(`csv: ${error instanceof Error ? error.message : String(error)}`);
|
|
56
|
+
return 1;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function runCount(args, output) {
|
|
60
|
+
let options;
|
|
61
|
+
try {
|
|
62
|
+
options = parseCommonOptions(args);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
return usageError(output, error instanceof Error ? error.message : String(error), "csv count --help");
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
output.log(await csv.count(args.path, options));
|
|
68
|
+
return 0;
|
|
69
|
+
} catch (error) {
|
|
70
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
71
|
+
output.error(`csv: ${message}`);
|
|
72
|
+
return 1;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function runLines(args, output) {
|
|
76
|
+
let input;
|
|
77
|
+
try {
|
|
78
|
+
input = parseLinesInput(args);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
return usageError(output, error instanceof Error ? error.message : String(error), "csv lines --help");
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
await streamLines(input, output);
|
|
84
|
+
return 0;
|
|
85
|
+
} catch (error) {
|
|
86
|
+
if (isBrokenPipe(error))
|
|
87
|
+
return 0;
|
|
88
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
89
|
+
output.error(`csv: ${message}`);
|
|
90
|
+
return 1;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function parseLinesInput(values) {
|
|
94
|
+
const { limit } = values;
|
|
95
|
+
const options = parseCommonOptions(values, values.strict === !0 && limit !== void 0);
|
|
96
|
+
if (limit !== void 0 && options.strict === !0) {
|
|
97
|
+
if (options.compression !== "none")
|
|
98
|
+
throw Error("--strict with --limit does not support compressed input");
|
|
99
|
+
if (options.delimiter === "auto")
|
|
100
|
+
throw Error("--strict with --limit requires a fixed input delimiter");
|
|
101
|
+
if (options.encoding === "auto")
|
|
102
|
+
throw Error("--strict with --limit requires a fixed input encoding");
|
|
103
|
+
if (options.chunkSize !== void 0 && options.chunkSize !== 1)
|
|
104
|
+
throw Error("--strict with --limit requires --chunk-size 1");
|
|
105
|
+
options.chunkSize = 1;
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
json: values.json,
|
|
109
|
+
...limit === void 0 ? {} : { limit },
|
|
110
|
+
options,
|
|
111
|
+
outputDelimiter: values["output-delimiter"],
|
|
112
|
+
path: values.path
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function parseCommonOptions(values, fixedFormat = !1) {
|
|
116
|
+
const options = values.strict ? { strict: !0 } : { where: parseWhereOptions(values) };
|
|
117
|
+
options.delimiter = values.delimiter ?? (fixedFormat ? "," : "auto");
|
|
118
|
+
options.encoding = values.encoding ?? (fixedFormat ? "utf8" : "auto");
|
|
119
|
+
if (values["chunk-size"] !== void 0)
|
|
120
|
+
options.chunkSize = values["chunk-size"];
|
|
121
|
+
if (values["fixed-columns"] !== void 0)
|
|
122
|
+
options.fixedColumns = values["fixed-columns"];
|
|
123
|
+
if (values.columns !== void 0)
|
|
124
|
+
options.columns = parseColumns(values.columns, "columns");
|
|
125
|
+
if (values["expected-header"].length > 0)
|
|
126
|
+
options.expectedHeaders = values["expected-header"];
|
|
127
|
+
if (values["require-header"] === !0)
|
|
128
|
+
options.requireHeader = !0;
|
|
129
|
+
if (values["min-data-rows"] !== void 0)
|
|
130
|
+
options.minDataRows = values["min-data-rows"];
|
|
131
|
+
options.compression = parseCompression(values) ?? (fixedFormat ? "none" : "auto");
|
|
132
|
+
return options;
|
|
133
|
+
}
|
|
134
|
+
function parseColumnIndex(value, label) {
|
|
135
|
+
const number = Number(value);
|
|
136
|
+
if (!Number.isSafeInteger(number) || number < 0)
|
|
137
|
+
throw Error(`${label} must be an integer greater than or equal to 0: ${value}`);
|
|
138
|
+
return number;
|
|
139
|
+
}
|
|
140
|
+
function parseColumns(value, label) {
|
|
141
|
+
const columns = value.length === 0 ? [] : value.split(",").map((column) => parseColumnIndex(column, label));
|
|
142
|
+
normalizeColumns(columns);
|
|
143
|
+
return columns;
|
|
144
|
+
}
|
|
145
|
+
function parseCompression(values) {
|
|
146
|
+
const compression = values.compression;
|
|
147
|
+
const zipEntry = values["zip-entry"];
|
|
148
|
+
const maxCompressionRatio = values["max-compression-ratio"];
|
|
149
|
+
const maxDecompressedBytes = values["max-decompressed-bytes"];
|
|
150
|
+
if (compression !== "zip") {
|
|
151
|
+
if (zipEntry !== void 0)
|
|
152
|
+
throw Error("--zip-entry requires --compression zip");
|
|
153
|
+
return compression;
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
entry: zipEntry,
|
|
157
|
+
format: "zip",
|
|
158
|
+
...maxCompressionRatio === void 0 ? {} : { maxCompressionRatio },
|
|
159
|
+
...maxDecompressedBytes === void 0 ? {} : { maxDecompressedBytes }
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
async function streamLines(input, output) {
|
|
163
|
+
let chunks = [];
|
|
164
|
+
let chunksLength = 0;
|
|
165
|
+
let emitted = 0;
|
|
166
|
+
batches:
|
|
167
|
+
for await (const rows of csv.rows(input.path, input.options)) {
|
|
168
|
+
for (const row of rows) {
|
|
169
|
+
const record = input.json ? `${JSON.stringify(row)}
|
|
170
|
+
` : serializeCsvRecord(row, input.outputDelimiter);
|
|
171
|
+
chunks.push(record);
|
|
172
|
+
chunksLength += record.length;
|
|
173
|
+
++emitted;
|
|
174
|
+
if (chunksLength >= OUTPUT_BUFFER_SIZE) {
|
|
175
|
+
await output.write(chunks.join(""));
|
|
176
|
+
chunks = [];
|
|
177
|
+
chunksLength = 0;
|
|
178
|
+
}
|
|
179
|
+
if (emitted === input.limit)
|
|
180
|
+
break batches;
|
|
181
|
+
}
|
|
182
|
+
if (chunksLength > 0) {
|
|
183
|
+
await output.write(chunks.join(""));
|
|
184
|
+
chunks = [];
|
|
185
|
+
chunksLength = 0;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (chunksLength > 0)
|
|
189
|
+
await output.write(chunks.join(""));
|
|
190
|
+
}
|
|
191
|
+
function serializeCsvRecord(row, delimiter) {
|
|
192
|
+
return `${row.map((field) => serializeCsvField(field, delimiter)).join(delimiter)}
|
|
193
|
+
`;
|
|
194
|
+
}
|
|
195
|
+
function serializeCsvField(field, delimiter) {
|
|
196
|
+
if (!field.includes(delimiter) && !field.includes('"') && !field.includes("\r") && !field.includes(`
|
|
197
|
+
`))
|
|
198
|
+
return field;
|
|
199
|
+
return `"${field.replaceAll('"', '""')}"`;
|
|
200
|
+
}
|
|
201
|
+
function isBrokenPipe(error) {
|
|
202
|
+
return isObject(error) && error.code === "EPIPE";
|
|
203
|
+
}
|
|
204
|
+
function parseWhereOptions(values) {
|
|
205
|
+
const filters = [];
|
|
206
|
+
if (values.where !== void 0)
|
|
207
|
+
filters.push(parseWhereFilter(values.where, "--where"));
|
|
208
|
+
for (const { key, value } of values["where-eq"]) {
|
|
209
|
+
const column = parseFilterColumn(key, "--where-eq");
|
|
210
|
+
filters.push(csv.column(column).equals(value));
|
|
211
|
+
}
|
|
212
|
+
for (const { key, value } of values["where-neq"]) {
|
|
213
|
+
const column = parseFilterColumn(key, "--where-neq");
|
|
214
|
+
filters.push(csv.column(column).doesNotEqual(value));
|
|
215
|
+
}
|
|
216
|
+
const inValuesByColumn = new Map;
|
|
217
|
+
for (const { key, value } of values["where-in"]) {
|
|
218
|
+
const column = parseFilterColumn(key, "--where-in");
|
|
219
|
+
const columnValues = inValuesByColumn.get(column);
|
|
220
|
+
if (columnValues === void 0)
|
|
221
|
+
inValuesByColumn.set(column, [value]);
|
|
222
|
+
else
|
|
223
|
+
columnValues.push(value);
|
|
224
|
+
}
|
|
225
|
+
for (const [column, inValues] of inValuesByColumn)
|
|
226
|
+
filters.push(csv.column(column).isOneOf(inValues));
|
|
227
|
+
const notInValuesByColumn = new Map;
|
|
228
|
+
for (const { key, value } of values["where-noin"]) {
|
|
229
|
+
const column = parseFilterColumn(key, "--where-noin");
|
|
230
|
+
const columnValues = notInValuesByColumn.get(column);
|
|
231
|
+
if (columnValues === void 0)
|
|
232
|
+
notInValuesByColumn.set(column, [value]);
|
|
233
|
+
else
|
|
234
|
+
columnValues.push(value);
|
|
235
|
+
}
|
|
236
|
+
for (const [column, notInValues] of notInValuesByColumn)
|
|
237
|
+
filters.push(csv.column(column).isNoneOf(notInValues));
|
|
238
|
+
for (const { key, value } of values["where-prefix"]) {
|
|
239
|
+
const column = parseFilterColumn(key, "--where-prefix");
|
|
240
|
+
filters.push(csv.column(column).startsWith(value));
|
|
241
|
+
}
|
|
242
|
+
for (const expression of values["where-regex"])
|
|
243
|
+
filters.push(parseRegexExpression(expression));
|
|
244
|
+
const first = filters[0];
|
|
245
|
+
if (first === void 0)
|
|
246
|
+
return;
|
|
247
|
+
return filters.length === 1 ? first : csv.all(first, ...filters.slice(1));
|
|
248
|
+
}
|
|
249
|
+
function parseFilterColumn(key, option) {
|
|
250
|
+
return normalizeFilterColumn(parseColumnIndex(key, `${option} column`));
|
|
251
|
+
}
|
|
252
|
+
function parseRegexExpression({ key, value }) {
|
|
253
|
+
const column = parseFilterColumn(key, "--where-regex");
|
|
254
|
+
const closingSlash = value.lastIndexOf("/");
|
|
255
|
+
if (!value.startsWith("/") || closingSlash === 0)
|
|
256
|
+
throw Error(`--where-regex must use <column>=/<pattern>/<flags>: ${JSON.stringify(`${key}=${value}`)}`);
|
|
257
|
+
const source = value.slice(1, closingSlash);
|
|
258
|
+
const flags = value.slice(closingSlash + 1);
|
|
259
|
+
return csv.column(column).hasMatch(new RegExp(source, flags));
|
|
260
|
+
}
|
|
261
|
+
function parseWhereFilter(value, label, depth = 0) {
|
|
262
|
+
if (depth > MAX_FILTER_NESTING)
|
|
263
|
+
throw Error(`--where nesting exceeds ${MAX_FILTER_NESTING}`);
|
|
264
|
+
if (!isObject(value))
|
|
265
|
+
throw Error(`${label} must be a JSON object`);
|
|
266
|
+
if ("all" in value) {
|
|
267
|
+
requireExactKeys(value, ["all"], label);
|
|
268
|
+
return parseWhereGroup(value.all, `${label}.all`, csv.all, depth);
|
|
269
|
+
}
|
|
270
|
+
if ("any" in value) {
|
|
271
|
+
requireExactKeys(value, ["any"], label);
|
|
272
|
+
return parseWhereGroup(value.any, `${label}.any`, csv.any, depth);
|
|
273
|
+
}
|
|
274
|
+
if ("not" in value) {
|
|
275
|
+
requireExactKeys(value, ["not"], label);
|
|
276
|
+
return csv.not(parseWhereFilter(value.not, `${label}.not`, depth + 1));
|
|
277
|
+
}
|
|
278
|
+
return parseWherePredicate(value, label);
|
|
279
|
+
}
|
|
280
|
+
function parseWhereGroup(value, label, combine, depth) {
|
|
281
|
+
if (!Array.isArray(value) || value.length === 0)
|
|
282
|
+
throw Error(`${label} must be a non-empty array`);
|
|
283
|
+
const first = parseWhereFilter(value[0], `${label}[0]`, depth + 1);
|
|
284
|
+
const rest = value.slice(1).map((filter, index) => parseWhereFilter(filter, `${label}[${String(index + 1)}]`, depth + 1));
|
|
285
|
+
return combine(first, ...rest);
|
|
286
|
+
}
|
|
287
|
+
function parseWherePredicate(value, label) {
|
|
288
|
+
const column = value.column;
|
|
289
|
+
if (typeof column !== "number")
|
|
290
|
+
throw Error(`${label}.column must be a number`);
|
|
291
|
+
normalizeFilterColumn(column);
|
|
292
|
+
if ("equals" in value) {
|
|
293
|
+
requireExactKeys(value, ["column", "equals"], label);
|
|
294
|
+
return csv.column(column).equals(requireString(value.equals, `${label}.equals`));
|
|
295
|
+
}
|
|
296
|
+
if ("in" in value) {
|
|
297
|
+
requireExactKeys(value, ["column", "in"], label);
|
|
298
|
+
if (!Array.isArray(value.in) || value.in.length === 0)
|
|
299
|
+
throw Error(`${label}.in must be a non-empty string array`);
|
|
300
|
+
return csv.column(column).isOneOf(value.in.map((item, index) => requireString(item, `${label}.in[${String(index)}]`)));
|
|
301
|
+
}
|
|
302
|
+
if ("notEquals" in value) {
|
|
303
|
+
requireExactKeys(value, ["column", "notEquals"], label);
|
|
304
|
+
return csv.column(column).doesNotEqual(requireString(value.notEquals, `${label}.notEquals`));
|
|
305
|
+
}
|
|
306
|
+
if ("notIn" in value) {
|
|
307
|
+
requireExactKeys(value, ["column", "notIn"], label);
|
|
308
|
+
if (!Array.isArray(value.notIn) || value.notIn.length === 0)
|
|
309
|
+
throw Error(`${label}.notIn must be a non-empty string array`);
|
|
310
|
+
return csv.column(column).isNoneOf(value.notIn.map((item, index) => requireString(item, `${label}.notIn[${String(index)}]`)));
|
|
311
|
+
}
|
|
312
|
+
if ("startsWith" in value) {
|
|
313
|
+
requireExactKeys(value, ["column", "startsWith"], label);
|
|
314
|
+
return csv.column(column).startsWith(requireString(value.startsWith, `${label}.startsWith`));
|
|
315
|
+
}
|
|
316
|
+
if ("regex" in value) {
|
|
317
|
+
requireExactKeys(value, ["column", "regex"], label);
|
|
318
|
+
if (!isObject(value.regex))
|
|
319
|
+
throw Error(`${label}.regex must contain source and optional flags strings`);
|
|
320
|
+
requireExactKeys(value.regex, ["source", "flags"], `${label}.regex`, !0);
|
|
321
|
+
const source = requireString(value.regex.source, `${label}.regex.source`);
|
|
322
|
+
const flags = value.regex.flags === void 0 ? "" : requireString(value.regex.flags, `${label}.regex.flags`);
|
|
323
|
+
return csv.column(column).hasMatch(new RegExp(source, flags));
|
|
324
|
+
}
|
|
325
|
+
throw Error(`${label} must contain equals, in, notEquals, notIn, startsWith, or regex`);
|
|
326
|
+
}
|
|
327
|
+
function isObject(value) {
|
|
328
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
329
|
+
}
|
|
330
|
+
function requireString(value, label) {
|
|
331
|
+
if (typeof value !== "string")
|
|
332
|
+
throw Error(`${label} must be a string`);
|
|
333
|
+
return value;
|
|
334
|
+
}
|
|
335
|
+
function requireExactKeys(value, allowedKeys, label, allowMissing = !1) {
|
|
336
|
+
const keys = Object.keys(value);
|
|
337
|
+
const unknownKey = keys.find((key) => !allowedKeys.includes(key));
|
|
338
|
+
if (unknownKey !== void 0)
|
|
339
|
+
throw Error(`${label} contains unknown property: ${unknownKey}`);
|
|
340
|
+
if (!allowMissing) {
|
|
341
|
+
const missingKey = allowedKeys.find((key) => !Object.hasOwn(value, key));
|
|
342
|
+
if (missingKey !== void 0)
|
|
343
|
+
throw Error(`${label} is missing property: ${missingKey}`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
function usageError(output, message, helpCommand) {
|
|
347
|
+
output.error(`csv: ${message}
|
|
348
|
+
Run '${helpCommand}' for usage.`);
|
|
349
|
+
return 2;
|
|
350
|
+
}
|