@konstit/csv 0.5.1 → 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.
package/README.md CHANGED
@@ -143,6 +143,33 @@ The filter also applies to the header, which does not match `'SP'` here. Combine
143
143
  See [Filters](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#filters) for matching rules
144
144
  and supported regex syntax.
145
145
 
146
+ ### Transform accepted rows
147
+
148
+ To print each person's name and state from `data.csv`, expand the state abbreviation in column 2. If you also supply `where`, it checks the original fields before the transforms run.
149
+
150
+ ```ts
151
+ import { csv } from '@konstit/csv';
152
+
153
+ const stateName = csv.column(2).map({ SP: 'São Paulo', RJ: 'Rio de Janeiro' });
154
+ for await (
155
+ const batch of csv.rows('data.csv', {
156
+ skipRows: 1,
157
+ columns: [1, 2],
158
+ transform: [stateName],
159
+ })
160
+ ) {
161
+ for (const [name, state,] of batch) {
162
+ console.log(`${name}, ${state}`);
163
+ }
164
+ }
165
+ // Ada, São Paulo
166
+ // Grace, Rio de Janeiro
167
+ ```
168
+
169
+ Run `bun run examples/api-rows-transforms.ts` from the repository to try two more [streaming examples](https://github.com/Konstit-Engenharia/csv-parser/blob/main/examples/api-rows-transforms.ts) with sample orders. The first cleans names, cities, and amounts. The second formats order IDs using numbered and named captures.
170
+
171
+ See [field transforms](https://github.com/Konstit-Engenharia/csv-parser/blob/main/docs/api.md#field-transforms) for Unicode rules, replacement, value mapping, and date formatting.
172
+
146
173
  ### Read compressed files
147
174
 
148
175
  Create a gzip copy of the sample file:
@@ -2,6 +2,105 @@
2
2
 
3
3
  This file tracks third-party code incorporated into distributed native binaries and third-party test data, examples, and compatibility references used by this repository.
4
4
 
5
+ ## uni-algo and the Unicode Character Database
6
+
7
+ The native library uses [uni-algo v1.2.0](https://github.com/uni-algo/uni-algo/tree/v1.2.0) under its public domain license and incorporates its Unicode 15.1 data for normalization, casing and whitespace.
8
+ The Diacritic property table is derived from [Unicode 17.0 PropList.txt](https://www.unicode.org/Public/17.0.0/ucd/PropList.txt).
9
+
10
+ ### Unicode 15.1 data license
11
+
12
+ This software contains data derived from processing the Unicode data files.
13
+ The following license applies to the data files: https://www.unicode.org/license.txt
14
+
15
+ UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
16
+
17
+ See Terms of Use <https://www.unicode.org/copyright.html>
18
+ for definitions of Unicode Inc.'s Data Files and Software.
19
+
20
+ NOTICE TO USER: Carefully read the following legal agreement.
21
+ BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S
22
+ DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"),
23
+ YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
24
+ TERMS AND CONDITIONS OF THIS AGREEMENT.
25
+ IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE
26
+ THE DATA FILES OR SOFTWARE.
27
+
28
+ COPYRIGHT AND PERMISSION NOTICE
29
+
30
+ Copyright (c) 1991-2023 Unicode, Inc. All rights reserved.
31
+ Distributed under the Terms of Use in https://www.unicode.org/copyright.html.
32
+
33
+ Permission is hereby granted, free of charge, to any person obtaining
34
+ a copy of the Unicode data files and any associated documentation
35
+ (the "Data Files") or Unicode software and any associated documentation
36
+ (the "Software") to deal in the Data Files or Software
37
+ without restriction, including without limitation the rights to use,
38
+ copy, modify, merge, publish, distribute, and/or sell copies of
39
+ the Data Files or Software, and to permit persons to whom the Data Files
40
+ or Software are furnished to do so, provided that either
41
+ (a) this copyright and permission notice appear with all copies
42
+ of the Data Files or Software, or
43
+ (b) this copyright and permission notice appear in associated
44
+ Documentation.
45
+
46
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
47
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
48
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
49
+ NONINFRINGEMENT OF THIRD PARTY RIGHTS.
50
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
51
+ NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
52
+ DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
53
+ DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
54
+ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
55
+ PERFORMANCE OF THE DATA FILES OR SOFTWARE.
56
+
57
+ Except as contained in this notice, the name of a copyright holder
58
+ shall not be used in advertising or otherwise to promote the sale,
59
+ use or other dealings in these Data Files or Software without prior
60
+ written authorization of the copyright holder.
61
+
62
+ ### Unicode 17.0 Diacritic data
63
+
64
+ UNICODE LICENSE V3
65
+
66
+ COPYRIGHT AND PERMISSION NOTICE
67
+
68
+ Copyright © 1991-2026 Unicode, Inc.
69
+
70
+ NOTICE TO USER: Carefully read the following legal agreement. BY
71
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
72
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
73
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
74
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
75
+
76
+ Permission is hereby granted, free of charge, to any person obtaining a
77
+ copy of data files and any associated documentation (the "Data Files") or
78
+ software and any associated documentation (the "Software") to deal in the
79
+ Data Files or Software without restriction, including without limitation
80
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
81
+ copies of the Data Files or Software, and to permit persons to whom the
82
+ Data Files or Software are furnished to do so, provided that either (a)
83
+ this copyright and permission notice appear with all copies of the Data
84
+ Files or Software, or (b) this copyright and permission notice appear in
85
+ associated Documentation.
86
+
87
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
88
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
89
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
90
+ THIRD PARTY RIGHTS.
91
+
92
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
93
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
94
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
95
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
96
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
97
+ FILES OR SOFTWARE.
98
+
99
+ Except as contained in this notice, the name of a copyright holder shall
100
+ not be used in advertising or otherwise to promote the sale, use or other
101
+ dealings in these Data Files or Software without prior written
102
+ authorization of the copyright holder.
103
+
5
104
  ## RE2
6
105
 
7
106
  - Source: https://github.com/google/re2
package/dist/api.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { NativeCsvBatch } from './batches.js';
2
2
  import type { CsvFileProbe } from './file-stream.js';
3
3
  import { all, any, column, not, re } from './filter.js';
4
+ import { transform } from './transforms.js';
4
5
  import type { CsvBatchesOptions, CsvColumns, CsvCountOptions, CsvParseOptions, CsvProjectedRow, CsvRowsOptions, CsvShard, CsvShardingOptions } from './types.js';
5
6
  /**
6
7
  * Parse one in-memory CSV buffer into materialized rows.
@@ -101,6 +102,8 @@ declare function findCsvSafeShards(path: string, shardCount: number, suppliedOpt
101
102
  * record-safe sharding helpers in one discoverable object.
102
103
  */
103
104
  export declare const csv: {
105
+ /** Build a reusable field transform, then bind it to physical input columns with on(). */
106
+ transform: typeof transform;
104
107
  /**
105
108
  * Combine one or more filters with logical AND semantics.
106
109
  * @param first - First filter in the group.
package/dist/api.js CHANGED
@@ -15,7 +15,10 @@ import {
15
15
  not,
16
16
  re
17
17
  } from "./filter.js";
18
- import { latin1Rows } from "./latin1-rows.js";
18
+ import {
19
+ canUseFilteredLatin1Cleanup,
20
+ latin1Rows
21
+ } from "./latin1-rows.js";
19
22
  import { latin1RowsParser } from "./native.js";
20
23
  import {
21
24
  normalizeFixedColumnsCount,
@@ -30,6 +33,7 @@ import {
30
33
  validateRowSelection
31
34
  } from "./parser.js";
32
35
  import { rejectStrictSchemaUnsupported } from "./strict-schema.js";
36
+ import { transform } from "./transforms.js";
33
37
  export async function parse(buffer, suppliedOptions = {}) {
34
38
  const options = snapshotCsvOptions(suppliedOptions);
35
39
  if ("compression" in options && options.compression !== void 0)
@@ -41,13 +45,8 @@ export async function parse(buffer, suppliedOptions = {}) {
41
45
  const columns = options.columns;
42
46
  const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
43
47
  const input = prepareCsvBufferInput(buffer, options.encoding, options.delimiter);
44
- using parser = createPreparedParser(toParserOptions(options, input.parserEncoding), projected ? columns : void 0, filters);
45
- const batch = parser.writeBatch(input.bytes, !0);
46
- try {
47
- return materializeRows(batch, columns, projected);
48
- } finally {
49
- batch.close();
50
- }
48
+ using parser = createPreparedParser(toParserOptions(options, input.parserEncoding), projected ? columns : void 0, filters, options.transform);
49
+ return consumeBatchRows(parser.writeBatch(input.bytes, !0), columns, projected);
51
50
  }
52
51
  export function rows(path, options = {}) {
53
52
  return iterateRows(path, snapshotCsvOptions(options));
@@ -58,19 +57,19 @@ export async function* iterateRows(path, options, probeFormat) {
58
57
  const columns = options.columns;
59
58
  const projected = filters !== void 0 || options.strict !== !0 && columns !== void 0;
60
59
  await using input = await prepareCsvFileInput(path, options, "read-ahead", probeFormat);
61
- const parserOptions = toParserOptions(options, input.parserEncoding, input.delimiter);
62
60
  const reusableRows = options.reuseArrays === !0 ? [] : void 0;
63
- if (options.strict !== !0 && input.parserEncoding === "latin1") {
61
+ if (options.strict !== !0 && input.parserEncoding === "latin1" && (!options.transform?.length || canUseFilteredLatin1Cleanup(columns, filters, options.transform))) {
64
62
  validateRowSelection(options);
65
63
  const fixedColumns = normalizeFixedColumnsCount(options.fixedColumns, "fixed column count");
66
- const createParser = latin1RowsParser(fixedColumns);
64
+ const createParser = latin1RowsParser(fixedColumns, Boolean(options.transform?.length));
67
65
  const chunks = options.limit === 0 ? [] : input.chunks();
68
- yield* latin1Rows(chunks, input.delimiter, columns, filters, createParser, reusableRows, parserOptions);
66
+ yield* latin1Rows(chunks, input.delimiter, columns, filters, createParser, reusableRows, options);
69
67
  return;
70
68
  }
71
- using parser = createPreparedParser(parserOptions, projected ? columns : void 0, filters);
72
- for await (using batch of parseFileChunks(input, parser, options.limit))
73
- yield materializeRows(batch, columns, projected, reusableRows);
69
+ const parserOptions = toParserOptions(options, input.parserEncoding, input.delimiter);
70
+ using parser = createPreparedParser(parserOptions, projected ? columns : void 0, filters, options.transform, "rows");
71
+ for await (const batch of parseFileChunks(input, parser, options.limit))
72
+ yield consumeBatchRows(batch, columns, projected, reusableRows);
74
73
  }
75
74
  export function batches(path, options = {}) {
76
75
  return iterateBatches(path, snapshotCsvOptions(options));
@@ -82,7 +81,7 @@ async function* iterateBatches(path, options) {
82
81
  if (options.strict === !0 && columns !== void 0)
83
82
  throw Error("strict CSV validation is not supported for projected batches; use csv.rows() for strict projection");
84
83
  await using input = await prepareCsvFileInput(path, options);
85
- using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), columns, filters);
84
+ using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), columns, filters, options.transform);
86
85
  yield* parseFileChunks(input, parser, options.limit);
87
86
  }
88
87
  export async function count(path, suppliedOptions = {}) {
@@ -91,8 +90,7 @@ export async function count(path, suppliedOptions = {}) {
91
90
  await using input = await prepareCsvFileInput(path, options, "count");
92
91
  if (options.strict === !0 && filters !== void 0)
93
92
  throw Error("strict CSV validation is not supported for count filters");
94
- using parser = createPreparedParser(toParserOptions(options, input.parserEncoding, input.delimiter), void 0, filters);
95
- return await countFileChunks(input, parser, options);
93
+ return await countFileChunks(input, toParserOptions(options, input.parserEncoding, input.delimiter), filters);
96
94
  }
97
95
  function findCsvSafeSplitOffsets(path, shardCount, suppliedOptions = {}) {
98
96
  const options = snapshotCsvOptions(suppliedOptions);
@@ -110,6 +108,7 @@ function shardingDelimiter(options, operation) {
110
108
  return options.delimiter ?? ",";
111
109
  }
112
110
  export const csv = {
111
+ transform,
113
112
  all,
114
113
  any,
115
114
  column,
@@ -136,7 +135,8 @@ function toParserOptions(options, encoding, delimiter = options.delimiter) {
136
135
  minDataRows: options.minDataRows
137
136
  };
138
137
  }
139
- function materializeRows(batch, columns, projected, target = []) {
138
+ function consumeBatchRows(nativeBatch, columns, projected, target = []) {
139
+ using batch = nativeBatch;
140
140
  return batch.rowsInto(target, projected ? void 0 : columns);
141
141
  }
142
142
  function rejectFilteredStrictSchema(options) {
package/dist/batches.js CHANGED
@@ -1,5 +1,9 @@
1
1
  import { read } from "bun:ffi";
2
- import { decodeMaterializedField } from "./materialize-field.js";
2
+ import { isUtf8 } from "node:buffer";
3
+ import {
4
+ decodeMaterializedField,
5
+ prepareRow
6
+ } from "./materialize-field.js";
3
7
  import {
4
8
  EMPTY_BUFFER,
5
9
  native,
@@ -12,6 +16,8 @@ import {
12
16
  normalizeFilterColumn
13
17
  } from "./normalize.js";
14
18
  const visitBatchRows = Symbol("visitBatchRows");
19
+ const WINDOW_BYTES = 1024;
20
+ const MAX_WINDOW_FIELD_BYTES = 64;
15
21
 
16
22
  export class NativeCsvRowView {
17
23
  #data;
@@ -145,14 +151,13 @@ export class NativeCsvBatch {
145
151
  const rowOffsetWords = this.#rowOffsetWordsView();
146
152
  const fieldOffsetWords = this.#fieldOffsetWordsView();
147
153
  const data = this.data();
154
+ const dataLength = data.byteLength;
148
155
  target.length = rowCount;
149
156
  if (columns !== void 0) {
150
157
  for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
151
- const fieldStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
152
- const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
153
- const existing = target[rowIndex];
154
- const row = existing === void 0 ? [] : existing;
155
- row.length = selectedColumns.length;
158
+ const fieldStart = offsetAt(rowOffsetWords, rowIndex, rowIndex, totalFields);
159
+ const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, rowIndex, totalFields);
160
+ const row = prepareRow(target[rowIndex], selectedColumns.length);
156
161
  for (let outputIndex = 0;outputIndex < selectedColumns.length; ++outputIndex) {
157
162
  const column = selectedColumns[outputIndex] ?? 0;
158
163
  const fieldIndex = fieldStart + column;
@@ -160,27 +165,63 @@ export class NativeCsvBatch {
160
165
  row[outputIndex] = "";
161
166
  continue;
162
167
  }
163
- const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", data.byteLength);
164
- const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", data.byteLength);
168
+ const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", dataLength);
169
+ const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", dataLength);
165
170
  row[outputIndex] = decodeMaterializedField(data, start, end, "utf8");
166
171
  }
167
172
  target[rowIndex] = row;
168
173
  }
169
174
  return target;
170
175
  }
176
+ let windowStart = 0;
177
+ let windowEnd = 0;
178
+ let text = "";
179
+ let byteIndexed = !0;
180
+ let utf16Offsets;
181
+ const flags = native.symbols.csv_batch_quoted_rows_ptr(this.#requireHandle());
182
+ const quotedRows = flags === null ? void 0 : new Uint8Array(toArrayBuffer(flags, 0, rowCount));
183
+ let fieldStart = offsetAt(rowOffsetWords, 0, 0, totalFields);
184
+ let start = offsetAt(fieldOffsetWords, fieldStart, "field offset", dataLength);
171
185
  for (let rowIndex = 0;rowIndex < rowCount; ++rowIndex) {
172
- const fieldStart = offsetAt(rowOffsetWords, rowIndex, `row ${rowIndex} offset`, totalFields);
173
- const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, `row ${rowIndex} offset`, totalFields);
174
- const existing = target[rowIndex];
175
- const row = existing === void 0 ? [] : existing;
176
- row.length = fieldEnd - fieldStart;
186
+ const fieldEnd = offsetAt(rowOffsetWords, rowIndex + 1, rowIndex, totalFields);
187
+ const row = prepareRow(target[rowIndex], fieldEnd - fieldStart);
188
+ const leading = quotedRows?.[rowIndex] ?? 0;
189
+ const trailing = leading * 2;
177
190
  for (let fieldIndex = fieldStart;fieldIndex < fieldEnd; ++fieldIndex) {
178
- const start = offsetAt(fieldOffsetWords, fieldIndex, "field offset", data.byteLength);
179
- const end = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", data.byteLength);
191
+ const rawEnd = offsetAt(fieldOffsetWords, fieldIndex + 1, "field offset", dataLength);
192
+ const end = rawEnd - trailing;
193
+ start += leading;
180
194
  const column = fieldIndex - fieldStart;
181
- row[column] = decodeMaterializedField(data, start, end, "utf8");
195
+ const length = end - start;
196
+ let value;
197
+ if (length > 2 && length <= MAX_WINDOW_FIELD_BYTES) {
198
+ if (start < windowStart || end > windowEnd) {
199
+ windowStart = start;
200
+ windowEnd = utf8WindowEnd(data, start);
201
+ text = decodeMaterializedField(data, start, windowEnd, "utf8");
202
+ byteIndexed = text.length === windowEnd - start;
203
+ if (!byteIndexed) {
204
+ utf16Offsets ??= new Int16Array(WINDOW_BYTES + 1);
205
+ if (!indexUtf16Boundaries(data.subarray(start, windowEnd), utf16Offsets))
206
+ text = "";
207
+ }
208
+ }
209
+ const from = start - windowStart;
210
+ const to = end - windowStart;
211
+ if (byteIndexed)
212
+ value = text.slice(from, to);
213
+ else if (text.length > 0 && utf16Offsets !== void 0) {
214
+ const first = utf16Offsets[from] ?? -1;
215
+ const last = utf16Offsets[to] ?? -1;
216
+ if (first >= 0 && last >= 0)
217
+ value = text.slice(first, last);
218
+ }
219
+ }
220
+ row[column] = value ?? decodeMaterializedField(data, start, end, "utf8");
221
+ start = rawEnd;
182
222
  }
183
223
  target[rowIndex] = row;
224
+ fieldStart = fieldEnd;
184
225
  }
185
226
  return target;
186
227
  }
@@ -385,18 +426,49 @@ const MAX_DIRECT_ROW_INDEX_EXCLUSIVE = Math.floor(2147483647 / BigUint64Array.BY
385
426
  function offsetWords(offsets) {
386
427
  return new Uint32Array(offsets.buffer, offsets.byteOffset, offsets.length * 2);
387
428
  }
429
+ function utf8WindowEnd(data, start) {
430
+ const limit = start + WINDOW_BYTES;
431
+ if (limit >= data.length)
432
+ return data.length;
433
+ let end = limit;
434
+ while (limit - end < 3 && (data[end] & 192) === 128)
435
+ --end;
436
+ return end;
437
+ }
438
+ function indexUtf16Boundaries(bytes, offsets) {
439
+ if (!isUtf8(bytes))
440
+ return !1;
441
+ let units = 0;
442
+ for (let i = 0;i < bytes.length; ++i) {
443
+ const byte = bytes[i];
444
+ if ((byte & 192) === 128)
445
+ offsets[i] = -1;
446
+ else {
447
+ offsets[i] = units;
448
+ units += byte >= 240 ? 2 : 1;
449
+ }
450
+ }
451
+ offsets[bytes.length] = units;
452
+ return !0;
453
+ }
388
454
  function offsetAt(offsets, index, label, upperBound) {
389
455
  const wordIndex = index * 2;
390
456
  const low = offsets[wordIndex];
391
457
  const high = offsets[wordIndex + 1];
392
- if (low === void 0 || high === void 0 || wordIndex % 2 !== 0)
393
- throw RangeError(`${label} index out of range: ${index}`);
458
+ if (high === 0 && low !== void 0 && low <= upperBound && Number.isInteger(index))
459
+ return low;
460
+ return checkedWideOffset(low, high, index, label, upperBound);
461
+ }
462
+ function checkedWideOffset(low, high, index, label, upperBound) {
463
+ const description = typeof label === "number" ? `row ${label} offset` : label;
464
+ if (low === void 0 || high === void 0 || !Number.isInteger(index))
465
+ throw RangeError(`${description} index out of range: ${index}`);
394
466
  if (high > MAX_SAFE_OFFSET_HIGH_WORD) {
395
467
  const value = BigInt(high) * UINT32_BASE_BIGINT + BigInt(low);
396
- throw RangeError(`${label} exceeds Number.MAX_SAFE_INTEGER: ${value}`);
468
+ throw RangeError(`${description} exceeds Number.MAX_SAFE_INTEGER: ${value}`);
397
469
  }
398
470
  const offset = low + high * UINT32_BASE;
399
471
  if (offset > upperBound)
400
- throw RangeError(`${label} exceeds backing storage: ${offset}`);
472
+ throw RangeError(`${description} exceeds backing storage: ${offset}`);
401
473
  return offset;
402
474
  }
@@ -5,7 +5,11 @@ import {
5
5
  } from "./cli-schema.js";
6
6
  import { formatBytes } from "./format-bytes.js";
7
7
  import { inspectCsvFile } from "./inspect-file.js";
8
- import { normalizeFilterColumn } from "./normalize.js";
8
+ import {
9
+ normalizeFilterColumn,
10
+ validateRegex
11
+ } from "./normalize.js";
12
+ import { snapshotTransforms } from "./transforms.js";
9
13
  const MAX_FILTER_NESTING = 128;
10
14
  const OUTPUT_BUFFER_SIZE = 65536;
11
15
  export async function runCli(arguments_, customOutput) {
@@ -82,7 +86,7 @@ async function runCount(args, output) {
82
86
  async function runLines(args, output) {
83
87
  let options;
84
88
  try {
85
- options = { ...parseCommonOptions(args), limit: args.limit };
89
+ options = { ...parseCommonOptions(args), limit: args.limit, transform: parseTransformOptions(args) };
86
90
  } catch (error) {
87
91
  return usageError(output, error instanceof Error ? error.message : String(error), "csv lines --help");
88
92
  }
@@ -166,6 +170,104 @@ function serializeCsvField(field, delimiter) {
166
170
  function isBrokenPipe(error) {
167
171
  return isObject(error) && error.code === "EPIPE";
168
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
+ }
169
271
  function parseWhereOptions(values) {
170
272
  const filters = [];
171
273
  if (values.where !== void 0)
@@ -297,6 +399,9 @@ function requireString(value, label) {
297
399
  throw Error(`${label} must be a string`);
298
400
  return value;
299
401
  }
402
+ function optionalString(value, label) {
403
+ return value === void 0 ? void 0 : requireString(value, label);
404
+ }
300
405
  function requireExactKeys(value, allowedKeys, label, allowMissing = !1) {
301
406
  const keys = Object.keys(value);
302
407
  const unknownKey = keys.find((key) => !allowedKeys.includes(key));
@@ -49,6 +49,8 @@ declare const lines: import("@konstit/cli").HandledCommand<"lines", {
49
49
  json: boolean;
50
50
  "output-delimiter": string;
51
51
  limit: number | undefined;
52
+ transform: readonly import("@konstit/cli").KeyValuePair[];
53
+ "transform-json": unknown;
52
54
  }, {}, false, "filters" | "zip-limits" | "schema">;
53
55
  export type CountArguments = Infer<typeof count>;
54
56
  export type LinesArguments = Infer<typeof lines>;
@@ -111,6 +113,8 @@ export declare const csvCommand: import("@konstit/cli").HandledCommand<"csv", {}
111
113
  json: boolean;
112
114
  "output-delimiter": string;
113
115
  limit: number | undefined;
116
+ transform: readonly import("@konstit/cli").KeyValuePair[];
117
+ "transform-json": unknown;
114
118
  }, {}, false, "filters" | "zip-limits" | "schema">;
115
119
  probe: import("@konstit/cli").HandledCommand<"probe", {
116
120
  path: string;
@@ -194,6 +194,15 @@ const lines = command("lines", {
194
194
  option("limit", rowCount, {
195
195
  valueName: "N",
196
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"
197
206
  })
198
207
  ],
199
208
  afterHelp: `${fileHelp}
@@ -203,7 +212,8 @@ Header and minimum data row checks apply to the consumed input prefix.
203
212
 
204
213
  Examples:
205
214
  csv lines data.csv --json --skip-rows 1 --limit 10
206
- csv lines data.csv --columns 0,2 --where-eq 3=active`
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'`
207
217
  });
208
218
  const probe = command("probe", {
209
219
  about: "Inspect file size, compression, encoding, delimiter, line endings, and first record width",
@@ -21,6 +21,9 @@ 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;
@@ -28,7 +28,8 @@ export const DELIMITER_CANDIDATES = [
28
28
  { byte: 124, delimiter: "|" },
29
29
  { byte: 58, delimiter: ":" },
30
30
  { byte: 94, delimiter: "^" },
31
- { byte: 126, delimiter: "~" }
31
+ { byte: 126, delimiter: "~" },
32
+ { byte: 64, delimiter: "@" }
32
33
  ];
33
34
  const COMPRESSION_EXTENSIONS = [
34
35
  ".deflate-raw",
@@ -262,12 +263,12 @@ export function scanCsvFileFormat(prefix, sourceEnded, scoreDelimiters) {
262
263
  bytes = new TextEncoder().encode(text);
263
264
  }
264
265
  }
265
- const counts = scoreDelimiters ? new Uint32Array(8) : void 0;
266
- const encodingCode = native.symbols.csv_probe_format(bytes.length === 0 ? EMPTY_BUFFER : bytes, bytes.length, sourceEnded, bomEncoding === void 0, counts === void 0 ? null : ptr(counts));
266
+ const counts = scoreDelimiters ? new Uint32Array(DELIMITER_CANDIDATES.length + 1) : void 0;
267
+ const encodingCode = native.symbols.csv_probe_format_v2(bytes.length === 0 ? EMPTY_BUFFER : bytes, bytes.length, sourceEnded, bomEncoding === void 0, counts === void 0 ? null : ptr(counts));
267
268
  const encoding = bomEncoding ?? PROBED_BYTE_ENCODINGS[encodingCode];
268
269
  if (encoding === void 0)
269
270
  throw Error("NUL in encoding probe: specify the encoding explicitly");
270
- return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[7] === 0 ? [] : [counts] };
271
+ return { bytes, encoding, skipBytes, counts: counts === void 0 || counts[DELIMITER_CANDIDATES.length] === 0 ? [] : [counts] };
271
272
  }
272
273
  function requireDelimiter(path, rows) {
273
274
  const result = selectDelimiter(path, rows);
@@ -286,18 +287,21 @@ export function selectDelimiter(path, rows) {
286
287
  if (rows.length === 0)
287
288
  return { reason: "no-records" };
288
289
  const stableCandidates = [];
290
+ let hasStableAtSign = !1;
289
291
  for (let candidateIndex = 0;candidateIndex < DELIMITER_CANDIDATES.length; ++candidateIndex) {
290
292
  const separatorCount = rows[0]?.[candidateIndex] ?? 0;
291
293
  if (separatorCount === 0)
292
294
  continue;
293
295
  if (rows.every((row) => row[candidateIndex] === separatorCount)) {
294
296
  const candidate = DELIMITER_CANDIDATES[candidateIndex];
295
- if (candidate !== void 0)
297
+ if (candidate?.delimiter === "@")
298
+ hasStableAtSign = !0;
299
+ else if (candidate !== void 0)
296
300
  stableCandidates.push({ delimiter: candidate.delimiter, separatorCount });
297
301
  }
298
302
  }
299
303
  if (stableCandidates.length === 0)
300
- return { reason: "no-stable-separator" };
304
+ return hasStableAtSign ? { delimiter: "@" } : { reason: "no-stable-separator" };
301
305
  const extensionHint = delimiterFromExtension(path);
302
306
  const confirmedHint = stableCandidates.find((candidate) => candidate.delimiter === extensionHint);
303
307
  if (confirmedHint !== void 0)