| 389 | } |
| 390 | |
| 391 | const decodeRecords = <IE, Done>(options: DecodeOptions | undefined): Channel.Channel< |
| 392 | Arr.NonEmptyReadonlyArray<Decoded>, |
| 393 | IE | CsvError, |
| 394 | Done, |
| 395 | Arr.NonEmptyReadonlyArray<string>, |
| 396 | IE, |
| 397 | Done |
| 398 | > => { |
| 399 | const delimiter = checkDelimiter(options?.delimiter ?? ",") |
| 400 | const maxRecordSize = options?.maxRecordSize ?? defaultMaxRecordSize |
| 401 | if (!(maxRecordSize > 0)) { |
| 402 | throw new Error(`Csv: maxRecordSize must be positive, got ${maxRecordSize}`) |
| 403 | } |
| 404 | const ignoreEmptyLines = options?.ignoreEmptyLines === true |
| 405 | const useHeaders = options?.headers === true |
| 406 | return Channel.fromTransform((upstream, _scope) => |
| 407 | Effect.sync(() => { |
| 408 | const parser = new Parser(delimiter, maxRecordSize, ignoreEmptyLines) |
| 409 | let headers: Row | undefined |
| 410 | // Plain assignment is faster than `Object.fromEntries`, but a `__proto__` |
| 411 | // header would set the prototype instead of a property. |
| 412 | let assignable = false |
| 413 | let next: Pull.Pull<never, CsvError, Done> | undefined |
| 414 | |
| 415 | const toRecord = (row: Parsed): Decoded => { |
| 416 | if (!useHeaders) return { value: row.cells, record: row.record } |
| 417 | if (row.cells.length !== headers!.length) { |
| 418 | throw new CsvError({ |
| 419 | kind: "Header", |
| 420 | message: `Expected ${headers!.length} cells, got ${row.cells.length}`, |
| 421 | record: row.record, |
| 422 | line: row.line, |
| 423 | column: undefined |
| 424 | }) |
| 425 | } |
| 426 | if (!assignable) { |
| 427 | return { value: Object.fromEntries(headers!.map((name, i) => [name, row.cells[i]])), record: row.record } |
| 428 | } |
| 429 | const value: globalThis.Record<string, string> = {} |
| 430 | for (let i = 0; i < headers!.length; i++) value[headers![i]] = row.cells[i] |
| 431 | return { value, record: row.record } |
| 432 | } |
| 433 | |
| 434 | const emit = ( |
| 435 | run: (out: Array<Parsed>) => void |
| 436 | ): Pull.Pull<Arr.NonEmptyReadonlyArray<Decoded>, IE | CsvError, Done> => { |
| 437 | const rows: Array<Parsed> = [] |
| 438 | const out: Array<Decoded> = [] |
| 439 | try { |
| 440 | run(rows) |
| 441 | } catch (error) { |
| 442 | if (!isCsvError(error)) throw error |
| 443 | next = Effect.fail(error) |
| 444 | } |
| 445 | try { |
| 446 | for (const row of rows) { |
| 447 | if (useHeaders && headers === undefined) { |
| 448 | if (new Set(row.cells).size !== row.cells.length) { |