@nicolastoulemont/std 0.7.2 → 0.8.1
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 +571 -166
- package/dist/adt/index.d.mts +1 -1
- package/dist/adt/index.mjs +1 -1
- package/dist/adt-CPG_sa8q.mjs +2 -0
- package/dist/adt-CPG_sa8q.mjs.map +1 -0
- package/dist/brand/index.d.mts +1 -1
- package/dist/brand/index.mjs +1 -1
- package/dist/brand-DZgGDrAe.mjs +2 -0
- package/dist/brand-DZgGDrAe.mjs.map +1 -0
- package/dist/brand.types-B3NDX1vo.d.mts +62 -0
- package/dist/brand.types-B3NDX1vo.d.mts.map +1 -0
- package/dist/context/index.d.mts +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/{context-CCHj1nab.mjs → context-0xDbwtpx.mjs} +2 -2
- package/dist/context-0xDbwtpx.mjs.map +1 -0
- package/dist/{context-r8ESJiFn.d.mts → context-B2dWloPl.d.mts} +2 -18
- package/dist/context-B2dWloPl.d.mts.map +1 -0
- package/dist/data/index.d.mts +1 -1
- package/dist/data/index.mjs +1 -1
- package/dist/{data-BLXO4XwS.mjs → data-BHYPdqWZ.mjs} +2 -2
- package/dist/{data-BLXO4XwS.mjs.map → data-BHYPdqWZ.mjs.map} +1 -1
- package/dist/{discriminator.types-CTURejXz.d.mts → discriminator.types-C-ygT2S1.d.mts} +1 -1
- package/dist/discriminator.types-C-ygT2S1.d.mts.map +1 -0
- package/dist/{dual-CZhzZslG.mjs → dual-fN6OUwN_.mjs} +1 -1
- package/dist/{dual-CZhzZslG.mjs.map → dual-fN6OUwN_.mjs.map} +1 -1
- package/dist/duration/index.d.mts +2 -0
- package/dist/duration/index.mjs +1 -0
- package/dist/duration-CYoDHcOR.mjs +2 -0
- package/dist/duration-CYoDHcOR.mjs.map +1 -0
- package/dist/either/index.d.mts +1 -1
- package/dist/either/index.mjs +1 -1
- package/dist/{either-BMLPfvMl.mjs → either-G7uOu4Ar.mjs} +2 -2
- package/dist/either-G7uOu4Ar.mjs.map +1 -0
- package/dist/{equality-CoyUHWh9.mjs → equality-BX6BUidG.mjs} +1 -1
- package/dist/{equality-CoyUHWh9.mjs.map → equality-BX6BUidG.mjs.map} +1 -1
- package/dist/{flow-D8_tllWl.mjs → flow-CNyLsPGb.mjs} +1 -1
- package/dist/flow-CNyLsPGb.mjs.map +1 -0
- package/dist/functions/index.d.mts +1 -1
- package/dist/functions/index.mjs +1 -1
- package/dist/functions-ByAk682_.mjs +2 -0
- package/dist/functions-ByAk682_.mjs.map +1 -0
- package/dist/fx/index.d.mts +1 -1
- package/dist/fx/index.mjs +1 -1
- package/dist/fx-DUXDxwsU.mjs +2 -0
- package/dist/fx-DUXDxwsU.mjs.map +1 -0
- package/dist/{fx.runtime-DclEDyjY.mjs → fx.runtime-jQxh77s3.mjs} +2 -2
- package/dist/{fx.runtime-DclEDyjY.mjs.map → fx.runtime-jQxh77s3.mjs.map} +1 -1
- package/dist/{fx.types-DeEWEltG.d.mts → fx.types-BdN1EWxr.d.mts} +1 -1
- package/dist/{fx.types-DeEWEltG.d.mts.map → fx.types-BdN1EWxr.d.mts.map} +1 -1
- package/dist/{fx.types-Bg-Mmdm5.mjs → fx.types-DyQVgTS8.mjs} +1 -1
- package/dist/{fx.types-Bg-Mmdm5.mjs.map → fx.types-DyQVgTS8.mjs.map} +1 -1
- package/dist/index-B4WfexUL.d.mts +57 -0
- package/dist/index-B4WfexUL.d.mts.map +1 -0
- package/dist/{index-DXbYlSnB.d.mts → index-BA0EsFxS.d.mts} +5 -74
- package/dist/index-BA0EsFxS.d.mts.map +1 -0
- package/dist/{index-UzMbg1dh.d.mts → index-BqJ1GWAF.d.mts} +20 -56
- package/dist/index-BqJ1GWAF.d.mts.map +1 -0
- package/dist/index-BsPOcZk9.d.mts +96 -0
- package/dist/index-BsPOcZk9.d.mts.map +1 -0
- package/dist/{index-DEAWPlcI.d.mts → index-CIvNgjsx.d.mts} +24 -56
- package/dist/index-CIvNgjsx.d.mts.map +1 -0
- package/dist/{index-B_iY5tq0.d.mts → index-CNTYbcY9.d.mts} +1 -21
- package/dist/index-CNTYbcY9.d.mts.map +1 -0
- package/dist/{index-Cq2IFito.d.mts → index-Ctqe1fD1.d.mts} +3 -17
- package/dist/index-Ctqe1fD1.d.mts.map +1 -0
- package/dist/{index-B_wWGszy.d.mts → index-D7mFNjot.d.mts} +1 -5
- package/dist/index-D7mFNjot.d.mts.map +1 -0
- package/dist/{index-CUZn-ohG.d.mts → index-D8rDE60Y.d.mts} +23 -54
- package/dist/index-D8rDE60Y.d.mts.map +1 -0
- package/dist/{index-By6dNRc4.d.mts → index-DR7hzXU4.d.mts} +3 -23
- package/dist/{index-By6dNRc4.d.mts.map → index-DR7hzXU4.d.mts.map} +1 -1
- package/dist/{index-DKS1g1oC.d.mts → index-DUki2Bcp.d.mts} +54 -45
- package/dist/index-DUki2Bcp.d.mts.map +1 -0
- package/dist/{index-BNQ9xSAz.d.mts → index-MsJqfQu0.d.mts} +64 -70
- package/dist/index-MsJqfQu0.d.mts.map +1 -0
- package/dist/{index-CGiLfREk.d.mts → index-UINIHFuh.d.mts} +39 -15
- package/dist/index-UINIHFuh.d.mts.map +1 -0
- package/dist/{index-BiiE8NS7.d.mts → index-crtzMG48.d.mts} +14 -23
- package/dist/index-crtzMG48.d.mts.map +1 -0
- package/dist/{index-B1-tBzc0.d.mts → index-dCRymj_g.d.mts} +23 -71
- package/dist/{index-B1-tBzc0.d.mts.map → index-dCRymj_g.d.mts.map} +1 -1
- package/dist/index-uE3S3Krx.d.mts +245 -0
- package/dist/index-uE3S3Krx.d.mts.map +1 -0
- package/dist/index.d.mts +21 -19
- package/dist/index.mjs +1 -1
- package/dist/layer/index.d.mts +1 -1
- package/dist/layer/index.mjs +1 -1
- package/dist/{layer-BttmtDrs.mjs → layer-CKtH7TRL.mjs} +2 -2
- package/dist/layer-CKtH7TRL.mjs.map +1 -0
- package/dist/{layer.types-DgpCIsk_.d.mts → layer.types-BB0MrvLg.d.mts} +4 -4
- package/dist/{layer.types-DgpCIsk_.d.mts.map → layer.types-BB0MrvLg.d.mts.map} +1 -1
- package/dist/multithread/index.d.mts +1 -1
- package/dist/multithread/index.mjs +1 -1
- package/dist/{multithread-xUUh4eLn.mjs → multithread-Cyc8Bz45.mjs} +2 -2
- package/dist/multithread-Cyc8Bz45.mjs.map +1 -0
- package/dist/option/index.d.mts +1 -1
- package/dist/option/index.mjs +1 -1
- package/dist/{option-Tfbo4wty.mjs → option-C2iCxAuJ.mjs} +2 -2
- package/dist/option-C2iCxAuJ.mjs.map +1 -0
- package/dist/{option.types-D1mm0zUb.mjs → option.types-CbY_swma.mjs} +1 -1
- package/dist/{option.types-D1mm0zUb.mjs.map → option.types-CbY_swma.mjs.map} +1 -1
- package/dist/{option.types-qPevEZQd.d.mts → option.types-D9hrKcfa.d.mts} +3 -3
- package/dist/{option.types-qPevEZQd.d.mts.map → option.types-D9hrKcfa.d.mts.map} +1 -1
- package/dist/order/index.d.mts +1 -1
- package/dist/order/index.mjs +1 -1
- package/dist/order-BXOBEKvB.mjs +2 -0
- package/dist/order-BXOBEKvB.mjs.map +1 -0
- package/dist/{pipeable-rfqacPxZ.d.mts → pipeable-BIrevC0D.d.mts} +1 -1
- package/dist/{pipeable-rfqacPxZ.d.mts.map → pipeable-BIrevC0D.d.mts.map} +1 -1
- package/dist/pipeable-Dp1_23zH.mjs +2 -0
- package/dist/{pipeable-COGyGMUV.mjs.map → pipeable-Dp1_23zH.mjs.map} +1 -1
- package/dist/predicate/index.d.mts +1 -1
- package/dist/predicate/index.mjs +1 -1
- package/dist/{predicate-DUhhQqWY.mjs → predicate-D_1SsIi4.mjs} +2 -2
- package/dist/predicate-D_1SsIi4.mjs.map +1 -0
- package/dist/provide/index.d.mts +1 -1
- package/dist/provide/index.mjs +1 -1
- package/dist/{provide-BmSM3Ruy.mjs → provide--yZE8x-n.mjs} +2 -2
- package/dist/provide--yZE8x-n.mjs.map +1 -0
- package/dist/queue/index.d.mts +1 -1
- package/dist/queue/index.mjs +1 -1
- package/dist/{queue-Sg6KJerl.mjs → queue-apiEOlRD.mjs} +2 -2
- package/dist/queue-apiEOlRD.mjs.map +1 -0
- package/dist/{queue.types-CD2LOu37.d.mts → queue.types-B-l5XYbU.d.mts} +1 -1
- package/dist/{queue.types-CD2LOu37.d.mts.map → queue.types-B-l5XYbU.d.mts.map} +1 -1
- package/dist/result/index.d.mts +1 -1
- package/dist/result/index.mjs +1 -1
- package/dist/{result-BEzV0DYC.mjs → result-D3VY0qBG.mjs} +2 -2
- package/dist/result-D3VY0qBG.mjs.map +1 -0
- package/dist/{result.types-_xDAei3-.d.mts → result.types-BKzChyWY.d.mts} +3 -3
- package/dist/{result.types-_xDAei3-.d.mts.map → result.types-BKzChyWY.d.mts.map} +1 -1
- package/dist/schedule/index.d.mts +1 -1
- package/dist/schedule/index.mjs +1 -1
- package/dist/schedule-B9K_2Z21.d.mts +183 -0
- package/dist/schedule-B9K_2Z21.d.mts.map +1 -0
- package/dist/schedule-C6iN3oMt.mjs +2 -0
- package/dist/schedule-C6iN3oMt.mjs.map +1 -0
- package/dist/schema/index.d.mts +2 -0
- package/dist/schema/index.mjs +1 -0
- package/dist/schema-CJ-aaQe8.mjs +2 -0
- package/dist/schema-CJ-aaQe8.mjs.map +1 -0
- package/dist/schema.shared-Bjyroa6b.mjs +2 -0
- package/dist/schema.shared-Bjyroa6b.mjs.map +1 -0
- package/dist/schema.types-CBEXCwfs.d.mts +60 -0
- package/dist/schema.types-CBEXCwfs.d.mts.map +1 -0
- package/dist/scope/index.d.mts +1 -1
- package/dist/scope/index.mjs +1 -1
- package/dist/{scope-CZdp4wKX.d.mts → scope-CuM3CzwG.d.mts} +3 -9
- package/dist/scope-CuM3CzwG.d.mts.map +1 -0
- package/dist/{scope-D_kzd1nT.mjs → scope-gVt4PESc.mjs} +2 -2
- package/dist/scope-gVt4PESc.mjs.map +1 -0
- package/dist/service/index.d.mts +1 -1
- package/dist/service/index.mjs +1 -1
- package/dist/{service-3PYQTUdH.mjs → service-CWAIEH46.mjs} +2 -2
- package/dist/service-CWAIEH46.mjs.map +1 -0
- package/dist/{service-DrXU7KJG.d.mts → service-D8mr0wwg.d.mts} +2 -8
- package/dist/service-D8mr0wwg.d.mts.map +1 -0
- package/dist/{service-resolution-C19smeaO.mjs → service-resolution-BefYr4nR.mjs} +1 -1
- package/dist/{service-resolution-C19smeaO.mjs.map → service-resolution-BefYr4nR.mjs.map} +1 -1
- package/package.json +9 -1
- package/dist/adt-DajUZvJe.mjs +0 -2
- package/dist/adt-DajUZvJe.mjs.map +0 -1
- package/dist/brand-Bia3Vj6l.mjs +0 -2
- package/dist/brand-Bia3Vj6l.mjs.map +0 -1
- package/dist/context-CCHj1nab.mjs.map +0 -1
- package/dist/context-r8ESJiFn.d.mts.map +0 -1
- package/dist/data.tagged-error.types-CGiKD-ES.d.mts +0 -29
- package/dist/data.tagged-error.types-CGiKD-ES.d.mts.map +0 -1
- package/dist/discriminator.types-CTURejXz.d.mts.map +0 -1
- package/dist/either-BMLPfvMl.mjs.map +0 -1
- package/dist/flow-D8_tllWl.mjs.map +0 -1
- package/dist/functions-BkevX2Dw.mjs +0 -2
- package/dist/functions-BkevX2Dw.mjs.map +0 -1
- package/dist/fx-K-a9Smhn.mjs +0 -2
- package/dist/fx-K-a9Smhn.mjs.map +0 -1
- package/dist/index-7Lv982Om.d.mts +0 -217
- package/dist/index-7Lv982Om.d.mts.map +0 -1
- package/dist/index-BNQ9xSAz.d.mts.map +0 -1
- package/dist/index-B_iY5tq0.d.mts.map +0 -1
- package/dist/index-B_wWGszy.d.mts.map +0 -1
- package/dist/index-BiiE8NS7.d.mts.map +0 -1
- package/dist/index-CGiLfREk.d.mts.map +0 -1
- package/dist/index-CUZn-ohG.d.mts.map +0 -1
- package/dist/index-Cq2IFito.d.mts.map +0 -1
- package/dist/index-DEAWPlcI.d.mts.map +0 -1
- package/dist/index-DKS1g1oC.d.mts.map +0 -1
- package/dist/index-DXbYlSnB.d.mts.map +0 -1
- package/dist/index-UzMbg1dh.d.mts.map +0 -1
- package/dist/layer-BttmtDrs.mjs.map +0 -1
- package/dist/multithread-xUUh4eLn.mjs.map +0 -1
- package/dist/option-Tfbo4wty.mjs.map +0 -1
- package/dist/order-D5c4QChk.mjs +0 -2
- package/dist/order-D5c4QChk.mjs.map +0 -1
- package/dist/pipeable-COGyGMUV.mjs +0 -2
- package/dist/predicate-DUhhQqWY.mjs.map +0 -1
- package/dist/provide-BmSM3Ruy.mjs.map +0 -1
- package/dist/queue-Sg6KJerl.mjs.map +0 -1
- package/dist/result-BEzV0DYC.mjs.map +0 -1
- package/dist/schedule-C6tjcJ1O.mjs +0 -2
- package/dist/schedule-C6tjcJ1O.mjs.map +0 -1
- package/dist/schedule-DlX2Dg69.d.mts +0 -144
- package/dist/schedule-DlX2Dg69.d.mts.map +0 -1
- package/dist/scope-CZdp4wKX.d.mts.map +0 -1
- package/dist/scope-D_kzd1nT.mjs.map +0 -1
- package/dist/service-3PYQTUdH.mjs.map +0 -1
- package/dist/service-DrXU7KJG.d.mts.map +0 -1
- /package/dist/{chunk-C934ptG5.mjs → chunk-oQKkju2G.mjs} +0 -0
- /package/dist/{option-CBCwzF0L.mjs → option-CXXiA1w-.mjs} +0 -0
- /package/dist/{result-B5WbPg8C.mjs → result-xFLfwriM.mjs} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"either-G7uOu4Ar.mjs","names":["mapped","Result.ok","Result.err","Option.some","Option.none"],"sources":["../src/either/either.ts"],"sourcesContent":["/**\n * Biased disjoint union primitives for modeling two valid branches (`Left` / `Right`).\n *\n * **Mental model**\n * - `Either<L, R>` represents two meaningful outcomes.\n * - This module is right-biased for `map` / `flatMap`.\n *\n * **Common tasks**\n * - Construct with `Either.left` and `Either.right`.\n * - Transform with `Either.map`, `Either.mapLeft`, `Either.bimap`.\n * - Handle with `Either.match`, `Either.unwrapOr`, and conversions.\n *\n * **Gotchas**\n * - `Either.left` does not short-circuit in `Fx.gen`.\n * - Use `Result` when the left side should model failure semantics.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const value = Either.right(2)\n * const next = Either.map(value, (n) => n + 1)\n * ```\n *\n * @module\n */\nimport { FxTypeId } from \"../fx/fx.types\"\nimport { Option } from \"../option\"\nimport type { Option as OptionType } from \"../option/option.types\"\nimport { Result } from \"../result\"\nimport type { Result as ResultType } from \"../result/result.types\"\nimport { dual } from \"../shared/dual\"\nimport { isPromise } from \"../shared/is-promise\"\nimport { pipeable } from \"../shared/pipeable\"\nimport type {\n Either as EitherType,\n EitherAll,\n EitherBimap,\n EitherFilter,\n EitherFlatMap,\n EitherMap,\n EitherMapLeft,\n EitherMatch,\n EitherOrElse,\n EitherTap,\n EitherTapLeft,\n EitherUnwrapOr,\n EitherUnwrapOrElse,\n} from \"./either.types\"\n\n/**\n * Re-exported `Either` type.\n *\n * @example\n * ```ts\n * import type { Either } from \"@nicolastoulemont/std\"\n *\n * type Example = Either.Either<unknown, unknown>\n * ```\n */\nexport type Either<L, R> = EitherType<L, R>\n\n/* oxlint-disable no-unsafe-type-assertion -- Either constructors encode Fx marker channels and left/right union normalization through intentional assertions. */\n\n// ============================================================================\n// Constructors\n// ============================================================================\n\n/**\n * Create a right Either value (success/preferred path).\n *\n * By convention, right represents the correct/preferred outcome.\n * In Fx.gen(), this returns the value without short-circuiting.\n *\n * @param value - The right value\n * @returns An Either in the right state\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const value = Either.right(42)\n * // => { _tag: \"Right\", value: 42 }\n * ```\n */\nexport const right = <R, L = never>(value: R): EitherType<L, R> => ({\n _tag: \"Right\",\n value,\n [FxTypeId]: {\n _A: () => value as L | R,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n pipe: pipeable,\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, R, unknown> {\n return value\n },\n})\n\n/**\n * Create a left Either value (alternative path).\n *\n * By convention, left represents the alternative outcome.\n * Unlike Result's err(), left doesn't imply an error - it's a valid value.\n *\n * In Fx.gen(), left returns its value without short-circuiting.\n * This is the key difference from Result.err() which short-circuits.\n *\n * @param value - The left value\n * @returns An Either in the left state\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const value = Either.left(\"missing\")\n * // => { _tag: \"Left\", value: \"missing\" }\n * ```\n */\nexport const left = <L, R = never>(value: L): EitherType<L, R> => ({\n _tag: \"Left\",\n value,\n [FxTypeId]: {\n _A: () => value as L | R,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n pipe: pipeable,\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<never, L, unknown> {\n return value\n },\n})\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Type guard to check if an Either is in the right state.\n *\n * @param either - The Either to check\n * @returns True if right, false if left (with type narrowing)\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const isRight = Either.isRight(Either.right(1))\n * // => true\n * ```\n */\nexport const isRight = <L, R>(either: EitherType<L, R>): either is Extract<EitherType<L, R>, { _tag: \"Right\" }> =>\n either._tag === \"Right\"\n\n/**\n * isLeft utility.\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const isLeft = Either.isLeft(Either.left(\"missing\"))\n * // => true\n * ```\n */\nexport const isLeft = <L, R>(either: EitherType<L, R>): either is Extract<EitherType<L, R>, { _tag: \"Left\" }> =>\n either._tag === \"Left\"\n\n// ============================================================================\n// Right-biased Transformations\n// ============================================================================\n\n/**\n * Transform the right value of an Either.\n * Left values pass through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `map(either, fn)`\n * - Data-last: `pipe(either, map(fn))`\n *\n * Supports both sync and async callbacks.\n *\n * @param fn - Transformation function for right values\n * @returns The mapped Either in data-first form, or a function that maps an Either in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.right(2)\n * const dataFirst = Either.map(input, (n) => n + 1)\n * // => { _tag: \"Right\", value: 3 }\n *\n * const dataLast = Either.map((n: number) => n + 1)(input)\n * // => { _tag: \"Right\", value: 3 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const map: EitherMap = dual(2, (either: EitherType<unknown, unknown>, fn: (value: unknown) => unknown) => {\n if (either._tag === \"Left\") return either as any\n const mapped = fn(either.value)\n if (isPromise(mapped)) {\n return Promise.resolve(mapped).then(right) as any\n }\n return right(mapped) as any\n})\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n\n/**\n * Transform the left value of an Either.\n * Right values pass through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `mapLeft(either, fn)`\n * - Data-last: `pipe(either, mapLeft(fn))`\n *\n * Supports both sync and async callbacks.\n *\n * @param fn - Transformation function for left values\n * @returns The mapped Either in data-first form, or a function that maps an Either in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.left(\"missing\")\n * const dataFirst = Either.mapLeft(input, (msg) => msg.toUpperCase())\n * // => { _tag: \"Left\", value: \"MISSING\" }\n *\n * const dataLast = Either.mapLeft((msg: string) => msg.toUpperCase())(input)\n * // => { _tag: \"Left\", value: \"MISSING\" }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const mapLeft: EitherMapLeft = dual(\n 2,\n (either: EitherType<unknown, unknown>, fn: (value: unknown) => unknown) => {\n if (either._tag === \"Right\") return either as any\n const mapped = fn(either.value)\n if (isPromise(mapped)) {\n return Promise.resolve(mapped).then(left) as any\n }\n return left(mapped) as any\n },\n)\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n/**\n * Transform both sides of an Either simultaneously.\n * Unique to Either - not available in Result/Option.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `bimap(either, fnLeft, fnRight)`\n * - Data-last: `pipe(either, bimap(fnLeft, fnRight))`\n *\n * Supports both sync and async callbacks.\n *\n * @param fnLeft - Transformation function for left values\n * @param fnRight - Transformation function for right values\n * @returns The mapped Either in data-first form, or a function that bimaps an Either in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.left(\"missing\")\n * const dataFirst = Either.bimap(input, (left) => left.toUpperCase(), (right: number) => right + 1)\n * // => { _tag: \"Left\", value: \"MISSING\" }\n *\n * const dataLast = Either.bimap((left: string) => left.toUpperCase(), (right: number) => right + 1)(input)\n * // => { _tag: \"Left\", value: \"MISSING\" }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const bimap: EitherBimap = dual(\n 3,\n (either: EitherType<unknown, unknown>, fnLeft: (value: unknown) => unknown, fnRight: (value: unknown) => unknown) => {\n if (either._tag === \"Right\") {\n const mapped = fnRight(either.value)\n if (isPromise(mapped)) {\n return Promise.resolve(mapped).then(right) as any\n }\n return right(mapped) as any\n }\n const mapped = fnLeft(either.value)\n if (isPromise(mapped)) {\n return Promise.resolve(mapped).then(left) as any\n }\n return left(mapped) as any\n },\n)\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n/**\n * Chain operations that return Either.\n * Left values short-circuit the chain.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `flatMap(either, fn)`\n * - Data-last: `pipe(either, flatMap(fn))`\n *\n * Supports both sync and async callbacks. Combines left error unions.\n *\n * @param fn - Function that returns an Either\n * @returns The resulting Either in data-first form, or a function that flatMaps an Either in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.right(2)\n * const dataFirst = Either.flatMap(input, (n) => Either.right(n + 1))\n * // => { _tag: \"Right\", value: 3 }\n *\n * const dataLast = Either.flatMap((n: number) => Either.right(n + 1))(input)\n * // => { _tag: \"Right\", value: 3 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const flatMap: EitherFlatMap = dual(\n 2,\n (either: EitherType<unknown, unknown>, fn: (value: unknown) => unknown) => {\n if (either._tag === \"Left\") return either as any\n const result = fn(either.value)\n return result as any\n },\n)\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n/**\n * Execute a side effect on right values without modifying the Either.\n * Left values pass through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `tap(either, fn)`\n * - Data-last: `pipe(either, tap(fn))`\n *\n * Supports both sync and async side effects.\n *\n * @param fn - Side effect function for right values\n * @returns The original Either in data-first form, or a function that taps an Either in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * let seen = 0\n * const input = Either.right(2)\n * const dataFirst = Either.tap(input, (n) => {\n * seen = n\n * })\n * // => { _tag: \"Right\", value: 2 }\n *\n * const dataLast = Either.tap((n: number) => {\n * seen = n\n * })(input)\n * // => { _tag: \"Right\", value: 2 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const tap: EitherTap = dual(2, (either: EitherType<unknown, unknown>, fn: (value: unknown) => unknown) => {\n if (either._tag === \"Left\") return either as any\n const result = fn(either.value)\n if (isPromise(result)) {\n return Promise.resolve(result).then(() => either) as any\n }\n return either as any\n})\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n/**\n * Execute a side effect on left values without modifying the Either.\n * Right values pass through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `tapLeft(either, fn)`\n * - Data-last: `pipe(either, tapLeft(fn))`\n *\n * Supports both sync and async side effects.\n *\n * @param fn - Side effect function for left values\n * @returns The original Either in data-first form, or a function that taps left values in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * let seen = \"\"\n * const input = Either.left(\"missing\")\n * const dataFirst = Either.tapLeft(input, (msg) => {\n * seen = msg\n * })\n * // => { _tag: \"Left\", value: \"missing\" }\n *\n * const dataLast = Either.tapLeft((msg: string) => {\n * seen = msg\n * })(input)\n * // => { _tag: \"Left\", value: \"missing\" }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const tapLeft: EitherTapLeft = dual(\n 2,\n (either: EitherType<unknown, unknown>, fn: (value: unknown) => unknown) => {\n if (either._tag === \"Right\") return either as any\n const result = fn(either.value)\n if (isPromise(result)) {\n return Promise.resolve(result).then(() => either) as any\n }\n return either as any\n },\n)\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n// ============================================================================\n// Recovery/Fallback\n// ============================================================================\n\n/**\n * Recover from a left value by providing an alternative Either.\n * Right values pass through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `orElse(either, fn)`\n * - Data-last: `pipe(either, orElse(fn))`\n *\n * Supports both sync and async fallback functions. Combines right value unions.\n *\n * @param fn - Function that returns an alternative Either\n * @returns The original or fallback Either in data-first form, or a function that recovers from left in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.left(\"missing\")\n * const dataFirst = Either.orElse(input, () => Either.right(0))\n * // => { _tag: \"Right\", value: 0 }\n *\n * const dataLast = Either.orElse(() => Either.right(0))(input)\n * // => { _tag: \"Right\", value: 0 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const orElse: EitherOrElse = dual(2, (either: EitherType<unknown, unknown>, fn: (value: unknown) => unknown) => {\n if (either._tag === \"Right\") return either as any\n const result = fn(either.value)\n return result as any\n})\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n/**\n * Swap left and right values.\n * Unique to Either - not available in Result/Option.\n *\n * Curried for use with pipe().\n *\n * @returns A curried function that swaps left and right\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const swap = Either.swap<string, number>()\n * const value = swap(Either.left(\"missing\"))\n * // => { _tag: \"Right\", value: \"missing\" }\n * ```\n */\nexport const swap =\n <L, R>() =>\n (either: EitherType<L, R>): EitherType<R, L> =>\n either._tag === \"Left\" ? right(either.value) : left(either.value)\n\n// ============================================================================\n// Filtering\n// ============================================================================\n\n/**\n * Filter right values based on a predicate.\n * Failed predicates convert to left with onFail callback.\n * Left values pass through unchanged.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `filter(either, predicate, onFail)`\n * - Data-last: `pipe(either, filter(predicate, onFail))`\n *\n * @param predicate - Function to test right values\n * @param onFail - Function to produce left value on failure\n * @returns The filtered Either in data-first form, or a function that filters an Either in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.right(3)\n * const dataFirst = Either.filter(input, (n) => n > 0, (n) => `${n} must be positive`)\n * // => { _tag: \"Right\", value: 3 }\n *\n * const dataLast = Either.filter((n: number) => n > 0, (n) => `${n} must be positive`)(input)\n * // => { _tag: \"Right\", value: 3 }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- Required for overloaded return types in curried functions */\nexport const filter: EitherFilter = dual(\n 3,\n (\n either: EitherType<unknown, unknown>,\n predicate: (value: unknown) => boolean,\n onFail: (value: unknown) => unknown,\n ) => {\n if (either._tag === \"Left\") return either as any\n return predicate(either.value) ? (either as any) : left(onFail(either.value))\n },\n)\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n// ============================================================================\n// Combinators\n// ============================================================================\n\n/**\n * Combine multiple Eithers into a single Either.\n * Short-circuits on the first left value.\n *\n * Supports both array and object inputs with full type preservation.\n * For arrays of 1-6 elements, tuple types are inferred automatically.\n * For longer arrays, use `as const` to preserve tuple structure.\n *\n * @param eithers - Array or object of Eithers to combine\n * @returns Either with all right values or first left\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const combined = Either.all([Either.right(1), Either.right(2)] as const)\n * // => { _tag: \"Right\", value: [1, 2] }\n * ```\n */\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-member-access, strict-boolean-expressions, no-unsafe-assignment -- Required for handling union types in overloaded function */\nexport const all: EitherAll = (eithers: any): any => {\n // Array case\n if (Array.isArray(eithers)) {\n const values: unknown[] = []\n for (const either of eithers) {\n if (either._tag === \"Left\") return either\n values.push(either.value)\n }\n return right(values)\n }\n\n // Object case\n const result: Record<string, unknown> = {}\n for (const key in eithers) {\n const either = eithers[key]\n if (either._tag === \"Left\") return either\n result[key] = either.value\n }\n return right(result)\n}\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-member-access, strict-boolean-expressions, no-unsafe-assignment */\n// ============================================================================\n// Extraction\n// ============================================================================\n\n/**\n * Extract the right value or return a default.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `unwrapOr(either, defaultValue)`\n * - Data-last: `pipe(either, unwrapOr(defaultValue))`\n *\n * Uses NoInfer to prevent type inference from the default value.\n *\n * @param defaultValue - Value to return if Either is left\n * @returns The unwrapped value in data-first form, or a function that unwraps an Either with a default in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.left(\"missing\") as Either.Either<string, number>\n * const dataFirst = Either.unwrapOr(input, 0)\n * // => 0\n *\n * const dataLast = Either.unwrapOr(0)(input)\n * // => 0\n * ```\n */\nexport const unwrapOr: EitherUnwrapOr = dual(\n 2,\n <L, R>(either: EitherType<L, R>, defaultValue: NoInfer<R>): R =>\n either._tag === \"Right\" ? either.value : defaultValue,\n)\n\n/**\n * Extract the right value or compute one from the left value.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `unwrapOrElse(either, fn)`\n * - Data-last: `pipe(either, unwrapOrElse(fn))`\n *\n * @param fn - Function to compute default from left value\n * @returns The unwrapped value in data-first form, or a function that unwraps an Either lazily in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.left(\"missing\") as Either.Either<string, number>\n * const dataFirst = Either.unwrapOrElse(input, () => 0)\n * // => 0\n *\n * const dataLast = Either.unwrapOrElse(() => 0)(input)\n * // => 0\n * ```\n */\nexport const unwrapOrElse: EitherUnwrapOrElse = dual(\n 2,\n <L, R>(either: EitherType<L, R>, fn: (left: L) => R): R =>\n either._tag === \"Right\" ? either.value : fn(either.value),\n)\n\n/**\n * Pattern match on an Either with handlers for both cases.\n *\n * Supports both data-first and data-last calling styles:\n * - Data-first: `match(either, { Left: ..., Right: ... })`\n * - Data-last: `pipe(either, match({ Left: ..., Right: ... }))`\n *\n * @param handlers - Object with left and right handler functions\n * @returns The handler result in data-first form, or a function that matches an Either in data-last form\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const input = Either.right(2) as Either.Either<string, number>\n * const dataFirst = Either.match(input, {\n * Left: (left) => `error:${left}` ,\n * Right: (right) => `ok:${right}` ,\n * })\n * // => \"ok:2\"\n *\n * const dataLast = Either.match({\n * Left: (left: string) => `error:${left}` ,\n * Right: (right: number) => `ok:${right}` ,\n * })(input)\n * // => \"ok:2\"\n * ```\n */\nexport const match: EitherMatch = dual(\n 2,\n <L, R, U>(either: EitherType<L, R>, handlers: { Left: (value: L) => U; Right: (value: R) => U }): U =>\n either._tag === \"Right\" ? handlers.Right(either.value) : handlers.Left(either.value),\n)\n\n// ============================================================================\n// Conversions\n// ============================================================================\n\n/**\n * Convert a Result to an Either.\n * Result's ok becomes right, err becomes left.\n *\n * @param result - The Result to convert\n * @returns An Either with the same semantics\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * import { Result } from \"@nicolastoulemont/std\"\n *\n * const value = Either.fromResult(Result.ok(1))\n * // => { _tag: \"Right\", value: 1 }\n * ```\n */\nexport const fromResult = <R, E>(result: ResultType<R, E>): EitherType<E, R> =>\n result._tag === \"Ok\" ? right(result.value) : left(result.error)\n\n/**\n * Convert an Either to a Result.\n * Either's right becomes ok, left becomes err.\n *\n * Curried for use with pipe().\n *\n * @param either - The Either to convert\n * @returns A Result with error semantics\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const value = Either.toResult(Either.left(\"missing\"))\n * // => { _tag: \"Err\", error: \"missing\" }\n * ```\n */\nexport const toResult = <L, R>(either: EitherType<L, R>): ResultType<R, L> =>\n either._tag === \"Right\" ? Result.ok(either.value) : Result.err(either.value)\n\n/**\n * Convert an Option to an Either.\n * Option's some becomes right, none becomes left with onNone callback.\n *\n * @param option - The Option to convert\n * @param onNone - Function to produce left value for none\n * @returns An Either\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * import { Option } from \"@nicolastoulemont/std\"\n *\n * const value = Either.fromOption(Option.some(1), () => \"missing\")\n * // => { _tag: \"Right\", value: 1 }\n * ```\n */\nexport const fromOption = <R, L>(option: OptionType<R>, onNone: () => L): EitherType<L, R> =>\n option._tag === \"Some\" ? right(option.value) : left(onNone())\n\n/**\n * Convert an Either to an Option.\n * Either's right becomes some, left is discarded.\n *\n * Curried for use with pipe().\n *\n * @param either - The Either to convert\n * @returns An Option (left value is discarded)\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const value = Either.toOption(Either.left(\"missing\"))\n * // => { _tag: \"None\" }\n * ```\n */\nexport const toOption = <L, R>(either: EitherType<L, R>): OptionType<R> =>\n either._tag === \"Right\" ? Option.some(either.value) : Option.none<R>()\n\n/**\n * Convert a nullable value to an Either.\n * null/undefined becomes left with onNull callback, otherwise right.\n *\n * @param value - The nullable value\n * @param onNull - Function to produce left value for null/undefined\n * @returns An Either\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const value = Either.fromNullable(\"Ada\", () => \"missing\")\n * // => { _tag: \"Right\", value: \"Ada\" }\n * ```\n */\nexport const fromNullable = <R, L>(value: R | null | undefined, onNull: () => L): EitherType<L, R> =>\n value === null || value === undefined ? left(onNull()) : right(value)\n\n/**\n * Create an Either from a predicate.\n * Predicate success becomes right, failure becomes left with onFail callback.\n *\n * @param value - The value to test\n * @param predicate - Function to test the value\n * @param onFail - Function to produce left value on failure\n * @returns An Either\n *\n * @example\n * ```ts\n * import { Either } from \"@nicolastoulemont/std\"\n *\n * const value = Either.fromPredicate(3, (n) => n > 0, (n) => `${n} must be positive`)\n * // => { _tag: \"Right\", value: 3 }\n * ```\n */\nexport const fromPredicate = <R, L>(\n value: R,\n predicate: (value: R) => boolean,\n onFail: (value: R) => L,\n): EitherType<L, R> => (predicate(value) ? right(value) : left(onFail(value)))\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"ynBAuFA,MAAa,EAAuB,IAAgC,CAClE,KAAM,QACN,SACC,GAAW,CACV,OAAU,EACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,KAAM,EAEN,EAAE,OAAO,WAA0C,CACjD,OAAO,GAEV,EAsBY,EAAsB,IAAgC,CACjE,KAAM,OACN,SACC,GAAW,CACV,OAAU,EACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,KAAM,EAEN,EAAE,OAAO,WAA0C,CACjD,OAAO,GAEV,EAoBY,EAAiB,GAC5B,EAAO,OAAS,QAaL,EAAgB,GAC3B,EAAO,OAAS,OAgCL,EAAiB,EAAK,GAAI,EAAsC,IAAoC,CAC/G,GAAI,EAAO,OAAS,OAAQ,OAAO,EACnC,IAAM,EAAS,EAAG,EAAO,MAAM,CAI/B,OAHI,EAAU,EAAO,CACZ,QAAQ,QAAQ,EAAO,CAAC,KAAK,EAAM,CAErC,EAAM,EAAO,EACpB,CA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M,CAAG,EAAK,EAAO,EAAM,CAAC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const e=16777619,t=()=>({hashes:new WeakMap,inProgress:new WeakSet,objectIds:new WeakMap,nextObjectId:1}),n=(e,t)=>{let n=e.objectIds.get(t);if(n!==void 0)return n;let r=e.nextObjectId;return e.objectIds.set(t,r),e.nextObjectId++,r},r=(t,i)=>{let a=2166136261;if(t===null)return a^1853189228;if(t===void 0)return a^1970168933;switch(typeof t){case`boolean`:return a^(t?1:0);case`number`:return Number.isNaN(t)?a^5136718:Number.isFinite(t)?a^(t|0)^(t*1e6|0):a^(t>0?4812390:759787110);case`string`:for(let n=0;n<t.length;n++)a^=t.codePointAt(n),a=Math.imul(a,e);return a>>>0;case`object`:{let o=t,s=i.hashes.get(o);if(s!==void 0)return s;if(i.inProgress.has(o))return(a^1668899692^n(i,o))>>>0;if(t instanceof Date)return a^r(t.getTime(),i);if(i.inProgress.add(o),n(i,o),Array.isArray(t)){a^=23389;for(let n=0;n<t.length;n++)a^=r(t[n],i),a=Math.imul(a,e);let n=a>>>0;return i.inProgress.delete(o),i.hashes.set(o,n),n}a^=31613;let c=t,l=Object.keys(c).toSorted();for(let t of l)a^=r(t,i),a=Math.imul(a,e),a^=r(c[t],i),a=Math.imul(a,e);let u=a>>>0;return i.inProgress.delete(o),i.hashes.set(o,u),u}default:return a}};function i(e){return r(e,t())}const a=(e,t,n)=>{let r=e.get(t);return r?.has(n)===!0?!0:r===void 0?(e.set(t,new WeakSet([n])),!1):(r.add(n),!1)},o=(e,t,n)=>{if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(a(n,e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length?e.every((e,r)=>o(e,t[r],n)):!1;if(Array.isArray(e)!==Array.isArray(t))return!1;let r=e,i=t,s=Object.keys(r),c=Object.keys(i);return s.length===c.length?s.every(e=>o(r[e],i[e],n)):!1};function s(e,t){return o(e,t,new WeakMap)}function c(e){return(t,n)=>t===n?!0:t._tag!==e||n._tag!==e?!1:s(t,n)}function l(e){return t=>t._tag===e?i(t):0}function u(e){return(t,n)=>t===n?!0:t._tag!==n._tag||!e.includes(t._tag)?!1:s(t,n)}function d(e){return t=>e.includes(t._tag)?i(t):0}export{s as a,l as i,d as n,i as o,c as r,u as t};
|
|
2
|
-
//# sourceMappingURL=equality-
|
|
2
|
+
//# sourceMappingURL=equality-BX6BUidG.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"equality-CoyUHWh9.mjs","names":["result"],"sources":["../src/equality/equality.ts"],"sourcesContent":["import type { Discriminator } from \"../shared/discriminator.types\"\n\n// ============================================================================\n// Hashing (FNV-1a inspired algorithm)\n// ============================================================================\n\nconst FNV_OFFSET = 2166136261\nconst FNV_PRIME = 16777619\n// \"cycl\"\nconst CYCLE_MARKER = 0x6379636c\n\ntype HashState = {\n readonly hashes: WeakMap<object, number>\n readonly inProgress: WeakSet<object>\n readonly objectIds: WeakMap<object, number>\n nextObjectId: number\n}\n\nconst createHashState = (): HashState => ({\n hashes: new WeakMap<object, number>(),\n inProgress: new WeakSet<object>(),\n objectIds: new WeakMap<object, number>(),\n nextObjectId: 1,\n})\n\nconst getObjectId = (state: HashState, value: object): number => {\n const existing = state.objectIds.get(value)\n if (existing !== undefined) return existing\n const id = state.nextObjectId\n state.objectIds.set(value, id)\n state.nextObjectId++\n return id\n}\n\nconst deepHashInternal = (value: unknown, state: HashState): number => {\n let hash = FNV_OFFSET\n\n // \"null\" as hex\n if (value === null) return hash ^ 0x6e756c6c\n // \"unde\" as hex\n if (value === undefined) return hash ^ 0x756e6465\n\n /* oxlint-disable unicorn/prefer-math-trunc, no-case-declarations, switch-exhaustiveness-check -- Bitwise ops are intentional for FNV-1a hash: | 0 truncates to signed 32-bit, >>> 0 converts to unsigned 32-bit (Math.trunc cannot do this). Default case handles function, symbol, bigint. */\n switch (typeof value) {\n case \"boolean\":\n return hash ^ (value ? 1 : 0)\n\n case \"number\": {\n // Handle special cases: \"NaN\" as hex\n if (Number.isNaN(value)) return hash ^ 0x4e614e\n if (!Number.isFinite(value)) return hash ^ (value > 0 ? 0x496e66 : 0x2d496e66)\n // Mix the number bits into hash\n return hash ^ (value | 0) ^ ((value * 1000000) | 0)\n }\n\n case \"string\":\n for (let i = 0; i < value.length; i++) {\n hash ^= value.codePointAt(i)!\n hash = Math.imul(hash, FNV_PRIME)\n }\n // Convert to unsigned 32-bit\n return hash >>> 0\n\n case \"object\": {\n const objectValue = value\n\n const existingHash = state.hashes.get(objectValue)\n if (existingHash !== undefined) return existingHash\n\n if (state.inProgress.has(objectValue)) {\n return (hash ^ CYCLE_MARKER ^ getObjectId(state, objectValue)) >>> 0\n }\n\n if (value instanceof Date) {\n return hash ^ deepHashInternal(value.getTime(), state)\n }\n\n state.inProgress.add(objectValue)\n getObjectId(state, objectValue)\n\n if (Array.isArray(value)) {\n // \"[]\" as hex\n hash ^= 0x5b5d\n for (let i = 0; i < value.length; i++) {\n hash ^= deepHashInternal(value[i], state)\n hash = Math.imul(hash, FNV_PRIME)\n }\n const result = hash >>> 0\n state.inProgress.delete(objectValue)\n state.hashes.set(objectValue, result)\n return result\n }\n\n // Plain object: \"{}\" as hex\n hash ^= 0x7b7d\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for object iteration\n const obj = value as Record<string, unknown>\n // Sort keys for consistency\n const keys = Object.keys(obj).toSorted()\n for (const key of keys) {\n hash ^= deepHashInternal(key, state)\n hash = Math.imul(hash, FNV_PRIME)\n hash ^= deepHashInternal(obj[key], state)\n hash = Math.imul(hash, FNV_PRIME)\n }\n const result = hash >>> 0\n state.inProgress.delete(objectValue)\n state.hashes.set(objectValue, result)\n return result\n }\n\n default:\n // Handles: function, symbol, bigint\n return hash\n }\n /* oxlint-enable unicorn/prefer-math-trunc, no-case-declarations */\n}\n\n/**\n * Compute a 32-bit hash code for any value using an FNV-1a inspired algorithm.\n *\n * Handles: primitives, null, undefined, Date, arrays, plain objects, and cyclic structures.\n * Object keys are sorted for deterministic hashing regardless of insertion order.\n *\n * @param value - The value to hash (any type)\n * @returns A 32-bit unsigned integer hash code\n *\n * @example\n * ```ts\n * deepHash({ a: 1, b: 2 }) // deterministic number\n * deepHash({ b: 2, a: 1 }) // same number (keys sorted)\n * deepHash([1, 2, 3]) === deepHash([1, 2, 3]) // true\n * ```\n */\nexport function deepHash(value: unknown): number {\n return deepHashInternal(value, createHashState())\n}\n\ntype EqualsState = WeakMap<object, WeakSet<object>>\n\nconst markComparedPair = (state: EqualsState, a: object, b: object): boolean => {\n const compared = state.get(a)\n if (compared?.has(b) === true) return true\n if (compared === undefined) {\n state.set(a, new WeakSet<object>([b]))\n return false\n }\n compared.add(b)\n return false\n}\n\nconst deepEqualsInternal = (a: unknown, b: unknown, state: EqualsState): boolean => {\n // Same reference or both null/undefined\n if (a === b) return true\n\n // Different types\n if (typeof a !== typeof b) return false\n\n // Handle null\n if (a === null || b === null) return false\n\n // Primitives (already checked === above)\n if (typeof a !== \"object\") return false\n if (typeof b !== \"object\") return false\n\n const aObjRef = a\n const bObjRef = b\n\n if (markComparedPair(state, aObjRef, bObjRef)) return true\n\n // Date comparison\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime()\n }\n\n // Array comparison\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((item, index) => deepEqualsInternal(item, b[index], state))\n }\n\n // Plain object comparison\n if (Array.isArray(a) !== Array.isArray(b)) return false\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for object comparison\n const aObj = a as Record<string, unknown>\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for object comparison\n const bObj = b as Record<string, unknown>\n\n const aKeys = Object.keys(aObj)\n const bKeys = Object.keys(bObj)\n\n if (aKeys.length !== bKeys.length) return false\n\n return aKeys.every((key) => deepEqualsInternal(aObj[key], bObj[key], state))\n}\n\n// ============================================================================\n// Equality\n// ============================================================================\n\n/**\n * Deep structural equality comparison for two values.\n *\n * Compares by value rather than reference. Handles:\n * - Primitives (===)\n * - null and undefined\n * - Date objects (by timestamp)\n * - Arrays (element-wise, same length required)\n * - Plain objects (key-value pairs, same keys required)\n * - Cyclic/self-referential object graphs\n *\n * @param a - First value to compare\n * @param b - Second value to compare\n * @returns true if values are structurally equal\n *\n * @example\n * ```ts\n * deepEquals({ x: 1 }, { x: 1 }) // true\n * deepEquals([1, 2], [1, 2]) // true\n * deepEquals(new Date(0), new Date(0)) // true\n * deepEquals({ a: 1 }, { a: 1, b: 2 }) // false (different keys)\n * ```\n */\nexport function deepEquals(a: unknown, b: unknown): boolean {\n return deepEqualsInternal(a, b, new WeakMap<object, WeakSet<object>>())\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create an equals method for a specific record type.\n *\n * Returns a function that compares two values of the same record type.\n * Returns false if either value doesn't have the expected _tag.\n *\n * @template Tag - The discriminator string literal type\n * @template T - The record's data type (excluding _tag)\n * @param _tag - The expected _tag discriminator value\n * @returns A binary equality function for the record type\n *\n * @example\n * ```ts\n * const equalsPoint = createEqualsMethod<'Point', { x: number; y: number }>('Point')\n * equalsPoint(\n * { _tag: 'Point', x: 1, y: 2 },\n * { _tag: 'Point', x: 1, y: 2 }\n * ) // true\n * ```\n */\nexport function createEqualsMethod<Tag extends string, T>(\n _tag: Tag,\n): (a: T & Discriminator<Tag>, b: T & Discriminator<Tag>) => boolean {\n return (a, b) => {\n if (a === b) return true\n if (a._tag !== _tag || b._tag !== _tag) return false\n return deepEquals(a, b)\n }\n}\n\n/**\n * Create a hash method for a specific record type.\n *\n * Returns a function that computes a hash code for values of the record type.\n * Returns 0 if the value doesn't have the expected _tag.\n *\n * @template Tag - The discriminator string literal type\n * @template T - The record's data type (excluding _tag)\n * @param _tag - The expected _tag discriminator value\n * @returns A unary hash function for the record type\n *\n * @example\n * ```ts\n * const hashPoint = createHashMethod<'Point', { x: number; y: number }>('Point')\n * hashPoint({ _tag: 'Point', x: 1, y: 2 }) // number\n * ```\n */\nexport function createHashMethod<Tag extends string, T>(_tag: Tag): (value: T & Discriminator<Tag>) => number {\n return (value) => {\n if (value._tag !== _tag) return 0\n return deepHash(value)\n }\n}\n\n/**\n * Create an equals method for an ADT (any variant).\n *\n * Returns a function that compares two ADT values for structural equality.\n * Values must have the same _tag and be a known variant.\n *\n * @template T - The ADT type (union of all variants with _tag)\n * @param tags - Array of valid _tag values for this ADT\n * @returns A binary equality function for any variant of the ADT\n *\n * @example\n * ```ts\n * const equalsShape = createADTEqualsMethod<Circle | Square>(['Circle', 'Square'])\n * equalsShape(circle1, circle2) // true if structurally equal\n * equalsShape(circle, square) // false (different _tag)\n * ```\n */\nexport function createADTEqualsMethod<T extends { readonly _tag: string }>(tags: string[]): (a: T, b: T) => boolean {\n return (a, b) => {\n if (a === b) return true\n if (a._tag !== b._tag) return false\n if (!tags.includes(a._tag)) return false\n return deepEquals(a, b)\n }\n}\n\n/**\n * Create a hash method for an ADT (any variant).\n *\n * Returns a function that computes a hash code for any variant of the ADT.\n * Returns 0 if the value's _tag is not a known variant.\n *\n * @template T - The ADT type (union of all variants with _tag)\n * @param tags - Array of valid _tag values for this ADT\n * @returns A unary hash function for any variant of the ADT\n *\n * @example\n * ```ts\n * const hashShape = createADTHashMethod<Circle | Square>(['Circle', 'Square'])\n * hashShape(circle) // number\n * hashShape(square) // number\n * ```\n */\nexport function createADTHashMethod<T extends { readonly _tag: string }>(tags: string[]): (value: T) => number {\n return (value) => {\n if (!tags.includes(value._tag)) return 0\n return deepHash(value)\n }\n}\n"],"mappings":"AAMA,MACM,EAAY,SAWZ,OAAoC,CACxC,OAAQ,IAAI,QACZ,WAAY,IAAI,QAChB,UAAW,IAAI,QACf,aAAc,EACf,EAEK,GAAe,EAAkB,IAA0B,CAC/D,IAAM,EAAW,EAAM,UAAU,IAAI,EAAM,CAC3C,GAAI,IAAa,IAAA,GA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,KAAK,EAAK,CAI/B,OAFI,EAAM,SAAW,EAAM,OAEpB,EAAM,MAAO,GAAQ,EAAmB,EAAK,GAAM,EAAK,GAAM,EAAM,CAAC,CAFlC,IAgC5C,SAAgB,EAAW,EAAY,EAAqB,CAC1D,OAAO,EAAmB,EAAG,EAAG,IAAI,QAAmC,CA2BzE,SAAgB,EACd,EACmE,CACnE,OAAQ,EAAG,IACL,IAAM,EAAU,GAChB,EAAE,OAAS,GAAQ,EAAE,OAAS,EAAa,GACxC,EAAW,EAAG,EAAE,CAqB3B,SAAgB,EAAwC,EAAsD,CAC5G,MAAQ,IACF,EAAM,OAAS,EACZ,EAAS,EAAM,CADU,EAsBpC,SAAgB,EAA2D,EAAyC,CAClH,OAAQ,EAAG,IACL,IAAM,EAAU,GAChB,EAAE,OAAS,EAAE,MACb,CAAC,EAAK,SAAS,EAAE,KAAK,CAAS,GAC5B,EAAW,EAAG,EAAE,CAqB3B,SAAgB,EAAyD,EAAsC,CAC7G,MAAQ,IACD,EAAK,SAAS,EAAM,KAAK,CACvB,EAAS,EAAM,CADiB"}
|
|
1
|
+
{"version":3,"file":"equality-BX6BUidG.mjs","names":["result"],"sources":["../src/equality/equality.ts"],"sourcesContent":["import type { Discriminator } from \"../shared/discriminator.types\"\n\n// ============================================================================\n// Hashing (FNV-1a inspired algorithm)\n// ============================================================================\n\nconst FNV_OFFSET = 2166136261\nconst FNV_PRIME = 16777619\n// \"cycl\"\nconst CYCLE_MARKER = 0x6379636c\n\ntype HashState = {\n readonly hashes: WeakMap<object, number>\n readonly inProgress: WeakSet<object>\n readonly objectIds: WeakMap<object, number>\n nextObjectId: number\n}\n\nconst createHashState = (): HashState => ({\n hashes: new WeakMap<object, number>(),\n inProgress: new WeakSet<object>(),\n objectIds: new WeakMap<object, number>(),\n nextObjectId: 1,\n})\n\nconst getObjectId = (state: HashState, value: object): number => {\n const existing = state.objectIds.get(value)\n if (existing !== undefined) return existing\n const id = state.nextObjectId\n state.objectIds.set(value, id)\n state.nextObjectId++\n return id\n}\n\nconst deepHashInternal = (value: unknown, state: HashState): number => {\n let hash = FNV_OFFSET\n\n // \"null\" as hex\n if (value === null) return hash ^ 0x6e756c6c\n // \"unde\" as hex\n if (value === undefined) return hash ^ 0x756e6465\n\n /* oxlint-disable unicorn/prefer-math-trunc, no-case-declarations, switch-exhaustiveness-check -- Bitwise ops are intentional for FNV-1a hash: | 0 truncates to signed 32-bit, >>> 0 converts to unsigned 32-bit (Math.trunc cannot do this). Default case handles function, symbol, bigint. */\n switch (typeof value) {\n case \"boolean\":\n return hash ^ (value ? 1 : 0)\n\n case \"number\": {\n // Handle special cases: \"NaN\" as hex\n if (Number.isNaN(value)) return hash ^ 0x4e614e\n if (!Number.isFinite(value)) return hash ^ (value > 0 ? 0x496e66 : 0x2d496e66)\n // Mix the number bits into hash\n return hash ^ (value | 0) ^ ((value * 1000000) | 0)\n }\n\n case \"string\":\n for (let i = 0; i < value.length; i++) {\n hash ^= value.codePointAt(i)!\n hash = Math.imul(hash, FNV_PRIME)\n }\n // Convert to unsigned 32-bit\n return hash >>> 0\n\n case \"object\": {\n const objectValue = value\n\n const existingHash = state.hashes.get(objectValue)\n if (existingHash !== undefined) return existingHash\n\n if (state.inProgress.has(objectValue)) {\n return (hash ^ CYCLE_MARKER ^ getObjectId(state, objectValue)) >>> 0\n }\n\n if (value instanceof Date) {\n return hash ^ deepHashInternal(value.getTime(), state)\n }\n\n state.inProgress.add(objectValue)\n getObjectId(state, objectValue)\n\n if (Array.isArray(value)) {\n // \"[]\" as hex\n hash ^= 0x5b5d\n for (let i = 0; i < value.length; i++) {\n hash ^= deepHashInternal(value[i], state)\n hash = Math.imul(hash, FNV_PRIME)\n }\n const result = hash >>> 0\n state.inProgress.delete(objectValue)\n state.hashes.set(objectValue, result)\n return result\n }\n\n // Plain object: \"{}\" as hex\n hash ^= 0x7b7d\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for object iteration\n const obj = value as Record<string, unknown>\n // Sort keys for consistency\n const keys = Object.keys(obj).toSorted()\n for (const key of keys) {\n hash ^= deepHashInternal(key, state)\n hash = Math.imul(hash, FNV_PRIME)\n hash ^= deepHashInternal(obj[key], state)\n hash = Math.imul(hash, FNV_PRIME)\n }\n const result = hash >>> 0\n state.inProgress.delete(objectValue)\n state.hashes.set(objectValue, result)\n return result\n }\n\n default:\n // Handles: function, symbol, bigint\n return hash\n }\n /* oxlint-enable unicorn/prefer-math-trunc, no-case-declarations */\n}\n\n/**\n * Compute a 32-bit hash code for any value using an FNV-1a inspired algorithm.\n *\n * Handles: primitives, null, undefined, Date, arrays, plain objects, and cyclic structures.\n * Object keys are sorted for deterministic hashing regardless of insertion order.\n *\n * @param value - The value to hash (any type)\n * @returns A 32-bit unsigned integer hash code\n *\n * @example\n * ```ts\n * deepHash({ a: 1, b: 2 }) // deterministic number\n * deepHash({ b: 2, a: 1 }) // same number (keys sorted)\n * deepHash([1, 2, 3]) === deepHash([1, 2, 3]) // true\n * ```\n */\nexport function deepHash(value: unknown): number {\n return deepHashInternal(value, createHashState())\n}\n\ntype EqualsState = WeakMap<object, WeakSet<object>>\n\nconst markComparedPair = (state: EqualsState, a: object, b: object): boolean => {\n const compared = state.get(a)\n if (compared?.has(b) === true) return true\n if (compared === undefined) {\n state.set(a, new WeakSet<object>([b]))\n return false\n }\n compared.add(b)\n return false\n}\n\nconst deepEqualsInternal = (a: unknown, b: unknown, state: EqualsState): boolean => {\n // Same reference or both null/undefined\n if (a === b) return true\n\n // Different types\n if (typeof a !== typeof b) return false\n\n // Handle null\n if (a === null || b === null) return false\n\n // Primitives (already checked === above)\n if (typeof a !== \"object\") return false\n if (typeof b !== \"object\") return false\n\n const aObjRef = a\n const bObjRef = b\n\n if (markComparedPair(state, aObjRef, bObjRef)) return true\n\n // Date comparison\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime()\n }\n\n // Array comparison\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) return false\n return a.every((item, index) => deepEqualsInternal(item, b[index], state))\n }\n\n // Plain object comparison\n if (Array.isArray(a) !== Array.isArray(b)) return false\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for object comparison\n const aObj = a as Record<string, unknown>\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for object comparison\n const bObj = b as Record<string, unknown>\n\n const aKeys = Object.keys(aObj)\n const bKeys = Object.keys(bObj)\n\n if (aKeys.length !== bKeys.length) return false\n\n return aKeys.every((key) => deepEqualsInternal(aObj[key], bObj[key], state))\n}\n\n// ============================================================================\n// Equality\n// ============================================================================\n\n/**\n * Deep structural equality comparison for two values.\n *\n * Compares by value rather than reference. Handles:\n * - Primitives (===)\n * - null and undefined\n * - Date objects (by timestamp)\n * - Arrays (element-wise, same length required)\n * - Plain objects (key-value pairs, same keys required)\n * - Cyclic/self-referential object graphs\n *\n * @param a - First value to compare\n * @param b - Second value to compare\n * @returns true if values are structurally equal\n *\n * @example\n * ```ts\n * deepEquals({ x: 1 }, { x: 1 }) // true\n * deepEquals([1, 2], [1, 2]) // true\n * deepEquals(new Date(0), new Date(0)) // true\n * deepEquals({ a: 1 }, { a: 1, b: 2 }) // false (different keys)\n * ```\n */\nexport function deepEquals(a: unknown, b: unknown): boolean {\n return deepEqualsInternal(a, b, new WeakMap<object, WeakSet<object>>())\n}\n\n// ============================================================================\n// Factory Functions\n// ============================================================================\n\n/**\n * Create an equals method for a specific record type.\n *\n * Returns a function that compares two values of the same record type.\n * Returns false if either value doesn't have the expected _tag.\n *\n * @template Tag - The discriminator string literal type\n * @template T - The record's data type (excluding _tag)\n * @param _tag - The expected _tag discriminator value\n * @returns A binary equality function for the record type\n *\n * @example\n * ```ts\n * const equalsPoint = createEqualsMethod<'Point', { x: number; y: number }>('Point')\n * equalsPoint(\n * { _tag: 'Point', x: 1, y: 2 },\n * { _tag: 'Point', x: 1, y: 2 }\n * ) // true\n * ```\n */\nexport function createEqualsMethod<Tag extends string, T>(\n _tag: Tag,\n): (a: T & Discriminator<Tag>, b: T & Discriminator<Tag>) => boolean {\n return (a, b) => {\n if (a === b) return true\n if (a._tag !== _tag || b._tag !== _tag) return false\n return deepEquals(a, b)\n }\n}\n\n/**\n * Create a hash method for a specific record type.\n *\n * Returns a function that computes a hash code for values of the record type.\n * Returns 0 if the value doesn't have the expected _tag.\n *\n * @template Tag - The discriminator string literal type\n * @template T - The record's data type (excluding _tag)\n * @param _tag - The expected _tag discriminator value\n * @returns A unary hash function for the record type\n *\n * @example\n * ```ts\n * const hashPoint = createHashMethod<'Point', { x: number; y: number }>('Point')\n * hashPoint({ _tag: 'Point', x: 1, y: 2 }) // number\n * ```\n */\nexport function createHashMethod<Tag extends string, T>(_tag: Tag): (value: T & Discriminator<Tag>) => number {\n return (value) => {\n if (value._tag !== _tag) return 0\n return deepHash(value)\n }\n}\n\n/**\n * Create an equals method for an ADT (any variant).\n *\n * Returns a function that compares two ADT values for structural equality.\n * Values must have the same _tag and be a known variant.\n *\n * @template T - The ADT type (union of all variants with _tag)\n * @param tags - Array of valid _tag values for this ADT\n * @returns A binary equality function for any variant of the ADT\n *\n * @example\n * ```ts\n * const equalsShape = createADTEqualsMethod<Circle | Square>(['Circle', 'Square'])\n * equalsShape(circle1, circle2) // true if structurally equal\n * equalsShape(circle, square) // false (different _tag)\n * ```\n */\nexport function createADTEqualsMethod<T extends { readonly _tag: string }>(tags: string[]): (a: T, b: T) => boolean {\n return (a, b) => {\n if (a === b) return true\n if (a._tag !== b._tag) return false\n if (!tags.includes(a._tag)) return false\n return deepEquals(a, b)\n }\n}\n\n/**\n * Create a hash method for an ADT (any variant).\n *\n * Returns a function that computes a hash code for any variant of the ADT.\n * Returns 0 if the value's _tag is not a known variant.\n *\n * @template T - The ADT type (union of all variants with _tag)\n * @param tags - Array of valid _tag values for this ADT\n * @returns A unary hash function for any variant of the ADT\n *\n * @example\n * ```ts\n * const hashShape = createADTHashMethod<Circle | Square>(['Circle', 'Square'])\n * hashShape(circle) // number\n * hashShape(square) // number\n * ```\n */\nexport function createADTHashMethod<T extends { readonly _tag: string }>(tags: string[]): (value: T) => number {\n return (value) => {\n if (!tags.includes(value._tag)) return 0\n return deepHash(value)\n }\n}\n"],"mappings":"AAMA,MACM,EAAY,SAWZ,OAAoC,CACxC,OAAQ,IAAI,QACZ,WAAY,IAAI,QAChB,UAAW,IAAI,QACf,aAAc,EACf,EAEK,GAAe,EAAkB,IAA0B,CAC/D,IAAM,EAAW,EAAM,UAAU,IAAI,EAAM,CAC3C,GAAI,IAAa,IAAA,GAAW,OAAO,EACnC,IAAM,EAAK,EAAM,aAGjB,OAFA,EAAM,UAAU,IAAI,EAAO,EAAG,CAC9B,EAAM,eACC,GAGH,GAAoB,EAAgB,IAA6B,CACrE,IAAI,EAAO,WAGX,GAAI,IAAU,KAAM,OAAO,EAAO,WAElC,GAAI,IAAU,IAAA,GAAW,OAAO,EAAO,WAGvC,OAAQ,OAAO,EAAf,CACE,IAAK,UACH,OAAO,GAAQ,EAAQ,EAAI,GAE7B,IAAK,SAKH,OAHI,OAAO,MAAM,EAAM,CAAS,EAAO,QAClC,OAAO,SAAS,EAAM,CAEpB,GAAQ,EAAQ,IAAO,EAAQ,IAAW,GAFb,GAAQ,EAAQ,EAAI,QAAW,WAKrE,IAAK,SACH,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,IAChC,GAAQ,EAAM,YAAY,EAAE,CAC5B,EAAO,KAAK,KAAK,EAAM,EAAU,CAGnC,OAAO,IAAS,EAElB,IAAK,SAAU,CACb,IAAM,EAAc,EAEd,EAAe,EAAM,OAAO,IAAI,EAAY,CAClD,GAAI,IAAiB,IAAA,GAAW,OAAO,EAEvC,GAAI,EAAM,WAAW,IAAI,EAAY,CACnC,OAAQ,EAAO,WAAe,EAAY,EAAO,EAAY,IAAM,EAGrE,GAAI,aAAiB,KACnB,OAAO,EAAO,EAAiB,EAAM,SAAS,CAAE,EAAM,CAMxD,GAHA,EAAM,WAAW,IAAI,EAAY,CACjC,EAAY,EAAO,EAAY,CAE3B,M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C,GAAI,MAAM,QAAQ,EAAE,EAAI,MAAM,QAAQ,EAAE,CAEtC,OADI,EAAE,SAAW,EAAE,OACZ,EAAE,OAAO,EAAM,IAAU,EAAmB,EAAM,EAAE,GAAQ,EAAM,CAAC,CADxC,GAKpC,GAAI,MAAM,QAAQ,EAAE,GAAK,MAAM,QAAQ,EAAE,CAAE,MAAO,GAGlD,IAAM,EAAO,EAEP,EAAO,EAEP,EAAQ,OAAO,KAAK,EAAK,CACzB,EAAQ,OAAO,KAAK,EAAK,CAI/B,OAFI,EAAM,SAAW,EAAM,OAEpB,EAAM,MAAO,GAAQ,EAAmB,EAAK,GAAM,EAAK,GAAM,EAAM,CAAC,CAFlC,IAgC5C,SAAgB,EAAW,EAAY,EAAqB,CAC1D,OAAO,EAAmB,EAAG,EAAG,IAAI,QAAmC,CA2BzE,SAAgB,EACd,EACmE,CACnE,OAAQ,EAAG,IACL,IAAM,EAAU,GAChB,EAAE,OAAS,GAAQ,EAAE,OAAS,EAAa,GACxC,EAAW,EAAG,EAAE,CAqB3B,SAAgB,EAAwC,EAAsD,CAC5G,MAAQ,IACF,EAAM,OAAS,EACZ,EAAS,EAAM,CADU,EAsBpC,SAAgB,EAA2D,EAAyC,CAClH,OAAQ,EAAG,IACL,IAAM,EAAU,GAChB,EAAE,OAAS,EAAE,MACb,CAAC,EAAK,SAAS,EAAE,KAAK,CAAS,GAC5B,EAAW,EAAG,EAAE,CAqB3B,SAAgB,EAAyD,EAAsC,CAC7G,MAAQ,IACD,EAAK,SAAS,EAAM,KAAK,CACvB,EAAS,EAAM,CADiB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
function e(e){return e===null||typeof e!=`object`&&typeof e!=`function`?!1:typeof e.then==`function`}function t(...t){return((...r)=>{let i=r;for(let r=0;r<t.length;r++){let[a]=i=[t[r]?.(...i)];if(e(a))return n(a,t.slice(r+1))}return i[0]})}const n=async(e,t)=>{for(let n of t)e=n(await e);return await e};export{e as n,t};
|
|
2
|
-
//# sourceMappingURL=flow-
|
|
2
|
+
//# sourceMappingURL=flow-CNyLsPGb.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flow-CNyLsPGb.mjs","names":[],"sources":["../src/shared/is-promise.ts","../src/functions/flow.ts"],"sourcesContent":["/**\n * Check if a value is a Promise.\n */\nexport function isPromise(value: unknown): value is PromiseLike<unknown> {\n if (value === null) return false\n if (typeof value !== \"object\" && typeof value !== \"function\") return false\n return typeof (value as { then?: unknown }).then === \"function\"\n}\n","/**\n * Point-free function composition utilities.\n *\n * **Mental model**\n * - `flow(fn1, fn2...)` returns a new composed function.\n * - Each function receives the previous function output.\n *\n * **Common tasks**\n * - Build reusable transformation functions.\n * - Compose sync and async processing steps.\n *\n * **Gotchas**\n * - The first function controls the input parameter list.\n * - For immediate execution on a value, use `pipe`.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { flow } from \"@nicolastoulemont/std\"\n *\n * const toLabel = flow((n: number) => n + 1, (n) => `value:${n}`)\n * ```\n *\n * @module\n */\nimport { isPromise } from \"../shared/is-promise\"\nimport type { λ } from \"../shared/lambda.types\"\nimport type { FlowdFun } from \"./flow.types\"\n\n/**\n * Given a list of functions returns a function that will execute the given\n * functions one after another, always passing the result of the previous\n * function as an argument to the next function.\n *\n * If one of the given functions returns a promise, the promise will be resolved\n * before being passed to the next function.\n *\n * Type inference: This function provides automatic type inference for chains of\n * 1-15 functions. Each function's parameter type is automatically inferred from\n * the previous function's return type. For chains longer than 15 functions,\n * types must be explicitly specified.\n *\n * Async support: Functions can return Promises. The runtime automatically awaits\n * Promises before passing values to subsequent functions, and parameter types\n * use `Awaited<T>` to reflect this behavior. The final return type will be\n * Promise<T> if any function returns a Promise.\n *\n * @see {@link pipe} for immediate execution with an initial value\n *\n * @example\n * ```ts\n * import { flow } from \"@nicolastoulemont/std\"\n *\n * const toLabel = flow((n: number) => n + 1, (n) => `value:${n}`)\n * const result = toLabel(2)\n * // => \"value:3\"\n * ```\n */\n// 1 function\nexport function flow<A extends unknown[], B>(f1: (...args: A) => B): FlowdFun<[typeof f1]>\n// 2 functions\nexport function flow<A extends unknown[], B, C>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n): FlowdFun<[typeof f1, typeof f2]>\n// 3 functions\nexport function flow<A extends unknown[], B, C, D>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n): FlowdFun<[typeof f1, typeof f2, typeof f3]>\n// 4 functions\nexport function flow<A extends unknown[], B, C, D, E>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n): FlowdFun<[typeof f1, typeof f2, typeof f3, typeof f4]>\n// 5 functions\nexport function flow<A extends unknown[], B, C, D, E, F>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n): FlowdFun<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5]>\n// 6 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n): FlowdFun<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6]>\n// 7 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n): FlowdFun<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6, typeof f7]>\n// 8 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n): FlowdFun<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6, typeof f7, typeof f8]>\n// 9 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n): FlowdFun<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6, typeof f7, typeof f8, typeof f9]>\n// 10 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J, K>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n): FlowdFun<\n [typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6, typeof f7, typeof f8, typeof f9, typeof f10]\n>\n// 11 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J, K, L>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n): FlowdFun<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n ]\n>\n// 12 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J, K, L, M>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n f12: (arg: Awaited<L>) => M,\n): FlowdFun<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n typeof f12,\n ]\n>\n// 13 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J, K, L, M, N>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n f12: (arg: Awaited<L>) => M,\n f13: (arg: Awaited<M>) => N,\n): FlowdFun<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n typeof f12,\n typeof f13,\n ]\n>\n// 14 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J, K, L, M, N, O>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n f12: (arg: Awaited<L>) => M,\n f13: (arg: Awaited<M>) => N,\n f14: (arg: Awaited<N>) => O,\n): FlowdFun<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n typeof f12,\n typeof f13,\n typeof f14,\n ]\n>\n// 15 functions\nexport function flow<A extends unknown[], B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>(\n f1: (...args: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n f12: (arg: Awaited<L>) => M,\n f13: (arg: Awaited<M>) => N,\n f14: (arg: Awaited<N>) => O,\n f15: (arg: Awaited<O>) => P,\n): FlowdFun<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n typeof f12,\n typeof f13,\n typeof f14,\n typeof f15,\n ]\n>\n// Implementation signature (fallback for 16+ functions)\nexport function flow<Fns extends [λ, ...λ[]]>(...fns: Fns): FlowdFun<Fns> {\n // oxlint-disable-next-line\n return ((...args) => {\n // oxlint-disable-next-line\n let nextArgs: unknown[] = args\n\n for (let i = 0; i < fns.length; i++) {\n // oxlint-disable-next-line\n const [result] = (nextArgs = [fns[i]?.(...nextArgs)])\n if (isPromise(result)) return resolveAsync(result, fns.slice(i + 1))\n }\n\n return nextArgs[0]\n }) as FlowdFun<Fns>\n}\n\nconst resolveAsync = async (result: unknown, funs: λ[]) => {\n // oxlint-disable-next-line\n for (const fun of funs) result = fun(await result)\n return await result\n}\n"],"mappings":"AAGA,SAAgB,EAAU,EAA+C,CAGvE,OAFI,IAAU,MACV,OAAO,GAAU,UAAY,OAAO,GAAU,WAAmB,GAC9D,OAAQ,EAA6B,MAAS,WC2SvD,SAAgB,EAA8B,GAAG,EAAyB,CAExE,QAAS,GAAG,IAAS,CAEnB,IAAI,EAAsB,EAE1B,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,IAAK,CAEnC,GAAM,CAAC,GAAW,EAAW,CAAC,EAAI,KAAK,GAAG,EAAS,CAAC,CACpD,GAAI,EAAU,EAAO,CAAE,OAAO,EAAa,EAAQ,EAAI,MAAM,EAAI,EAAE,CAAC,CAGtE,OAAO,EAAS,KAIpB,MAAM,EAAe,MAAO,EAAiB,IAAc,CAEzD,IAAK,IAAM,KAAO,EAAM,EAAS,EAAI,MAAM,EAAO,CAClD,OAAO,MAAM"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as flow, t as pipe } from "../index-
|
|
1
|
+
import { n as flow, t as pipe } from "../index-D7mFNjot.mjs";
|
|
2
2
|
export { flow, pipe };
|
package/dist/functions/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../flow-
|
|
1
|
+
import{t as e}from"../flow-CNyLsPGb.mjs";import{t}from"../functions-ByAk682_.mjs";export{e as flow,t as pipe};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions-ByAk682_.mjs","names":[],"sources":["../src/functions/pipe.ts"],"sourcesContent":["/**\n * Data-first function composition utilities.\n *\n * **Mental model**\n * - `pipe(value, fn1, fn2...)` applies functions left-to-right.\n * - Supports sync/async chains and preserves type inference across overloads.\n *\n * **Common tasks**\n * - Build readable transformation pipelines.\n * - Mix sync and async functions in the same chain.\n *\n * **Gotchas**\n * - The first argument is always the input value.\n * - For point-free composition, use `flow`.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { pipe } from \"@nicolastoulemont/std\"\n *\n * const result = pipe(2, (n) => n + 1, (n) => n * 2)\n * ```\n *\n * @module\n */\nimport type { λ } from \"../shared/lambda.types\"\nimport { flow } from \"./flow\"\nimport type { PipeReturn } from \"./pipe.types\"\n\n/**\n * Like `flow` but takes an argument as its first parameter and invokes the pipe\n * with it.\n *\n * Note: unlike in `flow`, the first function of the pipe must take exactly one\n * argument.\n *\n * Type inference: This function provides automatic type inference for chains of\n * 1-15 functions. Each function's parameter type is automatically inferred from\n * the previous function's return type. For chains longer than 15 functions,\n * types must be explicitly specified.\n *\n * Async support: Functions can return Promises. The runtime automatically awaits\n * Promises before passing values to subsequent functions, and parameter types\n * use `Awaited<T>` to reflect this behavior. The final return type will be\n * Promise<T> if any function returns a Promise.\n *\n * @see {@link flow} for point-free function composition (returns a function)\n *\n * @example\n * ```ts\n * import { pipe } from \"@nicolastoulemont/std\"\n *\n * const result = pipe(2, (n) => n + 1, (n) => n * 3)\n * // => 9\n * ```\n */\n// 1 function\nexport function pipe<A, B>(arg: A, f1: (arg: A) => B): PipeReturn<[typeof f1], A>\n// 2 functions\nexport function pipe<A, B, C>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n): PipeReturn<[typeof f1, typeof f2], A>\n// 3 functions\nexport function pipe<A, B, C, D>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n): PipeReturn<[typeof f1, typeof f2, typeof f3], A>\n// 4 functions\nexport function pipe<A, B, C, D, E>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n): PipeReturn<[typeof f1, typeof f2, typeof f3, typeof f4], A>\n// 5 functions\nexport function pipe<A, B, C, D, E, F>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n): PipeReturn<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5], A>\n// 6 functions\nexport function pipe<A, B, C, D, E, F, G>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n): PipeReturn<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6], A>\n// 7 functions\nexport function pipe<A, B, C, D, E, F, G, H>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n): PipeReturn<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6, typeof f7], A>\n// 8 functions\nexport function pipe<A, B, C, D, E, F, G, H, I>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n): PipeReturn<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6, typeof f7, typeof f8], A>\n// 9 functions\nexport function pipe<A, B, C, D, E, F, G, H, I, J>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n): PipeReturn<[typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6, typeof f7, typeof f8, typeof f9], A>\n// 10 functions\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n): PipeReturn<\n [typeof f1, typeof f2, typeof f3, typeof f4, typeof f5, typeof f6, typeof f7, typeof f8, typeof f9, typeof f10],\n A\n>\n// 11 functions\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K, L>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n): PipeReturn<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n ],\n A\n>\n// 12 functions\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n f12: (arg: Awaited<L>) => M,\n): PipeReturn<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n typeof f12,\n ],\n A\n>\n// 13 functions\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n f12: (arg: Awaited<L>) => M,\n f13: (arg: Awaited<M>) => N,\n): PipeReturn<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n typeof f12,\n typeof f13,\n ],\n A\n>\n// 14 functions\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n f12: (arg: Awaited<L>) => M,\n f13: (arg: Awaited<M>) => N,\n f14: (arg: Awaited<N>) => O,\n): PipeReturn<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n typeof f12,\n typeof f13,\n typeof f14,\n ],\n A\n>\n// 15 functions\nexport function pipe<A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P>(\n arg: A,\n f1: (arg: A) => B,\n f2: (arg: Awaited<B>) => C,\n f3: (arg: Awaited<C>) => D,\n f4: (arg: Awaited<D>) => E,\n f5: (arg: Awaited<E>) => F,\n f6: (arg: Awaited<F>) => G,\n f7: (arg: Awaited<G>) => H,\n f8: (arg: Awaited<H>) => I,\n f9: (arg: Awaited<I>) => J,\n f10: (arg: Awaited<J>) => K,\n f11: (arg: Awaited<K>) => L,\n f12: (arg: Awaited<L>) => M,\n f13: (arg: Awaited<M>) => N,\n f14: (arg: Awaited<N>) => O,\n f15: (arg: Awaited<O>) => P,\n): PipeReturn<\n [\n typeof f1,\n typeof f2,\n typeof f3,\n typeof f4,\n typeof f5,\n typeof f6,\n typeof f7,\n typeof f8,\n typeof f9,\n typeof f10,\n typeof f11,\n typeof f12,\n typeof f13,\n typeof f14,\n typeof f15,\n ],\n A\n>\n// Implementation signature (fallback for 16+ functions)\n// oxlint-disable-next-line no-explicit-any\nexport function pipe<A, Fns extends [(arg: A) => any, ...λ[]]>(arg: A, ...fns: Fns): PipeReturn<Fns, A> {\n // @ts-expect-error - we want to use the any type here\n // oxlint-disable-next-line no-explicit-any, no-unsafe-return, no-unsafe-call, no-unsafe-type-assertion -- Required for pipe implementation\n return (flow(...(fns as [λ, ...λ[]])) as any)(arg)\n}\n"],"mappings":"wCAoUA,SAAgB,EAA+C,EAAQ,GAAG,EAA8B,CAGtG,OAAQ,EAAK,GAAI,EAAoB,CAAS,EAAI"}
|
package/dist/fx/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as fx_d_exports } from "../index-
|
|
1
|
+
import { t as fx_d_exports } from "../index-MsJqfQu0.mjs";
|
|
2
2
|
export { fx_d_exports as Fx };
|
package/dist/fx/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../fx-
|
|
1
|
+
import{t as e}from"../fx-DUXDxwsU.mjs";export{e as Fx};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-oQKkju2G.mjs";import{n as t,t as n}from"./fx.types-DyQVgTS8.mjs";import{t as r}from"./dual-fN6OUwN_.mjs";import{i,n as a,t as o}from"./result-D3VY0qBG.mjs";import{t as s}from"./option.types-CbY_swma.mjs";import{t as c}from"./option-C2iCxAuJ.mjs";import{t as l}from"./service-resolution-BefYr4nR.mjs";import{i as u,n as d,r as f,t as p}from"./queue-apiEOlRD.mjs";import{n as m,r as h,t as g}from"./fx.runtime-jQxh77s3.mjs";var _=class extends Error{_tag=`TypedFailure`;constructor(e){super(`TypedFailure`),this.error=e,this.name=`TypedFailure`}};const v=e=>e instanceof _,y=e=>typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`Err`&&`error`in e,b=e=>e instanceof s?e:y(e)?e.error:e,x=e=>e!=null&&typeof e[Symbol.iterator]==`function`,S=e=>new f({reason:e.reason}),C=e=>e instanceof Error?e:Error(`Fx.forEach defect was not an Error`,{cause:e}),w=()=>{throw Error(`Unreachable: Fx type marker should never execute at runtime`)},T=()=>w,E=async(e,t,n)=>{if(e._tag===`AsyncFx`){let r=e[Symbol.asyncIterator](),i=await r.next();for(;i.done!==!0;){if(t.aborted)throw S(t);let e=i.value;if(l(e)!==void 0){let a=await n(e,t);i=await r.next(a);continue}throw new _(b(e))}return i.value}let r=e[Symbol.iterator](),i=r.next();for(;i.done!==!0;){if(t.aborted)throw S(t);let e=i.value;if(l(e)!==void 0){let a=await n(e,t);i=r.next(a);continue}throw new _(b(e))}return i.value},D=r(e=>x(e[0])&&typeof e[1]==`function`,(e,t,r)=>{let i=[...e],a=r?.discard===!0;return{_tag:`AsyncFx`,[n]:{_A:T(),_E:T(),_R:T()},async*[Symbol.asyncIterator](){if(i.length===0)return a?void 0:[];let e=u({concurrency:r?.concurrency??`unbounded`}),n=a?void 0:[],o=i.length,s,c,l=!1,m=[],h=new Set,g=()=>{for(let e of h)e();h.clear()},_=()=>new Promise(e=>{h.add(e)}),y=(e,t)=>t.aborted?Promise.reject(S(t)):new Promise((n,r)=>{let i={yielded:e,signal:t,resolve:e=>{t.removeEventListener(`abort`,a),n(e)},reject:e=>{t.removeEventListener(`abort`,a),r(e)}},a=()=>{let e=m.indexOf(i);e!==-1&&m.splice(e,1),r(S(t))};t.addEventListener(`abort`,a,{once:!0}),m.push(i),g()}),b=e=>{let t=m.splice(0);for(let n of t)n.reject(e)},x=t=>{l||(l=!0,e.shutdown({mode:`abort`,reason:t}).catch(()=>{}))},w=e=>{if(v(e)){s===void 0&&c===void 0&&(s=e.error,x(e.error));return}if(!((e instanceof p||e instanceof f||e instanceof d)&&(s!==void 0||c!==void 0))&&c===void 0&&s===void 0){let t=C(e);c=t,x(t)}},T=()=>{--o,g()};for(let[r,a]of i.entries())e.enqueue(async({signal:e})=>{let i=await E(t(a,r),e,y);n!==void 0&&(n[r]=i)}).catch(w).finally(T);for(;;){if(c!==void 0)throw b(c),Error(`Fx.forEach defect`,{cause:c});if(s!==void 0)throw b(new p({reason:s})),yield s,Error(`Unreachable: Fx runtime short-circuits on first failure`);let e=m.shift();if(e!==void 0){if(e.signal.aborted){e.reject(S(e.signal));continue}try{let t=yield e.yielded;e.resolve(t)}catch(t){e.reject(C(t))}continue}if(o===0)break;await _()}return a?void 0:n}}});var O=e({Exit:()=>h,FxTypeId:()=>n,err:()=>X,fn:()=>G,forEach:()=>J,gen:()=>W,isServiceRequest:()=>t,match:()=>$,ok:()=>Y,option:()=>Z,retry:()=>q,run:()=>K,try:()=>Q});function k(e){return e._tag===`AsyncFx`?g(e):m(e)}const A=e=>new Promise(t=>{setTimeout(t,e)}),j=async e=>{e<=0||await A(e)},M=e=>{typeof e.return==`function`&&e.return(void 0)},N=async e=>{typeof e.return==`function`&&await e.return(void 0)},P=(e,t)=>({_tag:`SyncFx`,[n]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let n=0;attemptLoop:for(;;){let r=e[Symbol.iterator](),i=r.next();for(;i.done!==!0;){let e=i.value;if(l(e)!==void 0){let t=yield e;i=r.next(t);continue}if(n+=1,n<=t.maxRetries){M(r);continue attemptLoop}yield e;return}return i.value}}}),F=(e,t)=>({_tag:`AsyncFx`,[n]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){let n=0;attemptLoop:for(;;){if(e._tag===`AsyncFx`){let r=e[Symbol.asyncIterator](),i=await r.next();for(;i.done!==!0;){let e=i.value;if(l(e)!==void 0){let t=yield e;i=await r.next(t);continue}if(n+=1,n<=t.maxRetries){await j(t.delayForAttempt(n)),await N(r);continue attemptLoop}return yield e,void 0}return i.value}let r=e[Symbol.iterator](),i=r.next();for(;i.done!==!0;){let e=i.value;if(l(e)!==void 0){let t=yield e;i=r.next(t);continue}if(n+=1,n<=t.maxRetries){await j(t.delayForAttempt(n)),await N(r);continue attemptLoop}return yield e,void 0}return i.value}}}),I=r(2,(e,t)=>e._tag===`AsyncFx`||!t._sync?F(e,t):P(e,t));function L(e){if(e.length>0)return(...t)=>L(()=>e(...t));let t=e();return Symbol.asyncIterator in t?{_tag:`AsyncFx`,[n]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){let t=e(),n=await t.next();for(;n.done!==!0;){let e=yield n.value;n=await t.next(e)}return n.value}}:{_tag:`SyncFx`,[n]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let t=e(),n=t.next();for(;n.done!==!0;){let e=yield n.value;n=t.next(e)}return n.value}}}function R(e,t){let n=L(e);return k(t?(n._tag,t(n)):n)}const z=i,B=o,V=a,H=c,U=r(2,(e,t)=>t[e._tag](e)),W=L,G=R,K=k,q=I,J=D,Y=z,X=B,Z=H,Q=V,$=U;export{O as t};
|
|
2
|
+
//# sourceMappingURL=fx-DUXDxwsU.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fx-DUXDxwsU.mjs","names":["gen","result","makeQueue","gen","result","resultOk","resultErr","resultTry","optionFromNullable"],"sources":["../src/fx/foreach.ts","../src/fx/fx.ts"],"sourcesContent":["import { NoSuchElementError } from \"../option/option.types\"\nimport { make as makeQueue, QueueAbortedError, QueueClosedError, QueueTaskAbortedError } from \"../queue/queue\"\nimport type { Concurrency } from \"../queue/queue.types\"\nimport { asServiceRequest } from \"../service/service-resolution\"\nimport { dual } from \"../shared/dual\"\nimport { FxTypeId } from \"./fx.types\"\nimport type { AsyncFx, FxError, FxRequirements, FxValue, FxYield, RunnableFx } from \"./fx.types\"\n\n/* oxlint-disable no-await-in-loop -- Fx.forEach coordinates child iterators and queue scheduling sequentially at specific yield points. */\n\ntype ForEachValue<Discard extends boolean, B> = Discard extends true ? void : Array<B>\n\ntype FxForEachOptions<Discard extends boolean = false> = {\n readonly concurrency?: Concurrency\n readonly discard?: Discard\n}\n\ntype ForEachFx<\n F extends (a: never, i: number) => RunnableFx<unknown, unknown, unknown>,\n Discard extends boolean,\n> = AsyncFx<ForEachValue<Discard, FxValue<ReturnType<F>>>, FxError<ReturnType<F>>, FxRequirements<ReturnType<F>>>\n\ntype FxForEach = {\n <A, F extends (a: A, i: number) => RunnableFx<unknown, unknown, unknown>, const Discard extends boolean = false>(\n self: Iterable<A>,\n f: F,\n options?: FxForEachOptions<Discard>,\n ): ForEachFx<F, Discard>\n <A, F extends (a: A, i: number) => RunnableFx<unknown, unknown, unknown>, const Discard extends boolean = false>(\n f: F,\n options?: FxForEachOptions<Discard>,\n ): (self: Iterable<A>) => ForEachFx<F, Discard>\n}\n\ntype ServiceRequestEntry<E, R> = {\n readonly yielded: FxYield<E, R>\n readonly signal: AbortSignal\n readonly resolve: (value: unknown) => void\n readonly reject: (reason: Error) => void\n}\n\ntype ResultErrShape = {\n readonly _tag: \"Err\"\n readonly error: unknown\n}\n\nclass TypedFailure<E> extends Error {\n readonly _tag = \"TypedFailure\"\n\n constructor(readonly error: E) {\n super(\"TypedFailure\")\n this.name = \"TypedFailure\"\n }\n}\n\nconst isTypedFailure = <E>(value: unknown): value is TypedFailure<E> => value instanceof TypedFailure\n\nconst isResultErr = (value: unknown): value is ResultErrShape =>\n typeof value === \"object\" && value !== null && \"_tag\" in value && value._tag === \"Err\" && \"error\" in value\n\nconst toFailureValue = (yielded: unknown): unknown => {\n if (yielded instanceof NoSuchElementError) {\n return yielded\n }\n\n if (isResultErr(yielded)) {\n return yielded.error\n }\n\n return yielded\n}\n\nconst isIterable = (value: unknown): value is Iterable<unknown> =>\n value !== null &&\n value !== undefined &&\n typeof (value as { [Symbol.iterator]?: unknown })[Symbol.iterator] === \"function\"\n\nconst queueTaskAbortedError = (signal: AbortSignal): QueueTaskAbortedError =>\n new QueueTaskAbortedError({ reason: signal.reason })\n\nconst toError = (reason: unknown): Error =>\n reason instanceof Error ? reason : new Error(\"Fx.forEach defect was not an Error\", { cause: reason })\n\nconst unreachableType = (): never => {\n throw new Error(\"Unreachable: Fx type marker should never execute at runtime\")\n}\n\nconst typeMarker = <A>(): (() => A) => unreachableType\n\nconst runMappedFx = async <B, E, R>(\n fx: RunnableFx<B, E, R>,\n signal: AbortSignal,\n requestService: (yielded: FxYield<E, R>, signal: AbortSignal) => Promise<unknown>,\n): Promise<B> => {\n if (fx._tag === \"AsyncFx\") {\n const gen = fx[Symbol.asyncIterator]()\n let result = await gen.next()\n\n while (result.done !== true) {\n if (signal.aborted) {\n throw queueTaskAbortedError(signal)\n }\n\n const yielded = result.value\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest !== undefined) {\n const injected = await requestService(yielded, signal)\n result = await gen.next(injected)\n continue\n }\n\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- failure channel values come from generic E at runtime.\n throw new TypedFailure<E>(toFailureValue(yielded) as E)\n }\n\n return result.value\n }\n\n const gen = fx[Symbol.iterator]()\n let result = gen.next()\n\n while (result.done !== true) {\n if (signal.aborted) {\n throw queueTaskAbortedError(signal)\n }\n\n const yielded = result.value\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest !== undefined) {\n const injected = await requestService(yielded, signal)\n result = gen.next(injected)\n continue\n }\n\n // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- failure channel values come from generic E at runtime.\n throw new TypedFailure<E>(toFailureValue(yielded) as E)\n }\n\n return result.value\n}\n\nconst fxForEach = dual(\n (args) => isIterable(args[0]) && typeof args[1] === \"function\",\n <A, B, E, R>(\n self: Iterable<A>,\n f: (a: A, i: number) => RunnableFx<B, E, R>,\n options?: FxForEachOptions<boolean>,\n ): AsyncFx<Array<B> | void, E, R> => {\n const items = [...self]\n const discard = options?.discard === true\n\n const program: AsyncFx<Array<B> | void, E, R> = {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: typeMarker<Array<B> | void>(),\n _E: typeMarker<E>(),\n _R: typeMarker<R>(),\n },\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<E, R>, Array<B> | void, unknown> {\n if (items.length === 0) {\n return discard ? undefined : []\n }\n\n const queue = makeQueue({ concurrency: options?.concurrency ?? \"unbounded\" })\n const results: Array<B> | undefined = discard ? undefined : []\n\n let remaining = items.length\n let firstFailure: E | undefined\n let firstDefect: Error | undefined\n let queueAborted = false\n\n const serviceRequests: ServiceRequestEntry<E, R>[] = []\n const eventWaiters = new Set<() => void>()\n\n const notifyEvent = () => {\n for (const resolve of eventWaiters) {\n resolve()\n }\n eventWaiters.clear()\n }\n\n const waitForEvent = () =>\n new Promise<void>((resolve) => {\n eventWaiters.add(resolve)\n })\n\n const requestService = (yielded: FxYield<E, R>, signal: AbortSignal): Promise<unknown> => {\n if (signal.aborted) {\n return Promise.reject(queueTaskAbortedError(signal))\n }\n\n return new Promise<unknown>((resolve, reject) => {\n const entry: ServiceRequestEntry<E, R> = {\n yielded,\n signal,\n resolve: (value) => {\n signal.removeEventListener(\"abort\", onAbort)\n resolve(value)\n },\n reject: (reason) => {\n signal.removeEventListener(\"abort\", onAbort)\n reject(reason)\n },\n }\n\n const onAbort = () => {\n const index = serviceRequests.indexOf(entry)\n if (index !== -1) {\n serviceRequests.splice(index, 1)\n }\n reject(queueTaskAbortedError(signal))\n }\n\n signal.addEventListener(\"abort\", onAbort, { once: true })\n serviceRequests.push(entry)\n notifyEvent()\n })\n }\n\n const rejectPendingServiceRequests = (reason: Error) => {\n const pending = serviceRequests.splice(0)\n for (const request of pending) {\n request.reject(reason)\n }\n }\n\n const abortQueue = (reason: unknown) => {\n if (queueAborted) {\n return\n }\n\n queueAborted = true\n void queue.shutdown({ mode: \"abort\", reason }).catch(() => {\n // no-op: fail-fast cleanup should never interrupt parent error handling\n })\n }\n\n const onTaskFailure = (error: unknown) => {\n if (isTypedFailure<E>(error)) {\n if (firstFailure === undefined && firstDefect === undefined) {\n firstFailure = error.error\n abortQueue(error.error)\n }\n return\n }\n\n if (\n (error instanceof QueueAbortedError ||\n error instanceof QueueTaskAbortedError ||\n error instanceof QueueClosedError) &&\n (firstFailure !== undefined || firstDefect !== undefined)\n ) {\n return\n }\n\n if (firstDefect === undefined && firstFailure === undefined) {\n const defect = toError(error)\n firstDefect = defect\n abortQueue(defect)\n }\n }\n\n const onTaskSettled = () => {\n remaining -= 1\n notifyEvent()\n }\n\n for (const [index, item] of items.entries()) {\n void queue\n .enqueue(async ({ signal }) => {\n const value = await runMappedFx(f(item, index), signal, requestService)\n if (results !== undefined) {\n results[index] = value\n }\n })\n .catch(onTaskFailure)\n .finally(onTaskSettled)\n }\n\n while (true) {\n if (firstDefect !== undefined) {\n rejectPendingServiceRequests(firstDefect)\n throw new Error(\"Fx.forEach defect\", { cause: firstDefect })\n }\n\n if (firstFailure !== undefined) {\n rejectPendingServiceRequests(new QueueAbortedError({ reason: firstFailure }))\n yield firstFailure\n throw new Error(\"Unreachable: Fx runtime short-circuits on first failure\")\n }\n\n const request = serviceRequests.shift()\n if (request !== undefined) {\n if (request.signal.aborted) {\n request.reject(queueTaskAbortedError(request.signal))\n continue\n }\n\n try {\n const injected = yield request.yielded\n request.resolve(injected)\n } catch (error) {\n request.reject(toError(error))\n }\n continue\n }\n\n if (remaining === 0) {\n break\n }\n\n await waitForEvent()\n }\n\n return discard ? undefined : results\n },\n }\n\n return program\n },\n) as FxForEach\n\nexport { fxForEach as forEach }\n\n/* oxlint-enable no-await-in-loop */\n","/**\n * Lightweight effect runtime with typed success, error, and requirement channels.\n *\n * **Mental model**\n * - `Fx<A, E, R>` models computations that may fail and require services.\n * - Build with `Fx.gen`, run with `Fx.run`, and compose with `Layer`/`Provide`.\n *\n * **Common tasks**\n * - Create workflows with `Fx.gen`.\n * - Execute with `Fx.run` or `Fx.fn`.\n * - Retry with `Fx.retry` and match outcomes with `Fx.match`.\n *\n * **Gotchas**\n * - Dependencies (`R`) must be provided before execution.\n * - `Fx.run` returns `Exit`, not raw values.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const program = Fx.gen(function* () {\n * const value = yield* Fx.ok(2)\n * return value + 1\n * })\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: 3 }\n * ```\n *\n * @module\n */\nimport { fromNullable as optionFromNullable } from \"../option/option\"\nimport { ok as resultOk, err as resultErr, fromTry as resultTry } from \"../result/result\"\nimport type { RetrySchedule, SyncRetrySchedule } from \"../schedule/schedule\"\nimport { asServiceRequest } from \"../service/service-resolution\"\nimport { dual } from \"../shared/dual\"\nimport type { Exit as ExitType } from \"./exit\"\nimport { forEach as fxForEach } from \"./foreach\"\nimport { runSync, runAsync } from \"./fx.runtime\"\nimport { FxTypeId } from \"./fx.types\"\nimport type { RunnableFx, SyncFx, AsyncFx, FxYield, Fx as FxProtocol, FxGenerator, AsyncFxGenerator } from \"./fx.types\"\nexport {\n /**\n * `Exit` utilities namespace for `Fx.run` outcomes.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const exit = Fx.Exit.ok(1)\n * // => { _tag: \"Ok\", value: 1 }\n * ```\n *\n */\n Exit,\n} from \"./exit\"\nexport {\n /**\n * Type guard for Fx service requests.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const request = { _tag: \"ServiceRequest\", serviceKey: \"Logger\" } as Fx.ServiceRequest<unknown>\n * const isRequest = Fx.isServiceRequest(request)\n * // => true\n * ```\n *\n */\n isServiceRequest,\n} from \"./fx.types\"\nexport {\n /**\n * Runtime unique symbol identifying Fx values.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const marker = { [Fx.FxTypeId]: true }\n * // => Object.getOwnPropertySymbols(marker).includes(Fx.FxTypeId)\n * ```\n *\n */\n FxTypeId,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported core Fx protocol type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.Fx<unknown, unknown, unknown>\n * ```\n *\n */\n type Fx,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported synchronous Fx type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.SyncFx<unknown, unknown, unknown>\n * ```\n *\n */\n type SyncFx,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported asynchronous Fx type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.AsyncFx<unknown, unknown, unknown>\n * ```\n *\n */\n type AsyncFx,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported runnable Fx union type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.RunnableFx<unknown, unknown, unknown>\n * ```\n *\n */\n type RunnableFx,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported service-request protocol type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.ServiceRequest<unknown>\n * ```\n *\n */\n type ServiceRequest,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported helper extracting Fx success type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.FxValue<Fx.SyncFx<number>>\n * ```\n *\n */\n type FxValue,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported helper extracting Fx error type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.FxError<Fx.SyncFx<number, string>>\n * ```\n *\n */\n type FxError,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported helper extracting Fx requirements type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.FxRequirements<Fx.SyncFx<number, never, { readonly svc: unknown }>>\n * ```\n *\n */\n type FxRequirements,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported generator yield union for Fx internals.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.FxYield<unknown, unknown>\n * ```\n *\n */\n type FxYield,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported sync generator signature used by `Fx.gen`.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.FxGenerator<unknown, unknown, unknown>\n * ```\n *\n */\n type FxGenerator,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported async generator signature used by `Fx.gen`.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.AsyncFxGenerator<unknown, unknown, unknown>\n * ```\n *\n */\n type AsyncFxGenerator,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported sync Fx yieldable protocol type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.FxYieldable<unknown, unknown, unknown>\n * ```\n *\n */\n type FxYieldable,\n} from \"./fx.types\"\nexport {\n /**\n * Re-exported async Fx yieldable protocol type.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = Fx.AsyncFxYieldable<unknown, unknown, unknown>\n * ```\n *\n */\n type AsyncFxYieldable,\n} from \"./fx.types\"\n\n/* oxlint-disable no-unsafe-type-assertion, no-unsafe-assignment, no-unsafe-call, no-unsafe-member-access, no-unsafe-return, no-unsafe-argument, no-unnecessary-type-assertion -- Fx runtime adapters intentionally traverse erased generator channels and rehydrate typed effects through controlled dynamic boundaries. */\n\n// ============================================================================\n// Fx.run - Execute computations\n// ============================================================================\n\n/**\n * Execute a sync Fx computation and return the Exit.\n * Catches unexpected thrown exceptions and wraps them as Defect.\n * Only available when R = never (all dependencies provided).\n *\n * @param fx - The sync computation to execute\n * @returns Exit<A, E>\n */\nfunction fxRun<A, E>(fx: SyncFx<A, E>): ExitType<A, E>\n\n/**\n * Execute an async Fx computation and return a Promise of the Exit.\n * Catches unexpected thrown exceptions and wraps them as Defect.\n * Only available when R = never (all dependencies provided).\n *\n * @param fx - The async computation to execute\n * @returns Promise<Exit<A, E>>\n */\nfunction fxRun<A, E>(fx: AsyncFx<A, E>): Promise<ExitType<A, E>>\n\n/**\n * Execute an Fx computation (union type).\n * Returns Exit for sync, Promise<Exit> for async.\n * Catches unexpected thrown exceptions and wraps them as Defect.\n */\nfunction fxRun<A, E>(fx: RunnableFx<A, E>): ExitType<A, E> | Promise<ExitType<A, E>>\n\n/**\n * Implementation of Fx.run.\n * Detects sync vs async and executes appropriately.\n */\nfunction fxRun<A, E>(fx: RunnableFx<A, E>): ExitType<A, E> | Promise<ExitType<A, E>> {\n if (fx._tag === \"AsyncFx\") {\n return runAsync(fx)\n }\n return runSync(fx)\n}\n\n// ============================================================================\n// Fx.retry - Retry failed computations\n// ============================================================================\n\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, ms)\n })\n\nconst sleepIfNeeded = async (ms: number): Promise<void> => {\n if (ms <= 0) {\n return\n }\n await sleep(ms)\n}\n\nconst closeSyncAttempt = (gen: Generator<unknown, unknown, unknown>) => {\n if (typeof gen.return === \"function\") {\n gen.return(undefined)\n }\n}\n\nconst closeAsyncAttempt = async (\n gen: Generator<unknown, unknown, unknown> | AsyncGenerator<unknown, unknown, unknown>,\n) => {\n if (typeof gen.return === \"function\") {\n await gen.return(undefined)\n }\n}\n\nconst makeSyncRetryFx = <A, E, R>(fx: SyncFx<A, E, R>, schedule: SyncRetrySchedule): SyncFx<A, E, R> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as A,\n _E: () => undefined as unknown as E,\n _R: () => undefined as unknown as R,\n },\n *[Symbol.iterator](): Generator<FxYield<E, R>, A, unknown> {\n let retryAttempt = 0\n attemptLoop: while (true) {\n const gen = fx[Symbol.iterator]()\n let result = gen.next()\n\n while (result.done !== true) {\n const yielded = result.value\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest !== undefined) {\n const injected = yield yielded as FxYield<E, R>\n result = gen.next(injected)\n continue\n }\n\n retryAttempt += 1\n if (retryAttempt <= schedule.maxRetries) {\n closeSyncAttempt(gen)\n continue attemptLoop\n }\n\n // Forward the terminal typed failure to the outer runtime.\n yield yielded as FxYield<E, R>\n return undefined as never\n }\n\n return result.value\n }\n },\n})\n\n/* oxlint-disable no-await-in-loop -- retry execution is intentionally sequential across attempts and iterator steps. */\nconst makeAsyncRetryFx = <A, E, R>(fx: RunnableFx<A, E, R>, schedule: RetrySchedule): AsyncFx<A, E, R> => ({\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as A,\n _E: () => undefined as unknown as E,\n _R: () => undefined as unknown as R,\n },\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<E, R>, A, unknown> {\n let retryAttempt = 0\n\n attemptLoop: while (true) {\n if (fx._tag === \"AsyncFx\") {\n const gen = fx[Symbol.asyncIterator]()\n // Sequential async iterator protocol: each step depends on the previous one.\n let result = await gen.next()\n\n while (result.done !== true) {\n const yielded = result.value\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest !== undefined) {\n const injected = yield yielded as FxYield<E, R>\n // oxlint-disable-next-line no-await-in-loop\n result = await gen.next(injected)\n continue\n }\n\n retryAttempt += 1\n if (retryAttempt <= schedule.maxRetries) {\n const delayMs = schedule.delayForAttempt(retryAttempt)\n await sleepIfNeeded(delayMs)\n await closeAsyncAttempt(gen)\n continue attemptLoop\n }\n\n // Forward the terminal typed failure to the outer runtime.\n yield yielded as FxYield<E, R>\n return undefined as never\n }\n\n return result.value\n }\n\n const gen = fx[Symbol.iterator]()\n let result = gen.next()\n\n while (result.done !== true) {\n const yielded = result.value\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest !== undefined) {\n const injected = yield yielded as FxYield<E, R>\n result = gen.next(injected)\n continue\n }\n\n retryAttempt += 1\n if (retryAttempt <= schedule.maxRetries) {\n const delayMs = schedule.delayForAttempt(retryAttempt)\n await sleepIfNeeded(delayMs)\n await closeAsyncAttempt(gen)\n continue attemptLoop\n }\n\n // Forward the terminal typed failure to the outer runtime.\n yield yielded as FxYield<E, R>\n return undefined as never\n }\n\n return result.value\n }\n },\n})\n/* oxlint-enable no-await-in-loop */\n\n/**\n * Retry a computation according to the given schedule.\n *\n * Retries only typed failures (Err channel). Defects are not retried.\n */\ntype RetryResult<Fx extends RunnableFx<unknown, unknown, unknown>, S extends RetrySchedule> =\n Fx extends AsyncFx<infer A, infer E, infer R>\n ? AsyncFx<A, E, R>\n : S extends SyncRetrySchedule\n ? Fx extends SyncFx<infer A, infer E, infer R>\n ? SyncFx<A, E, R>\n : never\n : Fx extends SyncFx<infer A, infer E, infer R>\n ? AsyncFx<A, E, R>\n : never\n\nconst fxRetry: {\n <Fx extends RunnableFx<unknown, unknown, unknown>, S extends RetrySchedule>(fx: Fx, schedule: S): RetryResult<Fx, S>\n <S extends RetrySchedule>(\n schedule: S,\n ): <Fx extends RunnableFx<unknown, unknown, unknown>>(fx: Fx) => RetryResult<Fx, S>\n} = dual(\n 2,\n <Fx extends RunnableFx<unknown, unknown, unknown>, S extends RetrySchedule>(\n fx: Fx,\n schedule: S,\n ): RetryResult<Fx, S> => {\n if (fx._tag === \"AsyncFx\" || !schedule._sync) {\n return makeAsyncRetryFx(fx, schedule) as RetryResult<Fx, S>\n }\n return makeSyncRetryFx(fx as SyncFx<unknown, unknown, unknown>, schedule as SyncRetrySchedule) as RetryResult<Fx, S>\n },\n)\n\n// ============================================================================\n// Fx.gen - Create composable computations\n// ============================================================================\n\ntype FxGenError<Yielded> = Yielded extends FxProtocol<unknown, infer E, unknown> ? E : Yielded\ntype FxGenRequirements<Yielded> = Yielded extends FxProtocol<unknown, unknown, infer R> ? R : never\n\n/**\n * Create a composable computation from a sync generator function.\n * Returns a SyncFx that can be stored, passed around, and executed later.\n *\n * @template Yielded - The type of values yielded by the generator\n * @template A - The success value type\n * @param generatorFn - A function that returns a sync generator\n * @returns SyncFx<A, FxGenError<Yielded>, FxGenRequirements<Yielded>>\n *\n * @example\n * ```ts\n * import { Fx, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n * const readPort = Fx.gen(function* () {\n * return yield* Port\n * })\n * const exit = Fx.run(Provide.service(Port, 3000)(readPort))\n * // => { _tag: \"Ok\", value: 3000 }\n * ```\n */\nfunction fxGen<Yielded, A>(\n generatorFn: () => Generator<Yielded, A, unknown>,\n): SyncFx<A, FxGenError<Yielded>, FxGenRequirements<Yielded>>\n\n/**\n * Create a composable computation from an async generator function.\n * Returns an AsyncFx that can be stored, passed around, and executed later.\n *\n * @template Yielded - The type of values yielded by the generator\n * @template A - The success value type\n * @param generatorFn - A function that returns an async generator\n * @returns AsyncFx<A, FxGenError<Yielded>, FxGenRequirements<Yielded>>\n *\n * @example\n * ```ts\n * import { Fx, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Token = Service.tag<string>(\"Token\")\n * const readToken = Fx.gen(async function* () {\n * const token = yield* Token\n * const suffix = await Promise.resolve(\"-ok\")\n * return `${token}${suffix}`\n * })\n * const exit = await Fx.run(Provide.service(Token, \"abc\")(readToken))\n * // => { _tag: \"Ok\", value: \"abc-ok\" }\n * ```\n */\nfunction fxGen<Yielded, A>(\n generatorFn: () => AsyncGenerator<Yielded, A, unknown>,\n): AsyncFx<A, FxGenError<Yielded>, FxGenRequirements<Yielded>>\n\n/**\n * Create a composable computation from a sync generator function that takes parameters.\n * Returns a factory function that, when called with parameters, produces a SyncFx.\n *\n * @template P - The parameter types (must be non-empty)\n * @template Yielded - The type of values yielded by the generator\n * @template A - The success value type\n * @param generatorFn - A function that takes parameters and returns a sync generator\n * @returns A factory function that produces SyncFx<A, FxGenError<Yielded>, FxGenRequirements<Yielded>>\n *\n * @example\n * ```ts\n * import { Fx, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n * const describePort = Fx.gen(function* (label: string) {\n * const port = yield* Port\n * return `${label}:${port}`\n * })\n * const exit = Fx.run(Provide.service(Port, 3000)(describePort(\"port\")))\n * // => { _tag: \"Ok\", value: \"port:3000\" }\n * ```\n */\nfunction fxGen<P extends [unknown, ...unknown[]], Yielded, A>(\n generatorFn: (...params: P) => Generator<Yielded, A, unknown>,\n): (...params: P) => SyncFx<A, FxGenError<Yielded>, FxGenRequirements<Yielded>>\n\n/**\n * Create a composable computation from an async generator function that takes parameters.\n * Returns a factory function that, when called with parameters, produces an AsyncFx.\n *\n * @template P - The parameter types (must be non-empty)\n * @template Yielded - The type of values yielded by the generator\n * @template A - The success value type\n * @param generatorFn - A function that takes parameters and returns an async generator\n * @returns A factory function that produces AsyncFx<A, FxGenError<Yielded>, FxGenRequirements<Yielded>>\n *\n * @example\n * ```ts\n * import { Fx, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Token = Service.tag<string>(\"Token\")\n * const describeToken = Fx.gen(async function* (prefix: string) {\n * const token = yield* Token\n * const suffix = await Promise.resolve(\"!\")\n * return `${prefix}:${token}${suffix}`\n * })\n * const exit = await Fx.run(Provide.service(Token, \"abc\")(describeToken(\"token\")))\n * // => { _tag: \"Ok\", value: \"token:abc!\" }\n * ```\n */\nfunction fxGen<P extends [unknown, ...unknown[]], Yielded, A>(\n generatorFn: (...params: P) => AsyncGenerator<Yielded, A, unknown>,\n): (...params: P) => AsyncFx<A, FxGenError<Yielded>, FxGenRequirements<Yielded>>\n\n/**\n * Implementation of unified Fx.gen function.\n * Detects sync vs async generator and returns appropriate computation type.\n * For parameterized generators (length > 0), returns a factory function.\n */\n// oxlint-disable-next-line no-explicit-any\nfunction fxGen(generatorFn: (...args: any[]) => any): any {\n if (generatorFn.length > 0) {\n return (...params: unknown[]) => fxGen(() => generatorFn(...params))\n }\n\n // Check if we're dealing with async generator\n const testGen = generatorFn()\n const isAsync = Symbol.asyncIterator in testGen\n\n if (isAsync) {\n return {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined,\n _E: () => undefined,\n _R: () => undefined,\n },\n // oxlint-disable-next-line no-explicit-any\n async *[Symbol.asyncIterator](): AsyncGenerator<any, any, unknown> {\n const gen = generatorFn()\n let result = await gen.next()\n\n while (result.done !== true) {\n // Pass through yields (errors or services as Fx values)\n const injected = yield result.value\n // oxlint-disable-next-line no-await-in-loop\n result = await gen.next(injected)\n }\n\n return result.value\n },\n }\n }\n\n // Sync generator\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined,\n _E: () => undefined,\n _R: () => undefined,\n },\n // oxlint-disable-next-line no-explicit-any\n *[Symbol.iterator](): Generator<any, any, unknown> {\n const gen = generatorFn()\n let result = gen.next()\n\n while (result.done !== true) {\n const injected = yield result.value\n result = gen.next(injected)\n }\n\n return result.value\n },\n }\n}\n\n// ============================================================================\n// Fx.fn - Execute computations immediately\n// ============================================================================\n\ntype FxRunResult<F extends RunnableFx<unknown, unknown, unknown>> =\n F extends AsyncFx<infer A, infer E, unknown>\n ? Promise<ExitType<A, E>>\n : F extends SyncFx<infer A, infer E, unknown>\n ? ExitType<A, E>\n : never\n\n/**\n * Execute a sync computation immediately and return the Exit.\n * Catches unexpected thrown exceptions and wraps them as Defect.\n * For computations without service dependencies.\n *\n * @template A - The success value type\n * @template E - The error type\n * @param generatorFn - A function that returns a sync generator\n * @returns Exit<A, E>\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const exit = Fx.fn(function* () {\n * const a = yield* Fx.ok(10)\n * const b = yield* Fx.ok(20)\n * return a + b\n * })\n * // => { _tag: \"Ok\", value: 30 }\n * ```\n */\nfunction fxFn<A, E>(generatorFn: () => FxGenerator<A, E, never>): ExitType<A, E>\n\n/**\n * Execute an async computation immediately and return a Promise of the Exit.\n * Catches unexpected thrown exceptions and wraps them as Defect.\n * For computations without service dependencies.\n *\n * @template A - The success value type\n * @template E - The error type\n * @param generatorFn - A function that returns an async generator\n * @returns Promise<Exit<A, E>>\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const exit = await Fx.fn(async function* () {\n * const value = await Promise.resolve(2)\n * return value + 1\n * })\n * // => { _tag: \"Ok\", value: 3 }\n * ```\n */\nfunction fxFn<A, E>(generatorFn: () => AsyncFxGenerator<A, E, never>): Promise<ExitType<A, E>>\n\n/**\n * Execute a sync computation with service dependencies immediately.\n * Catches unexpected thrown exceptions and wraps them as Defect.\n * The second argument is required when the computation has service requirements (R ≠ never).\n *\n * @template A - The success value type\n * @template E - The error type from the computation\n * @template R - The required services type\n * @param generatorFn - A function that returns a sync generator with service requirements\n * @param provider - A function that provides the services (e.g., Provide.layer(AppLayer))\n * @returns Exit result from running the provided Fx (sync or async depending on provider output)\n *\n * @example\n * ```ts\n * import { Fx, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Port = Service.tag<number>(\"Port\")\n *\n * const exit = Fx.fn(function* () {\n * const port = yield* Port\n * return port + 1\n * }, Provide.service(Port, 3000))\n * // => { _tag: \"Ok\", value: 3001 }\n * ```\n */\nfunction fxFn<A, E, R, ProvidedFx extends RunnableFx<unknown, unknown, unknown>>(\n generatorFn: () => FxGenerator<A, E, R>,\n provider: (fx: SyncFx<A, E, R>) => ProvidedFx,\n): FxRunResult<ProvidedFx>\n\n/**\n * Execute an async computation with service dependencies immediately.\n * Catches unexpected thrown exceptions and wraps them as Defect.\n * The second argument is required when the computation has service requirements (R ≠ never).\n *\n * @template A - The success value type\n * @template E - The error type from the computation\n * @template R - The required services type\n * @param generatorFn - A function that returns an async generator with service requirements\n * @param provider - A function that provides the services (e.g., Provide.layer(AppLayer))\n * @returns Exit result from running the provided Fx (sync or async depending on provider output)\n *\n * @example\n * ```ts\n * import { Fx, Provide, Service } from \"@nicolastoulemont/std\"\n *\n * const Token = Service.tag<string>(\"Token\")\n *\n * const exit = await Fx.fn(async function* () {\n * const token = yield* Token\n * const suffix = await Promise.resolve(\"!\")\n * return `${token}${suffix}`\n * }, Provide.service(Token, \"abc\"))\n * // => { _tag: \"Ok\", value: \"abc!\" }\n * ```\n */\nfunction fxFn<A, E, R, ProvidedFx extends RunnableFx<unknown, unknown, unknown>>(\n generatorFn: () => AsyncFxGenerator<A, E, R>,\n provider: (fx: AsyncFx<A, E, R>) => ProvidedFx,\n): FxRunResult<ProvidedFx>\n\n/**\n * Implementation of Fx.fn.\n * Reuses fxGen() for Fx creation and fxRun() for execution to ensure consistent behavior.\n */\nfunction fxFn<A, E, E2, R>(\n generatorFn: () => FxGenerator<A, E, R> | AsyncFxGenerator<A, E, R>,\n provider?: ((fx: SyncFx<A, E, R>) => RunnableFx<A, E | E2>) | ((fx: AsyncFx<A, E, R>) => RunnableFx<A, E | E2>),\n): ExitType<A, E | E2> | Promise<ExitType<A, E | E2>> {\n // Create the Fx using fxGen (single source of truth for Fx creation)\n // Type cast needed because fxGen infers E/R from yielded Fx values,\n // while fxFn receives E/R as explicit type parameters\n // oxlint-disable-next-line no-explicit-any\n const fx = fxGen(generatorFn as any) as RunnableFx<A, E, R>\n\n if (provider) {\n // Apply provider and run\n const provided =\n fx._tag === \"AsyncFx\"\n ? (provider as (fx: AsyncFx<A, E, R>) => RunnableFx<A, E | E2>)(fx)\n : (provider as (fx: SyncFx<A, E, R>) => RunnableFx<A, E | E2>)(fx)\n return fxRun(provided as RunnableFx<A, E | E2>) as ExitType<A, E | E2> | Promise<ExitType<A, E | E2>>\n }\n\n // No provider - run directly (R must be never at the type level)\n return fxRun(fx as RunnableFx<A, E | E2>) as ExitType<A, E | E2> | Promise<ExitType<A, E | E2>>\n}\n\n// ============================================================================\n// Fx.ok / Fx.err / Fx.option - Convenience aliases\n// ============================================================================\n\n/**\n * Convenience alias for Result.ok.\n * Creates a successful Result that can be yielded in an Fx computation.\n *\n * @param value - The success value\n * @returns Result<T, never>\n *\n * @example\n * ```ts\n * const workflow = Fx.gen(function* () {\n * const value = yield* Fx.ok(42)\n * return value * 2\n * })\n * ```\n */\nconst fxOk = resultOk\n\n/**\n * Convenience alias for Result.err.\n * Creates an error Result that can be yielded in an Fx computation.\n *\n * @param error - The error value\n * @returns Result<never, E>\n *\n * @example\n * ```ts\n * const workflow = Fx.gen(function* () {\n * const config = yield* Config\n *\n * if (!config.dbUrl) {\n * return yield* Fx.err(new ValidationError({ field: \"dbUrl\" }))\n * }\n *\n * return config.dbUrl\n * })\n * ```\n */\nconst fxErr = resultErr\n\n/**\n * Convenience alias for Result.try.\n * Creates a Result that can be yielded in an Fx computation.\n *\n * @param fn - A function that returns a value or throws an error\n * @returns Result<T, E>\n *\n * @example\n * ```ts\n * const result = Fx.try(() => {\n * return 42\n * })\n *\n * const workflow = Fx.gen(function* () {\n * const result = yield* Fx.try(() => {\n * return 42\n * })\n * return result\n * })\n * ```\n */\nconst fxTry = resultTry\n\n/**\n * Convenience alias for Option.fromNullable.\n * Converts nullable values into an Option that can be yielded in an Fx computation.\n *\n * @param value - A possibly nullish value\n * @returns Option<NonNullable<T>>\n *\n * @example\n * ```ts\n * const workflow = Fx.gen(function* () {\n * const apiKey = yield* Fx.option(request.headers[\"x-api-key\"])\n * return apiKey\n * })\n * ```\n */\nconst fxOption = optionFromNullable\n\n// ============================================================================\n// Fx.match - Universal pattern matching\n// ============================================================================\n\n/**\n * Handler functions for matching on a tagged union by `_tag` discriminator.\n * Each handler receives the narrowed variant corresponding to its tag key.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Fx\n * ```\n */\nexport type TaggedMatch<T extends { readonly _tag: string }, R> = {\n readonly [K in T[\"_tag\"]]: (variant: Extract<T, { readonly _tag: K }>) => R\n}\n\n/**\n * Generic pattern matcher for any `_tag`-based discriminated union.\n *\n * Works with Exit, tagged errors, or any type with a `readonly _tag` discriminator.\n * Each handler receives the full narrowed variant object for its tag.\n *\n * Supports both data-first and data-last (pipe) calling styles.\n *\n * @example\n * ```ts\n * // Match on Exit\n * Fx.match(exit, {\n * Ok: (ok) => ok.value,\n * Err: (err) =>\n * Fx.match(err.error, {\n * DatabaseError: (e) => e.message,\n * NotFoundError: (e) => e.resourceId,\n * }),\n * Defect: (d) => String(d.defect),\n * })\n *\n * // Data-last with pipe\n * pipe(exit, Fx.match({\n * Ok: (ok) => ok.value,\n * Err: (err) => \"error\",\n * Defect: (d) => \"defect\",\n * }))\n * ```\n */\nconst fxMatch: {\n <T extends { readonly _tag: string }, R>(value: T, handlers: TaggedMatch<T, R>): R\n <T extends { readonly _tag: string }, R>(handlers: TaggedMatch<T, R>): (value: T) => R\n} = dual(\n 2,\n // oxlint-disable-next-line no-explicit-any\n (value: any, handlers: any): any => handlers[value._tag](value),\n)\n\n// ============================================================================\n// Exports\n// ============================================================================\n\n/**\n * Build typed computations from generator functions.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const program = Fx.gen(function* () {\n * const value = yield* Fx.ok(2)\n * return value + 1\n * })\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: 3 }\n * ```\n */\nexport const gen = fxGen\n\n/**\n * Run a generator function immediately and return its `Exit`.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const exit = Fx.fn(function* () {\n * return yield* Fx.ok(2)\n * })\n * // => { _tag: \"Ok\", value: 2 }\n * ```\n */\nexport const fn = fxFn\n\n/**\n * Execute an existing `Fx` value and produce an `Exit`.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const exit = Fx.run(Fx.gen(function* () {\n * return 1\n * }))\n * // => { _tag: \"Ok\", value: 1 }\n * ```\n */\nexport const run = fxRun\n\n/**\n * Retry failed computations according to a schedule.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * import { Schedule } from \"@nicolastoulemont/std\"\n *\n * const retried = Fx.retry(\n * Fx.gen(function* () {\n * return yield* Fx.err(\"boom\")\n * }),\n * Schedule.recurs(2),\n * )\n * const exit = Fx.run(retried)\n * // => { _tag: \"Err\", error: \"boom\" }\n * ```\n */\nexport const retry = fxRetry\n\n/**\n * Run an effectful function for each item in a collection.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const fx = Fx.forEach([1, 2, 3], (n) => Fx.gen(function* () {\n * return n * 2\n * }))\n * // => AsyncFx<readonly number[], ...>\n * ```\n */\nexport const forEach = fxForEach\n\n/**\n * Alias for `Result.ok` in `Fx` namespace.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const value = Fx.ok(42)\n * // => { _tag: \"Ok\", value: 42 }\n * ```\n */\nexport const ok = fxOk\n\n/**\n * Alias for `Result.err` in `Fx` namespace.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const value = Fx.err(\"boom\")\n * // => { _tag: \"Err\", error: \"boom\" }\n * ```\n */\nexport const err = fxErr\n\n/**\n * Alias for `Option.fromNullable` in `Fx` namespace.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const value = Fx.option(\"token\")\n * // => { _tag: \"Some\", value: \"token\" }\n * ```\n */\nexport const option = fxOption\n\nconst try_ = fxTry\n\nexport {\n /**\n * Alias for `Result.fromTry` in `Fx` namespace.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const parsed = Fx.try(() => Number.parseInt(\"42\", 10))\n * // => { _tag: \"Ok\", value: 42 }\n * ```\n *\n */\n try_ as try,\n}\n\n/**\n * Pattern matching helper for tagged unions.\n *\n * @example\n * ```ts\n * import { Fx } from \"@nicolastoulemont/std\"\n *\n * const value = Fx.match({ _tag: \"Ok\", value: 2 } as const, {\n * Ok: (ok) => ok.value + 1,\n * })\n * // => 3\n * ```\n */\nexport const match = fxMatch\n\n/* oxlint-enable no-unsafe-type-assertion, no-unsafe-assignment, no-unsafe-call, no-unsafe-member-access, no-unsafe-return, no-unsafe-argument, no-unnecessary-type-assertion */\n"],"mappings":"icA8CA,IAAM,EAAN,cAA8B,KAAM,CAClC,KAAgB,eAEhB,YAAY,EAAmB,CAC7B,MAAM,eAAe,CADF,KAAA,MAAA,EAEnB,KAAK,KAAO,iBAIhB,MAAM,EAAqB,GAA6C,aAAiB,EAEnF,EAAe,GACnB,OAAO,GAAU,YAAY,GAAkB,SAAU,GAAS,EAAM,OAAS,OAAS,UAAW,EAEjG,EAAkB,GAClB,aAAmB,EACd,EAGL,EAAY,EAAQ,CACf,EAAQ,MAGV,EAGH,EAAc,GAClB,GAAU,MAEV,OAAQ,EAA0C,OAAO,WAAc,WAEnE,EAAyB,GAC7B,IAAI,EAAsB,CAAE,OAAQ,EAAO,OAAQ,CAAC,CAEhD,EAAW,GACf,aAAkB,MAAQ,EAAa,MAAM,qCAAsC,CAAE,MAAO,EAAQ,CAAC,CAEjG,MAA+B,CACn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AAO,OAEjB,CA8HH,SAAS,EACP,EACA,EACoD,CAKpD,IAAM,EAAK,EAAM,EAAmB,CAYpC,OAJS,EANL,GAGA,EAAG,KACE,EAA6D,EAAG,EAM5D,EAJoC,CA0BnD,MAAM,EAAOE,EAsBP,EAAQC,EAuBR,EAAQC,EAiBR,EAAWC,EAkDX,EAGF,EACF,GAEC,EAAY,IAAuB,EAAS,EAAM,MAAM,EAAM,CAChE,CAqBY,EAAM,EAeN,EAAK,EAeL,EAAM,EAqBN,EAAQ,EAeR,EAAU,EAaV,EAAK,EAaL,EAAM,EAaN,EAAS,EAEhB,EAAO,EA+BA,EAAQ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./dual-
|
|
2
|
-
//# sourceMappingURL=fx.runtime-
|
|
1
|
+
import{t as e}from"./dual-fN6OUwN_.mjs";import{t}from"./option.types-CbY_swma.mjs";import{t as n}from"./service-resolution-BefYr4nR.mjs";const r=e=>({_tag:`Ok`,value:e}),i=e=>({_tag:`Err`,error:e}),a=e=>({_tag:`Defect`,defect:e}),o={ok:r,err:i,defect:a,isOk:e=>e._tag===`Ok`,isErr:e=>e._tag===`Err`,isDefect:e=>e._tag===`Defect`,match:e(2,(e,t)=>{switch(e._tag){case`Ok`:return t.Ok(e.value);case`Err`:return t.Err(e.error);case`Defect`:return t.Defect(e.defect)}}),getOrThrow:e=>{switch(e._tag){case`Ok`:return e.value;case`Err`:throw e.error;case`Defect`:throw e.defect}}};function s(e){try{let o=e[Symbol.iterator]().next();if(o.done!==!0){let e=o.value,r=n(e);return r===void 0?e instanceof t?i(e):typeof e==`object`&&e&&`_tag`in e&&e._tag===`Err`?i(e.error):i(e):a(Error(`Service "${r.key}" not provided. Use Provide.layer() to inject services.`))}return r(o.value)}catch(e){return a(e)}}async function c(e){try{let o=await e[Symbol.asyncIterator]().next();if(o.done!==!0){let e=o.value,r=n(e);return r===void 0?e instanceof t?i(e):typeof e==`object`&&e&&`_tag`in e&&e._tag===`Err`?i(e.error):i(e):a(Error(`Service "${r.key}" not provided. Use Provide.layer() to inject services.`))}return r(o.value)}catch(e){return a(e)}}export{s as n,o as r,c as t};
|
|
2
|
+
//# sourceMappingURL=fx.runtime-jQxh77s3.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fx.runtime-
|
|
1
|
+
{"version":3,"file":"fx.runtime-jQxh77s3.mjs","names":["exitDefect","exitErr","exitOk"],"sources":["../src/fx/exit.ts","../src/fx/fx.runtime.ts"],"sourcesContent":["import { dual } from \"../shared/dual\"\nimport type { Err, Ok } from \"../shared/type-utils.types\"\n\n// ============================================================================\n// Exit Types - Flat 3-variant discriminated union\n// ============================================================================\n\n/**\n * Represents an unexpected thrown exception (defect) caught during Fx execution.\n */\ntype Defect = {\n readonly _tag: \"Defect\"\n readonly defect: unknown\n}\n\n/**\n * Exit represents the outcome of an Fx computation.\n * A flat 3-variant discriminated union that cleanly separates:\n * - `Ok<A>`: successful result with value of type A\n * - `Err<E>`: typed failure with error of type E\n * - `Defect`: unexpected thrown exception (defect)\n *\n * @example\n * ```ts\n * const exit = Fx.run(computation)\n * switch (exit._tag) {\n * case \"Ok\": exit.value // A\n * case \"Err\": exit.error // E (clean!)\n * case \"Defect\": exit.defect // unknown\n * }\n * ```\n */\nexport type Exit<A, E> = Ok<A> | Err<E> | Defect\n\n// ============================================================================\n// Constructors\n// ============================================================================\n\n/**\n * Create a successful Exit.\n */\nexport const ok = <A>(value: A): Ok<A> => ({ _tag: \"Ok\", value })\n\n/**\n * Create a typed failure Exit.\n */\nexport const err = <E>(error: E): Err<E> => ({ _tag: \"Err\", error })\n\n/**\n * Create a defect Exit from an unexpected thrown value.\n */\nexport const defect = (thrown: unknown): Defect => ({ _tag: \"Defect\", defect: thrown })\n\n// ============================================================================\n// Guards\n// ============================================================================\n\n/**\n * Check if an Exit is a successful result.\n */\nconst isOk = <A, E>(exit: Exit<A, E>): exit is Ok<A> => exit._tag === \"Ok\"\n\n/**\n * Check if an Exit is a typed failure.\n */\nconst isErr = <A, E>(exit: Exit<A, E>): exit is Err<E> => exit._tag === \"Err\"\n\n/**\n * Check if an Exit is an unexpected defect.\n */\nconst isDefect = <A, E>(exit: Exit<A, E>): exit is Defect => exit._tag === \"Defect\"\n\n// ============================================================================\n// Match\n// ============================================================================\n\n/**\n * Handler functions for Exit.match.\n */\ntype ExitMatch<A, E, R> = {\n readonly Ok: (value: A) => R\n readonly Err: (error: E) => R\n readonly Defect: (defect: unknown) => R\n}\n\n/**\n * Pattern match on an Exit value.\n *\n * @example\n * ```ts\n * // Data-first\n * Exit.match(exit, {\n * Ok: (value) => `Success: ${value}`,\n * Err: (error) => `Error: ${error}`,\n * Defect: (defect) => `Defect: ${defect}`,\n * })\n *\n * // Data-last (pipe)\n * pipe(exit, Exit.match({\n * Ok: (value) => `Success: ${value}`,\n * Err: (error) => `Error: ${error}`,\n * Defect: (defect) => `Defect: ${defect}`,\n * }))\n * ```\n */\nconst match: {\n <A, E, R>(exit: Exit<A, E>, handlers: ExitMatch<A, E, R>): R\n <A, E, R>(handlers: ExitMatch<A, E, R>): (exit: Exit<A, E>) => R\n} = dual(2, <A, E, R>(exit: Exit<A, E>, handlers: ExitMatch<A, E, R>): R => {\n switch (exit._tag) {\n case \"Ok\":\n return handlers.Ok(exit.value)\n case \"Err\":\n return handlers.Err(exit.error)\n case \"Defect\":\n return handlers.Defect(exit.defect)\n }\n})\n\n// ============================================================================\n// Utility\n// ============================================================================\n\n/**\n * Extract the value from an Ok exit, or throw.\n * Useful for tests and scripts where you expect success.\n *\n * @throws The error for Err exits, or the defect for Defect exits\n */\nconst getOrThrow = <A, E>(exit: Exit<A, E>): A => {\n switch (exit._tag) {\n case \"Ok\":\n return exit.value\n case \"Err\":\n // oxlint-disable-next-line only-throw-error -- E is intentionally generic and may be a non-Error domain value.\n throw exit.error\n case \"Defect\":\n throw exit.defect\n }\n}\n\n// ============================================================================\n// Namespace\n// ============================================================================\n\n/**\n * Exit namespace containing all Exit utilities.\n */\nexport const Exit = {\n ok,\n err,\n defect,\n isOk,\n isErr,\n isDefect,\n match,\n getOrThrow,\n} as const\n","import { NoSuchElementError } from \"../option/option.types\"\nimport { asServiceRequest } from \"../service/service-resolution\"\nimport { ok as exitOk, err as exitErr, defect as exitDefect } from \"./exit\"\nimport type { Exit } from \"./exit\"\nimport type { AsyncFx, SyncFx } from \"./fx.types\"\n\nexport function runSync<A, E>(fx: SyncFx<A, E>): Exit<A, E> {\n try {\n const gen = fx[Symbol.iterator]()\n const result = gen.next()\n\n if (result.done !== true) {\n const yielded = result.value as unknown\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest !== undefined) {\n return exitDefect(\n new Error(`Service \"${serviceRequest.key}\" not provided. Use Provide.layer() to inject services.`),\n )\n }\n\n if (yielded instanceof NoSuchElementError) {\n return exitErr(yielded as E)\n }\n\n if (typeof yielded === \"object\" && yielded !== null && \"_tag\" in yielded && yielded._tag === \"Err\") {\n return exitErr((yielded as Record<string, unknown>)[\"error\"] as E)\n }\n\n return exitErr(yielded as E)\n }\n\n return exitOk(result.value)\n } catch (thrown) {\n return exitDefect(thrown)\n }\n}\n\nexport async function runAsync<A, E>(fx: AsyncFx<A, E>): Promise<Exit<A, E>> {\n try {\n const gen = fx[Symbol.asyncIterator]()\n const result = await gen.next()\n\n if (result.done !== true) {\n const yielded = result.value as unknown\n const serviceRequest = asServiceRequest(yielded)\n if (serviceRequest !== undefined) {\n return exitDefect(\n new Error(`Service \"${serviceRequest.key}\" not provided. Use Provide.layer() to inject services.`),\n )\n }\n\n if (yielded instanceof NoSuchElementError) {\n return exitErr(yielded as E)\n }\n\n if (typeof yielded === \"object\" && yielded !== null && \"_tag\" in yielded && yielded._tag === \"Err\") {\n return exitErr((yielded as Record<string, unknown>)[\"error\"] as E)\n }\n\n return exitErr(yielded as E)\n }\n\n return exitOk(result.value)\n } catch (thrown) {\n return exitDefect(thrown)\n }\n}\n"],"mappings":"yIAyCA,MAAa,EAAS,IAAqB,CA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B,EAAQ,CAehD,OAdI,IAAmB,IAAA,GAMnB,aAAmB,EACdC,EAAQ,EAAa,CAG1B,OAAO,GAAY,UAAY,GAAoB,SAAU,GAAW,EAAQ,OAAS,MACpFA,EAAS,EAAoC,MAAc,CAG7DA,EAAQ,EAAa,CAbnBD,EACD,MAAM,YAAY,EAAe,IAAI,yDAAyD,CACnG,CAcL,OAAOE,EAAO,EAAO,MAAM,OACpB,EAAQ,CACf,OAAOF,EAAW,EAAO"}
|
|
@@ -125,4 +125,4 @@ type AsyncFxYieldable<A, E = never, R = never> = Fx<A, E, R> & {
|
|
|
125
125
|
};
|
|
126
126
|
//#endregion
|
|
127
127
|
export { FxError as a, FxTypeId as c, FxYieldable as d, RunnableFx as f, isServiceRequest as h, Fx as i, FxValue as l, SyncFx as m, AsyncFxGenerator as n, FxGenerator as o, ServiceRequest as p, AsyncFxYieldable as r, FxRequirements as s, AsyncFx as t, FxYield as u };
|
|
128
|
-
//# sourceMappingURL=fx.types-
|
|
128
|
+
//# sourceMappingURL=fx.types-BdN1EWxr.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fx.types-
|
|
1
|
+
{"version":3,"file":"fx.types-BdN1EWxr.d.mts","names":[],"sources":["../src/fx/fx.types.ts"],"sourcesContent":[],"mappings":";;AAOA;AACA;AAUY,cAXC,QAWC,EAAA,OAAA,MAAA;AAES,KAZX,QAAA,GAYW,OAZO,QAYP;;;;;AAWvB;;;;AAGqB,KAhBT,EAgBS,CAAA,KAAA,EAAA,QAAA,KAAA,EAAA,QAAA,KAAA,CAAA,GAAA;EAAC,UAfV,QAAA,CAeU,EAAA;IAOT,SAAA,EAAA,EAAA,GACsF,GAtB5E,CAsB4E;IAKvF,SAAO,EAAA,EAAA,GAAA,GA1BI,CA0BE;IAKb,SAAO,EAAA,EAAA,GAAA,GA9BI,CA8BE;EAKb,CAAA;AAeZ,CAAA;;;;;AAA+C;AAMrB,KA/Cd,cA+Cc,CAAA,CAAA,CA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S1C;;;;EAAuC,CAAA,MAAA,CAAA,QAAA,GAAA,EAlD5B,SAkD4B,CAlDlB,OAkDkB,CAlDV,CAkDU,EAlDP,CAkDO,CAAA,EAlDH,CAkDG,EAAA,OAAA,CAAA;CACV;;;;;;AAMzC;;;AAAiE,KA9CrD,OA8CqD,CAAA,CAAA,EAAA,IAAA,KAAA,EAAA,IAAA,KAAA,CAAA,GA9ClB,EA8CkB,CA9Cf,CA8Ce,EA9CZ,CA8CY,EA9CT,CA8CS,CAAA,GAAA;EAAT,SAAA,IAAA,EAAA,SAAA;EACL;;;;EAAvB,CAAA,MAAA,CAAA,aAAA,GAAA,EAxCA,cAwCA,CAxCe,OAwCf,CAxCuB,CAwCvB,EAxC0B,CAwC1B,CAAA,EAxC8B,CAwC9B,EAAA,OAAA,CAAA;CAAc;;;;;KAjC9B,sCAAsC,OAAO,GAAG,GAAG,KAAK,QAAQ,GAAG,GAAG;;;;;KAUtE,uBAAuB,UAAU,QAAQ,GAAG,IAAI;;;;;KAMhD,4BAA4B,eAAe,QAAQ,GAAG,IAAI;;;;KAS1D,uCAAuC,GAAG,GAAG,GAAG;uBACrC,UAAU,QAAQ,GAAG,IAAI;;;;;KAMpC,4CAA4C,GAAG,GAAG,GAAG;4BACrC,eAAe,QAAQ,GAAG,IAAI"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const e=Symbol.for(`@repo/std/fx/FxTypeId`),t=e=>typeof e==`object`&&!!e&&`_tag`in e&&e._tag===`ServiceRequest`;export{t as n,e as t};
|
|
2
|
-
//# sourceMappingURL=fx.types-
|
|
2
|
+
//# sourceMappingURL=fx.types-DyQVgTS8.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fx.types-
|
|
1
|
+
{"version":3,"file":"fx.types-DyQVgTS8.mjs","names":[],"sources":["../src/fx/fx.types.ts"],"sourcesContent":["// ============================================================================\n// Service Request\n// ============================================================================\n\n/**\n * Unique symbol for Fx type identification.\n */\nexport const FxTypeId: unique symbol = Symbol.for(\"@repo/std/fx/FxTypeId\")\nexport type FxTypeId = typeof FxTypeId\n\n/**\n * Fx<A, E, R> is the base protocol for all effect types.\n * Explicitly carries type parameters for proper inference in generators.\n *\n * @template A - Success value type\n * @template E - Error type\n * @template R - Requirements type (services needed)\n */\nexport type Fx<out A, out E = never, out R = never> = {\n readonly [FxTypeId]: {\n readonly _A: () => A\n readonly _E: () => E\n readonly _R: () => R\n }\n}\n\n/**\n * ServiceRequest is yielded when accessing a service via yield*.\n * The runtime intercepts these and injects the service from context.\n * Implements Fx protocol with A=S, E=never, R=S (requires service S to produce S).\n */\nexport type ServiceRequest<S> = Fx<S, never, S> & {\n readonly _tag: \"ServiceRequest\"\n /** Phantom type for service identification */\n readonly _service: S\n readonly serviceKey: string\n}\n\n/**\n * Check if a value is a ServiceRequest.\n */\nexport const isServiceRequest = (value: unknown): value is ServiceRequest<unknown> =>\n typeof value === \"object\" && value !== null && \"_tag\" in value && value._tag === \"ServiceRequest\"\n\n/**\n * Extract the success type from an Fx.\n */\nexport type FxValue<T> = T extends Fx<infer A, unknown, unknown> ? A : never\n\n/**\n * Extract the error type from an Fx.\n */\nexport type FxError<T> = T extends Fx<unknown, infer E, unknown> ? E : never\n\n/**\n * Extract the requirements type from an Fx.\n */\nexport type FxRequirements<T> = T extends Fx<unknown, unknown, infer R> ? R : never\n\n// ============================================================================\n// Core Fx Types\n// ============================================================================\n\n/**\n * The type yielded by Fx generators at runtime.\n *\n * This union represents what flows through generator yield points:\n * - E: Error values that propagate through the computation\n * - ServiceClass<R>: Service requests that get intercepted and resolved from context\n *\n * Used for generator type annotations in Fx.gen(), Provide.layer(), and Layer implementations.\n */\nexport type FxYield<E, R> = E | ServiceClass<R>\n\n/**\n * ServiceClass type imported for FxYield.\n * This is a structural type that matches service classes.\n */\ntype ServiceClass<S> = Fx<S, never, S> & { _tag: \"Service\"; key: string }\n\n/**\n * SyncFx<A, E, R> represents a synchronous computation that:\n * - Produces a value of type A on success\n * - May fail with an error of type E\n * - Requires services of type R to run\n *\n * Use Fx.run() to execute when R = never (all dependencies provided).\n */\nexport type SyncFx<A, E = never, R = never> = Fx<A, E, R> & {\n readonly _tag: \"SyncFx\"\n\n /**\n * Iterator for yield* support in gen computations.\n * Yields error Results or ServiceClasses for service injection.\n */\n [Symbol.iterator](): Generator<FxYield<E, R>, A, unknown>\n}\n\n/**\n * AsyncFx<A, E, R> represents an asynchronous computation that:\n * - Produces a value of type A on success\n * - May fail with an error of type E\n * - Requires services of type R to run\n *\n * Use Fx.run() to execute when R = never (all dependencies provided).\n */\nexport type AsyncFx<A, E = never, R = never> = Fx<A, E, R> & {\n readonly _tag: \"AsyncFx\"\n\n /**\n * Async iterator for yield* support in async gen computations.\n * Yields error Results or ServiceClasses for service injection.\n */\n [Symbol.asyncIterator](): AsyncGenerator<FxYield<E, R>, A, unknown>\n}\n\n/**\n * RunnableFx<A, E, R> is a union of executable Fx types (sync or async).\n * Use this for functions that execute effects like Fx.run().\n */\nexport type RunnableFx<A, E = never, R = never> = SyncFx<A, E, R> | AsyncFx<A, E, R>\n\n// ============================================================================\n// Generator Types for Fx\n// ============================================================================\n\n/**\n * Sync generator type for Fx.gen.\n * Yields error Results or ServiceClasses, returns value of type A.\n */\nexport type FxGenerator<A, E, R> = Generator<FxYield<E, R>, A, unknown>\n\n/**\n * Async generator type for Fx.gen.\n * Yields error Results or ServiceClasses, returns value of type A.\n */\nexport type AsyncFxGenerator<A, E, R> = AsyncGenerator<FxYield<E, R>, A, unknown>\n\n// ============================================================================\n// Yieldable Types (for compatibility with existing gen module)\n// ============================================================================\n\n/**\n * FxYieldable extends the existing Yieldable protocol to support Fx values.\n */\nexport type FxYieldable<A, E = never, R = never> = Fx<A, E, R> & {\n [Symbol.iterator](): Generator<FxYield<E, R>, A, unknown>\n}\n\n/**\n * AsyncFxYieldable for async computations with Fx values.\n */\nexport type AsyncFxYieldable<A, E = never, R = never> = Fx<A, E, R> & {\n [Symbol.asyncIterator](): AsyncGenerator<FxYield<E, R>, A, unknown>\n}\n"],"mappings":"AAOA,MAAa,EAA0B,OAAO,IAAI,wBAAwB,CAkC7D,EAAoB,GAC/B,OAAO,GAAU,YAAY,GAAkB,SAAU,GAAS,EAAM,OAAS"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { t as Result } from "./result.types-BKzChyWY.mjs";
|
|
2
|
+
import { a as RefinementSchema, c as ValidationError, i as Refine, l as ValidationIssue, n as Input, o as SyncRefinementSchema, r as Output, s as SyncSchema, t as Infer } from "./schema.types-CBEXCwfs.mjs";
|
|
3
|
+
import { StandardSchemaV1 } from "@standard-schema/spec";
|
|
4
|
+
|
|
5
|
+
//#region src/schema/schema.d.ts
|
|
6
|
+
declare namespace schema_d_exports {
|
|
7
|
+
export { Infer, Input, Is, Output, Refine, RefineFn, RefinementSchema, SyncRefinementSchema, SyncSchema, ValidationError, ValidationIssue, is, parse, refine };
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Create a schema-backed parser.
|
|
11
|
+
*
|
|
12
|
+
* For sync schemas the returned parser is sync.
|
|
13
|
+
* For general Standard Schema values the returned parser is async.
|
|
14
|
+
*/
|
|
15
|
+
declare function parse<S extends SyncSchema>(schema: S): (value: Input<S>) => Result<Output<S>, ValidationError>;
|
|
16
|
+
declare function parse<S extends StandardSchemaV1>(schema: S): (value: Input<S>) => Promise<Result<Output<S>, ValidationError>>;
|
|
17
|
+
/**
|
|
18
|
+
* Create a sync-only schema-backed type guard that preserves the original value shape.
|
|
19
|
+
*
|
|
20
|
+
* Use this when a schema validates only a subset of a broader in-memory value.
|
|
21
|
+
* The narrowed type is `Base & Output<typeof schema>`, not the exact schema output.
|
|
22
|
+
*
|
|
23
|
+
* Supports both data-first and data-last styles:
|
|
24
|
+
* - Data-first: `Schema.refine(value, schema)`
|
|
25
|
+
* - Data-last: `Schema.refine(schema)(value)`
|
|
26
|
+
*
|
|
27
|
+
* Only use this with sync schemas that prove properties already present on the
|
|
28
|
+
* original value. Transforms, defaults, and coercions are not safe here because
|
|
29
|
+
* they can change the schema output without changing the original input value.
|
|
30
|
+
*/
|
|
31
|
+
type RefineFn = {
|
|
32
|
+
<S extends SyncSchema, Base extends Input<S>>(value: Base, schema: S): value is Refine<Base, S>;
|
|
33
|
+
<S extends SyncSchema>(schema: S): <Base extends Input<S>>(value: Base) => value is Refine<Base, S>;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Create a sync-only schema-backed type guard.
|
|
37
|
+
*
|
|
38
|
+
* Unlike `Schema.refine`, this narrows exactly to the schema output.
|
|
39
|
+
*
|
|
40
|
+
* This is intended for refinement schemas where the validated output is a
|
|
41
|
+
* subtype of the input value already in memory.
|
|
42
|
+
*
|
|
43
|
+
* Supports both data-first and data-last styles:
|
|
44
|
+
* - Data-first: `Schema.is(value, schema)`
|
|
45
|
+
* - Data-last: `Schema.is(schema)(value)`
|
|
46
|
+
*/
|
|
47
|
+
type Is = {
|
|
48
|
+
<Base, Sub extends Base>(value: Base, schema: SyncRefinementSchema<Base, Sub>): value is Sub;
|
|
49
|
+
<S extends SyncSchema>(value: unknown, schema: S): value is Output<S>;
|
|
50
|
+
<Base, Sub extends Base>(schema: SyncRefinementSchema<Base, Sub>): (value: Base) => value is Sub;
|
|
51
|
+
<S extends SyncSchema>(schema: S): (value: unknown) => value is Output<S>;
|
|
52
|
+
};
|
|
53
|
+
declare const refine: RefineFn;
|
|
54
|
+
declare const is: Is;
|
|
55
|
+
//#endregion
|
|
56
|
+
export { schema_d_exports as t };
|
|
57
|
+
//# sourceMappingURL=index-B4WfexUL.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-B4WfexUL.d.mts","names":[],"sources":["../src/schema/schema.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;iBAgDgB,gBAAgB,oBAAoB,YAAY,MAAM,OAAO,OAAW,OAAO,IAAI;iBACnF,gBAAgB,0BACtB,YACC,MAAM,OAAO,QAAQ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