/** * @license MIT * @author Teffen Ellis, et al. * @copyright Sister Software */ import type { ReadableWritablePair, StreamPipeOptions } from "node:stream/web"; import { type CharacterSequenceInput } from "#core/CharacterSequence"; import { type AsyncChunkIterator, type AsyncDataResource, type ByteRange } from "#internal/shared"; import { type AsManyWorkersOptions } from "#parallel/segment-workers"; import { type SegmentOptions } from "#parallel/segments"; /** * Initialization options for creating a spliterator. */ export interface SpliteratorInit { /** * The character to delimit by. Typically a newline or comma. * * @default Delimiters.LineFeed */ delimiter?: CharacterSequenceInput; /** * The byte offset to start reading from. * * This is an advanced option that is not typically used. * * @default 0 */ position?: number; /** * Whether to drop empty slices, so a run of repeated delimiters emits no intervening slices. * * Setting this to `false` emits those empties and matches the behavior of `String.prototype.split`. * * @default true */ skipEmpty?: boolean; /** * Count of skipped matches before emitting a data. * * @default 0 */ drop?: number; /** * The maximum number of data slices to yield. * * Useful for limiting the number of emitted slices, i.e. lines in a file. * * Note that skipped slices are not counted towards the limit. * * @default Infinity */ take?: number; /** * Enable quote-aware splitting. A delimiter inside a double-quoted region does not split. Emitted slices retain their * quotes exactly as they appeared in the source. * * This is only splitting behavior. Decoding, stripping wrapping quotes, and unescaping doubled quotes are left to the * caller. * * The asynchronous engine requires a single-byte delimiter for this mode. Every {@linkcode Delimiters} entry * qualifies. A multi-byte delimiter that straddles a chunk boundary would require the scanner to toggle quote state * again while rescanning the boundary. * * @default false */ enableQuoteHandling?: boolean; /** * Whether to treat a carriage return immediately preceding a delimiter as part of the delimiter — i.e. CRLF * normalization when splitting on `\n`, matching `node:readline`'s `crlfDelay: Infinity`. Only a `\r` directly before * an actual delimiter match is trimmed. A trailing `\r` at end-of-input is preserved. * * {@linkcode CSVSpliterator} defaults this to `true` for row splitting. RFC 4180 mandates CRLF row terminators. * everywhere else the default is `false`. * * @default false */ crlf?: boolean; /** * Whether input that ends inside a double-quoted region is read anyway, as one final record holding the rest of the * input. By default it throws an {@linkcode UnterminatedQuoteError} once the records before it have been yielded, * since a quote that never closes swallows every later record and the result reads like a smaller file. Only * meaningful with {@linkcode enableQuoteHandling}. * * @default false */ allowUnterminatedQuote?: boolean; /** * Whether a source beginning with the zstd or gzip magic bytes is decompressed before it is split. Honoured by * {@linkcode AsyncSpliterator} and by the format readers' `from` and `fromAsync`; the synchronous * {@linkcode Spliterator} engine reads its bytes as given. * * @default true */ decompress?: boolean; /** * Whether to emit debug information. */ debug?: boolean; } /** * Initialization options for creating an asynchronous spliterator. */ export interface AsyncSpliteratorInit extends SpliteratorInit { /** * The buffer chunk size to read from the file, i.e. the high-water mark for the file read operation. * * @default BlockSize * 16 * @minimum The delimiter byte length * 4 or block size of the file system. Whichever is greater. * @maximum The byte length of the file. */ highWaterMark?: number; /** * Whether to automatically dispose of the source once the iterator is done. * * @default false */ autoDispose?: boolean; /** * Whether a path `p` reads `p.zst`, or failing that `p.gz`, when one exists. A path that already ends in a compressed * extension, and any source that is not a path, is read as given. * * @default true */ preferCompressed?: boolean; } /** * An asynchronous spliterator for reading delimited byte streams. * * ```ts * import { AsyncSpliterator } from "spliterator" * * const file = await AsyncSpliterator.from("data.csv") * * for await (const line of file) { * console.log(line) * } * ``` * * @see {@linkcode Spliterator} for the synchronous version. */ export declare class AsyncSpliterator implements AsyncIterableIterator, AsyncDisposable { #private; /** * Create a new delimited generator from an asynchronous byte stream. * * @param source - The data resource to read from. * @param init - The initialization options for the generator. * * @returns A new generator instance, yielding byte ranges. */ static from(source: AsyncChunkIterator, init?: AsyncSpliteratorInit): AsyncSpliterator; /** * Create a new delimited generator from a resource such as a file handle or URL. * * @param source - The data resource to read from. * @param init - The initialization options for the generator. * * @returns A new generator instance, yielding byte ranges. */ static from(source: AsyncDataResource, init?: AsyncSpliteratorInit): Promise; /** * Create a new delimited generator from a resource such as a file handle, URL, or byte stream. * * @param source - The data resource to read from. * @param init - The initialization options for the generator. * * @returns A new generator instance, yielding byte ranges. */ static from(source: AsyncDataResource | AsyncChunkIterator, init?: AsyncSpliteratorInit): AsyncSpliterator | Promise; /** * Stream-count delimiter occurrences without materialising the split slices. * * This has `wc -l` semantics for the default line-feed delimiter: a final unterminated record does not add to the * count. Quote-aware mode excludes delimiters inside quoted regions. A path or URL is opened independently, so it can * be counted before being passed to {@linkcode from}; an arbitrary async iterable is inherently consumed. */ static count(source: AsyncDataResource | AsyncChunkIterator, init?: AsyncSpliteratorInit): Promise; /** * Dispose of the spliterator, closing the file handle if necessary. */ [Symbol.asyncDispose](): Promise; /** * Create a new delimited generator from a data resource. */ static toTransformStream(init: SpliteratorInit): TransformStream; /** * Create a new delimited generator from an asynchronous byte stream. * * @param source - The file to read from. * @param init - The initialization options for the generator. * @see {@linkcode AsyncSpliterator.from} to create a new generator from a data resource. */ constructor(source: AsyncChunkIterator, init?: AsyncSpliteratorInit); /** * Pull the next range. * * The yielded value is a **view** into the read buffer, valid until the next pull: the buffer is compacted in place * as reading proceeds, and cleared on dispose. Decode or `slice()` a range before pulling again to keep it. * {@linkcode toArray} copies for you. */ next(): Promise>; /** * Collect all the byte ranges from the file. * * Each range is copied, because a range {@linkcode next} yields is a view that the next pull may overwrite. * * **This method will read the entire file into memory.** */ /** * Pull every queued range at once, as one contiguous view from the first range's start to the last range's end. * * The view spans whole records only, with the delimiters between them (and any carriage returns before those * delimiters) left in, and the last record's delimiter left out, exactly as {@linkcode next} would have cut each one. * A quoted region never straddles two windows, because the engine cut the records with quote state in hand. One * window per fill is one `await` per high-water mark of input instead of one per record, which is what a consumer * that scans records in bulk, such as the CSV cell scanner, wants. * * The engine's `skipEmpty`, `drop`, and `take` are not applied here: a window cannot have records removed from its * middle without ceasing to be contiguous, so a consumer applies all three itself. Like a per-record slice, the view * is valid until the next pull, when buffer compression may slide the bytes beneath it. */ nextWindow(): Promise>; toArray(): Promise; /** * Collect all the byte ranges from the file as a string. * * **This method will read the entire file into memory.** */ toDecodedArray(decoder?: import("node:util").TextDecoder): Promise; /** * Wraps the spliterator in a readable stream. * * This is useful for piping the spliterator to other streams. * * @returns A readable stream of byte ranges. */ toReadableStream(): ReadableStream; /** * Pipes the spliterator to a writable stream. * * ```ts * const spliterator = await AsyncSpliterator.from("data.csv") * * const textStream = spliterator.pipeThrough(new TextDecoderStream()) * ``` * * @see {@linkcode toReadableStream} to first convert the spliterator to a readable stream. */ pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; /** * Iterate over the byte ranges in the file, yielding each range. between delimiters. */ [Symbol.asyncIterator](): this; return(): Promise>; /** * Compute delimiter-aligned `[start, end)` byte ranges dividing `source` into up to `concurrency` segments. The * boundary primitive for parallel parsing — hand each range to a worker (with its own handle). See * {@linkcode asManyWorkers} for the turnkey worker version. */ static segments(source: AsyncDataResource, options: SegmentOptions): Promise; /** * Split `source` into delimiter-aligned segments and return one {@linkcode AsyncSpliterator} per segment. All share * the event loop (no worker threads) — for moderate jobs or to overlap I/O. Returns at most `concurrency` instances. * * @param source - The data resource to read from. * @param options - Delimiter, desired concurrency, and optional probe size. * * @returns One `AsyncSpliterator` per non-empty segment, possibly fewer than `concurrency`. */ static asMany(source: AsyncDataResource, options: SegmentOptions): Promise; /** * Parse `source` across worker threads. Each worker owns a handle to a delimiter-aligned segment, runs the `worker` * handler module per record, and streams results back to the main thread as one merged async iterator — for a * single-thread writer. Results interleave across segments. * * The handler returns a value (structured-cloned back), a `Uint8Array` (transferred zero-copy), or `undefined` (the * record is skipped). The handler module's top-level code runs once per worker — load models/handles there. * * @param source A file path or URL (file handles cannot cross threads → `TypeError` otherwise). * @param options Handler module, delimiter, concurrency, and batching/backpressure tuning. */ static asManyWorkers(source: AsyncDataResource, options: AsManyWorkersOptions): AsyncIterableIterator; } //# sourceMappingURL=AsyncSpliterator.d.ts.map