| 442 | * @since 4.0.0 |
| 443 | */ |
| 444 | export const makeChannel = <IE>(headers: Record<string, string>): Channel.Channel< |
| 445 | Arr.NonEmptyReadonlyArray<Part>, |
| 446 | MultipartError | IE, |
| 447 | void, |
| 448 | Arr.NonEmptyReadonlyArray<Uint8Array>, |
| 449 | IE, |
| 450 | unknown |
| 451 | > => |
| 452 | Channel.fromTransform((upstream) => |
| 453 | Effect.map(makeConfig(headers), (config) => { |
| 454 | let partsBuffer: Array<Part> = [] |
| 455 | let exit = Option.none<Exit.Exit<never, IE | MultipartError | Cause.Done>>() |
| 456 | |
| 457 | const parser = MP.make({ |
| 458 | ...config, |
| 459 | onField(info, value) { |
| 460 | partsBuffer.push(new FieldImpl(info.name, info.contentType, MP.decodeField(info, value))) |
| 461 | }, |
| 462 | onFile(info) { |
| 463 | let chunks: Array<Uint8Array> = [] |
| 464 | let finished = false |
| 465 | const pullChunks = Channel.fromPull( |
| 466 | Effect.succeed(Effect.suspend(function loop(): Pull.Pull<Arr.NonEmptyReadonlyArray<Uint8Array>> { |
| 467 | if (!Arr.isReadonlyArrayNonEmpty(chunks)) { |
| 468 | return finished ? Cause.done() : Effect.flatMap(pump, loop) |
| 469 | } |
| 470 | const chunk = chunks |
| 471 | chunks = [] |
| 472 | return Effect.succeed(chunk) |
| 473 | })) |
| 474 | ) |
| 475 | partsBuffer.push(new FileImpl(info, pullChunks)) |
| 476 | return function(chunk) { |
| 477 | if (chunk === null) { |
| 478 | finished = true |
| 479 | } else { |
| 480 | chunks.push(chunk) |
| 481 | } |
| 482 | } |
| 483 | }, |
| 484 | onError(error_) { |
| 485 | exit = Option.some(Exit.fail(convertError(error_))) |
| 486 | }, |
| 487 | onDone() { |
| 488 | if (Option.isNone(exit)) { |
| 489 | exit = Option.some(Exit.fail(Cause.Done())) |
| 490 | } |
| 491 | } |
| 492 | }) |
| 493 | |
| 494 | const pump = upstream.pipe( |
| 495 | Effect.flatMap((chunk) => { |
| 496 | for (let i = 0; i < chunk.length; i++) { |
| 497 | parser.write(chunk[i]) |
| 498 | } |
| 499 | return Effect.void |
| 500 | }), |
| 501 | Effect.catchCause((cause) => { |