@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/cli.js
CHANGED
|
@@ -1,605 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
normalizeColumns,
|
|
6
|
-
normalizeFilterColumn,
|
|
7
|
-
normalizeFixedColumnsCount
|
|
8
|
-
} from "./normalize.js";
|
|
9
|
-
const help = `Usage: csv <command>
|
|
10
|
-
|
|
11
|
-
Commands:
|
|
12
|
-
count <path> [options] Count CSV records
|
|
13
|
-
lines <path> [options] Stream matching CSV records to stdout
|
|
14
|
-
|
|
15
|
-
Options:
|
|
16
|
-
-h, --help Show this help
|
|
17
|
-
|
|
18
|
-
Run 'csv <command> --help' for command options.
|
|
19
|
-
|
|
20
|
-
Run without installing:
|
|
21
|
-
bunx @konstit/csv <command> <path>`;
|
|
22
|
-
const countHelp = `Usage: csv count <path> [options]
|
|
23
|
-
|
|
24
|
-
Count every CSV record, including the header row.
|
|
25
|
-
|
|
26
|
-
File options:
|
|
27
|
-
--delimiter <value> One safe ASCII character or auto (default: ,)
|
|
28
|
-
--encoding <value> utf8, latin1, iso88591, or iso-8859-1 (default: utf8)
|
|
29
|
-
--chunk-size <bytes> Integer from 1 through 67108864 (default: 1048576)
|
|
30
|
-
--compression <format> auto, gzip, deflate, deflate-raw, brotli, zstd, or zip (default: none)
|
|
31
|
-
--zip-entry <path> Entry used with --compression zip
|
|
32
|
-
--max-compression-ratio <ratio> ZIP expansion ratio integer from 1 through 4294967295
|
|
33
|
-
--max-decompressed-bytes <bytes> Positive ZIP output byte limit
|
|
34
|
-
|
|
35
|
-
Parser options:
|
|
36
|
-
--strict Enable strict RFC 4180 validation
|
|
37
|
-
--fixed-columns <count> Require this positive field count in strict mode
|
|
38
|
-
--columns <indexes> Validate indexes; does not change the count
|
|
39
|
-
--selected-columns <indexes> Alias for --columns; do not use both
|
|
40
|
-
--expected-header <value> Expected header; repeat per column; requires --strict
|
|
41
|
-
--require-header Require a header row; requires --strict
|
|
42
|
-
--min-data-rows <count> Require a non-negative data row count; requires --strict
|
|
43
|
-
|
|
44
|
-
Friendly filter options (repeatable):
|
|
45
|
-
--where-eq <column=value> Match one exact value
|
|
46
|
-
--where-in <column=value> Add a value to a column IN filter
|
|
47
|
-
--where-neq <column=value> Exclude one exact value
|
|
48
|
-
--where-noin <column=value> Add a value to a column NOT IN filter
|
|
49
|
-
--where-prefix <column=value> Match a value prefix
|
|
50
|
-
--where-regex <column=/re/flags> Match an RE2-compatible JavaScript regex
|
|
51
|
-
|
|
52
|
-
Advanced filter option:
|
|
53
|
-
--where <json> Advanced filter JSON
|
|
54
|
-
|
|
55
|
-
Friendly filter clauses use AND. Repeated --where-in and --where-noin clauses for
|
|
56
|
-
the same column form one filter. Advanced JSON can nest all, any, and not.
|
|
57
|
-
Quote values that contain spaces or shell characters. Regex flags can be i, m, s, and u.
|
|
58
|
-
|
|
59
|
-
Compatibility:
|
|
60
|
-
Strict mode cannot use filter options.
|
|
61
|
-
--fixed-columns and schema options require --strict.
|
|
62
|
-
ZIP options require --compression zip and --zip-entry.
|
|
63
|
-
|
|
64
|
-
Examples:
|
|
65
|
-
csv count data.csv --delimiter ';' --chunk-size 262144
|
|
66
|
-
csv count data.csv --where-eq 2=SP
|
|
67
|
-
csv count data.csv --where-neq 2=SP
|
|
68
|
-
csv count data.csv --where-in 2=SP --where-in 2=RJ --where-prefix 1=A
|
|
69
|
-
csv count data.csv --where-regex '1=/^ana/i'`;
|
|
70
|
-
const linesHelp = `Usage: csv lines <path> [options]
|
|
71
|
-
|
|
72
|
-
Parse a CSV file and stream matching records as normalized UTF-8 CSV or NDJSON.
|
|
73
|
-
CSV output uses comma delimiters and LF record endings by default.
|
|
74
|
-
|
|
75
|
-
File options:
|
|
76
|
-
--delimiter <value> Input delimiter: one safe ASCII character or auto (default: ,)
|
|
77
|
-
--encoding <value> utf8, latin1, iso88591, or iso-8859-1 (default: utf8)
|
|
78
|
-
--chunk-size <bytes> Integer from 1 through 67108864 (default: 1048576)
|
|
79
|
-
--compression <format> auto, gzip, deflate, deflate-raw, brotli, zstd, or zip (default: none)
|
|
80
|
-
--zip-entry <path> Entry used with --compression zip
|
|
81
|
-
--max-compression-ratio <ratio> ZIP expansion ratio integer from 1 through 4294967295
|
|
82
|
-
--max-decompressed-bytes <bytes> Positive ZIP output byte limit
|
|
83
|
-
|
|
84
|
-
Output options:
|
|
85
|
-
--json Emit one JSON string array per record (NDJSON)
|
|
86
|
-
--output-delimiter <value> One safe ASCII output delimiter (default: ,)
|
|
87
|
-
--limit <N> Stop after matching output record N, numbered from 1
|
|
88
|
-
|
|
89
|
-
Parser options:
|
|
90
|
-
--strict Enable strict RFC 4180 validation
|
|
91
|
-
--fixed-columns <count> Require this positive field count in strict mode
|
|
92
|
-
--columns <indexes> Select zero-based input columns and output order
|
|
93
|
-
--selected-columns <indexes> Alias for --columns; do not use both
|
|
94
|
-
--expected-header <value> Expected header; repeat per column; requires --strict
|
|
95
|
-
--require-header Require a header row; requires --strict
|
|
96
|
-
--min-data-rows <count> Require a non-negative data row count; requires --strict
|
|
97
|
-
|
|
98
|
-
Friendly filter options (repeatable):
|
|
99
|
-
--where-eq <column=value> Match one exact value
|
|
100
|
-
--where-in <column=value> Add a value to a column IN filter
|
|
101
|
-
--where-neq <column=value> Exclude one exact value
|
|
102
|
-
--where-noin <column=value> Add a value to a column NOT IN filter
|
|
103
|
-
--where-prefix <column=value> Match a value prefix
|
|
104
|
-
--where-regex <column=/re/flags> Match an RE2-compatible JavaScript regex
|
|
105
|
-
|
|
106
|
-
Advanced filter option:
|
|
107
|
-
--where <json> Advanced filter JSON
|
|
108
|
-
|
|
109
|
-
Filters use original input column indexes. Friendly filter clauses use AND.
|
|
110
|
-
Repeated --where-in and --where-noin clauses for the same column form one filter.
|
|
111
|
-
Advanced JSON can nest all, any, and not. Quote values that contain spaces or
|
|
112
|
-
shell characters. Regex flags can be i, m, s, and u.
|
|
113
|
-
|
|
114
|
-
CSV output is normalized and can differ from the input quoting, delimiter, and
|
|
115
|
-
record endings. With --json, stdout contains only NDJSON string arrays. A quoted
|
|
116
|
-
field can contain physical newlines. With --strict and --limit, validation stops
|
|
117
|
-
at the selected record and uses one-byte input chunks. Partial output can exist
|
|
118
|
-
if a later input error occurs.
|
|
119
|
-
|
|
120
|
-
Compatibility:
|
|
121
|
-
Strict mode cannot use filter options.
|
|
122
|
-
--fixed-columns and schema options require --strict.
|
|
123
|
-
--json cannot be combined with --output-delimiter.
|
|
124
|
-
--limit cannot be combined with --min-data-rows.
|
|
125
|
-
--strict with --limit requires a fixed delimiter and uses --chunk-size 1.
|
|
126
|
-
--strict with --limit cannot use --compression, including auto.
|
|
127
|
-
ZIP options require --compression zip and --zip-entry.
|
|
128
|
-
|
|
129
|
-
Examples:
|
|
130
|
-
csv lines data.csv
|
|
131
|
-
csv lines data.csv --json --limit 10
|
|
132
|
-
csv lines input.tsv --delimiter $'\\t' --output-delimiter ','
|
|
133
|
-
csv lines data.csv --columns 0,2 --where-eq 3=active --limit 10
|
|
134
|
-
csv lines data.csv.gz --compression auto > selected.csv`;
|
|
135
|
-
const countOptionDefinitions = {
|
|
136
|
-
columns: { type: "string" },
|
|
137
|
-
compression: { type: "string" },
|
|
138
|
-
delimiter: { type: "string" },
|
|
139
|
-
encoding: { type: "string" },
|
|
140
|
-
"chunk-size": { type: "string" },
|
|
141
|
-
"expected-header": { multiple: !0, type: "string" },
|
|
142
|
-
"fixed-columns": { type: "string" },
|
|
143
|
-
help: { short: "h", type: "boolean" },
|
|
144
|
-
"max-compression-ratio": { type: "string" },
|
|
145
|
-
"max-decompressed-bytes": { type: "string" },
|
|
146
|
-
"min-data-rows": { type: "string" },
|
|
147
|
-
"require-header": { type: "boolean" },
|
|
148
|
-
"selected-columns": { type: "string" },
|
|
149
|
-
strict: { type: "boolean" },
|
|
150
|
-
where: { type: "string" },
|
|
151
|
-
"where-eq": { multiple: !0, type: "string" },
|
|
152
|
-
"where-in": { multiple: !0, type: "string" },
|
|
153
|
-
"where-neq": { multiple: !0, type: "string" },
|
|
154
|
-
"where-noin": { multiple: !0, type: "string" },
|
|
155
|
-
"where-prefix": { multiple: !0, type: "string" },
|
|
156
|
-
"where-regex": { multiple: !0, type: "string" },
|
|
157
|
-
"zip-entry": { type: "string" }
|
|
158
|
-
};
|
|
159
|
-
const linesOptionDefinitions = {
|
|
160
|
-
...countOptionDefinitions,
|
|
161
|
-
json: { type: "boolean" },
|
|
162
|
-
limit: { type: "string" },
|
|
163
|
-
"output-delimiter": { type: "string" }
|
|
164
|
-
};
|
|
165
|
-
const compressionFormats = new Set(["auto", "gzip", "deflate", "deflate-raw", "brotli", "zstd"]);
|
|
166
|
-
const encodings = new Set(["utf8", "latin1", "iso88591", "iso-8859-1"]);
|
|
167
|
-
const MAX_CHUNK_SIZE = 67108864;
|
|
168
|
-
const MAX_FILTER_NESTING = 128;
|
|
169
|
-
const OUTPUT_BUFFER_SIZE = 65536;
|
|
170
|
-
async function run(arguments_) {
|
|
171
|
-
const command = arguments_[0];
|
|
172
|
-
if (command === "-h" || command === "--help") {
|
|
173
|
-
console.log(help);
|
|
174
|
-
return 0;
|
|
175
|
-
}
|
|
176
|
-
if (command === void 0)
|
|
177
|
-
return usageError("missing command");
|
|
178
|
-
if (command === "count")
|
|
179
|
-
return runCount(arguments_.slice(1));
|
|
180
|
-
if (command === "lines")
|
|
181
|
-
return runLines(arguments_.slice(1));
|
|
182
|
-
return usageError(`unknown command: ${command}`);
|
|
183
|
-
}
|
|
184
|
-
async function runCount(arguments_) {
|
|
185
|
-
let input;
|
|
186
|
-
try {
|
|
187
|
-
input = parseCountInput(arguments_);
|
|
188
|
-
} catch (error) {
|
|
189
|
-
return usageError(error instanceof Error ? error.message : String(error), "csv count --help");
|
|
190
|
-
}
|
|
191
|
-
if (input.help) {
|
|
192
|
-
console.log(countHelp);
|
|
193
|
-
return 0;
|
|
194
|
-
}
|
|
195
|
-
try {
|
|
196
|
-
console.log(await csv.count(input.path, input.options));
|
|
197
|
-
return 0;
|
|
198
|
-
} catch (error) {
|
|
199
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
200
|
-
console.error(`csv: ${message}`);
|
|
201
|
-
return 1;
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
async function runLines(arguments_) {
|
|
205
|
-
let input;
|
|
206
|
-
try {
|
|
207
|
-
input = parseLinesInput(arguments_);
|
|
208
|
-
} catch (error) {
|
|
209
|
-
return usageError(error instanceof Error ? error.message : String(error), "csv lines --help");
|
|
210
|
-
}
|
|
211
|
-
if (input.help) {
|
|
212
|
-
console.log(linesHelp);
|
|
213
|
-
return 0;
|
|
214
|
-
}
|
|
215
|
-
try {
|
|
216
|
-
await streamLines(input);
|
|
217
|
-
return 0;
|
|
218
|
-
} catch (error) {
|
|
219
|
-
if (isBrokenPipe(error))
|
|
220
|
-
return 0;
|
|
221
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
222
|
-
console.error(`csv: ${message}`);
|
|
223
|
-
return 1;
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
function parseCountInput(arguments_) {
|
|
227
|
-
const { positionals, values } = parseArgs({
|
|
228
|
-
allowPositionals: !0,
|
|
229
|
-
args: [...arguments_],
|
|
230
|
-
options: countOptionDefinitions,
|
|
231
|
-
strict: !0
|
|
232
|
-
});
|
|
233
|
-
if (values.help === !0)
|
|
234
|
-
return { help: !0, options: {}, path: "" };
|
|
235
|
-
if (positionals.length !== 1)
|
|
236
|
-
throw Error("count requires one file path");
|
|
237
|
-
const options = parseCommonOptions(values);
|
|
238
|
-
if (!isCountOptions(options))
|
|
239
|
-
throw Error("count options are incompatible");
|
|
240
|
-
return { help: !1, options, path: positionals[0] ?? "" };
|
|
241
|
-
}
|
|
242
|
-
function parseLinesInput(arguments_) {
|
|
243
|
-
const { positionals, values } = parseArgs({
|
|
244
|
-
allowPositionals: !0,
|
|
245
|
-
args: [...arguments_],
|
|
246
|
-
options: linesOptionDefinitions,
|
|
247
|
-
strict: !0
|
|
248
|
-
});
|
|
249
|
-
if (values.help === !0)
|
|
250
|
-
return { help: !0, json: !1, options: {}, outputDelimiter: ",", path: "" };
|
|
251
|
-
if (positionals.length !== 1)
|
|
252
|
-
throw Error("lines requires one file path");
|
|
253
|
-
const options = parseCommonOptions(values);
|
|
254
|
-
const limit = values.limit === void 0 ? void 0 : parseInteger(values.limit, "limit", 1);
|
|
255
|
-
if (limit !== void 0 && options.minDataRows !== void 0)
|
|
256
|
-
throw Error("--limit cannot be combined with --min-data-rows");
|
|
257
|
-
if (limit !== void 0 && options.strict === !0) {
|
|
258
|
-
if (options.compression !== void 0)
|
|
259
|
-
throw Error("--strict with --limit does not support compressed input");
|
|
260
|
-
if (options.delimiter === "auto")
|
|
261
|
-
throw Error("--strict with --limit requires a fixed input delimiter");
|
|
262
|
-
if (options.chunkSize !== void 0 && options.chunkSize !== 1)
|
|
263
|
-
throw Error("--strict with --limit requires --chunk-size 1");
|
|
264
|
-
options.chunkSize = 1;
|
|
265
|
-
}
|
|
266
|
-
if (!isRowsOptions(options))
|
|
267
|
-
throw Error("lines options are incompatible");
|
|
268
|
-
const json = values.json === !0;
|
|
269
|
-
if (json && values["output-delimiter"] !== void 0)
|
|
270
|
-
throw Error("--json cannot be combined with --output-delimiter");
|
|
271
|
-
const outputDelimiter = values["output-delimiter"] === void 0 ? "," : parseOutputDelimiter(values["output-delimiter"]);
|
|
272
|
-
return {
|
|
273
|
-
help: !1,
|
|
274
|
-
json,
|
|
275
|
-
...limit === void 0 ? {} : { limit },
|
|
276
|
-
options,
|
|
277
|
-
outputDelimiter,
|
|
278
|
-
path: positionals[0] ?? ""
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
function parseCommonOptions(values) {
|
|
282
|
-
const options = {};
|
|
283
|
-
if (values.delimiter !== void 0)
|
|
284
|
-
options.delimiter = parseDelimiter(values.delimiter);
|
|
285
|
-
if (values.encoding !== void 0)
|
|
286
|
-
options.encoding = parseEncoding(values.encoding);
|
|
287
|
-
if (values["chunk-size"] !== void 0)
|
|
288
|
-
options.chunkSize = parseInteger(values["chunk-size"], "chunk size", 1, MAX_CHUNK_SIZE);
|
|
289
|
-
if (values.strict === !0)
|
|
290
|
-
options.strict = !0;
|
|
291
|
-
if (values["fixed-columns"] !== void 0) {
|
|
292
|
-
options.fixedColumns = parseInteger(values["fixed-columns"], "fixed columns", 1);
|
|
293
|
-
normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
|
|
294
|
-
}
|
|
295
|
-
if (values.columns !== void 0)
|
|
296
|
-
options.columns = parseColumns(values.columns, "columns");
|
|
297
|
-
if (values["selected-columns"] !== void 0)
|
|
298
|
-
options.selectedColumns = parseColumns(values["selected-columns"], "selected columns");
|
|
299
|
-
if (options.columns !== void 0 && options.selectedColumns !== void 0)
|
|
300
|
-
throw Error("use --columns or --selected-columns, not both");
|
|
301
|
-
if (values["expected-header"] !== void 0)
|
|
302
|
-
options.expectedHeaders = values["expected-header"];
|
|
303
|
-
if (values["require-header"] === !0)
|
|
304
|
-
options.requireHeader = !0;
|
|
305
|
-
if (values["min-data-rows"] !== void 0)
|
|
306
|
-
options.minDataRows = parseInteger(values["min-data-rows"], "minimum data rows", 0);
|
|
307
|
-
options.where = parseWhereOptions(values);
|
|
308
|
-
options.compression = parseCompression(values);
|
|
309
|
-
validateCountOptionCombinations(options);
|
|
310
|
-
return options;
|
|
311
|
-
}
|
|
312
|
-
function parseDelimiter(value) {
|
|
313
|
-
if (value === "auto")
|
|
314
|
-
return value;
|
|
315
|
-
if (value.length !== 1 || value.charCodeAt(0) > 127 || value === '"' || value === "\r" || value === `
|
|
316
|
-
`)
|
|
317
|
-
throw Error(`delimiter must be one safe ASCII character or auto: ${JSON.stringify(value)}`);
|
|
318
|
-
return value;
|
|
319
|
-
}
|
|
320
|
-
function parseOutputDelimiter(value) {
|
|
321
|
-
const delimiter = parseDelimiter(value);
|
|
322
|
-
if (delimiter === "auto")
|
|
323
|
-
throw Error("output delimiter must be one safe ASCII character; auto is not supported");
|
|
324
|
-
return delimiter;
|
|
325
|
-
}
|
|
326
|
-
function parseEncoding(value) {
|
|
327
|
-
if (!encodings.has(value))
|
|
328
|
-
throw Error(`unsupported encoding: ${value}`);
|
|
329
|
-
return value;
|
|
330
|
-
}
|
|
331
|
-
function parseInteger(value, label, minimum, maximum = Number.MAX_SAFE_INTEGER) {
|
|
332
|
-
const number = Number(value);
|
|
333
|
-
if (!Number.isSafeInteger(number) || number < minimum || number > maximum) {
|
|
334
|
-
const range = maximum === Number.MAX_SAFE_INTEGER ? `greater than or equal to ${String(minimum)}` : `from ${String(minimum)} through ${String(maximum)}`;
|
|
335
|
-
throw Error(`${label} must be an integer ${range}: ${value}`);
|
|
336
|
-
}
|
|
337
|
-
return number;
|
|
338
|
-
}
|
|
339
|
-
function parseColumns(value, label) {
|
|
340
|
-
const columns = value.length === 0 ? [] : value.split(",").map((column) => parseInteger(column, label, 0));
|
|
341
|
-
normalizeColumns(columns);
|
|
342
|
-
return columns;
|
|
343
|
-
}
|
|
344
|
-
function parseCompression(values) {
|
|
345
|
-
const compression = values.compression;
|
|
346
|
-
const zipEntry = values["zip-entry"];
|
|
347
|
-
const maxCompressionRatio = values["max-compression-ratio"];
|
|
348
|
-
const maxDecompressedBytes = values["max-decompressed-bytes"];
|
|
349
|
-
if (typeof compression !== "string") {
|
|
350
|
-
if (zipEntry !== void 0 || maxCompressionRatio !== void 0 || maxDecompressedBytes !== void 0)
|
|
351
|
-
throw Error("ZIP options require --compression zip");
|
|
352
|
-
return;
|
|
353
|
-
}
|
|
354
|
-
if (compression !== "zip") {
|
|
355
|
-
if (!compressionFormats.has(compression))
|
|
356
|
-
throw Error(`unsupported compression format: ${compression}`);
|
|
357
|
-
if (zipEntry !== void 0 || maxCompressionRatio !== void 0 || maxDecompressedBytes !== void 0)
|
|
358
|
-
throw Error("ZIP options require --compression zip");
|
|
359
|
-
return compression;
|
|
360
|
-
}
|
|
361
|
-
if (typeof zipEntry !== "string" || zipEntry.length === 0)
|
|
362
|
-
throw Error("--compression zip requires --zip-entry <path>");
|
|
363
|
-
return {
|
|
364
|
-
entry: zipEntry,
|
|
365
|
-
format: "zip",
|
|
366
|
-
...typeof maxCompressionRatio === "string" ? { maxCompressionRatio: parseUint32(maxCompressionRatio, "maximum compression ratio") } : {},
|
|
367
|
-
...typeof maxDecompressedBytes === "string" ? { maxDecompressedBytes: parseInteger(maxDecompressedBytes, "maximum decompressed bytes", 1) } : {}
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
function validateCountOptionCombinations(options) {
|
|
371
|
-
const hasStrictSchemaOptions = options.expectedHeaders !== void 0 || options.requireHeader === !0 || options.minDataRows !== void 0;
|
|
372
|
-
if (hasStrictSchemaOptions && options.strict !== !0)
|
|
373
|
-
throw Error("--expected-header, --require-header, and --min-data-rows require --strict");
|
|
374
|
-
if (options.fixedColumns !== void 0 && options.strict !== !0)
|
|
375
|
-
throw Error("--fixed-columns requires --strict");
|
|
376
|
-
if (options.strict === !0 && options.where !== void 0)
|
|
377
|
-
throw Error("--strict cannot be combined with filter options");
|
|
378
|
-
}
|
|
379
|
-
function isCountOptions(options) {
|
|
380
|
-
if (options.columns !== void 0 && options.selectedColumns !== void 0)
|
|
381
|
-
return !1;
|
|
382
|
-
return options.strict !== !0 || options.where === void 0;
|
|
383
|
-
}
|
|
384
|
-
function isRowsOptions(options) {
|
|
385
|
-
if (options.columns !== void 0 && options.selectedColumns !== void 0)
|
|
386
|
-
return !1;
|
|
387
|
-
if (options.workerCount !== void 0 && options.workerCount !== 1)
|
|
388
|
-
return !1;
|
|
389
|
-
return options.strict !== !0 || options.where === void 0;
|
|
390
|
-
}
|
|
391
|
-
async function streamLines(input) {
|
|
392
|
-
let chunks = [];
|
|
393
|
-
let chunksLength = 0;
|
|
394
|
-
let emitted = 0;
|
|
395
|
-
output:
|
|
396
|
-
for await (const rows of csv.rows(input.path, input.options)) {
|
|
397
|
-
for (const row of rows) {
|
|
398
|
-
const record = input.json ? `${JSON.stringify(row)}
|
|
399
|
-
` : serializeCsvRecord(row, input.outputDelimiter);
|
|
400
|
-
chunks.push(record);
|
|
401
|
-
chunksLength += record.length;
|
|
402
|
-
++emitted;
|
|
403
|
-
if (chunksLength >= OUTPUT_BUFFER_SIZE) {
|
|
404
|
-
await Bun.write(Bun.stdout, chunks.join(""));
|
|
405
|
-
chunks = [];
|
|
406
|
-
chunksLength = 0;
|
|
407
|
-
}
|
|
408
|
-
if (emitted === input.limit)
|
|
409
|
-
break output;
|
|
410
|
-
}
|
|
411
|
-
if (chunksLength > 0) {
|
|
412
|
-
await Bun.write(Bun.stdout, chunks.join(""));
|
|
413
|
-
chunks = [];
|
|
414
|
-
chunksLength = 0;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
if (chunksLength > 0)
|
|
418
|
-
await Bun.write(Bun.stdout, chunks.join(""));
|
|
419
|
-
}
|
|
420
|
-
function serializeCsvRecord(row, delimiter) {
|
|
421
|
-
return `${row.map((field) => serializeCsvField(field, delimiter)).join(delimiter)}
|
|
422
|
-
`;
|
|
423
|
-
}
|
|
424
|
-
function serializeCsvField(field, delimiter) {
|
|
425
|
-
if (!field.includes(delimiter) && !field.includes('"') && !field.includes("\r") && !field.includes(`
|
|
426
|
-
`))
|
|
427
|
-
return field;
|
|
428
|
-
return `"${field.replaceAll('"', '""')}"`;
|
|
429
|
-
}
|
|
430
|
-
function isBrokenPipe(error) {
|
|
431
|
-
return isObject(error) && error.code === "EPIPE";
|
|
432
|
-
}
|
|
433
|
-
function parseUint32(value, label) {
|
|
434
|
-
const number = Number(value);
|
|
435
|
-
if (!Number.isInteger(number) || number <= 0 || number > 4294967295)
|
|
436
|
-
throw Error(`${label} must be an integer from 1 through 4294967295: ${value}`);
|
|
437
|
-
return number;
|
|
438
|
-
}
|
|
439
|
-
function parseWhereOptions(values) {
|
|
440
|
-
const filters = [];
|
|
441
|
-
if (values.where !== void 0)
|
|
442
|
-
filters.push(parseWhereJson(values.where));
|
|
443
|
-
for (const expression of values["where-eq"] ?? []) {
|
|
444
|
-
const { column, value } = parseColumnValue(expression, "--where-eq");
|
|
445
|
-
filters.push(csv.column(column).equals(value));
|
|
446
|
-
}
|
|
447
|
-
for (const expression of values["where-neq"] ?? []) {
|
|
448
|
-
const { column, value } = parseColumnValue(expression, "--where-neq");
|
|
449
|
-
filters.push(csv.column(column).doesNotEqual(value));
|
|
450
|
-
}
|
|
451
|
-
const inValuesByColumn = new Map;
|
|
452
|
-
for (const expression of values["where-in"] ?? []) {
|
|
453
|
-
const { column, value } = parseColumnValue(expression, "--where-in");
|
|
454
|
-
const columnValues = inValuesByColumn.get(column);
|
|
455
|
-
if (columnValues === void 0)
|
|
456
|
-
inValuesByColumn.set(column, [value]);
|
|
457
|
-
else
|
|
458
|
-
columnValues.push(value);
|
|
459
|
-
}
|
|
460
|
-
for (const [column, inValues] of inValuesByColumn)
|
|
461
|
-
filters.push(csv.column(column).isOneOf(inValues));
|
|
462
|
-
const notInValuesByColumn = new Map;
|
|
463
|
-
for (const expression of values["where-noin"] ?? []) {
|
|
464
|
-
const { column, value } = parseColumnValue(expression, "--where-noin");
|
|
465
|
-
const columnValues = notInValuesByColumn.get(column);
|
|
466
|
-
if (columnValues === void 0)
|
|
467
|
-
notInValuesByColumn.set(column, [value]);
|
|
468
|
-
else
|
|
469
|
-
columnValues.push(value);
|
|
470
|
-
}
|
|
471
|
-
for (const [column, notInValues] of notInValuesByColumn)
|
|
472
|
-
filters.push(csv.column(column).isNoneOf(notInValues));
|
|
473
|
-
for (const expression of values["where-prefix"] ?? []) {
|
|
474
|
-
const { column, value } = parseColumnValue(expression, "--where-prefix");
|
|
475
|
-
filters.push(csv.column(column).startsWith(value));
|
|
476
|
-
}
|
|
477
|
-
for (const expression of values["where-regex"] ?? [])
|
|
478
|
-
filters.push(parseRegexExpression(expression));
|
|
479
|
-
const first = filters[0];
|
|
480
|
-
if (first === void 0)
|
|
481
|
-
return;
|
|
482
|
-
return filters.length === 1 ? first : csv.all(first, ...filters.slice(1));
|
|
483
|
-
}
|
|
484
|
-
function parseColumnValue(expression, option) {
|
|
485
|
-
const separator = expression.indexOf("=");
|
|
486
|
-
if (separator <= 0)
|
|
487
|
-
throw Error(`${option} must use <column>=<value>: ${JSON.stringify(expression)}`);
|
|
488
|
-
const column = parseInteger(expression.slice(0, separator), `${option} column`, 0);
|
|
489
|
-
normalizeFilterColumn(column);
|
|
490
|
-
return { column, value: expression.slice(separator + 1) };
|
|
491
|
-
}
|
|
492
|
-
function parseRegexExpression(expression) {
|
|
493
|
-
const { column, value } = parseColumnValue(expression, "--where-regex");
|
|
494
|
-
const closingSlash = value.lastIndexOf("/");
|
|
495
|
-
if (!value.startsWith("/") || closingSlash === 0)
|
|
496
|
-
throw Error(`--where-regex must use <column>=/<pattern>/<flags>: ${JSON.stringify(expression)}`);
|
|
497
|
-
const source = value.slice(1, closingSlash);
|
|
498
|
-
const flags = value.slice(closingSlash + 1);
|
|
499
|
-
return csv.column(column).hasMatch(new RegExp(source, flags));
|
|
500
|
-
}
|
|
501
|
-
function parseWhereJson(value) {
|
|
502
|
-
let parsed;
|
|
503
|
-
try {
|
|
504
|
-
parsed = JSON.parse(value);
|
|
505
|
-
} catch (error) {
|
|
506
|
-
throw Error(`--where must be valid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
507
|
-
}
|
|
508
|
-
return parseWhereFilter(parsed, "--where");
|
|
509
|
-
}
|
|
510
|
-
function parseWhereFilter(value, label, depth = 0) {
|
|
511
|
-
if (depth > MAX_FILTER_NESTING)
|
|
512
|
-
throw Error(`--where nesting exceeds ${MAX_FILTER_NESTING}`);
|
|
513
|
-
if (!isObject(value))
|
|
514
|
-
throw Error(`${label} must be a JSON object`);
|
|
515
|
-
if ("all" in value) {
|
|
516
|
-
requireExactKeys(value, ["all"], label);
|
|
517
|
-
return parseWhereGroup(value.all, `${label}.all`, csv.all, depth);
|
|
518
|
-
}
|
|
519
|
-
if ("any" in value) {
|
|
520
|
-
requireExactKeys(value, ["any"], label);
|
|
521
|
-
return parseWhereGroup(value.any, `${label}.any`, csv.any, depth);
|
|
522
|
-
}
|
|
523
|
-
if ("not" in value) {
|
|
524
|
-
requireExactKeys(value, ["not"], label);
|
|
525
|
-
return csv.not(parseWhereFilter(value.not, `${label}.not`, depth + 1));
|
|
526
|
-
}
|
|
527
|
-
return parseWherePredicate(value, label);
|
|
528
|
-
}
|
|
529
|
-
function parseWhereGroup(value, label, combine, depth) {
|
|
530
|
-
if (!Array.isArray(value) || value.length === 0)
|
|
531
|
-
throw Error(`${label} must be a non-empty array`);
|
|
532
|
-
const filters = value.map((filter, index) => parseWhereFilter(filter, `${label}[${String(index)}]`, depth + 1));
|
|
533
|
-
const first = filters[0];
|
|
534
|
-
if (first === void 0)
|
|
535
|
-
throw Error(`${label} must be a non-empty array`);
|
|
536
|
-
return combine(first, ...filters.slice(1));
|
|
537
|
-
}
|
|
538
|
-
function parseWherePredicate(value, label) {
|
|
539
|
-
if (!isObject(value))
|
|
540
|
-
throw Error(`${label} must be an object`);
|
|
541
|
-
const column = value.column;
|
|
542
|
-
if (typeof column !== "number")
|
|
543
|
-
throw Error(`${label}.column must be a number`);
|
|
544
|
-
normalizeFilterColumn(column);
|
|
545
|
-
if ("equals" in value) {
|
|
546
|
-
requireExactKeys(value, ["column", "equals"], label);
|
|
547
|
-
return csv.column(column).equals(requireString(value.equals, `${label}.equals`));
|
|
548
|
-
}
|
|
549
|
-
if ("in" in value) {
|
|
550
|
-
requireExactKeys(value, ["column", "in"], label);
|
|
551
|
-
if (!Array.isArray(value.in) || value.in.length === 0)
|
|
552
|
-
throw Error(`${label}.in must be a non-empty string array`);
|
|
553
|
-
return csv.column(column).isOneOf(value.in.map((item, index) => requireString(item, `${label}.in[${String(index)}]`)));
|
|
554
|
-
}
|
|
555
|
-
if ("notEquals" in value) {
|
|
556
|
-
requireExactKeys(value, ["column", "notEquals"], label);
|
|
557
|
-
return csv.column(column).doesNotEqual(requireString(value.notEquals, `${label}.notEquals`));
|
|
558
|
-
}
|
|
559
|
-
if ("notIn" in value) {
|
|
560
|
-
requireExactKeys(value, ["column", "notIn"], label);
|
|
561
|
-
if (!Array.isArray(value.notIn) || value.notIn.length === 0)
|
|
562
|
-
throw Error(`${label}.notIn must be a non-empty string array`);
|
|
563
|
-
return csv.column(column).isNoneOf(value.notIn.map((item, index) => requireString(item, `${label}.notIn[${String(index)}]`)));
|
|
564
|
-
}
|
|
565
|
-
if ("startsWith" in value) {
|
|
566
|
-
requireExactKeys(value, ["column", "startsWith"], label);
|
|
567
|
-
return csv.column(column).startsWith(requireString(value.startsWith, `${label}.startsWith`));
|
|
568
|
-
}
|
|
569
|
-
if ("regex" in value) {
|
|
570
|
-
requireExactKeys(value, ["column", "regex"], label);
|
|
571
|
-
if (!isObject(value.regex))
|
|
572
|
-
throw Error(`${label}.regex must contain source and optional flags strings`);
|
|
573
|
-
requireExactKeys(value.regex, ["source", "flags"], `${label}.regex`, !0);
|
|
574
|
-
const source = requireString(value.regex.source, `${label}.regex.source`);
|
|
575
|
-
const flags = value.regex.flags === void 0 ? "" : requireString(value.regex.flags, `${label}.regex.flags`);
|
|
576
|
-
return csv.column(column).hasMatch(new RegExp(source, flags));
|
|
577
|
-
}
|
|
578
|
-
throw Error(`${label} must contain equals, in, notEquals, notIn, startsWith, or regex`);
|
|
579
|
-
}
|
|
580
|
-
function isObject(value) {
|
|
581
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
582
|
-
}
|
|
583
|
-
function requireString(value, label) {
|
|
584
|
-
if (typeof value !== "string")
|
|
585
|
-
throw Error(`${label} must be a string`);
|
|
586
|
-
return value;
|
|
587
|
-
}
|
|
588
|
-
function requireExactKeys(value, allowedKeys, label, allowMissing = !1) {
|
|
589
|
-
const keys = Object.keys(value);
|
|
590
|
-
const unknownKey = keys.find((key) => !allowedKeys.includes(key));
|
|
591
|
-
if (unknownKey !== void 0)
|
|
592
|
-
throw Error(`${label} contains unknown property: ${unknownKey}`);
|
|
593
|
-
if (!allowMissing) {
|
|
594
|
-
const missingKey = allowedKeys.find((key) => !Object.hasOwn(value, key));
|
|
595
|
-
if (missingKey !== void 0)
|
|
596
|
-
throw Error(`${label} is missing property: ${missingKey}`);
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
function usageError(message, helpCommand = "csv --help") {
|
|
600
|
-
console.error(`csv: ${message}
|
|
601
|
-
Run '${helpCommand}' for usage.`);
|
|
602
|
-
return 2;
|
|
603
|
-
}
|
|
604
|
-
if (import.meta.main)
|
|
605
|
-
process.exitCode = await run(Bun.argv.slice(2));
|
|
2
|
+
import { runCli } from "./cli-command.js";
|
|
3
|
+
process.exitCode = await runCli(Bun.argv.slice(2));
|
package/dist/file-stream.d.ts
CHANGED
|
@@ -1,11 +1,70 @@
|
|
|
1
1
|
import type { CsvDelimiter, CsvFileOptions } from './types.js';
|
|
2
|
-
|
|
2
|
+
export declare const FILE_PROBE_SIZE: number;
|
|
3
|
+
export declare const DELIMITER_CANDIDATES: readonly [{
|
|
4
|
+
readonly byte: 44;
|
|
5
|
+
readonly delimiter: ",";
|
|
6
|
+
}, {
|
|
7
|
+
readonly byte: 9;
|
|
8
|
+
readonly delimiter: "\t";
|
|
9
|
+
}, {
|
|
10
|
+
readonly byte: 59;
|
|
11
|
+
readonly delimiter: ";";
|
|
12
|
+
}, {
|
|
13
|
+
readonly byte: 124;
|
|
14
|
+
readonly delimiter: "|";
|
|
15
|
+
}, {
|
|
16
|
+
readonly byte: 58;
|
|
17
|
+
readonly delimiter: ":";
|
|
18
|
+
}, {
|
|
19
|
+
readonly byte: 94;
|
|
20
|
+
readonly delimiter: "^";
|
|
21
|
+
}, {
|
|
22
|
+
readonly byte: 126;
|
|
23
|
+
readonly delimiter: "~";
|
|
24
|
+
}];
|
|
25
|
+
interface CompressionExtensionHint {
|
|
26
|
+
extension: string;
|
|
27
|
+
format: Bun.CompressionFormat;
|
|
28
|
+
signatureRequired: boolean;
|
|
29
|
+
}
|
|
30
|
+
export interface CsvFileInput extends AsyncDisposable {
|
|
3
31
|
readonly delimiter: CsvDelimiter;
|
|
32
|
+
/** Encoding expected by the native parser after any stream transcoding. */
|
|
33
|
+
readonly parserEncoding: 'utf8' | 'latin1';
|
|
4
34
|
chunks(): AsyncIterable<Uint8Array>;
|
|
5
35
|
}
|
|
6
|
-
export
|
|
7
|
-
|
|
36
|
+
export type CsvFileProbe = (path: string, prefix: Uint8Array, sourceEnded: boolean, delimiter: CsvDelimiter) => {
|
|
37
|
+
delimiter: CsvDelimiter;
|
|
38
|
+
encoding: 'utf8' | 'latin1' | 'windows-1252' | 'utf-16le' | 'utf-16be';
|
|
39
|
+
skipBytes: number;
|
|
40
|
+
};
|
|
41
|
+
type FileReadMode = 'stream' | 'parse' | 'read-ahead' | 'count';
|
|
42
|
+
export declare function prepareCsvFileInput(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression' | 'delimiter' | 'encoding'>, readMode?: FileReadMode, probeFormat?: CsvFileProbe): Promise<CsvFileInput>;
|
|
43
|
+
export declare function readCsvFileChunks(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression'>, readMode?: FileReadMode): AsyncIterable<Uint8Array>;
|
|
8
44
|
export declare function rejectCompressedSharding(options: Pick<CsvFileOptions, 'compression'>, operation: string): void;
|
|
9
45
|
export declare function rejectAutoDelimiterSharding(options: Pick<CsvFileOptions, 'delimiter'>, operation: string): void;
|
|
46
|
+
export declare function detectDelimiter(path: string, probe: Uint8Array, sourceEnded: boolean): CsvDelimiter;
|
|
47
|
+
/** Detect the encoding and, when requested, score delimiters on the same prefix. */
|
|
48
|
+
export declare const probeCsvFileFormat: CsvFileProbe;
|
|
49
|
+
interface CsvFormatSample {
|
|
50
|
+
bytes: Uint8Array;
|
|
51
|
+
encoding: ReturnType<CsvFileProbe>['encoding'];
|
|
52
|
+
skipBytes: number;
|
|
53
|
+
counts: readonly Uint32Array[];
|
|
54
|
+
}
|
|
55
|
+
/** When scoring delimiters, structural bytes exclude the BOM and use UTF-8 for UTF-16 input. */
|
|
56
|
+
export declare function scanCsvFileFormat(prefix: Uint8Array, sourceEnded: boolean, scoreDelimiters: boolean): CsvFormatSample;
|
|
57
|
+
type DelimiterChoice = {
|
|
58
|
+
delimiter: CsvDelimiter;
|
|
59
|
+
} | {
|
|
60
|
+
reason: 'no-records' | 'no-stable-separator';
|
|
61
|
+
} | {
|
|
62
|
+
reason: 'ambiguous';
|
|
63
|
+
candidates: readonly CsvDelimiter[];
|
|
64
|
+
};
|
|
65
|
+
export declare function selectDelimiter(path: string, rows: readonly ArrayLike<number>[]): DelimiterChoice;
|
|
10
66
|
export declare function scanDelimiterCounts(probe: Uint8Array, sourceEnded: boolean): number[][];
|
|
67
|
+
export declare function isZipSignature(prefix: Uint8Array): boolean;
|
|
68
|
+
export declare function compressionFromPrefix(path: string, prefix: Uint8Array): Bun.CompressionFormat | undefined;
|
|
69
|
+
export declare function compressionFromExtension(path: string): CompressionExtensionHint | undefined;
|
|
11
70
|
export {};
|