@nicolastoulemont/std 0.6.0 → 0.7.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 +232 -33
- package/dist/adt/index.d.mts +2 -2
- package/dist/adt/index.mjs +1 -1
- package/dist/adt-DajUZvJe.mjs +2 -0
- package/dist/adt-DajUZvJe.mjs.map +1 -0
- package/dist/brand/index.d.mts +2 -2
- package/dist/brand/index.mjs +1 -1
- package/dist/brand-Bia3Vj6l.mjs +2 -0
- package/dist/brand-Bia3Vj6l.mjs.map +1 -0
- package/dist/context/index.d.mts +2 -0
- package/dist/context/index.mjs +1 -0
- package/dist/context-CCHj1nab.mjs +2 -0
- package/dist/context-CCHj1nab.mjs.map +1 -0
- package/dist/context-r8ESJiFn.d.mts +176 -0
- package/dist/context-r8ESJiFn.d.mts.map +1 -0
- package/dist/data/index.d.mts +2 -2
- package/dist/data/index.mjs +1 -1
- package/dist/data-BLXO4XwS.mjs +2 -0
- package/dist/data-BLXO4XwS.mjs.map +1 -0
- package/dist/data.tagged-error.types-CGiKD-ES.d.mts +29 -0
- package/dist/data.tagged-error.types-CGiKD-ES.d.mts.map +1 -0
- package/dist/{discriminator.types-9PxvrZki.d.mts → discriminator.types-CTURejXz.d.mts} +1 -1
- package/dist/discriminator.types-CTURejXz.d.mts.map +1 -0
- package/dist/dual-CZhzZslG.mjs +2 -0
- package/dist/dual-CZhzZslG.mjs.map +1 -0
- package/dist/either/index.d.mts +2 -2
- package/dist/either/index.mjs +1 -1
- package/dist/either-BMLPfvMl.mjs +2 -0
- package/dist/either-BMLPfvMl.mjs.map +1 -0
- package/dist/{equality-CD4_A1Op.mjs → equality-CoyUHWh9.mjs} +1 -1
- package/dist/{equality-CD4_A1Op.mjs.map → equality-CoyUHWh9.mjs.map} +1 -1
- package/dist/{flow-CYjiodlC.mjs → flow-D8_tllWl.mjs} +1 -1
- package/dist/flow-D8_tllWl.mjs.map +1 -0
- package/dist/functions/index.d.mts +2 -0
- package/dist/functions/index.mjs +1 -0
- package/dist/functions-BkevX2Dw.mjs +2 -0
- package/dist/functions-BkevX2Dw.mjs.map +1 -0
- package/dist/fx/index.d.mts +2 -3
- package/dist/fx/index.mjs +1 -1
- package/dist/fx-K-a9Smhn.mjs +2 -0
- package/dist/fx-K-a9Smhn.mjs.map +1 -0
- package/dist/fx.runtime-DclEDyjY.mjs +2 -0
- package/dist/fx.runtime-DclEDyjY.mjs.map +1 -0
- package/dist/{fx.types-CDVjDn_3.mjs → fx.types-Bg-Mmdm5.mjs} +1 -1
- package/dist/fx.types-Bg-Mmdm5.mjs.map +1 -0
- package/dist/{fx.types-B34asVRX.d.mts → fx.types-DeEWEltG.d.mts} +2 -2
- package/dist/{fx.types-B34asVRX.d.mts.map → fx.types-DeEWEltG.d.mts.map} +1 -1
- package/dist/index-7Lv982Om.d.mts +217 -0
- package/dist/index-7Lv982Om.d.mts.map +1 -0
- package/dist/{index-CklRfom5.d.mts → index-B1-tBzc0.d.mts} +263 -368
- package/dist/index-B1-tBzc0.d.mts.map +1 -0
- package/dist/index-BNQ9xSAz.d.mts +464 -0
- package/dist/index-BNQ9xSAz.d.mts.map +1 -0
- package/dist/index-B_iY5tq0.d.mts +241 -0
- package/dist/index-B_iY5tq0.d.mts.map +1 -0
- package/dist/index-B_wWGszy.d.mts +129 -0
- package/dist/index-B_wWGszy.d.mts.map +1 -0
- package/dist/index-BiiE8NS7.d.mts +108 -0
- package/dist/index-BiiE8NS7.d.mts.map +1 -0
- package/dist/index-By6dNRc4.d.mts +277 -0
- package/dist/index-By6dNRc4.d.mts.map +1 -0
- package/dist/{index-BzYtgdX0.d.mts → index-CGiLfREk.d.mts} +123 -16
- package/dist/index-CGiLfREk.d.mts.map +1 -0
- package/dist/index-CUZn-ohG.d.mts +490 -0
- package/dist/index-CUZn-ohG.d.mts.map +1 -0
- package/dist/index-Cq2IFito.d.mts +121 -0
- package/dist/index-Cq2IFito.d.mts.map +1 -0
- package/dist/{index-B2l8_CiD.d.mts → index-DEAWPlcI.d.mts} +155 -216
- package/dist/index-DEAWPlcI.d.mts.map +1 -0
- package/dist/{index-C4v_3f3-.d.mts → index-DKS1g1oC.d.mts} +95 -42
- package/dist/index-DKS1g1oC.d.mts.map +1 -0
- package/dist/{index-jeC5jyRh.d.mts → index-DXbYlSnB.d.mts} +64 -101
- package/dist/index-DXbYlSnB.d.mts.map +1 -0
- package/dist/{index-CjZ95Dsv.d.mts → index-UzMbg1dh.d.mts} +188 -202
- package/dist/index-UzMbg1dh.d.mts.map +1 -0
- package/dist/index.d.mts +23 -16
- package/dist/index.mjs +1 -1
- package/dist/layer/index.d.mts +2 -0
- package/dist/layer/index.mjs +1 -0
- package/dist/layer-BttmtDrs.mjs +2 -0
- package/dist/layer-BttmtDrs.mjs.map +1 -0
- package/dist/layer.types-DgpCIsk_.d.mts +100 -0
- package/dist/layer.types-DgpCIsk_.d.mts.map +1 -0
- package/dist/multithread/index.d.mts +2 -0
- package/dist/multithread/index.mjs +1 -0
- package/dist/multithread-xUUh4eLn.mjs +19 -0
- package/dist/multithread-xUUh4eLn.mjs.map +1 -0
- package/dist/option/index.d.mts +2 -3
- package/dist/option/index.mjs +1 -1
- package/dist/option-Tfbo4wty.mjs +2 -0
- package/dist/option-Tfbo4wty.mjs.map +1 -0
- package/dist/option.types-D1mm0zUb.mjs +2 -0
- package/dist/option.types-D1mm0zUb.mjs.map +1 -0
- package/dist/{option.types-ClJiBTdg.d.mts → option.types-qPevEZQd.d.mts} +7 -12
- package/dist/option.types-qPevEZQd.d.mts.map +1 -0
- package/dist/order/index.d.mts +2 -0
- package/dist/order/index.mjs +1 -0
- package/dist/order-D5c4QChk.mjs +2 -0
- package/dist/order-D5c4QChk.mjs.map +1 -0
- package/dist/pipeable-COGyGMUV.mjs +2 -0
- package/dist/pipeable-COGyGMUV.mjs.map +1 -0
- package/dist/{pipeable-B4YJA56p.d.mts → pipeable-rfqacPxZ.d.mts} +2 -9
- package/dist/{pipeable-B4YJA56p.d.mts.map → pipeable-rfqacPxZ.d.mts.map} +1 -1
- package/dist/predicate/index.d.mts +2 -2
- package/dist/predicate/index.mjs +1 -1
- package/dist/predicate-DUhhQqWY.mjs +2 -0
- package/dist/predicate-DUhhQqWY.mjs.map +1 -0
- package/dist/provide/index.d.mts +2 -0
- package/dist/provide/index.mjs +1 -0
- package/dist/provide-C2cWOx2B.mjs +2 -0
- package/dist/provide-C2cWOx2B.mjs.map +1 -0
- package/dist/queue/index.d.mts +2 -0
- package/dist/queue/index.mjs +1 -0
- package/dist/queue-Sg6KJerl.mjs +2 -0
- package/dist/queue-Sg6KJerl.mjs.map +1 -0
- package/dist/queue.types-CD2LOu37.d.mts +36 -0
- package/dist/queue.types-CD2LOu37.d.mts.map +1 -0
- package/dist/result/index.d.mts +2 -3
- package/dist/result/index.mjs +1 -1
- package/dist/result-BEzV0DYC.mjs +2 -0
- package/dist/result-BEzV0DYC.mjs.map +1 -0
- package/dist/{result.types-HHDzgSTV.d.mts → result.types-_xDAei3-.d.mts} +5 -97
- package/dist/result.types-_xDAei3-.d.mts.map +1 -0
- package/dist/schedule/index.d.mts +2 -0
- package/dist/schedule/index.mjs +1 -0
- package/dist/schedule-C6tjcJ1O.mjs +2 -0
- package/dist/schedule-C6tjcJ1O.mjs.map +1 -0
- package/dist/schedule-DlX2Dg69.d.mts +144 -0
- package/dist/schedule-DlX2Dg69.d.mts.map +1 -0
- package/dist/scope/index.d.mts +2 -0
- package/dist/scope/index.mjs +1 -0
- package/dist/scope-CZdp4wKX.d.mts +79 -0
- package/dist/scope-CZdp4wKX.d.mts.map +1 -0
- package/dist/scope-D_kzd1nT.mjs +2 -0
- package/dist/scope-D_kzd1nT.mjs.map +1 -0
- package/dist/service/index.d.mts +2 -0
- package/dist/service/index.mjs +1 -0
- package/dist/service-3PYQTUdH.mjs +2 -0
- package/dist/service-3PYQTUdH.mjs.map +1 -0
- package/dist/service-DrXU7KJG.d.mts +69 -0
- package/dist/service-DrXU7KJG.d.mts.map +1 -0
- package/dist/service-resolution-C19smeaO.mjs +2 -0
- package/dist/service-resolution-C19smeaO.mjs.map +1 -0
- package/package.json +50 -12
- package/dist/adt-CkRcY_GA.mjs +0 -2
- package/dist/adt-CkRcY_GA.mjs.map +0 -1
- package/dist/apply-fn.types-0g_9eXRy.d.mts +0 -8
- package/dist/apply-fn.types-0g_9eXRy.d.mts.map +0 -1
- package/dist/brand-Gy0kW6-n.mjs +0 -2
- package/dist/brand-Gy0kW6-n.mjs.map +0 -1
- package/dist/data-C0_3MGwm.mjs +0 -2
- package/dist/data-C0_3MGwm.mjs.map +0 -1
- package/dist/discriminator.types-9PxvrZki.d.mts.map +0 -1
- package/dist/either-CPzK-s8W.mjs +0 -2
- package/dist/either-CPzK-s8W.mjs.map +0 -1
- package/dist/err/index.d.mts +0 -2
- package/dist/err/index.mjs +0 -1
- package/dist/err-3KpQ4pj9.mjs +0 -2
- package/dist/err-3KpQ4pj9.mjs.map +0 -1
- package/dist/flow/index.d.mts +0 -2
- package/dist/flow/index.mjs +0 -1
- package/dist/flow-CYjiodlC.mjs.map +0 -1
- package/dist/fx-vqywVJhV.mjs +0 -2
- package/dist/fx-vqywVJhV.mjs.map +0 -1
- package/dist/fx.types-CDVjDn_3.mjs.map +0 -1
- package/dist/index-8Ne4GdOG.d.mts +0 -288
- package/dist/index-8Ne4GdOG.d.mts.map +0 -1
- package/dist/index-B2l8_CiD.d.mts.map +0 -1
- package/dist/index-BOrJQBPO.d.mts +0 -80
- package/dist/index-BOrJQBPO.d.mts.map +0 -1
- package/dist/index-BsXtpnw-.d.mts +0 -225
- package/dist/index-BsXtpnw-.d.mts.map +0 -1
- package/dist/index-BzYtgdX0.d.mts.map +0 -1
- package/dist/index-C4v_3f3-.d.mts.map +0 -1
- package/dist/index-CjZ95Dsv.d.mts.map +0 -1
- package/dist/index-CklRfom5.d.mts.map +0 -1
- package/dist/index-DZdmFtjA.d.mts +0 -79
- package/dist/index-DZdmFtjA.d.mts.map +0 -1
- package/dist/index-a4MEBZZ1.d.mts +0 -850
- package/dist/index-a4MEBZZ1.d.mts.map +0 -1
- package/dist/index-jeC5jyRh.d.mts.map +0 -1
- package/dist/option-DawZC1cE.mjs +0 -2
- package/dist/option-DawZC1cE.mjs.map +0 -1
- package/dist/option.types-ClJiBTdg.d.mts.map +0 -1
- package/dist/pipe/index.d.mts +0 -2
- package/dist/pipe/index.mjs +0 -1
- package/dist/pipe-BPpJyZf7.mjs +0 -2
- package/dist/pipe-BPpJyZf7.mjs.map +0 -1
- package/dist/pipeable-BA0mXhs4.mjs +0 -2
- package/dist/pipeable-BA0mXhs4.mjs.map +0 -1
- package/dist/predicate-Cy_oHA1Q.mjs +0 -2
- package/dist/predicate-Cy_oHA1Q.mjs.map +0 -1
- package/dist/result-CgGYLp0L.mjs +0 -2
- package/dist/result-CgGYLp0L.mjs.map +0 -1
- package/dist/result.types-HHDzgSTV.d.mts.map +0 -1
- /package/dist/{chunk-DAexk1S7.mjs → chunk-C934ptG5.mjs} +0 -0
- /package/dist/{option-Bb-taghv.mjs → option-CBCwzF0L.mjs} +0 -0
- /package/dist/{result-fiJhwVGz.mjs → result-B5WbPg8C.mjs} +0 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { t as ServiceClass } from "./service-DrXU7KJG.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/context/context.d.ts
|
|
4
|
+
declare namespace context_d_exports {
|
|
5
|
+
export { Context, add, empty, get, has, make, merge, size };
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Context<Services> is an immutable map storing service implementations.
|
|
9
|
+
* The Services type parameter tracks which services are available.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* import { Context } from "@nicolastoulemont/std"
|
|
14
|
+
*
|
|
15
|
+
* type Example = typeof Context
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @category Models
|
|
19
|
+
*/
|
|
20
|
+
type Context<Services = never> = {
|
|
21
|
+
readonly _tag: "Context";
|
|
22
|
+
readonly _services: ReadonlyMap<string, unknown>;
|
|
23
|
+
readonly _Services: Services;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Create an empty context with no services.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* import { Context } from "@nicolastoulemont/std"
|
|
31
|
+
*
|
|
32
|
+
* const ctx = Context.empty()
|
|
33
|
+
* // => { _tag: "Context", _services: Map(0) }
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @category Constructors
|
|
37
|
+
*/
|
|
38
|
+
declare const empty: () => Context;
|
|
39
|
+
/**
|
|
40
|
+
* Create a context with a single service.
|
|
41
|
+
*
|
|
42
|
+
* @param service - The service class (tag)
|
|
43
|
+
* @param impl - The service implementation
|
|
44
|
+
* @returns A context containing the service
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```ts
|
|
48
|
+
* import { Context } from "@nicolastoulemont/std"
|
|
49
|
+
*
|
|
50
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
51
|
+
*
|
|
52
|
+
* const Logger = Service.tag<{ log: (message: string) => void }>("Logger")
|
|
53
|
+
* const ctx = Context.make(Logger, { log: (message) => console.log(message) })
|
|
54
|
+
* // => context containing Logger
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* @category Utilities
|
|
58
|
+
*/
|
|
59
|
+
declare const make: <S>(service: ServiceClass<S>, impl: S) => Context<S>;
|
|
60
|
+
/**
|
|
61
|
+
* Add a service to an existing context (returns new context).
|
|
62
|
+
* Curried for use with pipe.
|
|
63
|
+
*
|
|
64
|
+
* @param service - The service class (tag)
|
|
65
|
+
* @param impl - The service implementation
|
|
66
|
+
* @returns A function that takes a context and returns a new context with the service added
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```ts
|
|
70
|
+
* import { Context } from "@nicolastoulemont/std"
|
|
71
|
+
*
|
|
72
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
73
|
+
*
|
|
74
|
+
* const Logger = Service.tag<{ log: (message: string) => void }>("Logger")
|
|
75
|
+
* const Clock = Service.tag<{ now: () => number }>("Clock")
|
|
76
|
+
* const base = Context.make(Logger, { log: () => undefined })
|
|
77
|
+
* const extended = Context.add(Clock, { now: () => 123 })(base)
|
|
78
|
+
* // => context with Logger and Clock
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
81
|
+
* @category Utilities
|
|
82
|
+
*/
|
|
83
|
+
declare const add: <S>(service: ServiceClass<S>, impl: S) => <Existing>(ctx: Context<Existing>) => Context<Existing | S>;
|
|
84
|
+
/**
|
|
85
|
+
* Merge two contexts together.
|
|
86
|
+
* If both contexts have the same service, the second context's implementation wins.
|
|
87
|
+
*
|
|
88
|
+
* @param a - First context
|
|
89
|
+
* @param b - Second context
|
|
90
|
+
* @returns A new context with services from both
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* import { Context } from "@nicolastoulemont/std"
|
|
95
|
+
*
|
|
96
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
97
|
+
*
|
|
98
|
+
* const Logger = Service.tag<{ log: (message: string) => void }>("Logger")
|
|
99
|
+
* const Clock = Service.tag<{ now: () => number }>("Clock")
|
|
100
|
+
* const a = Context.make(Logger, { log: () => undefined })
|
|
101
|
+
* const b = Context.make(Clock, { now: () => 123 })
|
|
102
|
+
* const merged = Context.merge(a, b)
|
|
103
|
+
* // => context with both services
|
|
104
|
+
* ```
|
|
105
|
+
*
|
|
106
|
+
* @category Utilities
|
|
107
|
+
*/
|
|
108
|
+
declare const merge: <A, B>(a: Context<A>, b: Context<B>) => Context<A | B>;
|
|
109
|
+
/**
|
|
110
|
+
* Get a service from a context.
|
|
111
|
+
* Throws if the service is not found.
|
|
112
|
+
*
|
|
113
|
+
* @param service - The service class (tag)
|
|
114
|
+
* @returns The service implementation
|
|
115
|
+
* @throws Error if service not found
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* import { Context } from "@nicolastoulemont/std"
|
|
120
|
+
*
|
|
121
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
122
|
+
*
|
|
123
|
+
* const Port = Service.tag<number>("Port")
|
|
124
|
+
* const ctx = Context.make(Port, 3000)
|
|
125
|
+
* const port = Context.get(ctx, Port)
|
|
126
|
+
* // => 3000
|
|
127
|
+
* ```
|
|
128
|
+
*
|
|
129
|
+
* @category Utilities
|
|
130
|
+
*/
|
|
131
|
+
declare function get<S>(ctx: Context<S>, service: ServiceClass<S>): S;
|
|
132
|
+
declare function get<S>(service: ServiceClass<S>): (ctx: Context<S>) => S;
|
|
133
|
+
/**
|
|
134
|
+
* Check if a context contains a specific service.
|
|
135
|
+
*
|
|
136
|
+
* @param ctx - The context to check
|
|
137
|
+
* @param service - The service class (tag)
|
|
138
|
+
* @returns true if the service is in the context
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```ts
|
|
142
|
+
* import { Context } from "@nicolastoulemont/std"
|
|
143
|
+
*
|
|
144
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
145
|
+
*
|
|
146
|
+
* const Port = Service.tag<number>("Port")
|
|
147
|
+
* const ctx = Context.make(Port, 3000)
|
|
148
|
+
* const present = Context.has(ctx, Port)
|
|
149
|
+
* // => true
|
|
150
|
+
* ```
|
|
151
|
+
*
|
|
152
|
+
* @category Guards
|
|
153
|
+
*/
|
|
154
|
+
declare const has: <S>(ctx: Context<unknown>, service: ServiceClass<S>) => boolean;
|
|
155
|
+
/**
|
|
156
|
+
* Get the size (number of services) in a context.
|
|
157
|
+
*
|
|
158
|
+
* @example
|
|
159
|
+
* ```ts
|
|
160
|
+
* import { Context } from "@nicolastoulemont/std"
|
|
161
|
+
*
|
|
162
|
+
* import { Service } from "@nicolastoulemont/std"
|
|
163
|
+
*
|
|
164
|
+
* const Port = Service.tag<number>("Port")
|
|
165
|
+
* const Logger = Service.tag<{ log: (message: string) => void }>("Logger")
|
|
166
|
+
* const ctx = Context.add(Logger, { log: () => undefined })(Context.make(Port, 3000))
|
|
167
|
+
* const count = Context.size(ctx)
|
|
168
|
+
* // => 2
|
|
169
|
+
* ```
|
|
170
|
+
*
|
|
171
|
+
* @category Getters
|
|
172
|
+
*/
|
|
173
|
+
declare const size: (ctx: Context<unknown>) => number;
|
|
174
|
+
//#endregion
|
|
175
|
+
export { context_d_exports as n, Context as t };
|
|
176
|
+
//# sourceMappingURL=context-r8ESJiFn.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-r8ESJiFn.d.mts","names":[],"sources":["../src/context/context.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;AAoKA;;;;;;;;;AA6BgB,KAhJJ,OAgJO,CAAA,WAAA,KAAA,CAAA,GAAA;EAAiB,SAAA,IAAA,EAAA,SAAA;EAAR,SAAA,SAAA,EA9IN,WA8IM,CAAA,MAAA,EAAA,OAAA,CAAA;EAAkC,SAAA,SAAA,EA5IxC,QA4IwC;CAAb;;;AACjD;;;;;;;AAoDA;;;;AAAmE,cA7KtD,KA6KsD,EAAA,GAAA,GA7K1C,OA6K0C;AAoBnE;;;;;;;;;;;;;;;;;;;;cAvKa,mBAAoB,aAAa,UAAU,MAAI,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;cAiCvD,kBACE,aAAa,UAAU,sBACpB,QAAQ,cAAY,QAAQ,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;cA8B5C,iBAAkB,QAAQ,OAAO,QAAQ,OAAK,QAAQ,IAAI;;;;;;;;;;;;;;;;;;;;;;;iBA6BvD,YAAY,QAAQ,aAAa,aAAa,KAAK;iBACnD,gBAAgB,aAAa,WAAW,QAAQ,OAAO;;;;;;;;;;;;;;;;;;;;;;cAoD1D,cAAe,2BAA2B,aAAa;;;;;;;;;;;;;;;;;;;cAoBvD,YAAa"}
|
package/dist/data/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { t as data_d_exports } from "../index-CGiLfREk.mjs";
|
|
2
|
+
export { data_d_exports as Data };
|
package/dist/data/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{n as e}from"../data-BLXO4XwS.mjs";export{e as Data};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C934ptG5.mjs";import{a as t,i as n,o as r,r as i}from"./equality-CoyUHWh9.mjs";import{t as a}from"./fx.types-Bg-Mmdm5.mjs";function o(e){let n=[...e];Object.defineProperty(n,`equals`,{value:e=>t(n,e),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(n,`hash`,{value:()=>r(n),enumerable:!1,writable:!1,configurable:!1});let i=n.map.bind(n);Object.defineProperty(n,`map`,{value:e=>o(i(e)),enumerable:!1,writable:!1,configurable:!1});let a=n.filter.bind(n);Object.defineProperty(n,`filter`,{value:e=>o(a(e)),enumerable:!1,writable:!1,configurable:!1});let s=n.slice.bind(n);Object.defineProperty(n,`slice`,{value:(e,t)=>o(s(e,t)),enumerable:!1,writable:!1,configurable:!1});let c=n.concat.bind(n);return Object.defineProperty(n,`concat`,{value:(...e)=>o(c(...e)),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(n)}function s(e){let n={...e};return Object.defineProperty(n,`equals`,{value:e=>t(n,e),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(n,`hash`,{value:()=>r(n),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(n)}function c(e){let t=t=>Object.freeze({...t,_tag:e});return t.is=t=>typeof t==`object`&&!!t&&`_tag`in t&&t._tag===e,t.equals=i(e),t.hash=n(e),t._tag=e,t}function l(e){return class extends Error{static _tag=e;_tag=e;[a]={_A:()=>void 0,_E:()=>this,_R:()=>void 0};constructor(...t){super(e),this.name=e;let n=t[0];n&&Object.assign(this,n),Object.setPrototypeOf(this,new.target.prototype)}*[Symbol.iterator](){throw yield this,Error(`Unreachable: Fx.gen should short-circuit on error`)}}}function u(...e){let n=[...e];return Object.defineProperty(n,`equals`,{value:e=>t(n,e),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(n,`hash`,{value:()=>r(n),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(n)}var d=e({TaggedError:()=>p,array:()=>g,struct:()=>m,tagged:()=>f,tuple:()=>h});const f=c,p=l,m=s,h=u,g=o;export{d as n,p as t};
|
|
2
|
+
//# sourceMappingURL=data-BLXO4XwS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-BLXO4XwS.mjs","names":["array","struct","tagged","TaggedError","tuple","taggedImpl","TaggedErrorImpl","structImpl","tupleImpl","arrayImpl"],"sources":["../src/data/data.array.ts","../src/data/data.struct.ts","../src/data/data.tagged.ts","../src/data/data.tagged-error.ts","../src/data/data.tuple.ts","../src/data/data.ts"],"sourcesContent":["import { deepEquals, deepHash } from \"../equality/equality\"\nimport type { ArrayValue } from \"./data.types\"\n\n/**\n * Create an array with structural equality.\n *\n * The returned array is frozen (immutable) and has non-enumerable\n * equals() and hash() methods for structural comparison.\n *\n * The map() and filter() methods are overridden to return ArrayValue,\n * enabling method chaining with preserved equality semantics.\n *\n * @template T - The element type of the array\n * @param items - The array elements\n * @returns A frozen array with equals(), hash(), map(), and filter()\n *\n * @see {@link tuple} for fixed-length typed tuples\n * @see {@link struct} for object value types\n *\n * @example\n * ```ts\n * const arr1 = array([1, 2, 3])\n * const arr2 = array([1, 2, 3])\n *\n * arr1.equals(arr2) // true\n * arr1.hash() // number\n *\n * // Chainable operations return ArrayValue\n * arr1.map(x => x * 2) // ArrayValue<number>\n * arr1.filter(x => x > 1) // ArrayValue<number>\n *\n * // Chained equality check\n * arr1.map(x => x * 2).equals(array([2, 4, 6])) // true\n *\n * // Array is frozen\n * arr1[0] = 5 // TypeError\n * arr1.push(4) // TypeError\n * ```\n */\nexport function array<T>(items: readonly T[]): ArrayValue<T> {\n const value = [...items]\n\n // Add equals method (non-enumerable)\n Object.defineProperty(value, \"equals\", {\n value: (other: readonly T[]) => deepEquals(value, other),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Add hash method (non-enumerable)\n Object.defineProperty(value, \"hash\", {\n value: () => deepHash(value),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Override map to return ArrayValue\n const originalMap = value.map.bind(value)\n Object.defineProperty(value, \"map\", {\n value: <U>(fn: (item: T, index: number, arr: readonly T[]) => U): ArrayValue<U> => {\n return array(originalMap(fn))\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Override filter to return ArrayValue\n const originalFilter = value.filter.bind(value)\n Object.defineProperty(value, \"filter\", {\n value: (fn: (item: T, index: number, arr: readonly T[]) => boolean): ArrayValue<T> => {\n return array(originalFilter(fn))\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Override slice to return ArrayValue\n const originalSlice = value.slice.bind(value)\n Object.defineProperty(value, \"slice\", {\n value: (start?: number, end?: number): ArrayValue<T> => {\n return array(originalSlice(start, end))\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Override concat to return ArrayValue\n const originalConcat = value.concat.bind(value)\n Object.defineProperty(value, \"concat\", {\n value: (...args: readonly (T | readonly T[])[]): ArrayValue<T> => {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for concat argument spread\n return array(originalConcat(...(args as T[][])))\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic array return type\n return Object.freeze(value) as unknown as ArrayValue<T>\n}\n","import { deepEquals, deepHash } from \"../equality/equality\"\nimport type { StructValue } from \"./data.types\"\n\n/**\n * Create a frozen value object with structural equality.\n *\n * Unlike tagged(), struct() does not add a _tag discriminator.\n * Use this for simple value objects that don't need discrimination.\n *\n * The returned object is frozen (immutable) and has non-enumerable\n * equals() and hash() methods for structural comparison.\n *\n * @template T - The object shape type\n * @param input - The object to wrap\n * @returns A frozen object with equals() and hash() methods\n *\n * @see {@link tagged} for discriminated value objects with _tag\n * @see {@link array} for array value types\n *\n * @example\n * ```ts\n * const point = struct({ x: 10, y: 20 })\n * const point2 = struct({ x: 10, y: 20 })\n *\n * point.equals(point2) // true\n * point.hash() // number\n *\n * // Object is frozen\n * point.x = 5 // TypeError\n *\n * // equals/hash are non-enumerable\n * Object.keys(point) // [\"x\", \"y\"]\n * ```\n */\nexport function struct<T extends Record<string, unknown>>(input: T): StructValue<T> {\n const value = { ...input }\n\n // Add equals method (non-enumerable)\n Object.defineProperty(value, \"equals\", {\n value: (other: T) => deepEquals(value, other),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Add hash method (non-enumerable)\n Object.defineProperty(value, \"hash\", {\n value: () => deepHash(value),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic struct return type\n return Object.freeze(value) as StructValue<T>\n}\n","import { createEqualsMethod, createHashMethod } from \"../equality/equality\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport type { TaggedConstructor, TaggedValue } from \"./data.types\"\n\n/**\n * Create a tagged value constructor without schema validation.\n *\n * Unlike variant(), this creates values directly without validation.\n * Values are frozen and have structural equality via equals() and hash() methods.\n *\n * @template T - The data shape type (excluding _tag)\n * @param tag - The _tag discriminator value\n * @returns A constructor function with is(), equals(), and hash() methods\n *\n * @see {@link variant} for validated variant with schema support\n * @see {@link struct} for untagged value objects\n *\n * @example\n * ```ts\n * const Person = tagged<{ name: string; age: number }>(\"Person\")\n *\n * const alice = Person({ name: \"Alice\", age: 30 })\n * // => { _tag: \"Person\", name: \"Alice\", age: 30 }\n *\n * Person.equals(alice, Person({ name: \"Alice\", age: 30 })) // true\n * Person.is(alice) // true\n *\n * // Type guard usage\n * if (Person.is(unknownValue)) {\n * console.log(unknownValue.name) // TypeScript knows it's a Person\n * }\n *\n * // Values are frozen (immutable)\n * alice.name = \"Bob\" // TypeError\n * ```\n */\nexport function tagged<T extends Record<string, unknown>>(tag: string): TaggedConstructor<typeof tag, T> {\n type Output = TaggedValue<typeof tag, T>\n\n // Constructor function\n const constructor = (input: T): Output => {\n return Object.freeze({ ...input, _tag: tag }) as Output\n }\n\n // Type guard\n constructor.is = (value: unknown): value is Output => {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"_tag\" in value &&\n // oxlint-disable-next-line no-unsafe-type-assertion -- Already checked with 'in' operator\n (value as Discriminator)._tag === tag\n )\n }\n\n // Equality (static method on constructor)\n constructor.equals = createEqualsMethod<typeof tag, T>(tag)\n\n // Hashing (static method on constructor)\n constructor.hash = createHashMethod<typeof tag, T>(tag)\n\n // Store tag for reflection\n constructor._tag = tag\n\n return constructor as TaggedConstructor<typeof tag, T>\n}\n","import { FxTypeId } from \"../fx/fx.types\"\nimport type { TaggedErrorFactory } from \"./data.tagged-error.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Tagged error factories intentionally cast to preserve ergonomic constructor signatures and Fx marker channels. */\n\n/**\n * Create a class-based tagged error type (Effect-style syntax).\n * Returns a class that can be extended to create custom error types.\n * Errors are native Error objects with proper stack traces and instanceof support.\n * Implements Yieldable protocol so errors can be directly yielded in Fx.gen computations.\n *\n * @template Tag - The error tag (discriminator string)\n * @param tag - The error tag\n * @returns A class that can be extended with custom data\n *\n * @example\n * ```ts\n * // Error with data\n * class NotFoundError extends TaggedError(\"NotFoundError\")<{ id: string }> {}\n * const err = new NotFoundError({ id: \"123\" })\n * err.id // \"123\"\n * err._tag // \"NotFoundError\"\n * err.stack // Error stack trace\n *\n * // Error without data\n * class UnauthorizedError extends TaggedError(\"UnauthorizedError\") {}\n * const err2 = new UnauthorizedError()\n *\n * // Direct yielding in Fx.gen computation\n * const program = Fx.gen(function* () {\n * yield* new NotFoundError({ id: \"123\" }) // Short-circuits with error\n * })\n *\n * // instanceof checks work\n * if (err instanceof NotFoundError) {\n * console.log(err.id)\n * }\n * ```\n */\nexport function TaggedError<Tag extends string>(tag: Tag): TaggedErrorFactory<Tag> {\n return class TaggedErrorImpl<Data extends object = object> extends Error {\n static readonly _tag: Tag = tag\n readonly _tag: Tag = tag\n\n readonly [FxTypeId] = {\n _A: () => undefined as never,\n _E: () => this as TaggedErrorImpl<Data>,\n _R: () => undefined as never,\n }\n\n constructor(...args: keyof Data extends never ? [] : [data: Data]) {\n super(tag)\n this.name = tag\n const data = args[0]\n if (data) Object.assign(this, data)\n Object.setPrototypeOf(this, new.target.prototype)\n }\n\n *[Symbol.iterator](): Generator<this, never, unknown> {\n yield this\n throw new Error(\"Unreachable: Fx.gen should short-circuit on error\")\n }\n } as unknown as TaggedErrorFactory<Tag>\n}\n\n/* oxlint-enable no-unsafe-type-assertion */\n","import { deepEquals, deepHash } from \"../equality/equality\"\nimport type { TupleValue } from \"./data.types\"\n\n/**\n * Create a tuple with structural equality.\n *\n * The returned tuple is frozen (immutable) and has non-enumerable\n * equals() and hash() methods for structural comparison.\n *\n * @template T - The tuple type as a readonly array of element types\n * @param args - The tuple elements\n * @returns A frozen tuple-like array with equals() and hash() methods\n *\n * @see {@link array} for variable-length arrays with equality\n * @see {@link struct} for object value types\n *\n * @example\n * ```ts\n * const t1 = tuple(1, \"hello\", true)\n * const t2 = tuple(1, \"hello\", true)\n *\n * t1.equals(t2) // true\n * t1.hash() // number\n *\n * // Access elements (typed)\n * t1[0] // number\n * t1[1] // string\n * t1[2] // boolean\n *\n * // Tuple is frozen\n * t1[0] = 5 // TypeError\n * ```\n */\nexport function tuple<T extends readonly unknown[]>(...args: T): TupleValue<T> {\n const value = [...args]\n\n // Add equals method (non-enumerable)\n Object.defineProperty(value, \"equals\", {\n value: (other: readonly unknown[]) => deepEquals(value, other),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Add hash method (non-enumerable)\n Object.defineProperty(value, \"hash\", {\n value: () => deepHash(value),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic tuple return type\n return Object.freeze(value) as unknown as TupleValue<T>\n}\n","/**\n * Structural data constructors for tagged objects, tuples, arrays, and records.\n *\n * **Mental model**\n * - `Data` helpers create immutable-friendly values with structural equality semantics.\n * - Use `tagged` and `TaggedError` to model domain objects and errors.\n *\n * **Common tasks**\n * - Build tagged records via `Data.tagged`.\n * - Define typed tagged errors with `Data.TaggedError`.\n * - Create structural containers with `Data.struct`, `Data.tuple`, and `Data.array`.\n *\n * **Gotchas**\n * - These constructors are value-level utilities, not validation schemas.\n * - Prefer explicit tagged names for debugging and pattern matching.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const User = Data.tagged<{ id: string }>(\"User\")\n * const user = User({ id: \"u1\" })\n * // => { _tag: \"User\", id: \"u1\" }\n * ```\n *\n * @module\n */\nimport { array as arrayImpl } from \"./data.array\"\nimport { struct as structImpl } from \"./data.struct\"\nimport { tagged as taggedImpl } from \"./data.tagged\"\nimport { TaggedError as TaggedErrorImpl } from \"./data.tagged-error\"\nimport { tuple as tupleImpl } from \"./data.tuple\"\n\n/**\n * Construct tagged data objects.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const User = Data.tagged<{ id: string }>(\"User\")\n * const user = User({ id: \"u1\" })\n * // => { _tag: \"User\", id: \"u1\" }\n * ```\n *\n * @category Constructors\n */\nexport const tagged = taggedImpl\n\n/**\n * Construct tagged error classes.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * class NotFoundError extends Data.TaggedError(\"NotFoundError\")<{ id: string }> {}\n * const error = new NotFoundError({ id: \"u1\" })\n * // => { _tag: \"NotFoundError\", id: \"u1\" }\n * ```\n *\n * @category Constructors\n */\nexport const TaggedError = TaggedErrorImpl\n\n/**\n * Construct immutable-like structs with stable structural behavior.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const point = Data.struct({ x: 1, y: 2 })\n * const same = point.equals({ x: 1, y: 2 })\n * // => true\n * ```\n *\n * @category Constructors\n */\nexport const struct = structImpl\n\n/**\n * Construct immutable-like tuples with stable structural behavior.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const pair = Data.tuple(\"left\", 1)\n * const first = pair[0]\n * // => \"left\"\n * ```\n *\n * @category Constructors\n */\nexport const tuple = tupleImpl\n\n/**\n * Construct immutable-like arrays with stable structural behavior.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const ids = Data.array([\"a\", \"b\"])\n * const upper = ids.map((id) => id.toUpperCase())\n * // => [\"A\", \"B\"]\n * ```\n *\n * @category Constructors\n */\nexport const array = arrayImpl\n"],"mappings":"sJAuCA,SAAgBA,EAAS,EAAoC,CAC3D,IAAM,EAAQ,CAAC,GAAG,EAAM,CAGxB,OAAO,eAAe,EAAO,SAAU,CACrC,MAAQ,GAAwB,EAAW,EAAO,EAAM,CACxD,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,OAAO,eAAe,EAAO,OAAQ,CACnC,UAAa,EAAS,EAAM,CAC5B,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,IAAM,EAAc,EAAM,IAAI,KAAK,EAAM,CACzC,OAAO,eAAe,EAAO,MAAO,CAClC,MAAW,GACFA,EAAM,EAAY,EAAG,CAAC,CAE/B,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,IAAM,EAAiB,EAAM,OAAO,KAAK,EAAM,CAC/C,OAAO,eAAe,EAAO,SAAU,CACrC,MAAQ,GACCA,EAAM,EAAe,EAAG,CAAC,CAElC,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,IAAM,EAAgB,EAAM,MAAM,KAAK,EAAM,CAC7C,OAAO,eAAe,EAAO,QAAS,CACpC,OAAQ,EAAgB,IACfA,EAAM,EAAc,EAAO,EAAI,CAAC,CAEzC,WAAY,GACZ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AoC,GAAG,EAAwB,CAC7E,IAAM,EAAQ,CAAC,GAAG,EAAK,CAmBvB,OAhBA,OAAO,eAAe,EAAO,SAAU,CACrC,MAAQ,GAA8B,EAAW,EAAO,EAAM,CAC9D,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,OAAO,eAAe,EAAO,OAAQ,CACnC,UAAa,EAAS,EAAM,CAC5B,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGK,OAAO,OAAO,EAAM,gFCJ7B,MAAa,EAASC,EAgBT,EAAcC,EAgBd,EAASC,EAgBT,EAAQC,EAgBR,EAAQC"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { i as Fx } from "./fx.types-DeEWEltG.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/data/data.tagged-error.types.d.ts
|
|
4
|
+
interface TaggedErrorCore<Tag extends string, Data extends object = object> extends Error, Fx<never, TaggedErrorCore<Tag, Data>, never> {
|
|
5
|
+
readonly _tag: Tag;
|
|
6
|
+
[Symbol.iterator](): Generator<TaggedErrorCore<Tag, Data>, never, unknown>;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Type for instances created by the TaggedError class factory.
|
|
10
|
+
* Extends Error and includes the tag, data, Fx protocol, and Yieldable protocol.
|
|
11
|
+
* When yielded, yields itself as an Fx type for proper inference.
|
|
12
|
+
*
|
|
13
|
+
* @template Tag - The error tag (discriminator string)
|
|
14
|
+
* @template Data - Additional error data (optional)
|
|
15
|
+
*/
|
|
16
|
+
type TaggedErrorInstance<Tag extends string, Data extends object = object> = TaggedErrorCore<Tag, Data> & Readonly<Data>;
|
|
17
|
+
/**
|
|
18
|
+
* Type for the class returned by TaggedError factory.
|
|
19
|
+
* Supports the Effect-style curried syntax: `TaggedError("Tag")<{ data }>` and `TaggedError("Tag")`
|
|
20
|
+
*
|
|
21
|
+
* @template Tag - The error tag (discriminator string)
|
|
22
|
+
*/
|
|
23
|
+
type TaggedErrorFactory<Tag extends string> = {
|
|
24
|
+
new <Data extends object = object>(...args: keyof Data extends never ? [] : [data: Data]): TaggedErrorInstance<Tag, Data>;
|
|
25
|
+
readonly _tag: Tag;
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
export { TaggedErrorFactory as t };
|
|
29
|
+
//# sourceMappingURL=data.tagged-error.types-CGiKD-ES.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data.tagged-error.types-CGiKD-ES.d.mts","names":[],"sources":["../src/data/data.tagged-error.types.ts"],"sourcesContent":[],"mappings":";;;UAGU,0EACA,OAAO,UAAU,gBAAgB,KAAK;iBAC/B;EAFP,CAAA,MAAA,CAAA,QAAA,GAAe,EAGF,SAHE,CAGQ,eAHR,CAGwB,GAHxB,EAG6B,IAH7B,CAAA,EAAA,KAAA,EAAA,OAAA,CAAA;;;;;;;;;;KAcpB,mBAbY,CAAA,YAAA,MAAA,EAAA,aAAA,MAAA,GAAA,MAAA,CAAA,GAa4D,eAb5D,CAa4E,GAb5E,EAaiF,IAbjF,CAAA,GAayF,QAbzF,CAakG,IAblG,CAAA;;AAAE;;;;;AAauF,KAQ9F,kBAR8F,CAAA,YAAA,MAAA,CAAA,GAAA;EAAQ,IAAA,CAAA,aAAA,MAAA,GAAA,MAAA,CAAA,CAAA,GAAA,IAAA,EAAA,MAU/F,IAV+F,SAAA,KAAA,GAAA,EAAA,GAAA,CAAA,IAAA,EAU9D,IAV8D,CAAA,CAAA,EAW7G,mBAX6G,CAWzF,GAXyF,EAWpF,IAXoF,CAAA;EAQtG,SAAA,IAAA,EAIK,GAJL;CAEO"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discriminator.types-CTURejXz.d.mts","names":[],"sources":["../src/shared/discriminator.types.ts"],"sourcesContent":[],"mappings":";KAAY;EAAA,SAAA,IAAA,EAA8D,GAAjD"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=function(e,t){if(typeof e==`function`)return function(){return e(arguments)?t.apply(this,arguments):(e=>t(e,...arguments))};switch(e){case 0:return t;case 1:return function(e){return arguments.length>0?t.call(this,e):t.bind(this)};case 2:return function(e,n){return arguments.length>=2?t.call(this,e,n):n=>t(n,e)};case 3:return function(e,n,r){return arguments.length>=3?t.call(this,e,n,r):r=>t(r,e,n)};case 4:return function(e,n,r,i){return arguments.length>=4?t.call(this,e,n,r,i):i=>t(i,e,n,r)};case 5:return function(e,n,r,i,a){return arguments.length>=5?t.call(this,e,n,r,i,a):a=>t(a,e,n,r,i)};default:return function(){if(arguments.length>=e)return t.apply(this,arguments);let n=arguments;return e=>t(e,...n)}}};export{e as t};
|
|
2
|
+
//# sourceMappingURL=dual-CZhzZslG.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dual-CZhzZslG.mjs","names":[],"sources":["../src/shared/dual.ts"],"sourcesContent":["/**\n * Dual function utility for creating functions that support both\n * data-first and data-last (curried) calling styles.\n *\n * This pattern is inspired by Effect's dual function implementation.\n * It enables better ergonomics by allowing direct function calls\n * without requiring pipe() for simple operations.\n *\n * @example\n * ```ts\n * // Define a dual function\n * const map = dual<\n * <T, U>(self: Option<T>, fn: (value: T) => U) => Option<U>,\n * <T, U>(fn: (value: T) => U) => (self: Option<T>) => Option<U>\n * >(2, (self, fn) => self.some ? some(fn(self.value)) : none())\n *\n * // Use data-first (direct call)\n * map(some(5), x => x * 2) // Option<10>\n *\n * // Use data-last (curried for pipe)\n * pipe(some(5), map(x => x * 2)) // Option<10>\n * ```\n */\n\n/**\n * Creates a function that can be called with all arguments (data-first)\n * or partially applied (data-last) for use in pipe chains.\n *\n * @param arity - The number of arguments in the data-first version (including self)\n * @param body - The implementation function that receives all arguments\n * @returns A function that supports both calling styles\n *\n * @remarks\n * The arity parameter is used to determine whether the function is being\n * called in data-first mode (all arguments provided) or data-last mode\n * (partial application for piping).\n *\n * TypeScript 5.4+ NoInfer is used where appropriate in consuming code\n * to prevent inference from fallback positions.\n */\n/* oxlint-disable no-explicit-any, ban-types, no-unsafe-function-type, no-unsafe-assignment, no-unsafe-return, no-unsafe-call, no-unsafe-type-assertion -- Required for highly polymorphic dual implementation that relies on runtime arity dispatch */\nexport const dual: {\n <DataFirst extends (...args: any) => any, DataLast extends (...args: any) => any>(\n arity: Parameters<DataFirst>[\"length\"],\n body: DataFirst,\n ): DataFirst & DataLast\n <DataFirst extends (...args: any) => any, DataLast extends (...args: any) => any>(\n isDataFirst: (args: IArguments) => boolean,\n body: DataFirst,\n ): DataFirst & DataLast\n} = function (arityOrIsDataFirst: number | ((args: IArguments) => boolean), body: Function) {\n if (typeof arityOrIsDataFirst === \"function\") {\n return function (this: unknown) {\n // oxlint-disable-next-line prefer-rest-params\n if (arityOrIsDataFirst(arguments)) {\n // oxlint-disable-next-line prefer-rest-params\n return body.apply(this, arguments)\n }\n // oxlint-disable-next-line prefer-rest-params\n return ((self: unknown) => body(self, ...arguments)) as unknown\n }\n }\n switch (arityOrIsDataFirst) {\n case 0:\n return body\n case 1:\n return function (this: unknown, a: unknown) {\n if (arguments.length > 0) {\n return body.call(this, a)\n }\n return body.bind(this)\n }\n case 2:\n return function (this: unknown, a: unknown, b: unknown) {\n if (arguments.length >= 2) {\n return body.call(this, a, b)\n }\n return (self: unknown) => body(self, a)\n }\n case 3:\n return function (this: unknown, a: unknown, b: unknown, c: unknown) {\n if (arguments.length >= 3) {\n return body.call(this, a, b, c)\n }\n return (self: unknown) => body(self, a, b)\n }\n case 4:\n return function (this: unknown, a: unknown, b: unknown, c: unknown, d: unknown) {\n if (arguments.length >= 4) {\n return body.call(this, a, b, c, d)\n }\n return (self: unknown) => body(self, a, b, c)\n }\n case 5:\n return function (this: unknown, a: unknown, b: unknown, c: unknown, d: unknown, e: unknown) {\n if (arguments.length >= 5) {\n return body.call(this, a, b, c, d, e)\n }\n return (self: unknown) => body(self, a, b, c, d)\n }\n default:\n return function (this: unknown) {\n // oxlint-disable-next-line prefer-rest-params\n if (arguments.length >= arityOrIsDataFirst) {\n // oxlint-disable-next-line prefer-rest-params\n return body.apply(this, arguments)\n }\n const args = arguments\n return (self: unknown) => body(self, ...args)\n }\n }\n} as any\n/* oxlint-enable no-explicit-any, ban-types, no-unsafe-function-type, no-unsafe-assignment, no-unsafe-return, no-unsafe-call, no-unsafe-type-assertion */\n"],"mappings":"AAyCA,MAAa,EAST,SAAU,EAA8D,EAAgB,CAC1F,GAAI,OAAO,GAAuB,WAChC,OAAO,UAAyB,CAO9B,OALI,EAAmB,UAAU,CAExB,EAAK,MAAM,KAAM,UAAU,EAG3B,GAAkB,EAAK,EAAM,GAAG,UAAU,GAGvD,OAAQ,EAAR,CACE,IAAK,GACH,OAAO,EACT,IAAK,GACH,OAAO,SAAyB,EAAY,CAI1C,OAHI,UAAU,OAAS,EACd,EAAK,KAAK,KAAM,EAAE,CAEpB,EAAK,KAAK,KAAK,EAE1B,IAAK,GACH,OAAO,SAAyB,EAAY,EAAY,CAItD,OAHI,UAAU,QAAU,EACf,EAAK,KAAK,KAAM,EAAG,EAAE,CAEtB,GAAkB,EAAK,EAAM,EAAE,EAE3C,IAAK,GACH,OAAO,SAAyB,EAAY,EAAY,EAAY,CAIlE,OAHI,UAAU,QAAU,EACf,EAAK,KAAK,KAAM,EAAG,EAAG,EAAE,CAEzB,GAAkB,EAAK,EAAM,EAAG,EAAE,EAE9C,IAAK,GACH,OAAO,SAAyB,EAAY,EAAY,EAAY,EAAY,CAI9E,OAHI,UAAU,QAAU,EACf,EAAK,KAAK,KAAM,EAAG,EAAG,EAAG,EAAE,CAE5B,GAAkB,EAAK,EAAM,EAAG,EAAG,EAAE,EAEjD,IAAK,GACH,OAAO,SAAyB,EAAY,EAAY,EAAY,EAAY,EAAY,CAI1F,OAHI,UAAU,QAAU,EACf,EAAK,KAAK,KAAM,EAAG,EAAG,EAAG,EAAG,EAAE,CAE/B,GAAkB,EAAK,EAAM,EAAG,EAAG,EAAG,EAAE,EAEpD,QACE,OAAO,UAAyB,CAE9B,GAAI,UAAU,QAAU,EAEtB,OAAO,EAAK,MAAM,KAAM,UAAU,CAEpC,IAAM,EAAO,UACb,MAAQ,IAAkB,EAAK,EAAM,GAAG,EAAK"}
|
package/dist/either/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { t as either_d_exports } from "../index-B1-tBzc0.mjs";
|
|
2
|
+
export { either_d_exports as Either };
|
package/dist/either/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{t as e}from"../either-BMLPfvMl.mjs";export{e as Either};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C934ptG5.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";import{t as n}from"./dual-CZhzZslG.mjs";import{n as r}from"./flow-D8_tllWl.mjs";import{t as i}from"./pipeable-COGyGMUV.mjs";import{r as a,t as o}from"./result-BEzV0DYC.mjs";import{i as s,n as c}from"./option-Tfbo4wty.mjs";var l=e({all:()=>C,bimap:()=>g,filter:()=>S,flatMap:()=>_,fromNullable:()=>j,fromOption:()=>k,fromPredicate:()=>M,fromResult:()=>D,isLeft:()=>p,isRight:()=>f,left:()=>d,map:()=>m,mapLeft:()=>h,match:()=>E,orElse:()=>b,right:()=>u,swap:()=>x,tap:()=>v,tapLeft:()=>y,toOption:()=>A,toResult:()=>O,unwrapOr:()=>w,unwrapOrElse:()=>T});const u=e=>({_tag:`Right`,value:e,[t]:{_A:()=>e,_E:()=>void 0,_R:()=>void 0},pipe:i,*[Symbol.iterator](){return e}}),d=e=>({_tag:`Left`,value:e,[t]:{_A:()=>e,_E:()=>void 0,_R:()=>void 0},pipe:i,*[Symbol.iterator](){return e}}),f=e=>e._tag===`Right`,p=e=>e._tag===`Left`,m=n(2,(e,t)=>{if(e._tag===`Left`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(u):u(n)}),h=n(2,(e,t)=>{if(e._tag===`Right`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(d):d(n)}),g=n(3,(e,t,n)=>{if(e._tag===`Right`){let t=n(e.value);return r(t)?Promise.resolve(t).then(u):u(t)}let i=t(e.value);return r(i)?Promise.resolve(i).then(d):d(i)}),_=n(2,(e,t)=>e._tag===`Left`?e:t(e.value)),v=n(2,(e,t)=>{if(e._tag===`Left`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(()=>e):e}),y=n(2,(e,t)=>{if(e._tag===`Right`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(()=>e):e}),b=n(2,(e,t)=>e._tag===`Right`?e:t(e.value)),x=()=>e=>e._tag===`Left`?u(e.value):d(e.value),S=n(3,(e,t,n)=>e._tag===`Left`||t(e.value)?e:d(n(e.value))),C=e=>{if(Array.isArray(e)){let t=[];for(let n of e){if(n._tag===`Left`)return n;t.push(n.value)}return u(t)}let t={};for(let n in e){let r=e[n];if(r._tag===`Left`)return r;t[n]=r.value}return u(t)},w=n(2,(e,t)=>e._tag===`Right`?e.value:t),T=n(2,(e,t)=>e._tag===`Right`?e.value:t(e.value)),E=n(2,(e,t)=>e._tag===`Right`?t.Right(e.value):t.Left(e.value)),D=e=>e._tag===`Ok`?u(e.value):d(e.error),O=e=>e._tag===`Right`?a(e.value):o(e.value),k=(e,t)=>e._tag===`Some`?u(e.value):d(t()),A=e=>e._tag===`Right`?s(e.value):c(),j=(e,t)=>e==null?d(t()):u(e),M=(e,t,n)=>t(e)?u(e):d(n(e));export{l as t};
|
|
2
|
+
//# sourceMappingURL=either-BMLPfvMl.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"either-BMLPfvMl.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 { pipeMethod } 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 *\n * @category Re-exports\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 *\n * @category Constructors\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: pipeMethod,\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 *\n * @category Constructors\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: pipeMethod,\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 *\n * @category Guards\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 *\n * @category Guards\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 async functions.\n *\n * @param fn - Transformation function for right values\n * @returns A curried function that transforms an Either\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 * @category Mapping\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 async functions.\n *\n * @param fn - Transformation function for left values\n * @returns A curried function that transforms an Either\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 * @category Mapping\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 async functions.\n *\n * @param fnLeft - Transformation function for left values\n * @param fnRight - Transformation function for right values\n * @returns A curried function that transforms an Either\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 * @category Mapping\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 async functions. Combines left error unions.\n *\n * @param fn - Function that returns an Either\n * @returns A curried function that chains Eithers\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 * @category Sequencing\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 async functions.\n *\n * @param fn - Side effect function for right values\n * @returns A curried function that executes side effects\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 * @category Sequencing\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 async functions.\n *\n * @param fn - Side effect function for left values\n * @returns A curried function that executes side effects\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 * @category Sequencing\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 async functions. Combines right value unions.\n *\n * @param fn - Function that returns an alternative Either\n * @returns A curried function that recovers from left\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 * @category Error Handling\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 *\n * @category Conversions\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 A curried function that filters an Either\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 * @category Filtering\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 * @category Combining\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 A curried function that extracts the value\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 *\n * @category Getters\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 A curried function that extracts the value\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 *\n * @category Getters\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 A curried function that pattern matches\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 *\n * @category Pattern Matching\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 *\n * @category Conversions\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 *\n * @category Conversions\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 *\n * @category Conversions\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 *\n * @category Conversions\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 *\n * @category Conversions\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 *\n * @category Constructors\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":"ynBA2FA,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,EAwBY,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,EAsBY,EAAiB,GAC5B,EAAO,OAAS,QAeL,EAAgB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,EAAK,GAAQ,CAAC,CAqBlD,EAAkB,GAC7B,EAAO,OAAS,QAAUC,EAAY,EAAO,MAAM,CAAGC,GAAgB,CAoB3D,GAAsB,EAA6B,IAC9D,GAAU,KAA8B,EAAK,GAAQ,CAAC,CAAG,EAAM,EAAM,CAqB1D,GACX,EACA,EACA,IACsB,EAAU,EAAM,CAAG,EAAM,EAAM,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-CoyUHWh9.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"equality-CD4_A1Op.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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W,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
|
+
{"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,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,GAA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,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-D8_tllWl.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flow-D8_tllWl.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 * @category Combinators\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,WC6SvD,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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"../flow-D8_tllWl.mjs";import{t}from"../functions-BkevX2Dw.mjs";export{e as flow,t as pipe};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"functions-BkevX2Dw.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 * @category Combinators\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":"wCAsUA,SAAgB,EAA+C,EAAQ,GAAG,EAA8B,CAGtG,OAAQ,EAAK,GAAI,EAAoB,CAAS,EAAI"}
|
package/dist/fx/index.d.mts
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
export { AsyncFx, AsyncFxGenerator, AsyncFxYieldable, Context, Context as ContextType, ExcludeScope, Exit, Exit as ExitType, Defect as ExitDefect, Fx, FxError, FxGenerator, Fx$1 as FxProtocol, Fx$1 as FxType, FxRequirements, FxTypeId, FxValue, FxYield, FxYieldable, Layer, LayerError, LayerRIn, LayerROut, Layer$1 as LayerType, MemoMap, MergeError, MergeROut, RunnableFx, ScopeTag as Scope, ScopeService, Service, ServiceClass, ServiceKey, ServiceOf, ServiceRequest, SyncFx, TaggedMatch, UnprovidedDeps, createMemoMap, createScope, err, fn, gen, isServiceClass, isServiceRequest, fxMatch as match, ok, provide, provideContext, provideService, run, serviceTag };
|
|
1
|
+
import { t as fx_d_exports } from "../index-BNQ9xSAz.mjs";
|
|
2
|
+
export { fx_d_exports as Fx };
|
package/dist/fx/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{t as e}from"../fx-K-a9Smhn.mjs";export{e as Fx};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-C934ptG5.mjs";import{n as t,t as n}from"./fx.types-Bg-Mmdm5.mjs";import{t as r}from"./dual-CZhzZslG.mjs";import{n as i,r as a,t as o}from"./result-BEzV0DYC.mjs";import{t as s}from"./option.types-D1mm0zUb.mjs";import{t as c}from"./option-Tfbo4wty.mjs";import{t as l}from"./service-resolution-C19smeaO.mjs";import{i as u,n as d,r as f,t as p}from"./queue-Sg6KJerl.mjs";import{n as m,r as h,t as g}from"./fx.runtime-DclEDyjY.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=a,B=o,V=i,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-K-a9Smhn.mjs.map
|