effect-app 4.0.0-beta.6 → 4.0.0-beta.60

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.
Files changed (130) hide show
  1. package/CHANGELOG.md +265 -0
  2. package/dist/Config.d.ts +7 -0
  3. package/dist/Config.d.ts.map +1 -0
  4. package/dist/Config.js +6 -0
  5. package/dist/ConfigProvider.d.ts +39 -0
  6. package/dist/ConfigProvider.d.ts.map +1 -0
  7. package/dist/ConfigProvider.js +42 -0
  8. package/dist/{ServiceMap.d.ts → Context.d.ts} +9 -12
  9. package/dist/Context.d.ts.map +1 -0
  10. package/dist/Context.js +87 -0
  11. package/dist/Effect.d.ts +8 -7
  12. package/dist/Effect.d.ts.map +1 -1
  13. package/dist/Effect.js +3 -2
  14. package/dist/Layer.d.ts +5 -4
  15. package/dist/Layer.d.ts.map +1 -1
  16. package/dist/Layer.js +1 -1
  17. package/dist/Operations.d.ts +51 -15
  18. package/dist/Operations.d.ts.map +1 -1
  19. package/dist/Pure.d.ts +2 -2
  20. package/dist/Pure.d.ts.map +1 -1
  21. package/dist/Pure.js +13 -13
  22. package/dist/Schema/Class.d.ts +39 -1
  23. package/dist/Schema/Class.d.ts.map +1 -1
  24. package/dist/Schema/Class.js +89 -12
  25. package/dist/Schema/SpecialJsonSchema.d.ts +40 -0
  26. package/dist/Schema/SpecialJsonSchema.d.ts.map +1 -0
  27. package/dist/Schema/SpecialJsonSchema.js +199 -0
  28. package/dist/Schema/SpecialOpenApi.d.ts +30 -0
  29. package/dist/Schema/SpecialOpenApi.d.ts.map +1 -0
  30. package/dist/Schema/SpecialOpenApi.js +120 -0
  31. package/dist/Schema/brand.d.ts +8 -5
  32. package/dist/Schema/brand.d.ts.map +1 -1
  33. package/dist/Schema/brand.js +1 -1
  34. package/dist/Schema/email.d.ts.map +1 -1
  35. package/dist/Schema/email.js +4 -3
  36. package/dist/Schema/ext.d.ts +142 -44
  37. package/dist/Schema/ext.d.ts.map +1 -1
  38. package/dist/Schema/ext.js +145 -35
  39. package/dist/Schema/moreStrings.d.ts.map +1 -1
  40. package/dist/Schema/moreStrings.js +6 -4
  41. package/dist/Schema/numbers.d.ts +8 -8
  42. package/dist/Schema/numbers.js +2 -2
  43. package/dist/Schema/phoneNumber.d.ts.map +1 -1
  44. package/dist/Schema/phoneNumber.js +3 -2
  45. package/dist/Schema.d.ts +21 -54
  46. package/dist/Schema.d.ts.map +1 -1
  47. package/dist/Schema.js +43 -64
  48. package/dist/client/apiClientFactory.d.ts +3 -3
  49. package/dist/client/apiClientFactory.d.ts.map +1 -1
  50. package/dist/client/apiClientFactory.js +12 -13
  51. package/dist/client/errors.d.ts +8 -0
  52. package/dist/client/errors.d.ts.map +1 -1
  53. package/dist/client/errors.js +35 -10
  54. package/dist/client/makeClient.d.ts +13 -12
  55. package/dist/client/makeClient.d.ts.map +1 -1
  56. package/dist/client/makeClient.js +5 -2
  57. package/dist/http/Request.d.ts.map +1 -1
  58. package/dist/http/Request.js +5 -5
  59. package/dist/ids.d.ts +1 -1
  60. package/dist/ids.d.ts.map +1 -1
  61. package/dist/ids.js +1 -1
  62. package/dist/index.d.ts +6 -8
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +7 -9
  65. package/dist/middleware.d.ts +2 -2
  66. package/dist/middleware.d.ts.map +1 -1
  67. package/dist/middleware.js +3 -3
  68. package/dist/rpc/MiddlewareMaker.d.ts +4 -3
  69. package/dist/rpc/MiddlewareMaker.d.ts.map +1 -1
  70. package/dist/rpc/MiddlewareMaker.js +6 -5
  71. package/dist/rpc/RpcContextMap.d.ts +2 -2
  72. package/dist/rpc/RpcContextMap.d.ts.map +1 -1
  73. package/dist/rpc/RpcContextMap.js +4 -4
  74. package/dist/rpc/RpcMiddleware.d.ts +4 -3
  75. package/dist/rpc/RpcMiddleware.d.ts.map +1 -1
  76. package/dist/rpc/RpcMiddleware.js +1 -1
  77. package/dist/utils/gen.d.ts +1 -1
  78. package/dist/utils/gen.d.ts.map +1 -1
  79. package/dist/utils/logger.d.ts +2 -2
  80. package/dist/utils/logger.d.ts.map +1 -1
  81. package/dist/utils/logger.js +3 -3
  82. package/dist/utils.d.ts +18 -0
  83. package/dist/utils.d.ts.map +1 -1
  84. package/dist/utils.js +24 -5
  85. package/package.json +29 -17
  86. package/src/Config.ts +14 -0
  87. package/src/ConfigProvider.ts +48 -0
  88. package/src/{ServiceMap.ts → Context.ts} +16 -17
  89. package/src/Effect.ts +11 -9
  90. package/src/Layer.ts +5 -4
  91. package/src/Pure.ts +17 -18
  92. package/src/Schema/Class.ts +114 -16
  93. package/src/Schema/SpecialJsonSchema.ts +216 -0
  94. package/src/Schema/SpecialOpenApi.ts +126 -0
  95. package/src/Schema/brand.ts +13 -7
  96. package/src/Schema/email.ts +4 -2
  97. package/src/Schema/ext.ts +222 -57
  98. package/src/Schema/moreStrings.ts +10 -6
  99. package/src/Schema/numbers.ts +2 -2
  100. package/src/Schema/phoneNumber.ts +3 -1
  101. package/src/Schema.ts +79 -103
  102. package/src/client/apiClientFactory.ts +16 -19
  103. package/src/client/errors.ts +46 -12
  104. package/src/client/makeClient.ts +32 -12
  105. package/src/http/Request.ts +7 -4
  106. package/src/ids.ts +1 -1
  107. package/src/index.ts +6 -9
  108. package/src/middleware.ts +2 -2
  109. package/src/rpc/MiddlewareMaker.ts +7 -6
  110. package/src/rpc/RpcContextMap.ts +6 -5
  111. package/src/rpc/RpcMiddleware.ts +5 -4
  112. package/src/utils/gen.ts +1 -1
  113. package/src/utils/logger.ts +2 -2
  114. package/src/utils.ts +26 -4
  115. package/test/dist/moreStrings.test.d.ts.map +1 -0
  116. package/test/dist/rpc.test.d.ts.map +1 -1
  117. package/test/dist/special.test.d.ts.map +1 -0
  118. package/test/moreStrings.test.ts +17 -0
  119. package/test/rpc.test.ts +26 -5
  120. package/test/schema.test.ts +292 -1
  121. package/test/special.test.ts +525 -0
  122. package/test/utils.test.ts +1 -1
  123. package/tsconfig.base.json +0 -1
  124. package/tsconfig.json +0 -1
  125. package/dist/ServiceMap.d.ts.map +0 -1
  126. package/dist/ServiceMap.js +0 -91
  127. package/dist/Struct.d.ts +0 -44
  128. package/dist/Struct.d.ts.map +0 -1
  129. package/dist/Struct.js +0 -29
  130. package/src/Struct.ts +0 -54
@@ -0,0 +1,126 @@
1
+ /**
2
+ * SpecialOpenApi — Deduplicates `components/schemas` entries in an OpenAPI spec.
3
+ *
4
+ * When `OpenApi.fromApi` generates the spec, different AST nodes sharing the
5
+ * same identifier can produce duplicate entries (e.g. "X" and "X1") in
6
+ * `components.schemas`. This module provides a transform function that
7
+ * collapses those duplicates and rewrites all `$ref` pointers accordingly.
8
+ *
9
+ * Usage with the OpenApi `Transform` annotation:
10
+ *
11
+ * ```ts
12
+ * import { OpenApi } from "effect/unstable"
13
+ * import { deduplicateOpenApiSchemas } from "./SpecialOpenApi.js"
14
+ *
15
+ * const api = HttpApi.make("myApi")
16
+ * .pipe(HttpApi.annotateContext(OpenApi.annotations({ transform: deduplicateOpenApiSchemas })))
17
+ * ```
18
+ */
19
+
20
+ /**
21
+ * Deduplicates `components.schemas` entries in an OpenAPI spec.
22
+ *
23
+ * Entries sharing the same base identifier (e.g. "X" and "X1") whose JSON
24
+ * representations are identical are collapsed into a single canonical entry,
25
+ * and all `$ref` pointers throughout the spec are rewritten to point to
26
+ * the canonical key.
27
+ *
28
+ * Designed to be used as the `transform` option in `OpenApi.annotations`.
29
+ */
30
+ export function deduplicateOpenApiSchemas(
31
+ spec: Record<string, any>
32
+ ): Record<string, any> {
33
+ const components = spec["components"] as Record<string, any> | undefined
34
+ if (!components) return spec
35
+ const schemas = components["schemas"] as Record<string, any> | undefined
36
+ if (!schemas) return spec
37
+
38
+ const keys = Object.keys(schemas)
39
+ if (keys.length === 0) return spec
40
+
41
+ // Group keys by base identifier (strip trailing digits)
42
+ const groups = new Map<string, Array<{ key: string; fingerprint: string }>>()
43
+ for (const key of keys) {
44
+ const base = getBaseIdentifier(key)
45
+ const fingerprint = JSON.stringify(schemas[key])
46
+ const group = groups.get(base)
47
+ if (group === undefined) {
48
+ groups.set(base, [{ key, fingerprint }])
49
+ } else {
50
+ group.push({ key, fingerprint })
51
+ }
52
+ }
53
+
54
+ // Build remapping from duplicate keys to canonical keys
55
+ const remapping = new Map<string, string>()
56
+ for (const [, group] of groups) {
57
+ if (group.length <= 1) continue
58
+ const seen = new Map<string, string>() // fingerprint -> canonical key
59
+ for (const entry of group) {
60
+ const canonical = seen.get(entry.fingerprint)
61
+ if (canonical !== undefined) {
62
+ remapping.set(entry.key, canonical)
63
+ } else {
64
+ seen.set(entry.fingerprint, entry.key)
65
+ }
66
+ }
67
+ }
68
+
69
+ if (remapping.size === 0) return spec
70
+
71
+ // Build new schemas object without duplicates
72
+ const newSchemas: Record<string, any> = {}
73
+ for (const key of keys) {
74
+ if (!remapping.has(key)) {
75
+ newSchemas[key] = schemas[key]
76
+ }
77
+ }
78
+
79
+ // Deep clone the spec, replace schemas, and rewrite all $ref pointers
80
+ const newSpec = structuredClone(spec)
81
+ newSpec["components"]["schemas"] = newSchemas
82
+ rewriteRefs(newSpec, remapping)
83
+
84
+ return newSpec
85
+ }
86
+
87
+ /**
88
+ * Extracts the base identifier from a schema key by stripping trailing
89
+ * digits appended by the gen() function.
90
+ * E.g. "X1" -> "X", "X" -> "X", "MyType2" -> "MyType"
91
+ */
92
+ function getBaseIdentifier(key: string): string {
93
+ const match = key.match(/^(.+?)(\d+)$/)
94
+ return match ? match[1]! : key
95
+ }
96
+
97
+ /**
98
+ * Recursively rewrites `$ref` values in a JSON object tree.
99
+ * Mutates the object in-place (caller should pass a deep clone).
100
+ */
101
+ function rewriteRefs(obj: any, remapping: Map<string, string>): void {
102
+ if (obj === null || typeof obj !== "object") return
103
+
104
+ if (Array.isArray(obj)) {
105
+ for (const item of obj) {
106
+ rewriteRefs(item, remapping)
107
+ }
108
+ return
109
+ }
110
+
111
+ if (typeof obj.$ref === "string") {
112
+ // OpenAPI refs look like "#/components/schemas/X1"
113
+ const prefix = "#/components/schemas/"
114
+ if (obj.$ref.startsWith(prefix)) {
115
+ const refKey = obj.$ref.slice(prefix.length)
116
+ const canonical = remapping.get(refKey)
117
+ if (canonical !== undefined) {
118
+ obj.$ref = prefix + canonical
119
+ }
120
+ }
121
+ }
122
+
123
+ for (const value of Object.values(obj)) {
124
+ rewriteRefs(value, remapping)
125
+ }
126
+ }
@@ -2,7 +2,6 @@
2
2
  /* eslint-disable @typescript-eslint/no-unsafe-return */
3
3
  import type { Option } from "effect"
4
4
  import * as B from "effect/Brand"
5
- import type * as Brand from "effect/Brand"
6
5
  import type * as Result from "effect/Result"
7
6
  import * as S from "effect/Schema"
8
7
 
@@ -21,7 +20,7 @@ export interface Constructor<in out A extends B.Brand<any>> {
21
20
  * Constructs a branded type from a value of type `A`, returning `Result.succeed`
22
21
  * if the provided `A` is valid, `Result.fail` otherwise.
23
22
  */
24
- result(args: Unbranded<A>): Result.Result<A, Brand.BrandError>
23
+ result(args: Unbranded<A>): Result.Result<A, B.BrandError>
25
24
  /**
26
25
  * Attempts to refine the provided value of type `A`, returning `true` if
27
26
  * the provided `A` is valid, `false` otherwise.
@@ -29,19 +28,26 @@ export interface Constructor<in out A extends B.Brand<any>> {
29
28
  is(a: Unbranded<A>): a is Unbranded<A> & A
30
29
  }
31
30
 
32
- export const fromBrand = <C extends Brand.Brand<string>>(
31
+ type BrandAnnotations<C extends B.Brand<any>> =
32
+ & S.Annotations.Filter
33
+ & (
34
+ C extends string ? { readonly toArbitrary?: S.Annotations.ToArbitrary.Declaration<C, readonly []> }
35
+ : {}
36
+ )
37
+
38
+ export const fromBrand = <C extends B.Brand<any>>(
33
39
  constructor: Constructor<C>,
34
- options?: S.Annotations.Filter
40
+ options?: BrandAnnotations<C>
35
41
  ) =>
36
- <Self extends S.Top>(self: Self): S.brand<Self["~rebuild.out"], Brand.Brand.Keys<C>> => {
42
+ <Self extends S.Top>(self: Self): S.brand<Self["~rebuild.out"], B.Brand.Keys<C>> => {
37
43
  const branded = S.fromBrand(options?.identifier ?? "Brand", constructor as any)(self as any)
38
44
  return options ? (branded as any).pipe(S.annotate(options)) : branded as any
39
45
  }
40
46
 
41
- export type Brands<P> = P extends B.Brand<any> ? Brand.Brand.Brands<P>
47
+ export type Brands<P> = P extends B.Brand<any> ? B.Brand.Brands<P>
42
48
  : never
43
49
 
44
- export type Unbranded<P> = P extends B.Brand<any> ? Brand.Brand.Unbranded<P> : P
50
+ export type Unbranded<P> = P extends B.Brand<any> ? B.Brand.Unbranded<P> : P
45
51
 
46
52
  export const nominal: <A extends B.Brand<any>>() => Constructor<A> = <
47
53
  A extends B.Brand<any>
@@ -16,7 +16,9 @@ export const Email = S
16
16
  identifier: "Email",
17
17
  title: "Email",
18
18
  description: "an email according to RFC 5322",
19
- jsonSchema: { format: "email", minLength: 3, /* a@b */ maxLength: 998 },
20
- arbitrary: () => (fc: any) => fc.emailAddress().map((_: any) => _ as Email)
19
+ jsonSchema: { format: "email", minLength: 3, /* a@b */ maxLength: 998 }
20
+ }),
21
+ S.annotate({
22
+ toArbitrary: () => (fc) => fc.emailAddress().map((_) => _ as Email)
21
23
  })
22
24
  )
package/src/Schema/ext.ts CHANGED
@@ -1,11 +1,20 @@
1
1
  /* eslint-disable @typescript-eslint/no-explicit-any */
2
2
  /* eslint-disable @typescript-eslint/no-unsafe-return */
3
- import { Effect, Option, pipe, Schema, type SchemaAST, SchemaGetter, SchemaIssue, SchemaParser, SchemaTransformation, type ServiceMap } from "effect"
3
+ import { Effect, Option, pipe, type SchemaAST, SchemaGetter, SchemaIssue, SchemaTransformation } from "effect"
4
4
  import * as S from "effect/Schema"
5
+ import { isDateValid } from "effect/Schema"
5
6
  import { type NonEmptyReadonlyArray } from "../Array.js"
7
+ import * as Context from "../Context.js"
6
8
  import { extendM, typedKeysOf } from "../utils.js"
7
9
  import { type AST } from "./schema.js"
8
10
 
11
+ type ProvidedCodec<Self extends S.Top, R> = S.Codec<
12
+ Self["Type"],
13
+ Self["Encoded"],
14
+ Exclude<Self["DecodingServices"], R>,
15
+ Exclude<Self["EncodingServices"], R>
16
+ >
17
+
9
18
  // TODO: v4 migration — withConstructorDefault signature changed, propertySignature removed
10
19
  // Constraint relaxed from `Self extends S.Top & S.WithoutConstructorDefault` to `Self extends S.Top`
11
20
  // because `.pipe()` widens the schema type to `Top` which doesn't satisfy `WithoutConstructorDefault`.
@@ -21,13 +30,108 @@ export const withDefaultConstructor = <A>(
21
30
  }
22
31
 
23
32
  // TODO: v4 migration - Date is no longer by default encoded to string.
24
- const DateFromString = Schema.Date.pipe(
25
- Schema.encodeTo(Schema.String, {
26
- decode: SchemaGetter.Date(),
27
- encode: SchemaGetter.transform((_) => _.toISOString())
28
- })
33
+ /*
34
+ in v4, there's the notion of `toCodecJson`, as a declaration and as a schema transformer.
35
+ this means that Date, Map/Set, etc, remain the same type Encoded as Decoded, but when transformed to and from JSON, will go through
36
+ the toCodecJson transformation, which for e.g Date will be the dateFromString transformation.
37
+
38
+ While this is a cool feature, our stack (especially the Store/Repository api) is based on having an Encoded shape representing the JSON shape, so we revert back to that for now.
39
+ */
40
+
41
+ /**
42
+ * Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for
43
+ * invalid dates instead of throwing.
44
+ *
45
+ * When to use:
46
+ * - You want a safe `toISOString()` that never throws.
47
+ *
48
+ * Behavior:
49
+ * - Returns `date.toISOString()` on success.
50
+ * - Returns `"Invalid Date"` if `toISOString()` throws (e.g. for
51
+ * `new Date(NaN)`).
52
+ * - Pure function; does not mutate input.
53
+ *
54
+ * **Example** (Safe date formatting)
55
+ *
56
+ * ```ts
57
+ * import { Formatter } from "effect"
58
+ *
59
+ * console.log(Formatter.formatDate(new Date("2024-01-15T10:30:00Z")))
60
+ * // 2024-01-15T10:30:00.000Z
61
+ *
62
+ * console.log(Formatter.formatDate(new Date("invalid")))
63
+ * // Invalid Date
64
+ * ```
65
+ *
66
+ * See also: {@link format}
67
+ *
68
+ * @internal
69
+ */
70
+ export function formatDate(date: Date): string {
71
+ try {
72
+ return date.toISOString()
73
+ } catch {
74
+ return "Invalid Date"
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Decodes a `string` into a `Date` and encodes a `Date` back to a `string`.
80
+ *
81
+ * When to use this:
82
+ * - Parsing ISO 8601 date strings from APIs or user input.
83
+ *
84
+ * Behavior:
85
+ * - Decode: creates a `Date` from the string (like `new Date(s)`).
86
+ * - Encode: converts the `Date` to an ISO string (like `date.toISOString()`),
87
+ * returning `"Invalid Date"` for invalid dates.
88
+ *
89
+ * **Example** (Date from string)
90
+ *
91
+ * ```ts
92
+ * import { Schema, SchemaTransformation } from "effect"
93
+ *
94
+ * const schema = Schema.String.pipe(
95
+ * Schema.decodeTo(Schema.Date, SchemaTransformation.dateFromString)
96
+ * )
97
+ * ```
98
+ *
99
+ * See also:
100
+ * - {@link numberFromString}
101
+ * - {@link dateTimeUtcFromString}
102
+ *
103
+ * @category Coercions
104
+ * @since 4.0.0
105
+ */
106
+ export const dateFromString: SchemaTransformation.Transformation<globalThis.Date, string> = new SchemaTransformation
107
+ .Transformation(
108
+ SchemaGetter.Date(),
109
+ SchemaGetter.transform(formatDate)
29
110
  )
30
111
 
112
+ const DateString = S.String.annotate({ expected: "a string in ISO 8601 format that will be decoded as a Date" })
113
+
114
+ /**
115
+ * Schema type for {@link DateFromString}.
116
+ *
117
+ * @category Schemas
118
+ * @since 4.0.0
119
+ */
120
+ export interface DateFromString extends S.decodeTo<S.Date, S.String> {}
121
+
122
+ /**
123
+ * A transformation schema that parses an ISO 8601 string into a `Date`.
124
+ *
125
+ * Decoding:
126
+ * - A `string` is decoded as a `Date`.
127
+ *
128
+ * Encoding:
129
+ * - A `Date` is encoded as a `string`.
130
+ *
131
+ * @since 4.0.0
132
+ */
133
+ export const DateFromString: DateFromString = DateString.pipe(S.decodeTo(S.Date, dateFromString))
134
+
31
135
  /**
32
136
  * Like the default Schema `Date` but from String with `withDefault` => now
33
137
  */
@@ -35,6 +139,13 @@ export const Date = Object.assign(DateFromString, {
35
139
  withDefault: DateFromString.pipe(withDefaultConstructor(() => new global.Date()))
36
140
  })
37
141
 
142
+ /**
143
+ * Like the default Schema `DateValid` but from String with `withDefault` => now
144
+ */
145
+ export const DateValid = Object.assign(Date.check(isDateValid()), {
146
+ withDefault: DateFromString.pipe(withDefaultConstructor(() => new global.Date()))
147
+ })
148
+
38
149
  /**
39
150
  * Like the default Schema `Boolean` but with `withDefault` => false
40
151
  */
@@ -43,10 +154,16 @@ export const Boolean = Object.assign(S.Boolean, {
43
154
  })
44
155
 
45
156
  /**
157
+ * You probably want to use `Finite` instead of this.
46
158
  * Like the default Schema `Number` but with `withDefault` => 0
47
159
  */
48
160
  export const Number = Object.assign(S.Number, { withDefault: S.Number.pipe(withDefaultConstructor(() => 0)) })
49
161
 
162
+ /**
163
+ * Like the default Schema `Finite` but with `withDefault` => 0
164
+ */
165
+ export const Finite = Object.assign(S.Finite, { withDefault: S.Finite.pipe(withDefaultConstructor(() => 0)) })
166
+
50
167
  /**
51
168
  * Like the default Schema `Literal` but with `withDefault` => literals[0]
52
169
  */
@@ -69,7 +186,7 @@ export const Literal = <Literals extends NonEmptyReadonlyArray<AST.LiteralValue>
69
186
  /**
70
187
  * Like the default Schema `Array` but with `withDefault` => []
71
188
  */
72
- export function Array<Value extends S.Top>(value: Value) {
189
+ export function Array<ValueSchema extends S.Top>(value: ValueSchema) {
73
190
  return pipe(
74
191
  S.Array(value),
75
192
  (s) => Object.assign(s, { withDefault: s.pipe(withDefaultConstructor(() => [])) })
@@ -77,60 +194,107 @@ export function Array<Value extends S.Top>(value: Value) {
77
194
  }
78
195
 
79
196
  /**
80
- * Like the default Schema `Map` but with `withDefault` => []
197
+ * An annotated `S.Array` of unique items that decodes to a `ReadonlySet`.
81
198
  */
82
- function Map_<Key extends S.Top, Value extends S.Top>(input: { key: Key; value: Value }) {
83
- return pipe(
84
- S.ReadonlyMap(input.key, input.value),
85
- (s) => Object.assign(s, { withDefault: s.pipe(withDefaultConstructor(() => new global.Map())) })
199
+ export const ReadonlySetFromArray = <ValueSchema extends S.Top>(value: ValueSchema): S.Codec<
200
+ ReadonlySet<ValueSchema["Type"]>,
201
+ readonly ValueSchema["Encoded"][],
202
+ ValueSchema["DecodingServices"],
203
+ ValueSchema["EncodingServices"]
204
+ > => {
205
+ const from = S
206
+ .Array(value)
207
+ .annotate({ expected: "an array of unique items that will be decoded as a ReadonlySet" })
208
+ const to = S.instanceOf(Set) as S.instanceOf<ReadonlySet<S.Schema.Type<ValueSchema>>>
209
+ const schema = from.pipe(
210
+ S.decodeTo(
211
+ to,
212
+ SchemaTransformation.transform({
213
+ decode: (arr) => new Set(arr) as ReadonlySet<S.Schema.Type<ValueSchema>>,
214
+ encode: (set) => [...set]
215
+ })
216
+ )
86
217
  )
218
+ return S.revealCodec(schema)
87
219
  }
88
220
 
89
- export { Map_ as Map }
221
+ /**
222
+ * An annotated `S.Array` of key-value tuples that decodes to a `ReadonlyMap`.
223
+ */
224
+ export const ReadonlyMapFromArray = <KeySchema extends S.Top, ValueSchema extends S.Top>(pair: {
225
+ readonly key: KeySchema
226
+ readonly value: ValueSchema
227
+ }): S.Codec<
228
+ ReadonlyMap<KeySchema["Type"], S.Schema.Type<ValueSchema>>,
229
+ readonly (readonly [KeySchema["Encoded"], ValueSchema["Encoded"]])[],
230
+ KeySchema["DecodingServices"] | ValueSchema["DecodingServices"],
231
+ KeySchema["EncodingServices"] | ValueSchema["EncodingServices"]
232
+ > => {
233
+ const from = S
234
+ .Array(S.Tuple([pair.key, pair.value]))
235
+ .annotate({ expected: "an array of key-value tuples that will be decoded as a ReadonlyMap" })
236
+ const to = S.instanceOf(Map) as S.instanceOf<
237
+ ReadonlyMap<S.Schema.Type<KeySchema>, S.Schema.Type<ValueSchema>>
238
+ >
239
+ const schema = from.pipe(
240
+ S.decodeTo(
241
+ to,
242
+ SchemaTransformation.transform({
243
+ decode: (
244
+ arr
245
+ ) => new Map(arr) as ReadonlyMap<S.Schema.Type<KeySchema>, S.Schema.Type<ValueSchema>>,
246
+ encode: (
247
+ map
248
+ ) => [...map.entries()] as any // fu
249
+ })
250
+ )
251
+ )
252
+ return S.revealCodec(schema)
253
+ }
90
254
 
91
255
  /**
92
- * Like the default Schema `ReadonlySet` but with `withDefault` => new Set()
256
+ * Like the default Schema `ReadonlySet` but from Array with `withDefault` => new Set()
93
257
  */
94
- export const ReadonlySet = <Value extends S.Top>(value: Value) =>
258
+ export const ReadonlySet = <ValueSchema extends S.Top>(value: ValueSchema) =>
95
259
  pipe(
96
- S.ReadonlySet(value),
97
- (s) => Object.assign(s, { withDefault: s.pipe(withDefaultConstructor(() => new Set<S.Schema.Type<Value>>())) })
260
+ ReadonlySetFromArray(value),
261
+ (s) =>
262
+ Object.assign(s, { withDefault: s.pipe(withDefaultConstructor(() => new Set<S.Schema.Type<ValueSchema>>())) })
98
263
  )
99
264
 
100
265
  /**
101
- * Like the default Schema `ReadonlyMap` but with `withDefault` => new Map()
266
+ * Like the default Schema `ReadonlyMap` but from Array with `withDefault` => new Map()
102
267
  */
103
- export const ReadonlyMap = <K extends S.Top, V extends S.Top>(pair: {
104
- readonly key: K
105
- readonly value: V
268
+ export const ReadonlyMap = <KeySchema extends S.Top, ValueSchema extends S.Top>(pair: {
269
+ readonly key: KeySchema
270
+ readonly value: ValueSchema
106
271
  }) =>
107
272
  pipe(
108
- S.ReadonlyMap(pair.key, pair.value),
273
+ ReadonlyMapFromArray(pair),
109
274
  (s) => Object.assign(s, { withDefault: s.pipe(withDefaultConstructor(() => new Map())) })
110
275
  )
111
276
 
112
277
  /**
113
278
  * Like the default Schema `NullOr` but with `withDefault` => null
114
279
  */
115
- export const NullOr = <S extends S.Top>(self: S) =>
280
+ export const NullOr = <Schema extends S.Top>(self: Schema) =>
116
281
  pipe(
117
282
  S.NullOr(self),
118
283
  (s) => Object.assign(s, { withDefault: s.pipe(withDefaultConstructor(() => null)) })
119
284
  )
120
285
 
121
- export const defaultDate = (s: S.Top) => s.pipe(withDefaultConstructor(() => new global.Date()))
286
+ export const defaultDate = <Schema extends S.Top>(schema: Schema) =>
287
+ schema.pipe(withDefaultConstructor(() => new global.Date()))
122
288
 
123
- export const defaultBool = (s: S.Top) => s.pipe(withDefaultConstructor(() => false))
289
+ export const defaultBool = <Schema extends S.Top>(schema: Schema) => schema.pipe(withDefaultConstructor(() => false))
124
290
 
125
- export const defaultNullable = (
126
- s: S.Top
127
- ) => s.pipe(withDefaultConstructor(() => null))
291
+ export const defaultNullable = <Schema extends S.Top>(schema: Schema) => schema.pipe(withDefaultConstructor(() => null))
128
292
 
129
- export const defaultArray = (s: S.Top) => s.pipe(withDefaultConstructor(() => []))
293
+ export const defaultArray = <Schema extends S.Top>(schema: Schema) => schema.pipe(withDefaultConstructor(() => []))
130
294
 
131
- export const defaultMap = (s: S.Top) => s.pipe(withDefaultConstructor(() => new Map()))
295
+ export const defaultMap = <Schema extends S.Top>(schema: Schema) => schema.pipe(withDefaultConstructor(() => new Map()))
132
296
 
133
- export const defaultSet = (s: S.Top) => s.pipe(withDefaultConstructor(() => new Set()))
297
+ export const defaultSet = <Schema extends S.Top>(schema: Schema) => schema.pipe(withDefaultConstructor(() => new Set()))
134
298
 
135
299
  export const withDefaultMake = <Self extends S.Top>(s: Self) => {
136
300
  const a = Object.assign(S.decodeSync(s as any) as WithDefaults<Self>, s)
@@ -160,7 +324,7 @@ export type WithDefaults<Self extends S.Top> = (
160
324
  // : never
161
325
 
162
326
  export const inputDate = extendM(
163
- S.Union([S.DateValid, S.Date]),
327
+ S.Union([S.DateValid, Date]).pipe(S.revealCodec),
164
328
  (s) => ({ withDefault: s.pipe(withDefaultConstructor(() => new globalThis.Date())) })
165
329
  )
166
330
 
@@ -211,7 +375,7 @@ export const transformTo = <To extends S.Top, From extends S.Top>(
211
375
  { message: "One way schema transformation, encoding is not allowed" }
212
376
  )
213
377
  )
214
- }) as any
378
+ })
215
379
  )
216
380
  )
217
381
 
@@ -228,7 +392,7 @@ export const transformToOrFail = <To extends S.Top, From extends S.Top, RD>(
228
392
  S.decodeTo(
229
393
  to,
230
394
  SchemaTransformation.transformOrFail({
231
- decode: decode as any,
395
+ decode,
232
396
  encode: (i: any) =>
233
397
  Effect.fail(
234
398
  new SchemaIssue.Forbidden(
@@ -236,33 +400,34 @@ export const transformToOrFail = <To extends S.Top, From extends S.Top, RD>(
236
400
  { message: "One way schema transformation, encoding is not allowed" }
237
401
  )
238
402
  )
239
- }) as any
403
+ })
240
404
  )
241
405
  )
242
406
 
243
- // TODO: v4 migration — S.declare API changed (no [self] + decode/encode pattern)
244
- // Need to find v4 equivalent for contextual schema wrapping
245
407
  export const provide = <Self extends S.Top, R>(
246
408
  self: Self,
247
- context: ServiceMap.ServiceMap<R>
248
- ): any => {
409
+ context: Context.Context<R>
410
+ ): ProvidedCodec<Self, R> => {
249
411
  const prov = Effect.provide(context)
250
- return S
251
- .declare((_u: unknown): _u is unknown => true) // placeholder — needs proper v4 declare
252
- .pipe(
253
- S.decodeTo(
254
- self,
255
- SchemaTransformation.transformOrFail({
256
- decode: (n: any) => prov(SchemaParser.decodeUnknownEffect(self)(n)),
257
- encode: (n: any) => prov(SchemaParser.encodeUnknownEffect(self)(n))
258
- }) as any
259
- ) as any
260
- )
261
- }
262
- // TODO: v4 migration — ServiceMap.pick and S.declare pattern removed
263
- export const contextFromServices = <Self extends S.Top, Tags extends readonly any[]>(
264
- _self: Self,
265
- ..._services: Tags
266
- ): any => {
267
- throw new Error("contextFromServices: not yet migrated to v4")
412
+ return self.pipe(
413
+ S.middlewareDecoding((effect) => prov(effect)),
414
+ S.middlewareEncoding((effect) => prov(effect))
415
+ ) as ProvidedCodec<Self, R>
268
416
  }
417
+ export const contextFromServices = <
418
+ Self extends S.Top,
419
+ Tags extends ReadonlyArray<Context.Key<any, any>>
420
+ >(
421
+ self: Self,
422
+ ...services: Tags
423
+ ): Effect.Effect<
424
+ ProvidedCodec<Self, Context.Service.Identifier<Tags[number]>>,
425
+ never,
426
+ Context.Service.Identifier<Tags[number]>
427
+ > =>
428
+ Effect.gen(function*() {
429
+ const context: Context.Context<Context.Service.Identifier<Tags[number]>> = Context.pick(...services)(
430
+ yield* Effect.services<Context.Service.Identifier<Tags[number]>>()
431
+ )
432
+ return provide(self, context)
433
+ })
@@ -140,10 +140,10 @@ const minLength = 6
140
140
  const maxLength = 50
141
141
  const size = 21
142
142
  const length = 10 * size
143
- const StringIdArb = (): S.LazyArbitrary<string> => (fc) =>
143
+ const StringIdArb = (): S.LazyArbitrary<StringId> => (fc) =>
144
144
  fc
145
145
  .uint8Array({ minLength: length, maxLength: length })
146
- .map((_) => customRandom(urlAlphabet, size, (size) => _.subarray(0, size))())
146
+ .map((_) => customRandom(urlAlphabet, size, (size) => _.subarray(0, size))() as StringId)
147
147
  /**
148
148
  * A string that is at least 6 characters long and a maximum of 50.
149
149
  */
@@ -154,7 +154,7 @@ export const StringId = extendM(
154
154
  fromBrand(nominal<StringId>(), {
155
155
  identifier: "StringId",
156
156
  title: "StringId",
157
- arbitrary: StringIdArb,
157
+ toArbitrary: () => (fc) => StringIdArb()(fc),
158
158
  jsonSchema: {}
159
159
  })
160
160
  ),
@@ -185,11 +185,13 @@ export function prefixedStringId<Brand extends StringId>() {
185
185
  const s: S.Codec<string & Brand, string> = StringId
186
186
  .pipe(
187
187
  S.refine((x: string): x is string & Brand => x.startsWith(pref), {
188
- arbitrary: arb,
189
188
  identifier: name,
190
189
  title: name
190
+ }),
191
+ S.annotate({
192
+ toArbitrary: () => (fc) => arb()(fc)
191
193
  })
192
- ) as any
194
+ ) as S.Codec<string & Brand, string>
193
195
  const schema = s.pipe(withDefaultMake)
194
196
  const make = () => (pref + StringId.make().substring(0, 50 - pref.length)) as Brand
195
197
 
@@ -246,10 +248,12 @@ export const Url = S
246
248
  .String
247
249
  .pipe(
248
250
  S.refine(isUrl, {
249
- arbitrary: (): S.LazyArbitrary<Url> => (fc) => fc.webUrl().map((_) => _ as Url),
250
251
  identifier: "Url",
251
252
  title: "Url",
252
253
  jsonSchema: { format: "uri" }
253
254
  }),
255
+ S.annotate({
256
+ toArbitrary: () => (fc) => fc.webUrl().map((_) => _ as Url)
257
+ }),
254
258
  withDefaultMake
255
259
  )
@@ -42,7 +42,7 @@ export type Int = number & IntBrand
42
42
 
43
43
  export interface PositiveNumberBrand extends Simplify<B.Brand<"PositiveNumber"> & NonNegativeNumberBrand> {}
44
44
  export const PositiveNumber = extendM(
45
- S.Number.pipe(
45
+ S.Finite.pipe(
46
46
  S.check(S.isGreaterThan(0)),
47
47
  fromBrand(nominal<PositiveNumber>(), {
48
48
  identifier: "PositiveNumber",
@@ -58,7 +58,7 @@ export type PositiveNumber = number & PositiveNumberBrand
58
58
  export interface NonNegativeNumberBrand extends Simplify<B.Brand<"NonNegativeNumber">> {}
59
59
  export const NonNegativeNumber = extendM(
60
60
  S
61
- .Number
61
+ .Finite
62
62
  .pipe(
63
63
  S.check(S.isGreaterThanOrEqualTo(0)),
64
64
  fromBrand(nominal<NonNegativeNumber>(), {
@@ -17,8 +17,10 @@ export const PhoneNumber = S
17
17
  identifier: "PhoneNumber",
18
18
  title: "PhoneNumber",
19
19
  description: "a phone number with at least 7 digits",
20
- arbitrary: () => (fc: any) => Numbers(7, 10)(fc).map((_: any) => _ as PhoneNumber),
21
20
  jsonSchema: { format: "phone" }
22
21
  }),
22
+ S.annotate({
23
+ toArbitrary: () => (fc) => Numbers(7, 10)(fc).map((_) => _ as PhoneNumber)
24
+ }),
23
25
  withDefaultMake
24
26
  )