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