@konstit/csv 0.6.0 → 0.7.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 (53) hide show
  1. package/README.md +113 -101
  2. package/THIRD_PARTY_NOTICES.md +27 -0
  3. package/dist/api.d.ts +84 -57
  4. package/dist/api.js +211 -40
  5. package/dist/batch-pipeline.d.ts +10 -0
  6. package/dist/batch-pipeline.js +83 -0
  7. package/dist/batches.d.ts +36 -1
  8. package/dist/batches.js +241 -5
  9. package/dist/cli-command.d.ts +7 -7
  10. package/dist/cli-command.js +325 -164
  11. package/dist/cli-schema.d.ts +51 -21
  12. package/dist/cli-schema.js +126 -65
  13. package/dist/cli.js +1 -1
  14. package/dist/file-stream.d.ts +66 -18
  15. package/dist/file-stream.js +534 -199
  16. package/dist/files.d.ts +17 -37
  17. package/dist/files.js +50 -21
  18. package/dist/gzip-reader.d.ts +2 -0
  19. package/dist/gzip-reader.js +37 -0
  20. package/dist/index.d.ts +3 -3
  21. package/dist/index.js +2 -2
  22. package/dist/inspect-file.d.ts +26 -3
  23. package/dist/inspect-file.js +169 -74
  24. package/dist/inspect-zip.d.ts +26 -0
  25. package/dist/inspect-zip.js +59 -0
  26. package/dist/latin1-rows.d.ts +11 -3
  27. package/dist/latin1-rows.js +276 -75
  28. package/dist/materialize-field.d.ts +6 -0
  29. package/dist/materialize-field.js +9 -0
  30. package/dist/native.d.ts +118 -20
  31. package/dist/native.js +53 -23
  32. package/dist/normalize.d.ts +7 -1
  33. package/dist/normalize.js +49 -9
  34. package/dist/options.d.ts +27 -12
  35. package/dist/parser.d.ts +34 -14
  36. package/dist/parser.js +296 -102
  37. package/dist/strict-schema.d.ts +7 -8
  38. package/dist/strict-schema.js +45 -83
  39. package/dist/transforms.d.ts +1 -3
  40. package/dist/transforms.js +17 -16
  41. package/dist/types.d.ts +192 -75
  42. package/dist/zip-entry.d.ts +14 -0
  43. package/dist/zip-entry.js +155 -0
  44. package/dist/zip-reader.d.ts +14 -3
  45. package/dist/zip-reader.js +65 -23
  46. package/package.json +34 -23
  47. package/prebuilds/darwin-arm64/libcsv_native.dylib +0 -0
  48. package/prebuilds/darwin-x64/libcsv_native.dylib +0 -0
  49. package/prebuilds/linux-x64/libcsv_native.so +0 -0
  50. package/prebuilds/manifest.json +18 -8
  51. package/prebuilds/provenance/darwin-arm64.json +1 -1
  52. package/prebuilds/provenance/darwin-x64.json +1 -1
  53. package/prebuilds/provenance/linux-x64.json +1 -1
@@ -1,14 +1,16 @@
1
- import { type Infer } from '@konstit/cli';
1
+ import { type Infer, type RunParsedOptions } from '@konstit/cli';
2
2
  declare const count: import("@konstit/cli").HandledCommand<"count", {
3
3
  path: string;
4
4
  "zip-entry": string | undefined;
5
5
  delimiter: string | undefined;
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;
6
+ encoding: "utf8" | "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" | "latin1" | "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" | "utf-16le" | "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
9
  "skip-rows": number | undefined;
10
+ "skip-empty-lines": boolean;
10
11
  "max-compression-ratio": number | undefined;
11
12
  "max-decompressed-bytes": number | undefined;
13
+ "max-record-bytes": number | undefined;
12
14
  strict: boolean;
13
15
  "fixed-columns": number | undefined;
14
16
  columns: number[] | undefined;
@@ -22,17 +24,20 @@ declare const count: import("@konstit/cli").HandledCommand<"count", {
22
24
  "where-noin": readonly import("@konstit/cli").KeyValuePair[];
23
25
  "where-prefix": readonly import("@konstit/cli").KeyValuePair[];
24
26
  "where-regex": readonly import("@konstit/cli").KeyValuePair[];
25
- }, {}, false, "filters" | "zip-limits" | "schema">;
27
+ limit: number | undefined;
28
+ }, {}, false, "zip-limits" | "schema", {}, never>;
26
29
  declare const lines: import("@konstit/cli").HandledCommand<"lines", {
27
30
  path: string;
28
31
  "zip-entry": string | undefined;
29
32
  delimiter: string | undefined;
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;
33
+ encoding: "utf8" | "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" | "latin1" | "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" | "utf-16le" | "x-user-defined" | "auto" | undefined;
31
34
  compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
32
35
  "chunk-size": number | undefined;
33
36
  "skip-rows": number | undefined;
37
+ "skip-empty-lines": boolean;
34
38
  "max-compression-ratio": number | undefined;
35
39
  "max-decompressed-bytes": number | undefined;
40
+ "max-record-bytes": number | undefined;
36
41
  strict: boolean;
37
42
  "fixed-columns": number | undefined;
38
43
  columns: number[] | undefined;
@@ -46,33 +51,47 @@ declare const lines: import("@konstit/cli").HandledCommand<"lines", {
46
51
  "where-noin": readonly import("@konstit/cli").KeyValuePair[];
47
52
  "where-prefix": readonly import("@konstit/cli").KeyValuePair[];
48
53
  "where-regex": readonly import("@konstit/cli").KeyValuePair[];
54
+ limit: number | undefined;
55
+ headers: boolean;
56
+ "headers-json": string[] | undefined;
57
+ "column-name": readonly string[];
49
58
  json: boolean;
59
+ mapped: boolean;
60
+ "no-quote": boolean;
61
+ "record-delimiter": "lf" | undefined;
50
62
  "output-delimiter": string;
51
- limit: number | undefined;
52
63
  transform: readonly import("@konstit/cli").KeyValuePair[];
53
64
  "transform-json": unknown;
54
- }, {}, false, "filters" | "zip-limits" | "schema">;
55
- export type CountArguments = Infer<typeof count>;
56
- export type LinesArguments = Infer<typeof lines>;
65
+ }, {}, false, "zip-limits" | "schema" | "header-source", {}, never>;
57
66
  declare const probe: import("@konstit/cli").HandledCommand<"probe", {
58
67
  path: string;
59
68
  "zip-entry": string | undefined;
60
69
  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;
70
+ encoding: "utf8" | "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" | "latin1" | "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" | "utf-16le" | "x-user-defined" | "auto" | undefined;
71
+ compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
62
72
  json: boolean;
63
- }, {}, false, string>;
64
- export type ProbeArguments = Infer<typeof probe>;
73
+ "sample-size": number | undefined;
74
+ }, {}, false, string, {}, never>;
75
+ type CamelCaseOptionName<Name extends string> = Name extends `${infer First}-${infer Rest}` ? `${First}${Capitalize<CamelCaseOptionName<Rest>>}` : Name;
76
+ type HandlerArguments<Parsed> = {
77
+ [Name in keyof Parsed as Name extends string ? CamelCaseOptionName<Name> : Name]: Parsed[Name];
78
+ };
79
+ export type CountArguments = HandlerArguments<Infer<typeof count>>;
80
+ export type LinesArguments = HandlerArguments<Infer<typeof lines>>;
81
+ export type ProbeArguments = HandlerArguments<Infer<typeof probe>>;
65
82
  export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}, {
66
83
  count: import("@konstit/cli").HandledCommand<"count", {
67
84
  path: string;
68
85
  "zip-entry": string | undefined;
69
86
  delimiter: string | undefined;
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;
87
+ encoding: "utf8" | "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" | "latin1" | "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" | "utf-16le" | "x-user-defined" | "auto" | undefined;
71
88
  compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
72
89
  "chunk-size": number | undefined;
73
90
  "skip-rows": number | undefined;
91
+ "skip-empty-lines": boolean;
74
92
  "max-compression-ratio": number | undefined;
75
93
  "max-decompressed-bytes": number | undefined;
94
+ "max-record-bytes": number | undefined;
76
95
  strict: boolean;
77
96
  "fixed-columns": number | undefined;
78
97
  columns: number[] | undefined;
@@ -86,17 +105,20 @@ export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}
86
105
  "where-noin": readonly import("@konstit/cli").KeyValuePair[];
87
106
  "where-prefix": readonly import("@konstit/cli").KeyValuePair[];
88
107
  "where-regex": readonly import("@konstit/cli").KeyValuePair[];
89
- }, {}, false, "filters" | "zip-limits" | "schema">;
108
+ limit: number | undefined;
109
+ }, {}, false, "zip-limits" | "schema", {}, never>;
90
110
  lines: import("@konstit/cli").HandledCommand<"lines", {
91
111
  path: string;
92
112
  "zip-entry": string | undefined;
93
113
  delimiter: string | undefined;
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;
114
+ encoding: "utf8" | "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" | "latin1" | "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" | "utf-16le" | "x-user-defined" | "auto" | undefined;
95
115
  compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
96
116
  "chunk-size": number | undefined;
97
117
  "skip-rows": number | undefined;
118
+ "skip-empty-lines": boolean;
98
119
  "max-compression-ratio": number | undefined;
99
120
  "max-decompressed-bytes": number | undefined;
121
+ "max-record-bytes": number | undefined;
100
122
  strict: boolean;
101
123
  "fixed-columns": number | undefined;
102
124
  columns: number[] | undefined;
@@ -110,22 +132,30 @@ export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}
110
132
  "where-noin": readonly import("@konstit/cli").KeyValuePair[];
111
133
  "where-prefix": readonly import("@konstit/cli").KeyValuePair[];
112
134
  "where-regex": readonly import("@konstit/cli").KeyValuePair[];
135
+ limit: number | undefined;
136
+ headers: boolean;
137
+ "headers-json": string[] | undefined;
138
+ "column-name": readonly string[];
113
139
  json: boolean;
140
+ mapped: boolean;
141
+ "no-quote": boolean;
142
+ "record-delimiter": "lf" | undefined;
114
143
  "output-delimiter": string;
115
- limit: number | undefined;
116
144
  transform: readonly import("@konstit/cli").KeyValuePair[];
117
145
  "transform-json": unknown;
118
- }, {}, false, "filters" | "zip-limits" | "schema">;
146
+ }, {}, false, "zip-limits" | "schema" | "header-source", {}, never>;
119
147
  probe: import("@konstit/cli").HandledCommand<"probe", {
120
148
  path: string;
121
149
  "zip-entry": string | undefined;
122
150
  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;
151
+ encoding: "utf8" | "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" | "latin1" | "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" | "utf-16le" | "x-user-defined" | "auto" | undefined;
152
+ compression: "auto" | "zip" | "gzip" | "deflate" | "deflate-raw" | "brotli" | "zstd" | "none" | undefined;
124
153
  json: boolean;
125
- }, {}, false, string>;
154
+ "sample-size": number | undefined;
155
+ }, {}, false, string, {}, never>;
126
156
  completion: import("@konstit/cli").HandledCommand<"completion", {
127
157
  shell: "bash" | "zsh" | "fish" | "powershell";
128
- }, {}, boolean, string>;
129
- }, true, string>;
130
- export declare function parseColumnIndex(value: string, label: string): number;
158
+ }, {}, boolean, string, {}, never>;
159
+ }, true, string, {}, never>;
160
+ export declare function runCli(argv: readonly string[], options?: Pick<RunParsedOptions, 'stdin' | 'stdout' | 'stderr'>): Promise<number>;
131
161
  export {};
@@ -8,6 +8,16 @@ import {
8
8
  } from "@konstit/cli";
9
9
  import packageInfo from "../package.json";
10
10
  import {
11
+ formatUsageError,
12
+ parseColumnIndex,
13
+ runCount,
14
+ runLines,
15
+ runProbe
16
+ } from "./cli-command.js";
17
+ import { MAX_INSPECTION_SAMPLE_SIZE } from "./inspect-file.js";
18
+ import { MAX_CHUNK_SIZE } from "./native.js";
19
+ import {
20
+ MAX_COLUMN_INDEX,
11
21
  normalizeColumns,
12
22
  resolveInputEncoding
13
23
  } from "./normalize.js";
@@ -65,16 +75,12 @@ const encodingParser = {
65
75
  }
66
76
  }
67
77
  };
68
- const compressionFormats = ["auto", "none", "gzip", "deflate", "deflate-raw", "brotli", "zstd", "zip"];
69
78
  const positiveUint32 = parsers.range(1, 4294967295, { integer: !0 });
70
79
  const rowCount = parsers.range(0, Number.MAX_SAFE_INTEGER, { integer: !0 });
71
- const byteSize = parsers.custom(parsers.byteSize.label, (input) => {
72
- const bare = Number(input);
73
- return parsers.byteSize.parse(Number.isNaN(bare) ? input : `${bare}B`);
74
- });
75
- const positiveByteSize = parsers.refine(byteSize, (bytes) => bytes > 0, "expected at least 1 byte");
76
- const chunkSize = parsers.refine(positiveByteSize, (bytes) => bytes <= 67108864, "expected at most 64 MiB");
77
- const inputDelimiter = parsers.regex(/^(?:auto|[\p{ASCII}--["\r\n]])$/v);
80
+ const positiveByteSize = parsers.refine(parsers.byteSize, (bytes) => bytes > 0, "expected at least 1 byte");
81
+ const chunkSize = parsers.refine(positiveByteSize, (bytes) => bytes <= MAX_CHUNK_SIZE, "expected at most 64 MiB");
82
+ const sampleSize = parsers.refine(positiveByteSize, (bytes) => bytes <= MAX_INSPECTION_SAMPLE_SIZE, "expected at most 1 MiB");
83
+ const inputDelimiter = parsers.regex(/^(?:auto|[[\p{ASCII}\u0080-\u00ff]--["\r\n]])$/v);
78
84
  const outputDelimiter = parsers.regex(/^[\p{ASCII}--["\r\n]]$/v);
79
85
  const columns = parsers.custom("INDEXES", (value) => {
80
86
  const indexes = value.length === 0 ? [] : value.split(",").map((column) => parseColumnIndex(column, "columns"));
@@ -84,34 +90,34 @@ const columns = parsers.custom("INDEXES", (value) => {
84
90
  const path = positional("path", parsers.string, { required: !0, valueHint: "file", describe: "Input file path" });
85
91
  const zipEntry = option("zip-entry", parsers.refine(parsers.string, (value) => value.length > 0, "expected a non-empty ZIP entry name"), {
86
92
  valueName: "PATH",
87
- describe: "Select an entry inside a ZIP archive"
93
+ describe: "Select a ZIP entry by exact path or glob, using !/ for nested archives"
88
94
  });
89
- const formatArgs = [
90
- option("delimiter", inputDelimiter, { valueName: "CHAR|auto", describe: "One safe ASCII character or auto (default: auto)" }),
91
- option("encoding", encodingParser, {
92
- valueName: "ENCODING",
93
- describe: "Input encoding or decoder alias (default: auto)"
94
- })
95
- ];
95
+ const delimiter = option("delimiter", inputDelimiter, {
96
+ valueName: "CHAR|auto",
97
+ describe: "One single-byte input separator or auto (default: auto). Non-ASCII separators require native Latin-1"
98
+ });
99
+ const encoding = option("encoding", encodingParser, {
100
+ valueName: "ENCODING",
101
+ describe: "Input encoding or decoder alias (default: auto)"
102
+ });
103
+ const compression = option("compression", parsers.enum(["auto", "none", "gzip", "deflate", "deflate-raw", "brotli", "zstd", "zip"]), {
104
+ valueName: "FORMAT",
105
+ describe: "Input compression (default: auto)"
106
+ });
107
+ const filePath = positional("path", parsers.string, { required: !0, valueHint: "file", describe: "Input file path, or - for stdin" });
96
108
  const fileArgs = [
97
- path,
98
- ...formatArgs,
99
- option("compression", parsers.enum(compressionFormats), {
100
- valueName: "FORMAT",
101
- describe: `Input compression (default: auto). Choices: ${compressionFormats.join(", ")}`
102
- }),
103
- option("chunk-size", chunkSize, {
104
- describe: "Read 1 B through 64 MiB per chunk (default: 1MiB). Example: 256KiB"
105
- }),
109
+ option("chunk-size", chunkSize, { describe: "Read 1 B through 64 MiB per chunk (default: 1MiB). Example: 256KiB" }),
106
110
  option("skip-rows", rowCount, { valueName: "N", describe: "Skip the first N input records before filtering, including any header" }),
111
+ flag("skip-empty-lines", { describe: "Ignore records with no bytes before their terminator" }),
107
112
  zipEntry,
108
113
  option("max-compression-ratio", positiveUint32, {
109
114
  valueName: "RATIO",
110
115
  describe: "Maximum ZIP expansion ratio, an integer from 1 through 4294967295"
111
116
  }),
112
117
  option("max-decompressed-bytes", positiveByteSize, { describe: "Maximum decompressed ZIP size (default: 64GiB)" }),
118
+ option("max-record-bytes", positiveByteSize, { describe: "Maximum logical record size, excluding its terminator" }),
113
119
  flag("strict", { describe: "Enable strict RFC 4180 validation" }),
114
- option("fixed-columns", positiveUint32, { valueName: "COUNT", describe: "Require this positive field count in strict mode" }),
120
+ option("fixed-columns", positiveUint32, { valueName: "COUNT", describe: "Require this many fields per input record" }),
115
121
  option("columns", columns, {
116
122
  describe: "Zero-based column indexes in output order. The count command validates the indexes only"
117
123
  }),
@@ -138,8 +144,6 @@ const fileArgs = [
138
144
  })
139
145
  ];
140
146
  const fileRelations = {
141
- requires: [["zip-entry", "compression"]],
142
- requiresIf: [["compression", "zip", "zip-entry"]],
143
147
  groups: [
144
148
  {
145
149
  name: "zip-limits",
@@ -149,43 +153,76 @@ const fileRelations = {
149
153
  },
150
154
  {
151
155
  name: "schema",
152
- members: ["fixed-columns", "expected-header", "require-header", "min-data-rows"],
156
+ members: ["expected-header", "require-header", "min-data-rows"],
153
157
  multiple: !0,
154
158
  requires: ["strict"]
155
- },
156
- {
157
- name: "filters",
158
- members: ["where", "where-eq", "where-neq", "where-in", "where-noin", "where-prefix", "where-regex"],
159
- multiple: !0,
160
- conflicts: ["strict"]
161
159
  }
162
160
  ]
163
161
  };
164
162
  const fileHelp = `ZIP input automatically selects the only data file, ignoring OS metadata.
165
- Explicit ZIP options require --compression zip and --zip-entry.
163
+ Use --zip-entry to select a ZIP member. ZIP limits require --zip-entry.
164
+ Use / or !/ to reach a nested entry, or a quoted glob to select a unique match.
166
165
  Filters use original input column indexes. Friendly filter clauses use AND.
167
- Strict mode cannot use filter options.
166
+ Strict mode validates consumed records, including those rejected by filters.
168
167
 
169
- Encodings: ${encodings.choices?.map(({ value, aliases }) => aliases ? `${value} (${aliases.join(", ")})` : value).join(", ")}
170
- Other Bun TextDecoder labels are also accepted.`;
168
+ Other Bun TextDecoder labels are also accepted by --encoding.`;
171
169
  const count = command("count", {
172
170
  ...fileRelations,
173
171
  about: "Count CSV records, including the header row",
174
- args: fileArgs,
175
- afterHelp: `${fileHelp}
176
-
177
- Examples:
178
- csv count data.csv --chunk-size 256KiB
179
- csv count data.csv --where-eq 2=SP
180
- csv count data.csv --where-regex '1=/^ana/i'`
172
+ args: [
173
+ filePath,
174
+ delimiter,
175
+ encoding,
176
+ compression,
177
+ ...fileArgs,
178
+ option("limit", rowCount, {
179
+ valueName: "N",
180
+ describe: "Stop after N matching records (0 counts none)"
181
+ })
182
+ ],
183
+ camelCaseArgs: !0,
184
+ handler: (args, context) => runCount(args, context),
185
+ afterHelp: fileHelp,
186
+ examples: [
187
+ { command: "cat data.csv | csv count -" },
188
+ { command: "csv count data.csv --chunk-size 256KiB" },
189
+ { args: { path: "data.csv", "where-eq": ["2=SP"], limit: 10 } },
190
+ { args: { path: "data.csv", "where-regex": ["1=/^ana/i"] } }
191
+ ]
181
192
  });
182
193
  const lines = command("lines", {
183
- ...fileRelations,
184
- conflicts: [["json", "output-delimiter"]],
194
+ groups: [...fileRelations.groups, { name: "header-source", members: ["headers", "headers-json"] }],
195
+ requires: [["mapped", "json"]],
196
+ requiresGroup: [["mapped", "header-source"], ["column-name", "header-source"]],
197
+ conflicts: [
198
+ ["json", "output-delimiter"],
199
+ ["columns", "column-name"],
200
+ ["columns", "headers"],
201
+ ["columns", "headers-json"],
202
+ ["strict", "no-quote"],
203
+ ["strict", "record-delimiter"]
204
+ ],
185
205
  about: "Stream matching records as normalized UTF-8 CSV or NDJSON",
186
206
  args: [
207
+ filePath,
208
+ delimiter,
209
+ encoding,
210
+ compression,
187
211
  ...fileArgs,
188
- flag("json", { describe: "Emit one JSON string array per record (NDJSON)" }),
212
+ flag("headers", { describe: "Read column names from the input header and omit that record" }),
213
+ option("headers-json", parsers.refine(parsers.json(), (value) => Array.isArray(value) && value.every((name) => typeof name === "string") && value.length <= MAX_COLUMN_INDEX + 1 && new Set(value).size === value.length, "expected an array of unique column names"), {
214
+ valueName: "JSON",
215
+ describe: "Assign a JSON array of unique column names without consuming a record"
216
+ }),
217
+ option("column-name", parsers.string, {
218
+ repeatable: !0,
219
+ unique: !0,
220
+ describe: "Select a header name in output order. Repeat for more columns"
221
+ }),
222
+ flag("json", { describe: "Emit one JSON array per record (NDJSON), or objects with --mapped" }),
223
+ flag("mapped", { describe: "Emit NDJSON objects keyed by column name. Requires --json and a header source" }),
224
+ flag("no-quote", { describe: "Treat double quotes in the input as literal data" }),
225
+ option("record-delimiter", parsers.enum(["lf"]), { describe: "End input records at LF and retain CR as data" }),
189
226
  option("output-delimiter", outputDelimiter, {
190
227
  valueName: "CHAR",
191
228
  default: ",",
@@ -202,23 +239,37 @@ const lines = command("lines", {
202
239
  }),
203
240
  option("transform-json", parsers.json(), {
204
241
  valueName: "JSON",
205
- describe: "Apply an array of column transform chains, including replace, map, and date"
242
+ describe: "Apply transform chains by index or header name, including replace, map, and date"
206
243
  })
207
244
  ],
245
+ camelCaseArgs: !0,
246
+ handler: (args, context) => runLines(args, context),
208
247
  afterHelp: `${fileHelp}
209
248
 
249
+ With a header source, --where and --transform-json also accept column names.
210
250
  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.
212
-
213
- Examples:
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'`
251
+ Header and minimum data row checks apply to the consumed input prefix.`,
252
+ examples: [
253
+ { command: "cat data.csv | csv lines - --json" },
254
+ { args: { path: "data.csv", json: !0, "skip-rows": 1, limit: 10 } },
255
+ { args: { path: "data.csv", columns: "0,2", "where-eq": ["3=active"] } },
256
+ { args: { path: "data.csv", "skip-rows": 1, transform: ["1,2=trim,upper"] } }
257
+ ]
217
258
  });
218
259
  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."
260
+ about: "Inspect CSV format and sampled record widths",
261
+ args: [
262
+ path,
263
+ delimiter,
264
+ encoding,
265
+ compression,
266
+ zipEntry,
267
+ option("sample-size", sampleSize, { describe: "Sample 1 B through 1 MiB of decompressed CSV (default: 64KiB)" }),
268
+ flag("json", { describe: "Emit the inspection as one JSON object" })
269
+ ],
270
+ camelCaseArgs: !0,
271
+ handler: (args, context) => runProbe(args, context),
272
+ afterHelp: "Omit --zip-entry to see the ZIP tree. Select by exact path or Bun glob. For a nested ZIP, use nested.zip/path or nested.zip!/path."
222
273
  });
223
274
  export const csvCommand = command("csv", {
224
275
  about: "Inspect, count, and stream CSV records",
@@ -231,14 +282,24 @@ export const csvCommand = command("csv", {
231
282
  probe,
232
283
  command("completion", {
233
284
  about: "Print a shell completion script for csv",
234
- args: [positional("shell", parsers.enum(completionShells), { required: !0, describe: completionShells.join(", ") })]
285
+ args: [positional("shell", parsers.enum(completionShells), { required: !0 })],
286
+ handler: async ({ shell }, { stdout }) => {
287
+ const { generateCompletion } = await import("@konstit/cli/completion");
288
+ await stdout(`${generateCompletion(csvCommand, shell).trimEnd()}
289
+ `);
290
+ }
235
291
  })
236
292
  ],
237
293
  afterHelp: "Run without installing: bunx @konstit/csv <command> <path>"
238
294
  });
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;
295
+ export async function runCli(argv, options) {
296
+ const result = csvCommand.tryParse(argv);
297
+ if (result.type === "error") {
298
+ const { commandPath, exitCode, message } = result.error;
299
+ const stderr = options?.stderr ?? ((chunk) => Bun.write(Bun.stderr, chunk));
300
+ await stderr(`${formatUsageError(message, commandPath)}
301
+ `);
302
+ return exitCode;
303
+ }
304
+ return csvCommand.runParsed(result, options);
244
305
  }
package/dist/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env bun
2
- import { runCli } from "./cli-command.js";
2
+ import { runCli } from "./cli-schema.js";
3
3
  process.exitCode = await runCli(Bun.argv.slice(2));
@@ -1,5 +1,6 @@
1
- import type { CsvDelimiter, CsvFileOptions } from './types.js';
1
+ import type { CsvDelimiter, CsvFileOptions, CsvInput } from './types.js';
2
2
  export declare const FILE_PROBE_SIZE: number;
3
+ export declare const COMPRESSION_PROBE_SIZE = 64;
3
4
  export declare const DELIMITER_CANDIDATES: readonly [{
4
5
  readonly byte: 44;
5
6
  readonly delimiter: ",";
@@ -25,49 +26,96 @@ export declare const DELIMITER_CANDIDATES: readonly [{
25
26
  readonly byte: 64;
26
27
  readonly delimiter: "@";
27
28
  }];
28
- interface CompressionExtensionHint {
29
- extension: string;
30
- format: Bun.CompressionFormat;
31
- signatureRequired: boolean;
32
- }
29
+ export type ResolvedCompression = Bun.CompressionFormat | 'none' | 'zip';
30
+ type CompressionProbeSource = {
31
+ readonly kind: 'stream';
32
+ } | {
33
+ readonly kind: 'file' | 'inspection';
34
+ readonly path: string;
35
+ };
33
36
  export interface CsvFileInput extends AsyncDisposable {
34
37
  readonly delimiter: CsvDelimiter;
35
38
  /** Encoding expected by the native parser after any stream transcoding. */
36
39
  readonly parserEncoding: 'utf8' | 'latin1';
40
+ /** True when the input is large enough, undefined when parse-ahead is unavailable. */
41
+ readonly canParseAhead?: boolean | undefined;
37
42
  chunks(): AsyncIterable<Uint8Array>;
38
43
  }
39
- export type CsvFileProbe = (path: string, prefix: Uint8Array, sourceEnded: boolean, delimiter: CsvDelimiter) => {
44
+ interface FileReadAhead {
45
+ readonly minimumParseAheadBytes: number;
46
+ canParseAhead: boolean;
47
+ }
48
+ interface DelimiterScores {
49
+ stableCounts: ArrayLike<number>;
50
+ quotedFields: ArrayLike<number>;
51
+ hasCompleteRecords: boolean;
52
+ hasSeparator: boolean;
53
+ }
54
+ type ProbeDialect = Pick<CsvFileOptions, 'quote' | 'recordDelimiter'>;
55
+ export type CsvFileProbe = (path: string, prefix: Uint8Array, sourceEnded: boolean, delimiter: CsvDelimiter, dialect?: ProbeDialect) => {
40
56
  delimiter: CsvDelimiter;
41
57
  encoding: 'utf8' | 'latin1' | 'windows-1252' | 'utf-16le' | 'utf-16be';
42
58
  skipBytes: number;
43
59
  };
44
- type FileReadMode = 'stream' | 'parse' | 'read-ahead' | 'count';
45
- export declare function prepareCsvFileInput(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression' | 'delimiter' | 'encoding'>, readMode?: FileReadMode, probeFormat?: CsvFileProbe): Promise<CsvFileInput>;
46
- export declare function readCsvFileChunks(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression'>, readMode?: FileReadMode): AsyncIterable<Uint8Array>;
60
+ type FileReadMode = 'stream' | 'parse' | 'batches' | 'read-ahead' | 'count' | 'raw-records';
61
+ export declare function prepareCsvFileInput(path: CsvInput, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression' | 'delimiter' | 'encoding'> & ProbeDialect, readMode?: FileReadMode, probeFormat?: CsvFileProbe): Promise<PreparedCsvFileInput>;
62
+ type CsvChunkIterator = AsyncIterator<Uint8Array, void>;
63
+ type CsvChunkResult = IteratorResult<Uint8Array, void>;
64
+ interface ActiveCsvFileInput {
65
+ phase: 'ready' | 'reading-prefix' | 'reading';
66
+ source: CsvChunkIterator | (() => CsvChunkIterator);
67
+ probedSource: CsvChunkIterator | undefined;
68
+ replay: Iterator<Uint8Array, void> | undefined;
69
+ }
70
+ declare class PreparedCsvFileInput implements CsvFileInput {
71
+ #private;
72
+ readonly delimiter: CsvDelimiter;
73
+ readonly parserEncoding: 'utf8' | 'latin1';
74
+ constructor(delimiter: CsvDelimiter, parserEncoding: 'utf8' | 'latin1', source: ActiveCsvFileInput['source'], readAhead: FileReadAhead | undefined, probedSource?: CsvChunkIterator);
75
+ get canParseAhead(): boolean | undefined;
76
+ /** Inspect an input prefix and put back the bytes that the data parser needs to see. */
77
+ readPrefix<T>(inspect: (next: () => Promise<CsvChunkResult>) => Promise<{
78
+ value: T;
79
+ replay: Iterator<Uint8Array, void>;
80
+ }>): Promise<T>;
81
+ chunks(): AsyncIterableIterator<Uint8Array, void>;
82
+ [Symbol.asyncDispose](): Promise<void>;
83
+ }
84
+ export declare function readCsvFileChunks(path: string, suppliedOptions: Pick<CsvFileOptions, 'chunkSize' | 'compression'>, readMode?: FileReadMode, onZipEntryName?: (name: string) => void, readAhead?: FileReadAhead): AsyncIterable<Uint8Array>;
47
85
  export declare function rejectCompressedSharding(options: Pick<CsvFileOptions, 'compression'>, operation: string): void;
48
- export declare function rejectAutoDelimiterSharding(options: Pick<CsvFileOptions, 'delimiter'>, operation: string): void;
49
- export declare function detectDelimiter(path: string, probe: Uint8Array, sourceEnded: boolean): CsvDelimiter;
86
+ export declare function detectDelimiter(path: string, probe: Uint8Array, sourceEnded: boolean, dialect?: ProbeDialect): CsvDelimiter;
87
+ export declare function detectBufferDelimiter(input: NodeJS.TypedArray | DataView, path: string, final: boolean, dialect?: ProbeDialect, stripBom?: boolean): CsvDelimiter;
50
88
  /** Detect the encoding and, when requested, score delimiters on the same prefix. */
51
89
  export declare const probeCsvFileFormat: CsvFileProbe;
52
90
  interface CsvFormatSample {
53
91
  bytes: Uint8Array;
54
92
  encoding: ReturnType<CsvFileProbe>['encoding'];
93
+ hasBom: boolean;
55
94
  skipBytes: number;
56
- counts: readonly Uint32Array[];
95
+ scores?: DelimiterScores;
57
96
  }
58
97
  /** When scoring delimiters, structural bytes exclude the BOM and use UTF-8 for UTF-16 input. */
59
- export declare function scanCsvFileFormat(prefix: Uint8Array, sourceEnded: boolean, scoreDelimiters: boolean): CsvFormatSample;
98
+ export declare function scanCsvFileFormat(prefix: Uint8Array, sourceEnded: boolean, scoreDelimiters: boolean, dialect?: ProbeDialect): CsvFormatSample;
60
99
  type DelimiterChoice = {
61
100
  delimiter: CsvDelimiter;
101
+ extensionHint?: string;
102
+ extensionBrokeTie?: true;
62
103
  } | {
63
104
  reason: 'no-records' | 'no-stable-separator';
105
+ } | {
106
+ reason: 'weak-separator';
107
+ candidate: CsvDelimiter;
64
108
  } | {
65
109
  reason: 'ambiguous';
66
110
  candidates: readonly CsvDelimiter[];
111
+ conflictingHint?: true;
67
112
  };
68
- export declare function selectDelimiter(path: string, rows: readonly ArrayLike<number>[]): DelimiterChoice;
69
- export declare function scanDelimiterCounts(probe: Uint8Array, sourceEnded: boolean): number[][];
113
+ export declare function delimiterAmbiguityError(candidates: readonly CsvDelimiter[]): Error;
114
+ export declare function selectDelimiter(path: string, scores: DelimiterScores): DelimiterChoice;
115
+ export declare function scanDelimiterScores(probe: Uint8Array, sourceEnded: boolean, { quote, recordDelimiter }?: ProbeDialect, maxRows?: number): DelimiterScores;
116
+ export declare function isDelimiterCandidate(byte: number | undefined): boolean;
70
117
  export declare function isZipSignature(prefix: Uint8Array): boolean;
71
- export declare function compressionFromPrefix(path: string, prefix: Uint8Array): Bun.CompressionFormat | undefined;
72
- export declare function compressionFromExtension(path: string): CompressionExtensionHint | undefined;
118
+ /** Select a reader from a bounded prefix. A live source can continue supplying evidence. */
119
+ export declare function probeCompression(prefix: Uint8Array, sourceEnded: true, source: CompressionProbeSource): ResolvedCompression;
120
+ export declare function probeCompression(prefix: Uint8Array, sourceEnded: boolean, source: CompressionProbeSource): ResolvedCompression | 'need-more';
73
121
  export {};