@konstit/csv 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +36 -3
  2. package/THIRD_PARTY_NOTICES.md +99 -0
  3. package/dist/api.d.ts +3 -0
  4. package/dist/api.js +34 -108
  5. package/dist/batches.d.ts +3 -4
  6. package/dist/batches.js +103 -29
  7. package/dist/cli-command.js +145 -75
  8. package/dist/cli-schema.d.ts +25 -5
  9. package/dist/cli-schema.js +48 -23
  10. package/dist/file-stream.d.ts +10 -3
  11. package/dist/file-stream.js +22 -17
  12. package/dist/files.js +32 -76
  13. package/dist/filter.d.ts +2 -3
  14. package/dist/filter.js +2 -0
  15. package/dist/index.d.ts +1 -1
  16. package/dist/inspect-file.d.ts +16 -6
  17. package/dist/inspect-file.js +67 -17
  18. package/dist/latin1-rows.d.ts +3 -3
  19. package/dist/latin1-rows.js +65 -15
  20. package/dist/materialize-field.d.ts +1 -0
  21. package/dist/materialize-field.js +10 -1
  22. package/dist/native.d.ts +47 -71
  23. package/dist/native.js +28 -86
  24. package/dist/normalize.d.ts +1 -40
  25. package/dist/normalize.js +25 -62
  26. package/dist/options-snapshot.d.ts +2 -2
  27. package/dist/options-snapshot.js +2 -0
  28. package/dist/parser.d.ts +17 -202
  29. package/dist/parser.js +152 -230
  30. package/dist/strict-schema.d.ts +1 -1
  31. package/dist/strict-schema.js +4 -3
  32. package/dist/transforms.d.ts +11 -0
  33. package/dist/transforms.js +192 -0
  34. package/dist/types.d.ts +77 -9
  35. package/dist/zip-reader.d.ts +2 -0
  36. package/dist/zip-reader.js +31 -21
  37. package/package.json +3 -2
  38. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  39. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  40. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  41. package/prebuilds/manifest.json +14 -8
  42. package/prebuilds/provenance/darwin-arm64.json +1 -1
  43. package/prebuilds/provenance/darwin-x64.json +1 -1
  44. package/prebuilds/provenance/linux-x64.json +1 -1
@@ -1,13 +1,15 @@
1
1
  import { csv } from "./api.js";
2
2
  import {
3
- csvCommand
3
+ csvCommand,
4
+ parseColumnIndex
4
5
  } from "./cli-schema.js";
5
6
  import { formatBytes } from "./format-bytes.js";
6
7
  import { inspectCsvFile } from "./inspect-file.js";
7
8
  import {
8
- normalizeColumns,
9
- normalizeFilterColumn
9
+ normalizeFilterColumn,
10
+ validateRegex
10
11
  } from "./normalize.js";
12
+ import { snapshotTransforms } from "./transforms.js";
11
13
  const MAX_FILTER_NESTING = 128;
12
14
  const OUTPUT_BUFFER_SIZE = 65536;
13
15
  export async function runCli(arguments_, customOutput) {
@@ -28,7 +30,7 @@ export async function runCli(arguments_, customOutput) {
28
30
  case "lines":
29
31
  return runLines(subcommand.args, output);
30
32
  case "probe":
31
- return runProbe(subcommand.args.path, subcommand.args["zip-entry"], output);
33
+ return runProbe(subcommand.args, output);
32
34
  case "completion":
33
35
  return runCompletion(subcommand.args.shell, output);
34
36
  }
@@ -38,17 +40,26 @@ async function runCompletion(shell, output) {
38
40
  output.log(generateCompletion(csvCommand, shell).trimEnd());
39
41
  return 0;
40
42
  }
41
- async function runProbe(path, entry, output) {
43
+ async function runProbe(args, output) {
42
44
  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)}`,
45
+ const result = await inspectCsvFile(args.path, { zipEntry: args["zip-entry"], encoding: args.encoding, delimiter: args.delimiter });
46
+ if (args.json) {
47
+ output.log(JSON.stringify(result));
48
+ return 0;
49
+ }
50
+ const lines = [
51
+ `File size: ${formatBytes(result.fileSizeBytes)}`,
52
+ `Encoding: ${result.encoding}${result.encodingSource === "explicit" ? " (explicit)" : ""}`,
53
+ `Delimiter: ${result.delimiter === null ? "undetermined" : JSON.stringify(result.delimiter)}${result.delimiterSource === "explicit" ? " (explicit)" : ""}`,
48
54
  `Line endings: ${result.lineEnding}`,
49
55
  `Compression: ${result.compression}`,
50
56
  `First record columns: ${String(result.firstRecordColumns ?? "unknown")}`
51
- ].join(`
57
+ ];
58
+ if (result.zipEntry !== null)
59
+ lines.push(`ZIP entry: ${JSON.stringify(result.zipEntry)}`);
60
+ if (result.delimiterReason !== null)
61
+ lines.push(`Delimiter detail: ${result.delimiterReason}`);
62
+ output.log(lines.join(`
52
63
  `));
53
64
  return 0;
54
65
  } catch (error) {
@@ -73,14 +84,14 @@ async function runCount(args, output) {
73
84
  }
74
85
  }
75
86
  async function runLines(args, output) {
76
- let input;
87
+ let options;
77
88
  try {
78
- input = parseLinesInput(args);
89
+ options = { ...parseCommonOptions(args), limit: args.limit, transform: parseTransformOptions(args) };
79
90
  } catch (error) {
80
91
  return usageError(output, error instanceof Error ? error.message : String(error), "csv lines --help");
81
92
  }
82
93
  try {
83
- await streamLines(input, output);
94
+ await streamLines(args, options, output);
84
95
  return 0;
85
96
  } catch (error) {
86
97
  if (isBrokenPipe(error))
@@ -90,58 +101,26 @@ async function runLines(args, output) {
90
101
  return 1;
91
102
  }
92
103
  }
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) {
104
+ function parseCommonOptions(values) {
116
105
  const options = values.strict ? { strict: !0 } : { where: parseWhereOptions(values) };
117
- options.delimiter = values.delimiter ?? (fixedFormat ? "," : "auto");
118
- options.encoding = values.encoding ?? (fixedFormat ? "utf8" : "auto");
106
+ options.delimiter = values.delimiter ?? "auto";
107
+ options.encoding = values.encoding ?? "auto";
108
+ options.skipRows = values["skip-rows"];
119
109
  if (values["chunk-size"] !== void 0)
120
110
  options.chunkSize = values["chunk-size"];
121
111
  if (values["fixed-columns"] !== void 0)
122
112
  options.fixedColumns = values["fixed-columns"];
123
113
  if (values.columns !== void 0)
124
- options.columns = parseColumns(values.columns, "columns");
114
+ options.columns = values.columns;
125
115
  if (values["expected-header"].length > 0)
126
116
  options.expectedHeaders = values["expected-header"];
127
117
  if (values["require-header"] === !0)
128
118
  options.requireHeader = !0;
129
119
  if (values["min-data-rows"] !== void 0)
130
120
  options.minDataRows = values["min-data-rows"];
131
- options.compression = parseCompression(values) ?? (fixedFormat ? "none" : "auto");
121
+ options.compression = parseCompression(values) ?? "auto";
132
122
  return options;
133
123
  }
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
124
  function parseCompression(values) {
146
125
  const compression = values.compression;
147
126
  const zipEntry = values["zip-entry"];
@@ -159,34 +138,24 @@ function parseCompression(values) {
159
138
  ...maxDecompressedBytes === void 0 ? {} : { maxDecompressedBytes }
160
139
  };
161
140
  }
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) {
141
+ async function streamLines(args, options, output) {
142
+ for await (const rows of csv.rows(args.path, options)) {
143
+ let chunks = [];
144
+ let chunksLength = 0;
145
+ for (const row of rows) {
146
+ const record = args.json ? `${JSON.stringify(row)}
147
+ ` : serializeCsvRecord(row, args["output-delimiter"]);
148
+ chunks.push(record);
149
+ chunksLength += record.length;
150
+ if (chunksLength >= OUTPUT_BUFFER_SIZE) {
183
151
  await output.write(chunks.join(""));
184
152
  chunks = [];
185
153
  chunksLength = 0;
186
154
  }
187
155
  }
188
- if (chunksLength > 0)
189
- await output.write(chunks.join(""));
156
+ if (chunksLength > 0)
157
+ await output.write(chunks.join(""));
158
+ }
190
159
  }
191
160
  function serializeCsvRecord(row, delimiter) {
192
161
  return `${row.map((field) => serializeCsvField(field, delimiter)).join(delimiter)}
@@ -201,6 +170,104 @@ function serializeCsvField(field, delimiter) {
201
170
  function isBrokenPipe(error) {
202
171
  return isObject(error) && error.code === "EPIPE";
203
172
  }
173
+ function parseTransformOptions(args) {
174
+ const transforms = [];
175
+ for (const [index, { key, value }] of args.transform.entries()) {
176
+ const label = `--transform[${index}]`;
177
+ const columns = key.split(",").map((column) => {
178
+ if (!/^[0-9]+$/.test(column))
179
+ throw Error(`${label} must start with comma-separated decimal column indexes`);
180
+ return parseColumnIndex(column, `${label} column`);
181
+ });
182
+ const steps = value.split(",").map((op) => {
183
+ if (!isCleanupTransform(op))
184
+ throw Error(`${label} expected trim, upper, lower, or unaccent, got ${JSON.stringify(op)}`);
185
+ return { op };
186
+ });
187
+ transforms.push(parseTransformChain({ columns, steps }, label));
188
+ }
189
+ const json = args["transform-json"];
190
+ if (json !== void 0) {
191
+ if (!Array.isArray(json))
192
+ throw Error("--transform-json must be a JSON array of chains");
193
+ for (const [index, chain] of json.entries())
194
+ transforms.push(parseTransformChain(chain, `--transform-json[${index}]`));
195
+ }
196
+ return transforms.length === 0 ? void 0 : snapshotTransforms(transforms);
197
+ }
198
+ function parseTransformChain(value, label) {
199
+ if (!isObject(value))
200
+ throw Error(`${label} must be an object with columns and steps`);
201
+ requireExactKeys(value, ["columns", "steps"], label);
202
+ const { columns, steps } = value;
203
+ if (!Array.isArray(columns))
204
+ throw Error(`${label}.columns must be a non-empty array of column indexes`);
205
+ const [first, ...rest] = columns.map((column, index) => {
206
+ if (typeof column !== "number")
207
+ throw Error(`${label}.columns[${index}] must be a number`);
208
+ return column;
209
+ });
210
+ if (first === void 0)
211
+ throw Error(`${label}.columns must be a non-empty array of column indexes`);
212
+ if (!Array.isArray(steps) || steps.length === 0)
213
+ throw Error(`${label}.steps must be a non-empty array`);
214
+ let chain = parseTransformStep(csv.transform(), steps[0], `${label}.steps[0]`);
215
+ for (let index = 1;index < steps.length; ++index)
216
+ chain = parseTransformStep(chain, steps[index], `${label}.steps[${index}]`);
217
+ return chain.on(first, ...rest);
218
+ }
219
+ function isCleanupTransform(op) {
220
+ return op === "trim" || op === "upper" || op === "lower" || op === "unaccent";
221
+ }
222
+ function parseTransformStep(chain, step, label) {
223
+ if (!isObject(step))
224
+ throw Error(`${label} must be an object with an op property`);
225
+ const op = requireString(step.op, `${label}.op`);
226
+ if (isCleanupTransform(op)) {
227
+ requireExactKeys(step, ["op"], label);
228
+ return chain[op]();
229
+ }
230
+ switch (op) {
231
+ case "replace": {
232
+ requireExactKeys(step, ["op", "search", "replacement"], label);
233
+ const search = step.search;
234
+ const replacement = requireString(step.replacement, `${label}.replacement`);
235
+ if (!isObject(search))
236
+ return chain.replace(requireString(search, `${label}.search`), replacement);
237
+ const searchLabel = `${label}.search`;
238
+ requireExactKeys(search, ["source", "flags"], searchLabel, !0);
239
+ const source = requireString(search.source, `${searchLabel}.source`);
240
+ const flags = optionalString(search.flags, `${searchLabel}.flags`);
241
+ let regex;
242
+ try {
243
+ regex = new RegExp(source, flags);
244
+ validateRegex({ source: regex.source, flags: regex.flags.replace("g", "") });
245
+ } catch (error) {
246
+ throw Error(`${searchLabel}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
247
+ }
248
+ return chain.replace(regex, replacement);
249
+ }
250
+ case "map": {
251
+ requireExactKeys(step, ["op", "values", "defaultValue"], label, !0);
252
+ const values = step.values;
253
+ if (!isObject(values))
254
+ throw Error(`${label}.values must be an object of strings`);
255
+ const mapping = new Map;
256
+ for (const [key, value] of Object.entries(values))
257
+ mapping.set(key, requireString(value, `${label}.values[${JSON.stringify(key)}]`));
258
+ return chain.map(mapping, optionalString(step.defaultValue, `${label}.defaultValue`));
259
+ }
260
+ case "date": {
261
+ requireExactKeys(step, ["op", "format", "defaultValue"], label, !0);
262
+ const format = step.format;
263
+ if (format !== "YYYY-MM-DD" && format !== "DD-MM-YYYY" && format !== "DD/MM/YYYY")
264
+ throw Error(`${label}.format must be YYYY-MM-DD, DD-MM-YYYY, or DD/MM/YYYY`);
265
+ return chain.date(format, optionalString(step.defaultValue, `${label}.defaultValue`));
266
+ }
267
+ default:
268
+ throw Error(`${label}.op is an unknown transform: ${JSON.stringify(op)}`);
269
+ }
270
+ }
204
271
  function parseWhereOptions(values) {
205
272
  const filters = [];
206
273
  if (values.where !== void 0)
@@ -332,6 +399,9 @@ function requireString(value, label) {
332
399
  throw Error(`${label} must be a string`);
333
400
  return value;
334
401
  }
402
+ function optionalString(value, label) {
403
+ return value === void 0 ? void 0 : requireString(value, label);
404
+ }
335
405
  function requireExactKeys(value, allowedKeys, label, allowMissing = !1) {
336
406
  const keys = Object.keys(value);
337
407
  const unknownKey = keys.find((key) => !allowedKeys.includes(key));
@@ -6,11 +6,12 @@ declare const count: import("@konstit/cli").HandledCommand<"count", {
6
6
  encoding: "utf8" | "utf-16le" | "latin1" | "ibm866" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-8-i" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "koi8-r" | "koi8-u" | "macintosh" | "windows-874" | "windows-1250" | "windows-1251" | "windows-1252" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic" | "gbk" | "gb18030" | "big5" | "euc-jp" | "iso-2022-jp" | "shift_jis" | "euc-kr" | "utf-16be" | "x-user-defined" | "auto" | undefined;
7
7
  compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
8
8
  "chunk-size": number | undefined;
9
+ "skip-rows": number | undefined;
9
10
  "max-compression-ratio": number | undefined;
10
11
  "max-decompressed-bytes": number | undefined;
11
12
  strict: boolean;
12
13
  "fixed-columns": number | undefined;
13
- columns: string | undefined;
14
+ columns: number[] | undefined;
14
15
  "expected-header": readonly string[];
15
16
  "require-header": boolean;
16
17
  "min-data-rows": number | undefined;
@@ -29,11 +30,12 @@ declare const lines: import("@konstit/cli").HandledCommand<"lines", {
29
30
  encoding: "utf8" | "utf-16le" | "latin1" | "ibm866" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-8-i" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "koi8-r" | "koi8-u" | "macintosh" | "windows-874" | "windows-1250" | "windows-1251" | "windows-1252" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic" | "gbk" | "gb18030" | "big5" | "euc-jp" | "iso-2022-jp" | "shift_jis" | "euc-kr" | "utf-16be" | "x-user-defined" | "auto" | undefined;
30
31
  compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
31
32
  "chunk-size": number | undefined;
33
+ "skip-rows": number | undefined;
32
34
  "max-compression-ratio": number | undefined;
33
35
  "max-decompressed-bytes": number | undefined;
34
36
  strict: boolean;
35
37
  "fixed-columns": number | undefined;
36
- columns: string | undefined;
38
+ columns: number[] | undefined;
37
39
  "expected-header": readonly string[];
38
40
  "require-header": boolean;
39
41
  "min-data-rows": number | undefined;
@@ -47,9 +49,19 @@ declare const lines: import("@konstit/cli").HandledCommand<"lines", {
47
49
  json: boolean;
48
50
  "output-delimiter": string;
49
51
  limit: number | undefined;
52
+ transform: readonly import("@konstit/cli").KeyValuePair[];
53
+ "transform-json": unknown;
50
54
  }, {}, false, "filters" | "zip-limits" | "schema">;
51
55
  export type CountArguments = Infer<typeof count>;
52
56
  export type LinesArguments = Infer<typeof lines>;
57
+ declare const probe: import("@konstit/cli").HandledCommand<"probe", {
58
+ path: string;
59
+ "zip-entry": string | undefined;
60
+ delimiter: string | undefined;
61
+ encoding: "utf8" | "utf-16le" | "latin1" | "ibm866" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-8-i" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "koi8-r" | "koi8-u" | "macintosh" | "windows-874" | "windows-1250" | "windows-1251" | "windows-1252" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic" | "gbk" | "gb18030" | "big5" | "euc-jp" | "iso-2022-jp" | "shift_jis" | "euc-kr" | "utf-16be" | "x-user-defined" | "auto" | undefined;
62
+ json: boolean;
63
+ }, {}, false, string>;
64
+ export type ProbeArguments = Infer<typeof probe>;
53
65
  export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}, {
54
66
  count: import("@konstit/cli").HandledCommand<"count", {
55
67
  path: string;
@@ -58,11 +70,12 @@ export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}
58
70
  encoding: "utf8" | "utf-16le" | "latin1" | "ibm866" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-8-i" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "koi8-r" | "koi8-u" | "macintosh" | "windows-874" | "windows-1250" | "windows-1251" | "windows-1252" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic" | "gbk" | "gb18030" | "big5" | "euc-jp" | "iso-2022-jp" | "shift_jis" | "euc-kr" | "utf-16be" | "x-user-defined" | "auto" | undefined;
59
71
  compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
60
72
  "chunk-size": number | undefined;
73
+ "skip-rows": number | undefined;
61
74
  "max-compression-ratio": number | undefined;
62
75
  "max-decompressed-bytes": number | undefined;
63
76
  strict: boolean;
64
77
  "fixed-columns": number | undefined;
65
- columns: string | undefined;
78
+ columns: number[] | undefined;
66
79
  "expected-header": readonly string[];
67
80
  "require-header": boolean;
68
81
  "min-data-rows": number | undefined;
@@ -81,11 +94,12 @@ export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}
81
94
  encoding: "utf8" | "utf-16le" | "latin1" | "ibm866" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-8-i" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "koi8-r" | "koi8-u" | "macintosh" | "windows-874" | "windows-1250" | "windows-1251" | "windows-1252" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic" | "gbk" | "gb18030" | "big5" | "euc-jp" | "iso-2022-jp" | "shift_jis" | "euc-kr" | "utf-16be" | "x-user-defined" | "auto" | undefined;
82
95
  compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
83
96
  "chunk-size": number | undefined;
97
+ "skip-rows": number | undefined;
84
98
  "max-compression-ratio": number | undefined;
85
99
  "max-decompressed-bytes": number | undefined;
86
100
  strict: boolean;
87
101
  "fixed-columns": number | undefined;
88
- columns: string | undefined;
102
+ columns: number[] | undefined;
89
103
  "expected-header": readonly string[];
90
104
  "require-header": boolean;
91
105
  "min-data-rows": number | undefined;
@@ -99,13 +113,19 @@ export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}
99
113
  json: boolean;
100
114
  "output-delimiter": string;
101
115
  limit: number | undefined;
116
+ transform: readonly import("@konstit/cli").KeyValuePair[];
117
+ "transform-json": unknown;
102
118
  }, {}, false, "filters" | "zip-limits" | "schema">;
103
119
  probe: import("@konstit/cli").HandledCommand<"probe", {
104
120
  path: string;
105
121
  "zip-entry": string | undefined;
106
- }, {}, boolean, string>;
122
+ delimiter: string | undefined;
123
+ encoding: "utf8" | "utf-16le" | "latin1" | "ibm866" | "iso-8859-2" | "iso-8859-3" | "iso-8859-4" | "iso-8859-5" | "iso-8859-6" | "iso-8859-7" | "iso-8859-8" | "iso-8859-8-i" | "iso-8859-10" | "iso-8859-13" | "iso-8859-14" | "iso-8859-15" | "iso-8859-16" | "koi8-r" | "koi8-u" | "macintosh" | "windows-874" | "windows-1250" | "windows-1251" | "windows-1252" | "windows-1253" | "windows-1254" | "windows-1255" | "windows-1256" | "windows-1257" | "windows-1258" | "x-mac-cyrillic" | "gbk" | "gb18030" | "big5" | "euc-jp" | "iso-2022-jp" | "shift_jis" | "euc-kr" | "utf-16be" | "x-user-defined" | "auto" | undefined;
124
+ json: boolean;
125
+ }, {}, false, string>;
107
126
  completion: import("@konstit/cli").HandledCommand<"completion", {
108
127
  shell: "bash" | "zsh" | "fish" | "powershell";
109
128
  }, {}, boolean, string>;
110
129
  }, true, string>;
130
+ export declare function parseColumnIndex(value: string, label: string): number;
111
131
  export {};
@@ -7,7 +7,10 @@ import {
7
7
  positional
8
8
  } from "@konstit/cli";
9
9
  import packageInfo from "../package.json";
10
- import { resolveInputEncoding } from "./normalize.js";
10
+ import {
11
+ normalizeColumns,
12
+ resolveInputEncoding
13
+ } from "./normalize.js";
11
14
  const encodings = parsers.enum([
12
15
  "auto",
13
16
  { value: "utf8", aliases: ["utf-8"] },
@@ -64,6 +67,7 @@ const encodingParser = {
64
67
  };
65
68
  const compressionFormats = ["auto", "none", "gzip", "deflate", "deflate-raw", "brotli", "zstd", "zip"];
66
69
  const positiveUint32 = parsers.range(1, 4294967295, { integer: !0 });
70
+ const rowCount = parsers.range(0, Number.MAX_SAFE_INTEGER, { integer: !0 });
67
71
  const byteSize = parsers.custom(parsers.byteSize.label, (input) => {
68
72
  const bare = Number(input);
69
73
  return parsers.byteSize.parse(Number.isNaN(bare) ? input : `${bare}B`);
@@ -72,18 +76,26 @@ const positiveByteSize = parsers.refine(byteSize, (bytes) => bytes > 0, "expecte
72
76
  const chunkSize = parsers.refine(positiveByteSize, (bytes) => bytes <= 67108864, "expected at most 64 MiB");
73
77
  const inputDelimiter = parsers.regex(/^(?:auto|[\p{ASCII}--["\r\n]])$/v);
74
78
  const outputDelimiter = parsers.regex(/^[\p{ASCII}--["\r\n]]$/v);
79
+ const columns = parsers.custom("INDEXES", (value) => {
80
+ const indexes = value.length === 0 ? [] : value.split(",").map((column) => parseColumnIndex(column, "columns"));
81
+ normalizeColumns(indexes);
82
+ return indexes;
83
+ });
75
84
  const path = positional("path", parsers.string, { required: !0, valueHint: "file", describe: "Input file path" });
76
85
  const zipEntry = option("zip-entry", parsers.refine(parsers.string, (value) => value.length > 0, "expected a non-empty ZIP entry name"), {
77
86
  valueName: "PATH",
78
87
  describe: "Select an entry inside a ZIP archive"
79
88
  });
80
- const fileArgs = [
81
- path,
89
+ const formatArgs = [
82
90
  option("delimiter", inputDelimiter, { valueName: "CHAR|auto", describe: "One safe ASCII character or auto (default: auto)" }),
83
91
  option("encoding", encodingParser, {
84
92
  valueName: "ENCODING",
85
93
  describe: "Input encoding or decoder alias (default: auto)"
86
- }),
94
+ })
95
+ ];
96
+ const fileArgs = [
97
+ path,
98
+ ...formatArgs,
87
99
  option("compression", parsers.enum(compressionFormats), {
88
100
  valueName: "FORMAT",
89
101
  describe: `Input compression (default: auto). Choices: ${compressionFormats.join(", ")}`
@@ -91,6 +103,7 @@ const fileArgs = [
91
103
  option("chunk-size", chunkSize, {
92
104
  describe: "Read 1 B through 64 MiB per chunk (default: 1MiB). Example: 256KiB"
93
105
  }),
106
+ option("skip-rows", rowCount, { valueName: "N", describe: "Skip the first N input records before filtering, including any header" }),
94
107
  zipEntry,
95
108
  option("max-compression-ratio", positiveUint32, {
96
109
  valueName: "RATIO",
@@ -99,13 +112,12 @@ const fileArgs = [
99
112
  option("max-decompressed-bytes", positiveByteSize, { describe: "Maximum decompressed ZIP size (default: 64GiB)" }),
100
113
  flag("strict", { describe: "Enable strict RFC 4180 validation" }),
101
114
  option("fixed-columns", positiveUint32, { valueName: "COUNT", describe: "Require this positive field count in strict mode" }),
102
- option("columns", parsers.string, {
103
- valueName: "INDEXES",
115
+ option("columns", columns, {
104
116
  describe: "Zero-based column indexes in output order. The count command validates the indexes only"
105
117
  }),
106
118
  option("expected-header", parsers.string, { repeatable: !0, describe: "Expected header value. Repeat once per column in strict mode" }),
107
119
  flag("require-header", { describe: "Require a header row in strict mode" }),
108
- option("min-data-rows", parsers.range(0, Number.MAX_SAFE_INTEGER, { integer: !0 }), {
120
+ option("min-data-rows", rowCount, {
109
121
  valueName: "COUNT",
110
122
  describe: "Require at least this many data rows in strict mode"
111
123
  }),
@@ -160,7 +172,6 @@ const count = command("count", {
160
172
  ...fileRelations,
161
173
  about: "Count CSV records, including the header row",
162
174
  args: fileArgs,
163
- argsOverrideSelf: !0,
164
175
  afterHelp: `${fileHelp}
165
176
 
166
177
  Examples:
@@ -170,7 +181,7 @@ Examples:
170
181
  });
171
182
  const lines = command("lines", {
172
183
  ...fileRelations,
173
- conflicts: [["json", "output-delimiter"], ["limit", "min-data-rows"]],
184
+ conflicts: [["json", "output-delimiter"]],
174
185
  about: "Stream matching records as normalized UTF-8 CSV or NDJSON",
175
186
  args: [
176
187
  ...fileArgs,
@@ -180,21 +191,34 @@ const lines = command("lines", {
180
191
  default: ",",
181
192
  describe: "One safe ASCII output delimiter (default: comma). Incompatible with --json"
182
193
  }),
183
- option("limit", parsers.range(1, Number.MAX_SAFE_INTEGER, { integer: !0 }), {
194
+ option("limit", rowCount, {
184
195
  valueName: "N",
185
- describe: "Stop after matching output record N, numbered from 1. Incompatible with --min-data-rows"
196
+ describe: "Emit at most N matching records (0 emits none)"
197
+ }),
198
+ option("transform", parsers.keyValue, {
199
+ repeatable: !0,
200
+ valueName: "COLUMNS=STEPS",
201
+ describe: "Apply comma-separated trim, upper, lower, or unaccent steps to zero-based input columns"
202
+ }),
203
+ option("transform-json", parsers.json(), {
204
+ valueName: "JSON",
205
+ describe: "Apply an array of column transform chains, including replace, map, and date"
186
206
  })
187
207
  ],
188
- argsOverrideSelf: !0,
189
208
  afterHelp: `${fileHelp}
190
209
 
191
- With --strict and --limit, validation stops at the selected record. Set a fixed
192
- delimiter and encoding (defaults: comma and UTF-8). Input must be uncompressed
193
- and the chunk size must be 1 byte. Earlier records can be written before a later error.
210
+ Strict validation includes skipped records and stops when the output limit is reached.
211
+ Header and minimum data row checks apply to the consumed input prefix.
194
212
 
195
213
  Examples:
196
- csv lines data.csv --json --limit 10
197
- csv lines data.csv --columns 0,2 --where-eq 3=active`
214
+ csv lines data.csv --json --skip-rows 1 --limit 10
215
+ csv lines data.csv --columns 0,2 --where-eq 3=active
216
+ csv lines data.csv --skip-rows 1 --transform '1,2=trim,upper'`
217
+ });
218
+ const probe = command("probe", {
219
+ about: "Inspect file size, compression, encoding, delimiter, line endings, and first record width",
220
+ args: [path, ...formatArgs, zipEntry, flag("json", { describe: "Emit the inspection as one JSON object" })],
221
+ afterHelp: "Samples up to 64 KiB of decompressed CSV. For a ZIP archive with multiple data files, select one with --zip-entry."
198
222
  });
199
223
  export const csvCommand = command("csv", {
200
224
  about: "Inspect, count, and stream CSV records",
@@ -204,12 +228,7 @@ export const csvCommand = command("csv", {
204
228
  subcommands: [
205
229
  count,
206
230
  lines,
207
- command("probe", {
208
- about: "Inspect file size, compression, encoding, delimiter, line endings, and first record width",
209
- args: [path, zipEntry],
210
- argsOverrideSelf: !0,
211
- afterHelp: "Samples up to 64 KiB of CSV. For a ZIP archive with multiple data files, select one with --zip-entry."
212
- }),
231
+ probe,
213
232
  command("completion", {
214
233
  about: "Print a shell completion script for csv",
215
234
  args: [positional("shell", parsers.enum(completionShells), { required: !0, describe: completionShells.join(", ") })]
@@ -217,3 +236,9 @@ export const csvCommand = command("csv", {
217
236
  ],
218
237
  afterHelp: "Run without installing: bunx @konstit/csv <command> <path>"
219
238
  });
239
+ export function parseColumnIndex(value, label) {
240
+ const number = Number(value);
241
+ if (!Number.isSafeInteger(number) || number < 0)
242
+ throw Error(`${label} must be an integer greater than or equal to 0: ${value}`);
243
+ return number;
244
+ }
@@ -21,13 +21,16 @@ export declare const DELIMITER_CANDIDATES: readonly [{
21
21
  }, {
22
22
  readonly byte: 126;
23
23
  readonly delimiter: "~";
24
+ }, {
25
+ readonly byte: 64;
26
+ readonly delimiter: "@";
24
27
  }];
25
28
  interface CompressionExtensionHint {
26
29
  extension: string;
27
30
  format: Bun.CompressionFormat;
28
31
  signatureRequired: boolean;
29
32
  }
30
- interface CsvFileInput extends AsyncDisposable {
33
+ export interface CsvFileInput extends AsyncDisposable {
31
34
  readonly delimiter: CsvDelimiter;
32
35
  /** Encoding expected by the native parser after any stream transcoding. */
33
36
  readonly parserEncoding: 'utf8' | 'latin1';
@@ -54,11 +57,15 @@ interface CsvFormatSample {
54
57
  }
55
58
  /** When scoring delimiters, structural bytes exclude the BOM and use UTF-8 for UTF-16 input. */
56
59
  export declare function scanCsvFileFormat(prefix: Uint8Array, sourceEnded: boolean, scoreDelimiters: boolean): CsvFormatSample;
57
- export declare function selectDelimiter(path: string, rows: readonly ArrayLike<number>[]): {
60
+ type DelimiterChoice = {
58
61
  delimiter: CsvDelimiter;
59
62
  } | {
60
- error: string;
63
+ reason: 'no-records' | 'no-stable-separator';
64
+ } | {
65
+ reason: 'ambiguous';
66
+ candidates: readonly CsvDelimiter[];
61
67
  };
68
+ export declare function selectDelimiter(path: string, rows: readonly ArrayLike<number>[]): DelimiterChoice;
62
69
  export declare function scanDelimiterCounts(probe: Uint8Array, sourceEnded: boolean): number[][];
63
70
  export declare function isZipSignature(prefix: Uint8Array): boolean;
64
71
  export declare function compressionFromPrefix(path: string, prefix: Uint8Array): Bun.CompressionFormat | undefined;