/** * @license MIT * @author Teffen Ellis, et al. * @copyright Sister Software */ import { CharacterSequence, type CharacterSequenceInput, Delimiters, normalizeCharacterInput, } from "#core/CharacterSequence" import { AsyncSpliterator, Spliterator, type SpliteratorInit } from "#core/Spliterator" import { cellScanEligibility, decodeForCellScan, reheadBatches, scanCsvCellBatches, scanCsvCells, scanCsvCellsStreaming, } from "#formats/csv-cells" import { splitRowColumns } from "#formats/csv-columns" import { bindTransformers, createRowEmitters, headerNames, type RowEmitter, type RowOutputMode, type RowSpliteratorInit, type RowTransformer, type RowTransformerEntry, type RowTransformerRecord, type RowTuple, } from "#formats/row-emitters" import type { AsyncChunkIterator, AsyncDataResource } from "#internal/shared" import { type AdaptiveSourceInit, openDelimitedRows } from "#io/adaptive-source" import { maybeDecompressSync } from "#io/compression" import { AsyncSequence, BATCHED_SOURCE, type BatchedAsyncIterable } from "#iterators/AsyncSequence" import { Sequence } from "#iterators/Sequence" export type { RowTuple } from "#formats/row-emitters" /** * An output mode for the CSV generator. */ export type CSVOutputMode = RowOutputMode export type CSVTransformer = RowTransformer export type CSVTransformerEntry = RowTransformerEntry export type CSVTransformerRecord = RowTransformerRecord export type CSVEmitter = RowEmitter export type CSVSpliteratorEmittedRecord = Record export const CSVSpliteratorEmitters: Record = createRowEmitters("") /** * CSV-specific options, in addition to {@linkcode RowSpliteratorInit}'s common row-shaping options. */ export interface CSVSpliteratorInit extends SpliteratorInit, RowSpliteratorInit { /** * The delimiter to use for columns in a row. * * @default Delimiters.Comma */ columnDelimiter?: CharacterSequenceInput /** * Whether to treat double-quoted regions as opaque. A delimiter inside `"…"` does not split. Wrapping quotes are * stripped and doubled quotes (`""`) unescape to `"`. * * Input that ends inside quotes throws an `UnterminatedQuoteError` unless `allowUnterminatedQuote` is set. * * @default true for CSV and PSV, false for TSV (the class's {@linkcode CSVSpliterator.EnableQuoteHandling}) */ enableQuoteHandling?: boolean /** * Normalize CRLF row terminators by treating a carriage return immediately preceding a row delimiter as part of that * delimiter. * * @default true */ crlf?: boolean /** * Trim leading and trailing whitespace from every column, header cells included, after quotes are stripped. RFC 4180 * treats that whitespace as part of the field; real-world sources pad it. Pass `false` to keep it. * * @default true */ trim?: boolean /** * How columns are found. `"auto"` scans every cell of a wholly in-memory source in one SIMD pass and slices the * decoded text, and otherwise uses `"rows"`. `"rows"` decodes and splits each row, as every version before 8.0.0 did. * Both produce the same values. * * The bulk path decodes the whole source on the first pull, even for `take(1)`, and a retained cell may keep the * whole decoded string alive. Use `"rows"` to avoid either cost. * * @default "auto" */ columnScan?: "auto" | "rows" } /** * The row generator behind {@linkcode CSVSpliterator.from}, kept at module scope so `from` can hand it to a * {@linkcode Sequence} while staying lazy — calling a generator function runs none of its body. `from` reads * `this.ColumnDelimiter` on the way in, so a subclass's delimiter still wins. */ function* splitRows( source: CharacterSequenceInput, init: CSVSpliteratorInit, defaultColumnDelimiter: number, defaultEnableQuoteHandling: boolean ) { const { // --- header = true, // Without a header row there are no column names, so a row can only be an array. // Declared before `normalizeKeys`, whose own default reads this one. mode = header === false ? "array" : "object", transformers: transformersInput = [], // Matches `fromAsync`. Keys are the header as written; `true` was the default for object rows before 10.0.0. normalizeKeys = false, columnDelimiter: columnDelimiterInput = defaultColumnDelimiter, enableQuoteHandling = defaultEnableQuoteHandling, // RFC 4180 mandates CRLF row terminators — accept them by default so the last column // never carries a stray `\r` on Windows-lineage sources. crlf = true, trim = true, columnScan = "auto", take: takeInput = Infinity, drop: dropInput = 0, decompress = true, ...rowInit } = init const drop = Math.max(0, dropInput) const take = Math.max(0, takeInput) const emitter = CSVSpliteratorEmitters[mode] let transformers: CSVTransformerEntry[] = [] let yieldCount = 0 const yieldLimit = take + drop const decoder = new TextDecoder() const columnDelimiter = new CharacterSequence(columnDelimiterInput ?? defaultColumnDelimiter) // A string is text by definition; bytes may arrive compressed. const bytes = typeof source === "string" ? normalizeCharacterInput(source) : maybeDecompressSync(normalizeCharacterInput(source), decompress) const rowDelimiter = new CharacterSequence(rowInit.delimiter ?? Delimiters.LineFeed) const plan = cellScanEligibility({ columnScan, rowDelimiter, columnDelimiter, enableQuoteHandling, position: rowInit.position, byteLength: bytes.byteLength, }) // Nothing to yield and no header to read: skip the whole-source decode the fast path would otherwise do first. The row // path, which stops after one row here, would yield nothing either. if (plan && take <= 0 && !header) return // The scanner loads asynchronously; a synchronous caller sees it only if something awaited `whenReady()` first. // // A string source is already the text the cells are sliced from. Encoding it produced `bytes`, so they are valid // UTF-8 and the kernel's UTF-16 offsets land on the string the caller passed: a lone surrogate encodes as the three // bytes of U+FFFD, one unit either way. Decoding here would cost a second copy of the source for every parse, and // the retained cells would keep that copy alive rather than the caller's own string. const text = plan && CharacterSequence.hasScanner() ? (typeof source === "string" ? source : decodeForCellScan(bytes)) : null if (plan && text !== null) { const batches = scanCsvCellBatches(bytes, text, { rowDelimiter: plan.rowDelimiter, columnDelimiter: plan.columnDelimiter, enableQuoteHandling, crlf, trim, skipEmpty: rowInit.skipEmpty ?? true, allowUnterminatedQuote: rowInit.allowUnterminatedQuote ?? false, }) let headerPending = header // One generator layer per row, not two: the batches are walked here rather than through a flattening generator. for (const batch of batches) { for (const columns of batch) { if (headerPending) { transformers = bindTransformers(headerNames(columns, normalizeKeys, mode), transformersInput) headerPending = false continue } if (yieldCount < drop) { yieldCount++ continue } if (yieldCount >= yieldLimit) return yield emitter ? emitter(columns, transformers) : columns yieldCount++ } } return } // Quote handling applies at both levels: rows must not split on newlines inside quotes, // columns must not split on quoted column delimiters. const rows = Spliterator.fromSync(bytes, { ...rowInit, crlf, enableQuoteHandling }) if (header) { const result = rows.next() if (result.done) return const columns = splitRowColumns(result.value, columnDelimiter, decoder, enableQuoteHandling, trim) transformers = bindTransformers(headerNames(columns, normalizeKeys, mode), transformersInput) } for (const row of rows) { if (yieldCount < drop) { yieldCount++ continue } if (yieldCount >= yieldLimit) break const columns = splitRowColumns(row, columnDelimiter, decoder, enableQuoteHandling, trim) yield emitter ? emitter(columns, transformers) : columns yieldCount++ } } /** * A static class spliterator for comma-separated values. * * **Performance:** the SIMD delimiter scan wins when scanning dominates — many rows, a few columns pulled out cheaply, * streaming to bound memory. When per-row work is heavy (a full `JSON.parse`, expensive transforms) it can dominate the * scan and erase the advantage. Benchmark against a mature native parser before swapping an existing loop for speed. * See {@link JSONSpliterator} for the measured case where per-row `JSON.parse` makes the streamed path a net loss. * * @see {@linkcode CSVSpliterator.from} for synchronous usage. * @see {@linkcode CSVSpliterator.fromAsync} for asynchronous usage. */ export abstract class CSVSpliterator { /** * The column delimiter used by the spliterator. * * @default Delimiters.Comma */ public static ColumnDelimiter: number = Delimiters.Comma /** * Whether double-quoted regions are opaque by default. {@linkcode TSVSpliterator} turns this off: the TSV format has * no quoting, and a `"` in a tab-separated source is an ordinary character. * * @default true */ public static EnableQuoteHandling = true constructor() { throw new TypeError("Static class cannot be instantiated. Did you mean `CSVSpliterator.from`?") } /** * Count logical data rows without decoding columns or constructing emitted records. * * Row boundaries follow {@linkcode from}, including quote handling and CRLF normalization. The header (when enabled), * `drop`, and `take` have the same effect they do when yielding rows. * * @see {@linkcode countAsync} for files and other asynchronous sources. */ public static count(source: CharacterSequenceInput, init: CSVSpliteratorInit = {}): number { const { header = true, enableQuoteHandling = this.EnableQuoteHandling, crlf = true, trim: _trim, drop = 0, take = Infinity, decompress = true, ...rowInit } = init const bytes = typeof source === "string" ? normalizeCharacterInput(source) : maybeDecompressSync(normalizeCharacterInput(source), decompress) const rows = Spliterator.fromSync(bytes, { ...rowInit, crlf, enableQuoteHandling }) if (header && rows.next().done) return 0 let skipped = 0 let count = 0 while (count < take) { const row = rows.next() if (row.done) break if (skipped < drop) { skipped++ continue } count++ } return count } /** * Count logical data rows without decoding columns or constructing emitted records. * * Row boundaries follow {@linkcode fromAsync}, including quote handling and CRLF normalization. The header (when * enabled), `drop`, and `take` have the same effect they do when yielding rows. A path or URL is opened independently * and can subsequently be passed to {@linkcode fromAsync}; an arbitrary async iterable is inherently consumed. */ public static async countAsync( source: AsyncDataResource | AsyncChunkIterator, init: CSVSpliteratorInit & AdaptiveSourceInit = {} ): Promise { const { header = true, enableQuoteHandling = this.EnableQuoteHandling, crlf = true, trim: _trim, drop = 0, take = Infinity, ...rowInit } = init const rows = await openDelimitedRows(source, { ...rowInit, crlf, enableQuoteHandling }) const iterator = Symbol.asyncIterator in rows ? rows[Symbol.asyncIterator]() : rows[Symbol.iterator]() try { if (header && (await iterator.next()).done) return 0 let skipped = 0 let count = 0 while (count < take) { const row = await iterator.next() if (row.done) break if (skipped < drop) { skipped++ continue } count++ } return count } finally { await iterator.return?.() } } /** * @yields Each row as an object with the header names as keys. */ public static from( source: CharacterSequenceInput, options?: CSVSpliteratorInit & { mode?: "object"; header?: true } ): Sequence /** * @yields Each row as a 3-tuple [key, value, idx]. */ public static from( source: CharacterSequenceInput, options?: CSVSpliteratorInit & { mode: "entries" } ): Sequence /** * @yields Each row as an array of columns. */ public static from( source: CharacterSequenceInput, options?: CSVSpliteratorInit & ({ mode: "array" } | { mode?: "array"; header: false }) ): Sequence /** * Given a byte array or string, split the data by rows (usually newline-delimited) and then by columns (usually * comma). * * @yields Each row, shaped according to the `mode` option. */ public static from(source: CharacterSequenceInput, init?: CSVSpliteratorInit): Sequence public static from(source: CharacterSequenceInput, init: CSVSpliteratorInit = {}) { return new Sequence(splitRows(source, init, this.ColumnDelimiter, this.EnableQuoteHandling)) } /** * @yields Each row as an object with the header names as keys. */ public static fromAsync( source: AsyncDataResource | AsyncChunkIterator, options?: CSVSpliteratorInit & AdaptiveSourceInit & { mode?: "object"; header?: true } ): AsyncSequence /** * @yields Each row as a 3-tuple [key, value, idx]. */ public static fromAsync( source: AsyncDataResource | AsyncChunkIterator, options?: CSVSpliteratorInit & AdaptiveSourceInit & { mode: "entries" } ): AsyncSequence /** * @yields Each row as an array of columns. */ public static fromAsync( source: AsyncDataResource | AsyncChunkIterator, options?: CSVSpliteratorInit & AdaptiveSourceInit & ({ mode: "array" } | { mode?: "array"; header: false }) ): AsyncSequence /** * Given an asynchronous data source, split the data by rows (usually newline-delimited) and then by columns (usually * comma). * * @param source The data source to split. * @param init Options for the spliterator. * * @yields Each row, shaped according to the `mode` option. */ public static fromAsync( source: AsyncDataResource | AsyncChunkIterator, init?: CSVSpliteratorInit & AdaptiveSourceInit ): AsyncSequence /** * Given an asynchronous data source, split the data by rows (usually newline-delimited) and then by columns (usually * comma). * * @param source The data source to split. * @param init Options for the spliterator. * * @yields Each row, shaped according to the `mode` option. */ public static fromAsync( source: AsyncDataResource | AsyncChunkIterator, init: CSVSpliteratorInit & AdaptiveSourceInit = {} ): AsyncSequence { const defaultColumnDelimiter = this.ColumnDelimiter const defaultEnableQuoteHandling = this.EnableQuoteHandling const { // --- header = true, // Without a header row there are no column names, so a row can only be an array. mode = header === false ? "array" : "object", transformers: transformersInput = [], normalizeKeys = false, columnDelimiter: columnDelimiterInput, enableQuoteHandling = defaultEnableQuoteHandling, // RFC 4180 mandates CRLF row terminators — accept them by default so the last column // never carries a stray `\r` on Windows-lineage sources. crlf = true, trim = true, columnScan = "auto", take = Infinity, drop = 0, ...rowInit } = init const emitter = CSVSpliteratorEmitters[mode] const columnDelimiter = new CharacterSequence(columnDelimiterInput ?? defaultColumnDelimiter) const rowDelimiter = new CharacterSequence(rowInit.delimiter ?? Delimiters.LineFeed) const skipEmpty = rowInit.skipEmpty ?? true const allowUnterminatedQuote = rowInit.allowUnterminatedQuote ?? false const decoder = new TextDecoder() // Populated by the header pass below before the first row op runs, since the source thunk resolves on the first // pull and the ops only run against what it returns. let transformers: CSVTransformerEntry[] = [] /** * The bulk branch: eligibility, then the fatal decode as the last gate. Invalid UTF-8 hands the same bytes to the * row engine, which the map op below still understands. Runs after `whenReady`, on the first pull. */ const bulkParser = (bytes: Uint8Array): Iterable => { const plan = cellScanEligibility({ columnScan, rowDelimiter, columnDelimiter, enableQuoteHandling, position: rowInit.position, byteLength: bytes.byteLength, }) const text = plan && CharacterSequence.hasScanner() ? decodeForCellScan(bytes) : null if (!plan || text === null) { return Spliterator.fromSync(bytes, { ...rowInit, crlf, enableQuoteHandling }) } return scanCsvCells(bytes, text, { rowDelimiter: plan.rowDelimiter, columnDelimiter: plan.columnDelimiter, enableQuoteHandling, crlf, trim, skipEmpty, allowUnterminatedQuote, }) } const toColumns = (row: Uint8Array | string[]): string[] => Array.isArray(row) ? row : splitRowColumns(row, columnDelimiter, decoder, enableQuoteHandling, trim) /** * The streaming counterpart of the bulk branch: the same eligibility, minus the size cap and `position`, which the * engine has already applied by the time it hands out a window. Returns the rows as the engine gave them when the * cell scanner does not apply. */ const scanWindows = ( rows: AsyncIterable | Iterable ): AsyncIterable | BatchedAsyncIterable | Iterable => { if (!(rows instanceof AsyncSpliterator) || !CharacterSequence.hasScanner()) return rows const plan = cellScanEligibility({ columnScan, rowDelimiter, columnDelimiter, enableQuoteHandling, position: undefined, byteLength: 0, }) if (!plan) return rows return scanCsvCellsStreaming( rows, { rowDelimiter: plan.rowDelimiter, columnDelimiter: plan.columnDelimiter, enableQuoteHandling, crlf, trim, skipEmpty, allowUnterminatedQuote, }, (window) => { const fallbackRows: string[][] = [] for (const row of Spliterator.fromSync(window, { ...rowInit, position: undefined, crlf, enableQuoteHandling, })) { fallbackRows.push(toColumns(row)) } return fallbackRows } ) } const openRows = async (): Promise< AsyncIterable | BatchedAsyncIterable | Iterable > => { // Quote handling applies at both levels: rows must not split on newlines inside quotes, // columns must not split on quoted column delimiters. const opened = await openDelimitedRows(source, { ...rowInit, crlf, enableQuoteHandling }, bulkParser) // The bulk branch awaits the scanner inside `openDelimitedRows`; the streaming branch has to do it here, or a // fresh process would take the row path for every file on its first parse. await CharacterSequence.whenReady() const rows = scanWindows(opened) if (header) { // Both engines return `this` from their iterator method. Consuming the header row here advances the cursor the // row ops will read. Returning `rows` afterwards resumes at row two rather than row one. The windowed scanner // hands out batches instead, so its first batch loses its head row and the remainder is put back in front. const iterator = Symbol.asyncIterator in rows ? rows[Symbol.asyncIterator]() : rows[Symbol.iterator]() try { if (BATCHED_SOURCE in rows) { const batches = iterator as AsyncIterator let result = await batches.next() while (!result.done && !result.value.length) { result = await batches.next() } if (result.done) return rows const [columns, ...remainder] = result.value transformers = bindTransformers(headerNames(columns!, normalizeKeys, mode), transformersInput) return reheadBatches(remainder, batches) } const result = await ( iterator as AsyncIterator | Iterator ).next() if (result.done) return rows const columns = toColumns(result.value) transformers = bindTransformers(headerNames(columns, normalizeKeys, mode), transformersInput) } catch (error) { try { await iterator.return?.() } catch { // The original error is the one worth reporting. } throw error } } return rows } let rows = AsyncSequence.from(openRows) // Dropped before parsing, as `from` does: a transformer never sees a row the caller asked to skip. if (drop > 0) { rows = rows.drop(drop) } let sequence: AsyncSequence = rows.map((row) => { const columns = toColumns(row) return emitter ? emitter(columns, transformers) : columns }) if (Number.isFinite(take)) { sequence = sequence.take(take) } return sequence } }