@nicolastoulemont/std 0.5.1 → 0.6.0
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 +341 -0
- package/dist/adt/index.d.mts +2 -2
- package/dist/adt/index.mjs +1 -1
- package/dist/adt-CkRcY_GA.mjs +2 -0
- package/dist/adt-CkRcY_GA.mjs.map +1 -0
- package/dist/{apply-fn.types-CMgY6WQe.d.mts → apply-fn.types-0g_9eXRy.d.mts} +1 -1
- package/dist/{apply-fn.types-CMgY6WQe.d.mts.map → apply-fn.types-0g_9eXRy.d.mts.map} +1 -1
- package/dist/brand/index.d.mts +1 -1
- package/dist/brand/index.mjs +1 -1
- package/dist/{brand-BUqMmkzC.mjs → brand-Gy0kW6-n.mjs} +2 -2
- package/dist/brand-Gy0kW6-n.mjs.map +1 -0
- package/dist/chunk-DAexk1S7.mjs +1 -0
- package/dist/data/index.d.mts +2 -2
- package/dist/data/index.mjs +1 -1
- package/dist/data-C0_3MGwm.mjs +2 -0
- package/dist/data-C0_3MGwm.mjs.map +1 -0
- package/dist/{discriminator.types-DkThfvNE.d.mts → discriminator.types-9PxvrZki.d.mts} +1 -1
- package/dist/discriminator.types-9PxvrZki.d.mts.map +1 -0
- package/dist/either/index.d.mts +1 -1
- package/dist/either/index.mjs +1 -1
- package/dist/either-CPzK-s8W.mjs +2 -0
- package/dist/either-CPzK-s8W.mjs.map +1 -0
- package/dist/equality-CD4_A1Op.mjs +2 -0
- package/dist/equality-CD4_A1Op.mjs.map +1 -0
- package/dist/err/index.d.mts +1 -1
- package/dist/err/index.mjs +1 -1
- package/dist/err-3KpQ4pj9.mjs +2 -0
- package/dist/err-3KpQ4pj9.mjs.map +1 -0
- package/dist/flow/index.d.mts +1 -1
- package/dist/flow/index.mjs +1 -1
- package/dist/flow-CYjiodlC.mjs +2 -0
- package/dist/flow-CYjiodlC.mjs.map +1 -0
- package/dist/fx/index.d.mts +3 -3
- package/dist/fx/index.mjs +1 -1
- package/dist/fx-vqywVJhV.mjs +2 -0
- package/dist/fx-vqywVJhV.mjs.map +1 -0
- package/dist/{fx.types-DO-8yG4c.d.mts → fx.types-B34asVRX.d.mts} +2 -7
- package/dist/{fx.types-DO-8yG4c.d.mts.map → fx.types-B34asVRX.d.mts.map} +1 -1
- package/dist/{fx.types-CXTwEa1G.mjs → fx.types-CDVjDn_3.mjs} +1 -1
- package/dist/{fx.types-CXTwEa1G.mjs.map → fx.types-CDVjDn_3.mjs.map} +1 -1
- package/dist/{index-78LWwTds.d.mts → index-8Ne4GdOG.d.mts} +2 -2
- package/dist/{index-78LWwTds.d.mts.map → index-8Ne4GdOG.d.mts.map} +1 -1
- package/dist/{index-BuLJRX1e.d.mts → index-B2l8_CiD.d.mts} +42 -52
- package/dist/index-B2l8_CiD.d.mts.map +1 -0
- package/dist/{index-BahMvQpA.d.mts → index-BOrJQBPO.d.mts} +2 -2
- package/dist/{index-BahMvQpA.d.mts.map → index-BOrJQBPO.d.mts.map} +1 -1
- package/dist/{index-CDio8mJY.d.mts → index-BsXtpnw-.d.mts} +7 -7
- package/dist/index-BsXtpnw-.d.mts.map +1 -0
- package/dist/{index-DtAPrec7.d.mts → index-BzYtgdX0.d.mts} +70 -62
- package/dist/index-BzYtgdX0.d.mts.map +1 -0
- package/dist/index-C4v_3f3-.d.mts +396 -0
- package/dist/index-C4v_3f3-.d.mts.map +1 -0
- package/dist/{index-BQ5wVDSP.d.mts → index-CjZ95Dsv.d.mts} +35 -47
- package/dist/index-CjZ95Dsv.d.mts.map +1 -0
- package/dist/{index-Bs5TTFlK.d.mts → index-CklRfom5.d.mts} +10 -10
- package/dist/index-CklRfom5.d.mts.map +1 -0
- package/dist/{index-IdejL485.d.mts → index-DZdmFtjA.d.mts} +2 -2
- package/dist/{index-IdejL485.d.mts.map → index-DZdmFtjA.d.mts.map} +1 -1
- package/dist/{index-UYodvXes.d.mts → index-a4MEBZZ1.d.mts} +41 -37
- package/dist/index-a4MEBZZ1.d.mts.map +1 -0
- package/dist/{index-DjjJIDaA.d.mts → index-jeC5jyRh.d.mts} +8 -8
- package/dist/index-jeC5jyRh.d.mts.map +1 -0
- package/dist/index.d.mts +16 -16
- package/dist/index.mjs +1 -1
- package/dist/option/index.d.mts +3 -3
- package/dist/option/index.mjs +1 -1
- package/dist/option-DawZC1cE.mjs +2 -0
- package/dist/option-DawZC1cE.mjs.map +1 -0
- package/dist/{option.types-Cluybn30.d.mts → option.types-ClJiBTdg.d.mts} +6 -11
- package/dist/option.types-ClJiBTdg.d.mts.map +1 -0
- package/dist/pipe/index.d.mts +1 -1
- package/dist/pipe/index.mjs +1 -1
- package/dist/pipe-BPpJyZf7.mjs +2 -0
- package/dist/{pipe-BROILDeC.mjs.map → pipe-BPpJyZf7.mjs.map} +1 -1
- package/dist/{pipeable-KHu4D8ol.d.mts → pipeable-B4YJA56p.d.mts} +1 -1
- package/dist/{pipeable-KHu4D8ol.d.mts.map → pipeable-B4YJA56p.d.mts.map} +1 -1
- package/dist/{pipeable-rQvolRqh.mjs → pipeable-BA0mXhs4.mjs} +2 -2
- package/dist/pipeable-BA0mXhs4.mjs.map +1 -0
- package/dist/predicate/index.d.mts +1 -1
- package/dist/predicate/index.mjs +1 -1
- package/dist/{predicate-DvXnfmeJ.mjs → predicate-Cy_oHA1Q.mjs} +1 -1
- package/dist/{predicate-DvXnfmeJ.mjs.map → predicate-Cy_oHA1Q.mjs.map} +1 -1
- package/dist/result/index.d.mts +2 -2
- package/dist/result/index.mjs +1 -1
- package/dist/result-CgGYLp0L.mjs +2 -0
- package/dist/result-CgGYLp0L.mjs.map +1 -0
- package/dist/result-fiJhwVGz.mjs +1 -0
- package/dist/{result.types-fIbuBwVQ.d.mts → result.types-HHDzgSTV.d.mts} +31 -17
- package/dist/result.types-HHDzgSTV.d.mts.map +1 -0
- package/package.json +3 -2
- package/dist/adt-DZmVJG4P.mjs +0 -2
- package/dist/adt-DZmVJG4P.mjs.map +0 -1
- package/dist/brand-BUqMmkzC.mjs.map +0 -1
- package/dist/data-DzqKBCQg.mjs +0 -2
- package/dist/data-DzqKBCQg.mjs.map +0 -1
- package/dist/discriminator.types-DkThfvNE.d.mts.map +0 -1
- package/dist/either-BDY9T5oz.mjs +0 -2
- package/dist/either-BDY9T5oz.mjs.map +0 -1
- package/dist/equality-D2EJvZm4.mjs +0 -2
- package/dist/equality-D2EJvZm4.mjs.map +0 -1
- package/dist/err-CYs4b1RV.mjs +0 -2
- package/dist/err-CYs4b1RV.mjs.map +0 -1
- package/dist/flow-CxKQ5yac.mjs +0 -2
- package/dist/flow-CxKQ5yac.mjs.map +0 -1
- package/dist/fx-C4UuWCqP.mjs +0 -2
- package/dist/fx-C4UuWCqP.mjs.map +0 -1
- package/dist/index-BQ5wVDSP.d.mts.map +0 -1
- package/dist/index-Bs5TTFlK.d.mts.map +0 -1
- package/dist/index-BuLJRX1e.d.mts.map +0 -1
- package/dist/index-CDio8mJY.d.mts.map +0 -1
- package/dist/index-DLlx9jiG.d.mts +0 -389
- package/dist/index-DLlx9jiG.d.mts.map +0 -1
- package/dist/index-DjjJIDaA.d.mts.map +0 -1
- package/dist/index-DtAPrec7.d.mts.map +0 -1
- package/dist/index-UYodvXes.d.mts.map +0 -1
- package/dist/option-Qiv7Ls7L.mjs +0 -2
- package/dist/option-Qiv7Ls7L.mjs.map +0 -1
- package/dist/option.types-By5UOfC2.mjs +0 -2
- package/dist/option.types-By5UOfC2.mjs.map +0 -1
- package/dist/option.types-Cluybn30.d.mts.map +0 -1
- package/dist/pipe-BROILDeC.mjs +0 -2
- package/dist/pipeable-rQvolRqh.mjs.map +0 -1
- package/dist/result-B68pxC7l.mjs +0 -2
- package/dist/result-B68pxC7l.mjs.map +0 -1
- package/dist/result.types-fIbuBwVQ.d.mts.map +0 -1
- /package/dist/{result-uRORQlAQ.mjs → option-Bb-taghv.mjs} +0 -0
package/README.md
CHANGED
|
@@ -1 +1,342 @@
|
|
|
1
1
|
# @nicolastoulemont/std
|
|
2
|
+
|
|
3
|
+
## Introduction
|
|
4
|
+
|
|
5
|
+
`@nicolastoulemont/std` is a functional TypeScript toolkit for modeling domain data, handling failures explicitly, and composing sync or async workflows.
|
|
6
|
+
It is designed for application code where clear control flow, predictable typing, and dependency-aware orchestration matter.
|
|
7
|
+
The API is small, pipe-friendly, and built around practical primitives you can combine incrementally.
|
|
8
|
+
|
|
9
|
+
## Installation
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pnpm add @nicolastoulemont/std
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quick Start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { Result, TaggedError, pipe } from "@nicolastoulemont/std"
|
|
19
|
+
|
|
20
|
+
class InvalidPortError extends TaggedError("InvalidPortError")<{ input: string }> {}
|
|
21
|
+
|
|
22
|
+
const parsePort = (input: string) =>
|
|
23
|
+
pipe(
|
|
24
|
+
Result.try(() => Number.parseInt(input, 10)),
|
|
25
|
+
Result.filter((n) => Number.isInteger(n) && n > 0, () => new InvalidPortError({ input })),
|
|
26
|
+
)
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { Fx, Layer, provide, serviceTag, pipe } from "@nicolastoulemont/std"
|
|
31
|
+
|
|
32
|
+
const Config = serviceTag<{ baseUrl: string }>("Config")
|
|
33
|
+
|
|
34
|
+
const ConfigLive = Layer.ok(Config, { baseUrl: "https://api.example.com" })
|
|
35
|
+
|
|
36
|
+
const program = Fx.gen(function* () {
|
|
37
|
+
const config = yield* Config
|
|
38
|
+
return config.baseUrl
|
|
39
|
+
})
|
|
40
|
+
|
|
41
|
+
const exit = Fx.run(pipe(program, provide(ConfigLive)))
|
|
42
|
+
|
|
43
|
+
const response = Fx.match(exit, {
|
|
44
|
+
Ok: (ok) => ({ status: 200, body: ok.value }),
|
|
45
|
+
Err: (err) => ({ status: 400, body: err.error }),
|
|
46
|
+
Defect: (defect) => ({ status: 500, body: String(defect.defect) }),
|
|
47
|
+
})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Main Modules
|
|
51
|
+
|
|
52
|
+
### Result
|
|
53
|
+
|
|
54
|
+
Result models success/failure with typed errors so transformations stay explicit and composable.
|
|
55
|
+
|
|
56
|
+
#### Abstract Example
|
|
57
|
+
|
|
58
|
+
```ts
|
|
59
|
+
import { Result, TaggedError, pipe } from "@nicolastoulemont/std"
|
|
60
|
+
|
|
61
|
+
class NotPositiveIntegerError extends TaggedError("NotPositiveIntegerError")<{ input: string }> {}
|
|
62
|
+
|
|
63
|
+
const parsePositiveInt = (input: string) => {
|
|
64
|
+
const parsed = Number.parseInt(input, 10)
|
|
65
|
+
return pipe(
|
|
66
|
+
Result.ok(parsed),
|
|
67
|
+
Result.filter((n) => Number.isInteger(n) && n > 0, () => new NotPositiveIntegerError({ input })),
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
#### Real-World Example
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
import { Result, TaggedError, pipe } from "@nicolastoulemont/std"
|
|
76
|
+
|
|
77
|
+
class ValidationError extends TaggedError("ValidationError")<{ message: string }> {}
|
|
78
|
+
class ConflictError extends TaggedError("ConflictError")<{ message: string }> {}
|
|
79
|
+
type SignupError = ValidationError | ConflictError
|
|
80
|
+
|
|
81
|
+
const validateEmail = (email: string) =>
|
|
82
|
+
email.includes("@")
|
|
83
|
+
? Result.ok(email)
|
|
84
|
+
: Result.err<SignupError>(new ValidationError({ message: "Invalid email" }))
|
|
85
|
+
|
|
86
|
+
const createUser = (email: string) =>
|
|
87
|
+
email === "taken@example.com"
|
|
88
|
+
? Result.err<SignupError>(new ConflictError({ message: "Email already used" }))
|
|
89
|
+
: Result.ok({ id: "u_123", email })
|
|
90
|
+
|
|
91
|
+
const signup = (email: string) => pipe(validateEmail(email), Result.flatMap(createUser))
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Option
|
|
95
|
+
|
|
96
|
+
Option models optional presence/absence when missing data is expected and not an error condition.
|
|
97
|
+
|
|
98
|
+
#### Abstract Example
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { Option, pipe } from "@nicolastoulemont/std"
|
|
102
|
+
|
|
103
|
+
const normalizedName = (value: string | undefined) =>
|
|
104
|
+
pipe(
|
|
105
|
+
Option.fromNullable(value),
|
|
106
|
+
Option.map((name) => name.trim()),
|
|
107
|
+
Option.filter((name) => name.length > 0),
|
|
108
|
+
Option.unwrapOr("Anonymous"),
|
|
109
|
+
)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
#### Real-World Example
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import { Option, pipe } from "@nicolastoulemont/std"
|
|
116
|
+
|
|
117
|
+
const readPagination = (query: URLSearchParams) => ({
|
|
118
|
+
page: pipe(
|
|
119
|
+
Option.fromNullable(query.get("page")),
|
|
120
|
+
Option.map((raw) => Number.parseInt(raw, 10)),
|
|
121
|
+
Option.filter((n) => Number.isInteger(n) && n > 0),
|
|
122
|
+
Option.unwrapOr(1),
|
|
123
|
+
),
|
|
124
|
+
limit: pipe(
|
|
125
|
+
Option.fromNullable(query.get("limit")),
|
|
126
|
+
Option.map((raw) => Number.parseInt(raw, 10)),
|
|
127
|
+
Option.filter((n) => Number.isInteger(n) && n > 0 && n <= 100),
|
|
128
|
+
Option.unwrapOr(20),
|
|
129
|
+
),
|
|
130
|
+
})
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Either
|
|
134
|
+
|
|
135
|
+
Either models two valid branches where both sides are meaningful outcomes rather than success versus failure.
|
|
136
|
+
|
|
137
|
+
#### Abstract Example
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
import { Either } from "@nicolastoulemont/std"
|
|
141
|
+
|
|
142
|
+
const parseSource = (input: "local" | "remote") =>
|
|
143
|
+
input === "local" ? Either.left("LOCAL") : Either.right("REMOTE")
|
|
144
|
+
|
|
145
|
+
const label = Either.match(parseSource("local"), {
|
|
146
|
+
Left: (source) => `Source: ${source}`,
|
|
147
|
+
Right: (source) => `Source: ${source}`,
|
|
148
|
+
})
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
#### Real-World Example
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
import { Either, pipe } from "@nicolastoulemont/std"
|
|
155
|
+
|
|
156
|
+
type Source = "cache" | "database"
|
|
157
|
+
type User = { id: string; name: string }
|
|
158
|
+
|
|
159
|
+
const findUser = (id: string) =>
|
|
160
|
+
id.startsWith("cached:")
|
|
161
|
+
? Either.left<Source, User>("cache")
|
|
162
|
+
: Either.right<Source, User>({ id, name: "Ada" })
|
|
163
|
+
|
|
164
|
+
const responseMeta = (id: string) =>
|
|
165
|
+
pipe(
|
|
166
|
+
findUser(id),
|
|
167
|
+
Either.match({
|
|
168
|
+
Left: (source) => ({ source, stale: true }),
|
|
169
|
+
Right: (user) => ({ source: "database" as const, stale: false, user }),
|
|
170
|
+
}),
|
|
171
|
+
)
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
### Fx
|
|
175
|
+
|
|
176
|
+
Fx models generator-based effects with typed dependencies and short-circuiting typed failures.
|
|
177
|
+
|
|
178
|
+
#### Abstract Example
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
import { Fx, Layer, provide, serviceTag, pipe } from "@nicolastoulemont/std"
|
|
182
|
+
|
|
183
|
+
const Clock = serviceTag<{ now: () => number }>("Clock")
|
|
184
|
+
const ClockLive = Layer.ok(Clock, { now: () => Date.now() })
|
|
185
|
+
|
|
186
|
+
const program = Fx.gen(function* () {
|
|
187
|
+
const clock = yield* Clock
|
|
188
|
+
return clock.now()
|
|
189
|
+
})
|
|
190
|
+
|
|
191
|
+
const exit = Fx.run(pipe(program, provide(ClockLive)))
|
|
192
|
+
|
|
193
|
+
const timestamp = Fx.match(exit, {
|
|
194
|
+
Ok: (ok) => ok.value,
|
|
195
|
+
Err: () => 0,
|
|
196
|
+
Defect: () => 0,
|
|
197
|
+
})
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
#### Real-World Example
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import { Fx, Layer, Result, TaggedError, provide, serviceTag, pipe } from "@nicolastoulemont/std"
|
|
204
|
+
|
|
205
|
+
const Api = serviceTag<{ postOrder: (input: { sku: string; qty: number }) => Promise<{ orderId: string }> }>("Api")
|
|
206
|
+
const ApiLive = Layer.ok(Api, {
|
|
207
|
+
postOrder: async () => ({ orderId: "ord_42" }),
|
|
208
|
+
})
|
|
209
|
+
|
|
210
|
+
class InvalidQuantityError extends TaggedError("InvalidQuantityError")<{ qty: number }> {}
|
|
211
|
+
|
|
212
|
+
const submitOrder = Fx.gen(function* (payload: { sku?: string; qty: number }) {
|
|
213
|
+
const api = yield* Api
|
|
214
|
+
const sku = yield* Fx.option(payload.sku)
|
|
215
|
+
const validQty = yield* Result.filter(
|
|
216
|
+
Result.ok(payload.qty),
|
|
217
|
+
(qty) => qty > 0,
|
|
218
|
+
(qty) => new InvalidQuantityError({ qty }),
|
|
219
|
+
)
|
|
220
|
+
return yield* Fx.try(() => api.postOrder({ sku, qty: validQty }))
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
const exit = Fx.run(pipe(submitOrder({ sku: "book-1", qty: 2 }), provide(ApiLive)))
|
|
224
|
+
|
|
225
|
+
const httpResponse = Fx.match(exit, {
|
|
226
|
+
Ok: (ok) => ({ status: 201, body: ok.value }),
|
|
227
|
+
Err: (err) => ({ status: 400, body: String(err.error) }),
|
|
228
|
+
Defect: () => ({ status: 500, body: "Unexpected defect" }),
|
|
229
|
+
})
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
### Adt
|
|
233
|
+
|
|
234
|
+
Adt provides schema-backed tagged variants so you can model domain state with exhaustive pattern matching.
|
|
235
|
+
|
|
236
|
+
#### Abstract Example
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
import { Adt, type AdtInfer } from "@nicolastoulemont/std"
|
|
240
|
+
import { z } from "zod"
|
|
241
|
+
|
|
242
|
+
const Shape = Adt.union("Shape", {
|
|
243
|
+
Circle: z.object({ radius: z.number() }),
|
|
244
|
+
Square: z.object({ side: z.number() }),
|
|
245
|
+
})
|
|
246
|
+
type Shape = AdtInfer<typeof Shape>
|
|
247
|
+
|
|
248
|
+
const describeShape = (shape: Shape) =>
|
|
249
|
+
Adt.match(shape, {
|
|
250
|
+
Circle: (value) => `circle(${value.radius})`,
|
|
251
|
+
Square: (value) => `square(${value.side})`,
|
|
252
|
+
})
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
#### Real-World Example
|
|
256
|
+
|
|
257
|
+
```ts
|
|
258
|
+
import { Adt, type AdtInfer } from "@nicolastoulemont/std"
|
|
259
|
+
import { z } from "zod"
|
|
260
|
+
|
|
261
|
+
const OrderState = Adt.union("OrderState", {
|
|
262
|
+
Draft: z.object({ id: z.string() }),
|
|
263
|
+
Confirmed: z.object({ id: z.string(), paymentId: z.string() }),
|
|
264
|
+
Shipped: z.object({ id: z.string(), trackingId: z.string() }),
|
|
265
|
+
})
|
|
266
|
+
type OrderState = AdtInfer<typeof OrderState>
|
|
267
|
+
|
|
268
|
+
const badgeLabel = (state: OrderState) =>
|
|
269
|
+
Adt.match(state, {
|
|
270
|
+
Draft: () => "Waiting for payment",
|
|
271
|
+
Confirmed: () => "Preparing shipment",
|
|
272
|
+
Shipped: (value) => `Shipped: ${value.trackingId}`,
|
|
273
|
+
})
|
|
274
|
+
```
|
|
275
|
+
|
|
276
|
+
### Data
|
|
277
|
+
|
|
278
|
+
Data creates immutable structural value objects (`Data.struct`, `Data.tuple`, `Data.array`, `Data.tagged`) with stable equality and hashing semantics.
|
|
279
|
+
|
|
280
|
+
#### Abstract Example
|
|
281
|
+
|
|
282
|
+
```ts
|
|
283
|
+
import { Data } from "@nicolastoulemont/std"
|
|
284
|
+
|
|
285
|
+
const a = Data.struct({ env: "prod", retries: 3 })
|
|
286
|
+
const b = Data.struct({ env: "prod", retries: 3 })
|
|
287
|
+
|
|
288
|
+
const same = a.equals(b) // true
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
#### Real-World Example
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
import { Data } from "@nicolastoulemont/std"
|
|
295
|
+
|
|
296
|
+
const previous = Data.struct({ search: "books", sort: "price-asc" })
|
|
297
|
+
const next = Data.struct({ search: "books", sort: "price-asc" })
|
|
298
|
+
|
|
299
|
+
if (previous.equals(next)) {
|
|
300
|
+
// Skip redundant fetch because filter state is structurally identical
|
|
301
|
+
}
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
### pipe / flow
|
|
305
|
+
|
|
306
|
+
pipe and flow compose sync/async transformations into readable, type-inferred data pipelines.
|
|
307
|
+
|
|
308
|
+
#### Abstract Example
|
|
309
|
+
|
|
310
|
+
```ts
|
|
311
|
+
import { pipe, flow } from "@nicolastoulemont/std"
|
|
312
|
+
|
|
313
|
+
const toLabel = flow(
|
|
314
|
+
(n: number) => n * 2,
|
|
315
|
+
(n) => n.toString(),
|
|
316
|
+
(s) => `value:${s}`,
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
const result = pipe(10, (n) => n + 1, toLabel) // "value:22"
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
#### Real-World Example
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
import { pipe } from "@nicolastoulemont/std"
|
|
326
|
+
|
|
327
|
+
type RawProfile = { name?: string; age?: string }
|
|
328
|
+
|
|
329
|
+
const normalizeProfile = (input: RawProfile) =>
|
|
330
|
+
pipe(
|
|
331
|
+
input,
|
|
332
|
+
(p) => ({ name: p.name?.trim() ?? "", age: Number.parseInt(p.age ?? "0", 10) }),
|
|
333
|
+
(p) => ({ ...p, age: Number.isNaN(p.age) ? 0 : p.age }),
|
|
334
|
+
(p) => ({ ...p, isAdult: p.age >= 18 }),
|
|
335
|
+
)
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
## Documentation
|
|
339
|
+
|
|
340
|
+
- Usage examples: `EXAMPLES.md`
|
|
341
|
+
- Fx integration notes: `docs/fx-react-integration.md`
|
|
342
|
+
- JSDoc conventions: `docs/jsdoc-style.md`
|
package/dist/adt/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export {
|
|
1
|
+
import { a as AdtCodecError, c as AdtInferInput, d as AdtValidationError, f as AdtVariant, g as AdtMatchHandlers, h as AdtVariantOf, i as AdtCodecDef, l as AdtInferOutput, m as AdtVariantNames, n as Adt, o as AdtExtractSchema, p as AdtVariantDef, r as AdtCodecConstraint, s as AdtInfer, t as createCodecError, u as AdtUnion } from "../index-C4v_3f3-.mjs";
|
|
2
|
+
export { Adt, AdtCodecConstraint, AdtCodecDef, AdtCodecError, AdtExtractSchema, AdtInfer, AdtInferInput, AdtInferOutput, AdtMatchHandlers, AdtUnion, AdtValidationError, AdtVariant, AdtVariantDef, AdtVariantNames, AdtVariantOf, createCodecError };
|
package/dist/adt/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{n as e,t}from"../adt-CkRcY_GA.mjs";export{t as Adt,e as createCodecError};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{i as e,n as t,r as n,t as r}from"./equality-CD4_A1Op.mjs";import{n as i}from"./flow-CYjiodlC.mjs";import{f as a,r as o}from"./result-CgGYLp0L.mjs";function s(e,t){let n=t[e._tag];return n(e)}function c(e){return typeof e!=`object`||!e?!1:Object.getPrototypeOf(e)===null||Object.getPrototypeOf(e)===Object.prototype}function l(e){return typeof e==`function`&&`_variant`in e&&e._variant===!0}function u(e){return e.issues?o({issues:e.issues.map(e=>({message:e.message,path:e.path?.map(e=>typeof e==`object`&&`key`in e?e.key:e)}))}):a(e.value)}function d(e,t,n){let r=e[`~standard`].validate(t);if(i(r))throw Error(`Async validation not supported. Schema for "${n}" returned a Promise. Use a synchronous schema or handle async validation separately.`);return u(r)}function f(e){return t=>c(t)&&`_tag`in t&&t._tag===e}function p(e){let t=new Set(e);return e=>c(e)&&`_tag`in e&&typeof e._tag==`string`&&t.has(e._tag)}function m(e,t,n,r){return n!==void 0&&r!==void 0?{kind:e,message:t,cause:n,validationIssues:r}:n===void 0?r===void 0?{kind:e,message:t}:{kind:e,message:t,validationIssues:r}:{kind:e,message:t,cause:n}}function h(e){return{to:e=>JSON.stringify(e),from:e=>{try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`_tag`in t){let{_tag:e,...n}=t;return n}return t}catch{return null}}}}function g(e,t,n){let r=h(e),i={json:n=>{let i=d(t,{...n,_tag:e},e);if(i._tag===`Err`)return o(m(`ValidationError`,`Cannot encode invalid data: ${i.error.issues.map(e=>e.message).join(`, `)}`,void 0,i.error.issues));try{return a(r.to(i.value))}catch(e){return o(m(`EncodingError`,`JSON encoding failed: ${e instanceof Error?e.message:String(e)}`,e))}}};if(n)for(let[r,s]of Object.entries(n))i[r]=n=>{let i=d(t,{...n,_tag:e},e);if(i._tag===`Err`)return o(m(`ValidationError`,`Cannot encode invalid data: ${i.error.issues.map(e=>e.message).join(`, `)}`,void 0,i.error.issues));try{return a(s.to(i.value))}catch(e){return o(m(`EncodingError`,`Encoding with codec '${r}' failed: ${e instanceof Error?e.message:String(e)}`,e))}};return i}function _(e,t,n){let r=h(e),i={json:n=>{let i=r.from(n);if(i===null)return o(m(`DecodingError`,`Invalid JSON format`));let s=d(t,{...i,_tag:e},e);return s._tag===`Err`?o(m(`ValidationError`,`Decoded data failed schema validation`,void 0,s.error.issues)):a({...s.value,_tag:e})}};if(n)for(let[r,s]of Object.entries(n))i[r]=n=>{let i;try{i=s.from(n)}catch(e){return o(m(`DecodingError`,`Decoding with codec '${r}' threw an error`,e))}if(i===null)return o(m(`DecodingError`,`Codec '${r}' failed to decode input`));let c=d(t,{...i,_tag:e},e);return c._tag===`Err`?o(m(`ValidationError`,`Decoded data failed schema validation`,void 0,c.error.issues)):a({...c.value,_tag:e})};return i}function v(t,r,i){let s=f(t),c=g(t,r,i),l=_(t,r,i),u=n(t),p=e(t),m=e=>{let n=d(r,{...e,_tag:t},t);return n._tag===`Err`?o(n.error):a({...n.value,_tag:t})};return m._variant=!0,m._tag=t,m.schema=r,i&&(m.codecs=i),m.is=s,m.to=c,m.from=l,m.equals=u,m.hash=p,m}function y(e,n){let i=Object.keys(n),a={};for(let[e,t]of Object.entries(n))l(t)?t._tag===e?a[e]=t:t.codecs?a[e]=v(e,t.schema,t.codecs):a[e]=v(e,t.schema):a[e]=v(e,t);return{_name:e,is:p(i),equals:r(i),hash:t(i),...a}}const b={union:y,variant:v,match:s};export{m as n,b as t};
|
|
2
|
+
//# sourceMappingURL=adt-CkRcY_GA.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adt-CkRcY_GA.mjs","names":[],"sources":["../src/adt/adt.match.ts","../src/shared/is-plain-object.ts","../src/adt/adt.utils.ts","../src/adt/adt.codec.ts","../src/adt/adt.variant.ts","../src/adt/adt.union.ts","../src/adt/adt.ts"],"sourcesContent":["/**\n * Handler functions for each variant in a discriminated union.\n * Each key maps to a function that receives the variant value and returns TResult.\n *\n * @template T - The discriminated union type (must have readonly _tag)\n * @template TResult - The return type of all handlers\n */\nexport type AdtMatchHandlers<T extends { readonly _tag: string }, TResult> = {\n [K in T[\"_tag\"]]: (value: Extract<T, { readonly _tag: K }>) => TResult\n}\n\n/**\n * Exhaustive pattern matching for discriminated unions.\n *\n * TypeScript will error if any variant is missing from handlers,\n * ensuring exhaustive handling of all cases.\n *\n * @template T - The discriminated union type (must have readonly _tag)\n * @template TResult - The return type of all handlers\n * @template Handlers - The handler object type (inferred)\n * @param value - A discriminated union value with _tag\n * @param handlers - An object with a handler function for each variant\n * @returns The result of calling the matching handler\n *\n * @see {@link union} for creating discriminated unions\n * @see {@link variant} for creating individual variant types\n *\n * @example\n * ```ts\n * const Shape = union('Shape', { Circle, Square })\n * type Shape = AdtInfer<typeof Shape>\n *\n * function describeShape(shape: Shape): string {\n * return match(shape, {\n * Circle: (c) => `Circle with radius ${c.radius}`,\n * Square: (s) => `Square with size ${s.size}`,\n * })\n * }\n * ```\n */\nexport function match<\n T extends { readonly _tag: string },\n TResult,\n Handlers extends AdtMatchHandlers<T, TResult> = AdtMatchHandlers<T, TResult>,\n>(value: T, handlers: Handlers): TResult {\n const tag = value._tag as keyof Handlers\n const handler = handlers[tag]\n // oxlint-disable-next-line no-explicit-any, no-unsafe-argument, no-unsafe-type-assertion -- Required for variant dispatch\n return handler(value as any)\n}\n","/**\n * Check if a value is a plain object.\n * A plain object is an object created with `{}`, `Object.create(null)`, or `new Object()`.\n * Arrays, functions, dates, maps, etc. are not considered plain objects.\n */\nexport function isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n\n return Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype\n}\n","import { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport { isPlainObject } from \"../shared/is-plain-object\"\nimport { isPromise } from \"../shared/is-promise\"\nimport type { AdtVariant, AdtValidationError } from \"./adt.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Check if a value is an AdtVariant created by variant().\n * AdtVariants are callable functions with static properties.\n */\nexport function isVariant(value: unknown): value is AdtVariant {\n return typeof value === \"function\" && \"_variant\" in value && value[\"_variant\"] === true\n}\n\n/**\n * Wrap Standard Schema validation result into our Result type.\n */\nfunction wrapValidationResult<T>(result: StandardSchemaV1.Result<T>): Result<T, AdtValidationError> {\n if (result.issues) {\n return err({\n issues: result.issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map((segment) => (typeof segment === \"object\" && \"key\" in segment ? segment.key : segment)),\n })),\n })\n }\n return ok(result.value)\n}\n\n/**\n * Validate data using a Standard Schema, enforcing sync-only validation.\n * Throws if the schema returns a Promise.\n */\nexport function validateSync<T>(\n schema: StandardSchemaV1<unknown, T>,\n data: unknown,\n _tag: string,\n): Result<T, AdtValidationError> {\n const result = schema[\"~standard\"].validate(data)\n\n if (isPromise(result)) {\n throw new Error(\n `Async validation not supported. Schema for \"${_tag}\" returned a Promise. ` +\n `Use a synchronous schema or handle async validation separately.`,\n )\n }\n\n return wrapValidationResult(result)\n}\n\n/**\n * Create a type guard function for a specific _tag.\n */\nexport function createIsGuard<Tag extends string, T>(\n _tag: Tag,\n): (value: unknown) => value is T & { readonly _tag: Tag } {\n return (value: unknown): value is T & { readonly _tag: Tag } => {\n return isPlainObject(value) && \"_tag\" in value && value[\"_tag\"] === _tag\n }\n}\n\n/**\n * Create a type guard function for multiple _tags (AdtUnion root guard).\n */\nexport function createIsAnyGuard<T>(_tags: readonly string[]): (value: unknown) => value is T {\n const _tagSet = new Set(_tags)\n return (value: unknown): value is T => {\n return isPlainObject(value) && \"_tag\" in value && typeof value[\"_tag\"] === \"string\" && _tagSet.has(value[\"_tag\"])\n }\n}\n","import { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport type {\n AdtCodecConstraint,\n AdtCodecDef,\n AdtCodecError,\n AdtInferInput,\n AdtInferOutput,\n AdtValidationError,\n ToMethods,\n FromMethods,\n} from \"./adt.types\"\nimport { validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a AdtCodecError with consistent structure.\n */\nexport function createCodecError(\n kind: AdtCodecError[\"kind\"],\n message: string,\n cause?: unknown,\n validationIssues?: AdtValidationError[\"issues\"],\n): AdtCodecError {\n if (cause !== undefined && validationIssues !== undefined) {\n return { kind, message, cause, validationIssues }\n }\n if (cause !== undefined) {\n return { kind, message, cause }\n }\n if (validationIssues !== undefined) {\n return { kind, message, validationIssues }\n }\n return { kind, message }\n}\n\n/**\n * Built-in JSON codec that works with any schema.\n * Encodes to JSON string and decodes with JSON.parse.\n */\nfunction createJsonCodec<Tag extends string, S extends StandardSchemaV1>(\n _tag: Tag,\n): AdtCodecDef<AdtInferOutput<S> & Discriminator<Tag>, string, AdtInferInput<S>> {\n return {\n to: (value) => {\n // JSON.stringify can throw for circular references, BigInt, etc.\n // We let it throw and catch it in the wrapper\n return JSON.stringify(value)\n },\n /* oxlint-disable no-unsafe-assignment, no-unsafe-type-assertion, no-unsafe-return -- Required for JSON parsing which returns unknown types */\n from: (input: string) => {\n try {\n const parsed = JSON.parse(input)\n // Return parsed object without _tag - it will be added during validation\n if (typeof parsed === \"object\" && parsed !== null && \"_tag\" in parsed) {\n const { _tag: _, ...rest } = parsed\n return rest as AdtInferInput<S>\n }\n return parsed\n } catch {\n return null\n }\n },\n /* oxlint-enable no-unsafe-assignment, no-unsafe-type-assertion, no-unsafe-return */\n }\n}\n\n/**\n * Create the \"to\" methods object with JSON codec and custom codecs.\n * All methods return Result<T, AdtCodecError> for consistent error handling.\n */\nexport function createToMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): ToMethods<S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const jsonCodec = createJsonCodec<Tag, S>(_tag)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const to: Record<string, (value: AdtInferInput<S>) => Result<any, AdtCodecError>> = {\n json: (value: AdtInferInput<S>): Result<string, AdtCodecError> => {\n // First, create a validated variant to ensure the encoded payload is well-typed.\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input into object\n const taggedInput = { ...(value as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(\", \")}`,\n undefined,\n result.error.issues,\n ),\n )\n }\n\n try {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for validated value cast\n return ok(jsonCodec.to(result.value as Output))\n } catch (e) {\n return err(\n createCodecError(\"EncodingError\", `JSON encoding failed: ${e instanceof Error ? e.message : String(e)}`, e),\n )\n }\n },\n }\n\n // Add custom codecs\n if (customCodecs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [name, codec] of Object.entries(customCodecs) as Array<[string, AdtCodecDef<Output, any, any>]>) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n to[name] = (value: AdtInferInput<S>): Result<any, AdtCodecError> => {\n // Validate input first\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input\n const taggedInput = { ...(value as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(\", \")}`,\n undefined,\n result.error.issues,\n ),\n )\n }\n\n try {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for validated value cast\n return ok(codec.to(result.value as Output))\n } catch (e) {\n return err(\n createCodecError(\n \"EncodingError\",\n `Encoding with codec '${name}' failed: ${e instanceof Error ? e.message : String(e)}`,\n e,\n ),\n )\n }\n }\n }\n }\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic return type\n return to as ToMethods<S, Codecs>\n}\n\n/**\n * Create the \"from\" methods object with JSON codec and custom codecs.\n * All methods return Result<T, AdtCodecError> for consistent error handling.\n */\nexport function createFromMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): FromMethods<Tag, S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const jsonCodec = createJsonCodec<Tag, S>(_tag)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const from: Record<string, (input: any) => Result<Output, AdtCodecError>> = {\n json: (input: string): Result<Output, AdtCodecError> => {\n // Decode\n const decoded = jsonCodec.from(input)\n if (decoded === null) {\n return err(createCodecError(\"DecodingError\", \"Invalid JSON format\"))\n }\n\n // Validate through schema\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading decoded value\n const taggedInput = { ...(decoded as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\"ValidationError\", \"Decoded data failed schema validation\", undefined, result.error.issues),\n )\n }\n\n // Ensure _tag in output\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n },\n }\n\n // Add custom codecs\n if (customCodecs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [name, codec] of Object.entries(customCodecs) as Array<[string, AdtCodecDef<Output, any, any>]>) {\n from[name] = (input: unknown): Result<Output, AdtCodecError> => {\n // Decode\n let decoded: unknown\n try {\n decoded = codec.from(input)\n } catch (e) {\n return err(createCodecError(\"DecodingError\", `Decoding with codec '${name}' threw an error`, e))\n }\n\n if (decoded === null) {\n return err(createCodecError(\"DecodingError\", `Codec '${name}' failed to decode input`))\n }\n\n // Validate through schema\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading decoded value\n const taggedInput = { ...(decoded as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n \"Decoded data failed schema validation\",\n undefined,\n result.error.issues,\n ),\n )\n }\n\n // Ensure _tag in output\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n }\n }\n }\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic return type\n return from as FromMethods<Tag, S, Codecs>\n}\n","import { createEqualsMethod, createHashMethod } from \"../equality/equality\"\nimport { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport { createToMethods, createFromMethods } from \"./adt.codec\"\nimport type { AdtCodecConstraint, AdtInferInput, AdtInferOutput, AdtVariant, AdtValidationError } from \"./adt.types\"\nimport { createIsGuard, validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a standalone tagged variant from a Standard Schema with optional codecs.\n *\n * Variants can be used independently or composed into an AdtUnion via union().\n * All defaults should be defined at the schema level (e.g., Zod's .default()).\n *\n * @template Tag - The string literal type for the _tag discriminator\n * @template S - The Standard Schema type for validation\n * @template Codecs - Optional codec definitions for custom serialization formats\n * @param _tag - The _tag discriminator value\n * @param schema - A Standard Schema compliant validator\n * @param codecs - Optional codec definitions for custom serialization formats\n * @returns A callable AdtVariant with is(), to, and from methods\n *\n * @see {@link union} for composing variants into discriminated unions\n * @see {@link tagged} for unvalidated tagged value constructors\n *\n * @example\n * ```ts\n * const CircleSchema = z.object({\n * radius: z.number().positive(),\n * color: z.string().default('blue')\n * })\n *\n * // Basic variant with JSON codec (always included)\n * const Circle = variant('Circle', CircleSchema)\n *\n * const result = Circle({ radius: 10 })\n * // { _tag: \"Ok\", value: { _tag: \"Circle\", radius: 10, color: \"blue\" } }\n *\n * Circle.is(someValue) // type guard\n *\n * const json = Circle.to.json({ radius: 10 }) // JSON string\n * const result2 = Circle.from.json(json) // Result<Circle, AdtCodecError>\n *\n * // Variant with custom codec\n * const Circle2 = variant('Circle', CircleSchema, {\n * graphic: {\n * to: (circle) => `(${circle.radius})`,\n * from: (input: string) => {\n * const match = input.match(/^\\((\\d+)\\)$/)\n * return match ? { radius: parseInt(match[1]!) } : null\n * }\n * }\n * })\n *\n * const graphic = Circle2.to.graphic({ radius: 10 }) // \"(10)\"\n * const result3 = Circle2.from.graphic(\"(10)\") // Result<Circle, AdtCodecError>\n * ```\n */\n// Overload: with codecs\nexport function variant<Tag extends string, S extends StandardSchemaV1, Codecs extends AdtCodecConstraint<Tag, S>>(\n _tag: Tag,\n schema: S,\n codecs: Codecs,\n): AdtVariant<Tag, S, Codecs>\n\n// Overload: without codecs\nexport function variant<Tag extends string, S extends StandardSchemaV1>(_tag: Tag, schema: S): AdtVariant<Tag, S>\n\n// Implementation\nexport function variant<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined,\n>(_tag: Tag, schema: S, codecs?: Codecs): AdtVariant<Tag, S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const isGuard = createIsGuard<Tag, Output>(_tag)\n const to = createToMethods(_tag, schema, codecs)\n const from = createFromMethods(_tag, schema, codecs)\n const equals = createEqualsMethod<Tag, AdtInferOutput<S>>(_tag)\n const hash = createHashMethod<Tag, AdtInferOutput<S>>(_tag)\n\n // Constructor function\n const constructor = (input: AdtInferInput<S>): Result<Output, AdtValidationError> => {\n // Add _tag to the input before validation\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input\n const taggedInput = { ...(input as object), _tag }\n\n // Validate using the schema\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(result.error)\n }\n\n // Ensure _tag is in the output (schema might strip unknown keys)\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n }\n\n // Attach static properties to constructor function\n constructor._variant = true as const\n constructor._tag = _tag\n constructor.schema = schema\n if (codecs) {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Conditional assignment of codecs\n ;(constructor as { codecs?: Codecs }).codecs = codecs\n }\n constructor.is = isGuard\n constructor.to = to\n constructor.from = from\n constructor.equals = equals\n constructor.hash = hash\n\n return constructor as AdtVariant<Tag, S, Codecs>\n}\n","import { createADTEqualsMethod, createADTHashMethod } from \"../equality/equality\"\nimport { variant } from \"./adt.variant\"\nimport type { AdtUnion, AdtVariantDef, AdtVariant } from \"./adt.types\"\nimport { createIsAnyGuard, isVariant } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Compose records or schemas into a discriminated union (AdtUnion).\n *\n * Accepts either:\n * - Pre-built AdtVariants from variant() (codecs are preserved)\n * - Raw Standard Schema validators (will be wrapped internally)\n *\n * When using pre-built records, the object key overrides the original _tag.\n *\n * @template R - Record of variant names to AdtVariants or StandardSchema validators\n * @param name - The name of this AdtUnion (for identification)\n * @param records - An object mapping _tag names to AdtVariants or schemas\n * @returns An AdtUnion object with accessors for each variant\n *\n * @see {@link variant} for creating individual variant types\n * @see {@link match} for exhaustive pattern matching on AdtUnion values\n *\n * @example\n * ```ts\n * // From pre-built variants\n * const Circle = variant('Circle', CircleSchema)\n * const Square = variant('Square', SquareSchema)\n * const Shape = union('Shape', { Circle, Square })\n *\n * // From raw schemas (JSON codec is automatically included)\n * const Shape = union('Shape', {\n * Circle: CircleSchema,\n * Square: SquareSchema\n * })\n *\n * // JSON codec works on all variants\n * Shape.Circle.to.json({ radius: 10 })\n * Shape.Circle.from.json(jsonString)\n *\n * // Mixed\n * const Shape = union('Shape', {\n * Circle, // Pre-built variant\n * Square: SquareSchema // Raw schema\n * })\n *\n * // Usage\n * Shape.Circle({ radius: 10 })\n * Shape.is(someValue) // type guard for any variant\n * Shape.Circle.is(someValue) // type guard for Circle\n * ```\n */\nexport function union<R extends Record<string, AdtVariantDef>>(name: string, records: R): AdtUnion<R> {\n const tags = Object.keys(records)\n const variants: Record<string, AdtVariant> = {}\n\n for (const [_tag, def] of Object.entries(records)) {\n if (isVariant(def)) {\n // Pre-built AdtVariant - key overrides original _tag\n if (def._tag === _tag) {\n // _tag matches key, use as-is (preserves codecs)\n variants[_tag] = def\n // oxlint-disable-next-line strict-boolean-expressions -- codecs can be undefined\n } else if (def.codecs) {\n // _tag differs from key - create new variant with key as _tag\n // Preserve codecs\n variants[_tag] = variant(_tag, def.schema, def.codecs)\n } else {\n // _tag differs from key and no codecs\n variants[_tag] = variant(_tag, def.schema)\n }\n } else {\n // Raw schema - wrap in variant\n // Note: Even without custom codecs, this still gets JSON codec!\n // oxlint-disable-next-line no-unsafe-type-assertion -- def is a StandardSchemaV1 in this branch\n variants[_tag] = variant(_tag, def as StandardSchemaV1)\n }\n }\n\n // Create the root type guard for any variant\n const isAnyVariant = createIsAnyGuard(tags)\n const equals = createADTEqualsMethod(tags)\n const hash = createADTHashMethod(tags)\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic AdtUnion return type\n return {\n _name: name,\n is: isAnyVariant,\n equals,\n hash,\n ...variants,\n } as AdtUnion<R>\n}\n","import { match } from \"./adt.match\"\nimport { union } from \"./adt.union\"\nimport { variant } from \"./adt.variant\"\n\nexport const Adt = {\n union,\n variant,\n match,\n} as const\n"],"mappings":"0JAwCA,SAAgB,EAId,EAAU,EAA6B,CAEvC,IAAM,EAAU,EADJ,EAAM,MAGlB,OAAO,EAAQ,EAAa,CC3C9B,SAAgB,EAAc,EAAuD,CAKnF,OAJsB,OAAO,GAAU,WAAnC,EACK,GAGF,OAAO,eAAe,EAAM,GAAK,MAAQ,OAAO,eAAe,EAAM,GAAK,OAAO,UCC1F,SAAgB,EAAU,EAAqC,CAC7D,OAAO,OAAO,GAAU,YAAc,aAAc,GAAS,EAAM,WAAgB,GAMrF,SAAS,EAAwB,EAAmE,CASlG,OARI,EAAO,OACF,EAAI,CACT,OAAQ,EAAO,OAAO,IAAK,IAAW,CACpC,QAAS,EAAM,QACf,KAAM,EAAM,MAAM,IAAK,GAAa,OAAO,GAAY,UAAY,QAAS,EAAU,EAAQ,IAAM,EAAS,CAC9G,EAAE,CACJ,CAAC,CAEG,EAAG,EAAO,MAAM,CAOzB,SAAgB,EACd,EACA,EACA,EAC+B,CAC/B,IAAM,EAAS,EAAO,aAAa,SAAS,EAAK,CAEjD,GAAI,EAAU,EAAO,CACnB,MAAU,MACR,+CAA+C,EAAK,uFAErD,CAGH,OAAO,EAAqB,EAAO,CAMrC,SAAgB,EACd,EACyD,CACzD,MAAQ,IACC,EAAc,EAAM,EAAI,SAAU,GAAS,EAAM,OAAY,EAOxE,SAAgB,EAAoB,EAA0D,CAC5F,IAAM,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A,UACA,QACD"}
|
|
@@ -5,4 +5,4 @@ type λ<TA extends any[] = any[], TR = any> = (...args: TA) => TR;
|
|
|
5
5
|
type ApplyFn<F extends λ, Arg> = F extends ((arg: Arg) => infer R) ? R : F extends ((arg: any) => infer R) ? R : never;
|
|
6
6
|
//#endregion
|
|
7
7
|
export { λ as n, ApplyFn as t };
|
|
8
|
-
//# sourceMappingURL=apply-fn.types-
|
|
8
|
+
//# sourceMappingURL=apply-fn.types-0g_9eXRy.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apply-fn.types-
|
|
1
|
+
{"version":3,"file":"apply-fn.types-0g_9eXRy.d.mts","names":[],"sources":["../src/shared/lambda.types.ts","../src/shared/apply-fn.types.ts"],"sourcesContent":[],"mappings":";KACY,kDAAkD,OAAO;;;ACMzD,KAAA,OAAO,CAAA,UAAW,CAAX,EAAA,GAAA,CAAA,GAAqB,CAArB,UAAA,CAAA,GAAA,EAAqC,GAArC,EAAA,GAAA,KAAA,EAAA,IAAA,CAAA,GAEf,CAFe,UAAA,CAAA,GAAA,EAAA,GAAA,EAAA,GAAA,KAAA,EAAA,IAAA,CAAA,GAAA,KAAA"}
|
package/dist/brand/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as unsafeMake, c as BrandKey, d as Unbrand, i as refine, l as BrandRefinement, n as is, o as Brand$1, r as make, s as BrandError, t as Brand, u as Branded } from "../index-
|
|
1
|
+
import { a as unsafeMake, c as BrandKey, d as Unbrand, i as refine, l as BrandRefinement, n as is, o as Brand$1, r as make, s as BrandError, t as Brand, u as Branded } from "../index-jeC5jyRh.mjs";
|
|
2
2
|
export { Brand, BrandError, BrandKey, BrandRefinement, Brand$1 as BrandType, Branded, Unbrand, is, make, refine, unsafeMake };
|
package/dist/brand/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,i as t,n,r,t as i}from"../brand-
|
|
1
|
+
import{a as e,i as t,n,r,t as i}from"../brand-Gy0kW6-n.mjs";export{i as Brand,n as is,r as make,t as refine,e as unsafeMake};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./result-
|
|
2
|
-
//# sourceMappingURL=brand-
|
|
1
|
+
import{t as e}from"./result-CgGYLp0L.mjs";const t=e=>e,n=e=>e,r=e=>t=>e(t),i=(t,n)=>r=>{if(!t(r)){let t=typeof n==`function`?n(r):n??`Brand validation failed`;return e.err({_tag:`BrandError`,value:r,message:t})}return e.ok(r)},a={make:t,unsafeMake:n,is:r,refine:i};export{n as a,i,r as n,t as r,a as t};
|
|
2
|
+
//# sourceMappingURL=brand-Gy0kW6-n.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"brand-Gy0kW6-n.mjs","names":[],"sources":["../src/brand/brand.ts"],"sourcesContent":["import { Result } from \"../result\"\nimport type { Result as ResultType } from \"../result/result.types\"\nimport type { BrandError, Branded, Unbrand, Validator } from \"./brand.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Branding is a deliberate nominal cast at the type level and requires explicit assertions. */\n\n/**\n * Create a branded value without validation.\n * This is a type-level cast with zero runtime cost.\n *\n * Use this when you trust the value source (e.g., from a database)\n * or when validation happens elsewhere.\n *\n * @template B - The branded type\n * @param value - The value to brand\n * @returns The value as a branded type\n *\n * @example\n * ```ts\n * type UserId = Branded<string, \"UserId\">\n *\n * // Trust the value from database\n * const userId = Brand.make<UserId>(row.id)\n *\n * // Or use in a validated factory\n * function createUserId(input: string): UserId {\n * if (!input.startsWith(\"user_\")) throw new Error(\"Invalid\")\n * return Brand.make<UserId>(input)\n * }\n * ```\n */\nexport const make = <B extends Branded<unknown, string>>(value: Unbrand<B>): B => {\n return value as B\n}\n\n/**\n * Alias for make() - explicitly indicates no validation occurs.\n * Prefer this when readability about the lack of validation is important.\n *\n * @template B - The branded type\n * @param value - The value to brand (unchecked)\n * @returns The value as a branded type\n *\n * @example\n * ```ts\n * type PositiveNumber = Branded<number, \"PositiveNumber\">\n *\n * // Explicitly unsafe - reader knows no validation\n * const n = Brand.unsafeMake<PositiveNumber>(-5) // No error, but logically wrong\n * ```\n */\nexport const unsafeMake = <B extends Branded<unknown, string>>(value: Unbrand<B>): B => {\n return value as B\n}\n\n/**\n * Create a type guard with validation for a branded type.\n * Returns a refinement predicate that narrows to the branded type.\n *\n * @template T - The base type\n * @template K - The brand key (string literal)\n * @param validator - A function that validates the base value\n * @returns A type guard that returns true if validation passes\n *\n * @example\n * ```ts\n * type PositiveNumber = Branded<number, \"PositiveNumber\">\n *\n * const isPositive = Brand.is<number, \"PositiveNumber\">(n => n > 0)\n *\n * const value: number = 42\n * if (isPositive(value)) {\n * // value is now PositiveNumber\n * acceptPositive(value) // OK\n * }\n * ```\n */\nexport const is = <T, K extends string>(validator: Validator<T>): ((value: T) => value is Branded<T, K>) => {\n return (value: T): value is Branded<T, K> => validator(value)\n}\n\n/**\n * Create a validated branded value wrapped in a Result.\n * Returns `Result.ok(brandedValue)` on success, `Result.err(BrandError)` on failure.\n *\n * The returned Result is yieldable in Fx.gen computations via `yield*`.\n *\n * @template B - The branded type\n * @param validator - A function that validates the base value\n * @param errorMessage - Optional custom error message (or function)\n * @returns A function that takes a value and returns a Result\n *\n * @example\n * ```ts\n * type Email = Branded<string, \"Email\">\n *\n * const parseEmail = Brand.refine<Email>(\n * s => s.includes(\"@\"),\n * (v) => `Invalid email: ${v}`\n * )\n *\n * // Basic usage\n * const result = parseEmail(\"user@example.com\")\n * // { _tag: \"Ok\", value: \"user@example.com\" }\n *\n * const bad = parseEmail(\"not-an-email\")\n * // { _tag: \"Err\", error: { _tag: \"BrandError\", value: \"not-an-email\", message: \"...\" } }\n *\n * // With Fx.gen computation\n * const computation = Fx.gen(function* () {\n * const email = yield* parseEmail(input)\n * return email\n * })\n *\n * // With pipe\n * pipe(\n * userInput,\n * parseEmail,\n * Result.map(email => sendTo(email)),\n * Result.unwrapOr(defaultEmail)\n * )\n * ```\n */\nexport const refine = <B extends Branded<unknown, string>>(\n validator: Validator<Unbrand<B>>,\n errorMessage?: string | ((value: Unbrand<B>) => string),\n): ((value: Unbrand<B>) => ResultType<B, BrandError<Unbrand<B>>>) => {\n return (value: Unbrand<B>) => {\n if (!validator(value)) {\n const msg = typeof errorMessage === \"function\" ? errorMessage(value) : (errorMessage ?? \"Brand validation failed\")\n return Result.err({ _tag: \"BrandError\" as const, value, message: msg })\n }\n return Result.ok(value as B)\n }\n}\n\n/**\n * Brand namespace containing utilities for nominal typing in TypeScript.\n *\n * Brand types add type-level distinctiveness to primitive types without\n * any runtime overhead. This prevents accidental mixing of semantically\n * different values that share the same structural type.\n *\n * @example\n * ```ts\n * import { Brand } from \"@nicolastoulemont/std\"\n * import type { Branded } from \"@nicolastoulemont/std\"\n *\n * // Define branded types\n * type UserId = Branded<string, \"UserId\">\n * type Email = Branded<string, \"Email\">\n *\n * // Create values\n * const userId = Brand.make<UserId>(\"user-123\")\n * const isValidEmail = Brand.is<Email>(s => s.includes(\"@\"))\n *\n * // Type safety\n * function sendEmail(email: Email) { ... }\n * sendEmail(userId) // Type error! UserId is not Email\n * ```\n */\nexport const Brand = {\n make,\n unsafeMake,\n is,\n refine,\n} as const\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"0CA+BA,MAAa,EAA4C,GAChD,EAmBI,EAAkD,GACtD,EAyBI,EAA2B,GAC9B,GAAqC,EAAU,EAAM,CA6ClD,GACX,EACA,IAEQ,GAAsB,CAC5B,GAAI,CAAC,EAAU,EAAM,CAAE,CACrB,IAAM,EAAM,OAAO,GAAiB,WAAa,EAAa,EAAM,CAAI,GAAgB,0BACxF,OAAO,EAAO,IAAI,CAAE,KAAM,aAAuB,QAAO,QAAS,EAAK,CAAC,CAEzE,OAAO,EAAO,GAAG,EAAW,EA6BnB,EAAQ,CACnB,OACA,aACA,KACA,SACD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&&e(r,Symbol.toStringTag,{value:`Module`}),r};export{t};
|
package/dist/data/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
export { ArrayValue, StructValue, TaggedConstructor, TaggedValue, TupleValue
|
|
1
|
+
import { a as TaggedValue, i as TaggedConstructor, n as ArrayValue, o as TupleValue, r as StructValue, t as Data } from "../index-BzYtgdX0.mjs";
|
|
2
|
+
export { ArrayValue, Data, StructValue, TaggedConstructor, TaggedValue, TupleValue };
|
package/dist/data/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{t as e}from"../data-C0_3MGwm.mjs";export{e as Data};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as e,i as t,o as n,r}from"./equality-CD4_A1Op.mjs";function i(t){let r=[...t];Object.defineProperty(r,`equals`,{value:t=>e(r,t),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(r,`hash`,{value:()=>n(r),enumerable:!1,writable:!1,configurable:!1});let a=r.map.bind(r);Object.defineProperty(r,`map`,{value:e=>i(a(e)),enumerable:!1,writable:!1,configurable:!1});let o=r.filter.bind(r);Object.defineProperty(r,`filter`,{value:e=>i(o(e)),enumerable:!1,writable:!1,configurable:!1});let s=r.slice.bind(r);Object.defineProperty(r,`slice`,{value:(e,t)=>i(s(e,t)),enumerable:!1,writable:!1,configurable:!1});let c=r.concat.bind(r);return Object.defineProperty(r,`concat`,{value:(...e)=>i(c(...e)),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(r)}function a(t){let r={...t};return Object.defineProperty(r,`equals`,{value:t=>e(r,t),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(r,`hash`,{value:()=>n(r),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(r)}function o(e){let n=t=>Object.freeze({...t,_tag:e});return n.is=t=>typeof t==`object`&&!!t&&`_tag`in t&&t._tag===e,n.equals=r(e),n.hash=t(e),n._tag=e,n}function s(...t){let r=[...t];return Object.defineProperty(r,`equals`,{value:t=>e(r,t),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(r,`hash`,{value:()=>n(r),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(r)}const c={tagged:o,struct:a,tuple:s,array:i};export{c as t};
|
|
2
|
+
//# sourceMappingURL=data-C0_3MGwm.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data-C0_3MGwm.mjs","names":[],"sources":["../src/data/data.array.ts","../src/data/data.struct.ts","../src/data/data.tagged.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 { 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","import { array } from \"./data.array\"\nimport { struct } from \"./data.struct\"\nimport { tagged } from \"./data.tagged\"\nimport { tuple } from \"./data.tuple\"\n\nexport const Data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,OAAO,eAAe,EAAO,OAAQ,CACnC,UAAa,EAAS,EAAM,CAC5B,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGK,OAAO,OAAO,EAAM,CClB7B,SAAgB,EAA0C,EAA+C,CAIvG,IAAM,EAAe,GACZ,OAAO,OAAO,CAAE,GAAG,EAAO,KAAM,EAAK,CAAC,CAuB/C,MAnBA,GAAY,GAAM,GAEd,OAAO,GAAU,YACjB,GACA,SAAU,GAET,EAAwB,OAAS,EAKtC,EAAY,OAAS,EAAkC,EAAI,CAG3D,EAAY,KAAO,EAAgC,EAAI,CAGvD,EAAY,KAAO,EAEZ,EC/BT,SAAgB,EAAoC,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,CChD7B,MAAa,EAAO,CAClB,SACA,SACA,QACA,QACD"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"discriminator.types-9PxvrZki.d.mts","names":[],"sources":["../src/shared/discriminator.types.ts"],"sourcesContent":[],"mappings":";KAAY;EAAA,SAAA,IAAA,EAA8D,GAAjD"}
|
package/dist/either/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as FlatMapReturn, C as unwrapOr, D as BimapReturn, E as AllObjectReturn, F as OrElseReturn, I as Right, L as RightValue, M as LeftValue, N as MapLeftReturn, O as Either$1, P as MapReturn, R as TapReturn, S as toResult, T as AllArrayReturn, _ as right, a as flatMap, b as tapLeft, c as fromPredicate, d as isRight, f as left, g as orElse, h as match, i as filter, j as Left, k as FilterReturn, l as fromResult, m as mapLeft, n as all, o as fromNullable, p as map, r as bimap, s as fromOption, t as Either, u as isLeft, v as swap, w as unwrapOrElse, x as toOption, y as tap } from "../index-
|
|
1
|
+
import { A as FlatMapReturn, C as unwrapOr, D as BimapReturn, E as AllObjectReturn, F as OrElseReturn, I as Right, L as RightValue, M as LeftValue, N as MapLeftReturn, O as Either$1, P as MapReturn, R as TapReturn, S as toResult, T as AllArrayReturn, _ as right, a as flatMap, b as tapLeft, c as fromPredicate, d as isRight, f as left, g as orElse, h as match, i as filter, j as Left, k as FilterReturn, l as fromResult, m as mapLeft, n as all, o as fromNullable, p as map, r as bimap, s as fromOption, t as Either, u as isLeft, v as swap, w as unwrapOrElse, x as toOption, y as tap } from "../index-CklRfom5.mjs";
|
|
2
2
|
export { AllArrayReturn, AllObjectReturn, BimapReturn, Either, Either$1 as EitherType, FilterReturn, FlatMapReturn, Left, LeftValue, MapLeftReturn, MapReturn, OrElseReturn, Right, RightValue, TapReturn, all, bimap, filter, flatMap, fromNullable, fromOption, fromPredicate, fromResult, isLeft, isRight, left, map, mapLeft, match, orElse, right, swap, tap, tapLeft, toOption, toResult, unwrapOr, unwrapOrElse };
|
package/dist/either/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{C as e,S as t,_ as n,a as r,b as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y,v as b,w as x,x as S,y as C}from"../either-
|
|
1
|
+
import{C as e,S as t,_ as n,a as r,b as i,c as a,d as o,f as s,g as c,h as l,i as u,l as d,m as f,n as p,o as m,p as h,r as g,s as _,t as v,u as y,v as b,w as x,x as S,y as C}from"../either-CPzK-s8W.mjs";export{v as Either,p as all,g as bimap,u as filter,r as flatMap,m as fromNullable,_ as fromOption,a as fromPredicate,d as fromResult,y as isLeft,o as isRight,s as left,h as map,f as mapLeft,l as match,c as orElse,n as right,b as swap,C as tap,i as tapLeft,S as toOption,t as toResult,e as unwrapOr,x as unwrapOrElse};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./fx.types-CDVjDn_3.mjs";import{n as t,t as n}from"./pipeable-BA0mXhs4.mjs";import{n as r}from"./flow-CYjiodlC.mjs";import{t as i}from"./result-CgGYLp0L.mjs";import{i as a,n as o}from"./option-DawZC1cE.mjs";const s=t=>({_tag:`Right`,value:t,[e]:{_A:()=>t,_E:()=>void 0,_R:()=>void 0},pipe:n,*[Symbol.iterator](){return t}}),c=t=>({_tag:`Left`,value:t,[e]:{_A:()=>t,_E:()=>void 0,_R:()=>void 0},pipe:n,*[Symbol.iterator](){return t}}),l=e=>e._tag===`Right`,u=e=>e._tag===`Left`,d=t(2,(e,t)=>{if(e._tag===`Left`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(s):s(n)}),f=t(2,(e,t)=>{if(e._tag===`Right`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(c):c(n)}),p=t(3,(e,t,n)=>{if(e._tag===`Right`){let t=n(e.value);return r(t)?Promise.resolve(t).then(s):s(t)}let i=t(e.value);return r(i)?Promise.resolve(i).then(c):c(i)}),m=t(2,(e,t)=>e._tag===`Left`?e:t(e.value)),h=t(2,(e,t)=>{if(e._tag===`Left`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(()=>e):e}),g=t(2,(e,t)=>{if(e._tag===`Right`)return e;let n=t(e.value);return r(n)?Promise.resolve(n).then(()=>e):e}),_=t(2,(e,t)=>e._tag===`Right`?e:t(e.value)),v=()=>e=>e._tag===`Left`?s(e.value):c(e.value),y=t(3,(e,t,n)=>e._tag===`Left`||t(e.value)?e:c(n(e.value))),b=e=>{if(Array.isArray(e)){let t=[];for(let n of e){if(n._tag===`Left`)return n;t.push(n.value)}return s(t)}let t={};for(let n in e){let r=e[n];if(r._tag===`Left`)return r;t[n]=r.value}return s(t)},x=t(2,(e,t)=>e._tag===`Right`?e.value:t),S=t(2,(e,t)=>e._tag===`Right`?e.value:t(e.value)),C=t(2,(e,t)=>e._tag===`Right`?t.Right(e.value):t.Left(e.value)),w=e=>e._tag===`Ok`?s(e.value):c(e.error),T=e=>e._tag===`Right`?i.ok(e.value):i.err(e.value),E=(e,t)=>e._tag===`Some`?s(e.value):c(t()),D=e=>e._tag===`Right`?a(e.value):o(),O=(e,t)=>e==null?c(t()):s(e),k=(e,t,n)=>t(e)?s(e):c(n(e)),A={left:c,right:s,isLeft:u,isRight:l,map:d,mapLeft:f,bimap:p,flatMap:m,tap:h,tapLeft:g,orElse:_,swap:v,filter:y,all:b,unwrapOr:x,unwrapOrElse:S,match:C,fromResult:w,toResult:T,fromOption:E,toOption:D,fromNullable:O,fromPredicate:k};export{x as C,T as S,s as _,m as a,g as b,k as c,l as d,c as f,_ as g,C as h,y as i,w as l,f as m,b as n,O as o,d as p,p as r,E as s,A as t,u,v,S as w,D as x,h as y};
|
|
2
|
+
//# sourceMappingURL=either-CPzK-s8W.mjs.map
|