viell-effect-schema-http 0.1.0 → 0.2.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 +43 -29
- package/dist/http/Body.d.ts +23 -13
- package/dist/http/Body.d.ts.map +1 -1
- package/dist/http/Body.js +18 -8
- package/dist/http/Body.js.map +1 -1
- package/dist/http/Operation.d.ts +270 -13
- package/dist/http/Operation.d.ts.map +1 -1
- package/dist/http/Operation.js +210 -11
- package/dist/http/Operation.js.map +1 -1
- package/dist/http/Policy.d.ts +3 -2
- package/dist/http/Policy.d.ts.map +1 -1
- package/dist/http/Policy.js +3 -2
- package/dist/http/Policy.js.map +1 -1
- package/dist/http/Request.d.ts +477 -85
- package/dist/http/Request.d.ts.map +1 -1
- package/dist/http/Request.js +621 -141
- package/dist/http/Request.js.map +1 -1
- package/dist/http/Response.d.ts +119 -5
- package/dist/http/Response.d.ts.map +1 -1
- package/dist/http/Response.js +88 -7
- package/dist/http/Response.js.map +1 -1
- package/dist/http/UrlEncoding.d.ts +23 -7
- package/dist/http/UrlEncoding.d.ts.map +1 -1
- package/dist/http/UrlEncoding.js +7 -3
- package/dist/http/UrlEncoding.js.map +1 -1
- package/dist/http/internal/fields.d.ts +17 -4
- package/dist/http/internal/fields.d.ts.map +1 -1
- package/dist/http/internal/fields.js +11 -6
- package/dist/http/internal/fields.js.map +1 -1
- package/dist/http/internal/input.d.ts +39 -0
- package/dist/http/internal/input.d.ts.map +1 -0
- package/dist/http/internal/input.js +40 -0
- package/dist/http/internal/input.js.map +1 -0
- package/dist/http/internal/shape.d.ts +44 -0
- package/dist/http/internal/shape.d.ts.map +1 -0
- package/dist/http/internal/shape.js +179 -0
- package/dist/http/internal/shape.js.map +1 -0
- package/package.json +12 -12
- package/src/http/Body.ts +39 -18
- package/src/http/Operation.ts +468 -33
- package/src/http/Policy.ts +3 -2
- package/src/http/Request.ts +1075 -251
- package/src/http/Response.ts +235 -22
- package/src/http/UrlEncoding.ts +31 -8
- package/src/http/internal/fields.ts +37 -9
- package/src/http/internal/input.ts +123 -0
- package/src/http/internal/shape.ts +279 -0
package/src/http/Response.ts
CHANGED
|
@@ -51,14 +51,114 @@ export class DecodeError<out E> extends Data.TaggedError("DecodeError")<{
|
|
|
51
51
|
* @remarks
|
|
52
52
|
* Build cases with {@link status} or {@link when}, then combine them with {@link orElse}.
|
|
53
53
|
* A declared status, including 4xx or 5xx, returns the decoder's value if decoding succeeds.
|
|
54
|
+
* Adjust a contract with {@link replace} and {@link remove}.
|
|
55
|
+
*
|
|
56
|
+
* `C` records each case and its key, which is what lets a replaced case leave the type. Annotating
|
|
57
|
+
* a value as `Response<A, E, R>` drops the keys, so no case of it can be addressed any more.
|
|
54
58
|
*/
|
|
55
|
-
export interface Response<
|
|
59
|
+
export interface Response<
|
|
60
|
+
out A,
|
|
61
|
+
out E = never,
|
|
62
|
+
out R = never,
|
|
63
|
+
out C extends AnyCase = AnyCase,
|
|
64
|
+
>
|
|
56
65
|
extends Pipeable.Pipeable {
|
|
57
66
|
readonly select: (metadata: Metadata) => Option.Option<Body.Decoder<A, E, R>>;
|
|
58
67
|
/** Media types contributed to the automatic `Accept` header, in declaration order. */
|
|
59
68
|
readonly accepts: ReadonlyArray<string>;
|
|
69
|
+
/** The contract's cases, in priority order. */
|
|
70
|
+
readonly cases: ReadonlyArray<C>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* One case of a contract: when it applies, what decodes it, and the key that addresses it.
|
|
75
|
+
*
|
|
76
|
+
* @remarks
|
|
77
|
+
* A {@link status} case is keyed by its status, and a {@link when} case by its `key` option, or
|
|
78
|
+
* `undefined` without one. Tags from {@link tag} are labels on results, not keys: they are optional
|
|
79
|
+
* and can repeat.
|
|
80
|
+
*/
|
|
81
|
+
export interface Case<out K, out A, out E, out R> {
|
|
82
|
+
readonly key: K;
|
|
83
|
+
readonly matches: (metadata: Metadata) => boolean;
|
|
84
|
+
readonly decoder: Body.Decoder<A, E, R>;
|
|
60
85
|
}
|
|
61
86
|
|
|
87
|
+
/** Any case of any contract: the bound of {@link Response}'s case parameter. */
|
|
88
|
+
export type AnyCase = Case<unknown, unknown, unknown, unknown>;
|
|
89
|
+
|
|
90
|
+
/** A value that can address a case: a status, or the `key` option of {@link when}. */
|
|
91
|
+
export type Key = string | number;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The results of a set of cases.
|
|
95
|
+
*
|
|
96
|
+
* @remarks
|
|
97
|
+
* This and the other helpers below are public so that the declaration of a transform held in an
|
|
98
|
+
* exported variable, such as `export const asText = Response.replace(200, Body.text)`, can name
|
|
99
|
+
* them. A private interface there stops the declaration emitting, and a private alias printed in
|
|
100
|
+
* full can lose its meaning.
|
|
101
|
+
*/
|
|
102
|
+
export type CaseValue<C> =
|
|
103
|
+
C extends Case<unknown, infer A, unknown, unknown> ? A : never;
|
|
104
|
+
|
|
105
|
+
/** The decoder failures of a set of cases. */
|
|
106
|
+
export type CaseFailure<C> =
|
|
107
|
+
C extends Case<unknown, unknown, infer E, unknown> ? E : never;
|
|
108
|
+
|
|
109
|
+
/** The services a set of cases requires. */
|
|
110
|
+
export type CaseServices<C> =
|
|
111
|
+
C extends Case<unknown, unknown, unknown, infer R> ? R : never;
|
|
112
|
+
|
|
113
|
+
type IsUnion<K, All = K> = K extends unknown
|
|
114
|
+
? [All] extends [K]
|
|
115
|
+
? false
|
|
116
|
+
: true
|
|
117
|
+
: never;
|
|
118
|
+
|
|
119
|
+
/** A record over a literal requires that key; one over `number`, `string` or a pattern does not. */
|
|
120
|
+
type IsLiteral<K> =
|
|
121
|
+
Record<never, never> extends Record<K & Key, unknown> ? false : true;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The keys of `C` that can be addressed. A widened or union key proves nothing about which case
|
|
125
|
+
* this is, so the type could not say what an edit leaves behind.
|
|
126
|
+
*/
|
|
127
|
+
export type KeyOf<C> =
|
|
128
|
+
C extends Case<infer K, unknown, unknown, unknown>
|
|
129
|
+
? IsUnion<K> extends false
|
|
130
|
+
? IsLiteral<K> extends true
|
|
131
|
+
? K
|
|
132
|
+
: never
|
|
133
|
+
: never
|
|
134
|
+
: never;
|
|
135
|
+
|
|
136
|
+
/** The cases of `C` other than those keyed exactly `K`. */
|
|
137
|
+
export type Without<C, K> =
|
|
138
|
+
C extends Case<infer CK, unknown, unknown, unknown>
|
|
139
|
+
? [CK] extends [K]
|
|
140
|
+
? never
|
|
141
|
+
: C
|
|
142
|
+
: never;
|
|
143
|
+
|
|
144
|
+
/** The compile error for a union of keys. Its one member's name is the message. */
|
|
145
|
+
export interface OneKeyAtATime<K> {
|
|
146
|
+
readonly "Pass one key at a time. Only the value passed is touched at run time, so a union of keys would leave cases the type says are gone.": K;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** The compile error for a key the contract lacks. Its one member's name is the message. */
|
|
150
|
+
export interface NoSuchCase<K> {
|
|
151
|
+
readonly "This contract has no case with this literal key. Only a literal status or `key` option can be addressed.": K;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The union check stays a separate member: nested in the other conditional it refuses nothing. The
|
|
156
|
+
* type would drop every member of the union, but at run time only the value passed is touched, so
|
|
157
|
+
* the other cases would stay and could reach a mapping that no longer expects them.
|
|
158
|
+
*/
|
|
159
|
+
type Addresses<C, K> = (IsUnion<K> extends false ? unknown : OneKeyAtATime<K>) &
|
|
160
|
+
([K] extends [KeyOf<C>] ? unknown : NoSuchCase<K>);
|
|
161
|
+
|
|
62
162
|
/**
|
|
63
163
|
* Read metadata from an Effect HTTP response without consuming its body.
|
|
64
164
|
*/
|
|
@@ -71,30 +171,65 @@ export const metadata = (
|
|
|
71
171
|
headerLines: Transport.responseHeaderLines(response),
|
|
72
172
|
});
|
|
73
173
|
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
): Response<A, E, R> => ({
|
|
174
|
+
const fromCases = <A, E, R, C extends AnyCase>(
|
|
175
|
+
cases: ReadonlyArray<C>,
|
|
176
|
+
): Response<A, E, R, C> => ({
|
|
78
177
|
...Pipeable.Prototype,
|
|
79
|
-
|
|
80
|
-
|
|
178
|
+
cases,
|
|
179
|
+
select: (info) => {
|
|
180
|
+
const selected = cases.find((entry) => entry.matches(info));
|
|
181
|
+
return selected === undefined
|
|
182
|
+
? Option.none()
|
|
183
|
+
: Option.some(selected.decoder as Body.Decoder<A, E, R>);
|
|
184
|
+
},
|
|
185
|
+
accepts: Array.from(
|
|
186
|
+
new Set(
|
|
187
|
+
cases.flatMap(({ decoder }) =>
|
|
188
|
+
decoder.mediaType === undefined ? [] : [decoder.mediaType],
|
|
189
|
+
),
|
|
190
|
+
),
|
|
191
|
+
),
|
|
81
192
|
});
|
|
82
193
|
|
|
194
|
+
/** A contract after an edit. Its signature states the types, which depend on the key removed. */
|
|
195
|
+
const edited = <Result>(cases: ReadonlyArray<AnyCase>): Result => {
|
|
196
|
+
const contract: unknown = fromCases(cases);
|
|
197
|
+
return contract as Result;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
/** The first position of a key. A key that got past the types must not silently edit nothing. */
|
|
201
|
+
const positionOf = (cases: ReadonlyArray<AnyCase>, key: Key): number => {
|
|
202
|
+
const position =
|
|
203
|
+
key === undefined ? -1 : cases.findIndex((entry) => entry.key === key);
|
|
204
|
+
if (position === -1)
|
|
205
|
+
throw new Error(
|
|
206
|
+
`This response contract has no case ${typeof key === "string" ? JSON.stringify(key) : String(key)}`,
|
|
207
|
+
);
|
|
208
|
+
return position;
|
|
209
|
+
};
|
|
210
|
+
|
|
83
211
|
/**
|
|
84
212
|
* Select a body decoder when a predicate accepts the response metadata.
|
|
85
213
|
*
|
|
214
|
+
* @example
|
|
215
|
+
* ```ts
|
|
216
|
+
* import { Body, Response } from "viell-effect-schema-http";
|
|
217
|
+
* const serverError = Response.when((info) => info.status >= 500, Body.text, {
|
|
218
|
+
* key: "server",
|
|
219
|
+
* });
|
|
220
|
+
* ```
|
|
221
|
+
*
|
|
86
222
|
* @remarks
|
|
87
223
|
* The predicate runs before body decoding. It cannot select by payload contents; use one schema
|
|
88
|
-
* with alternatives for payloads sharing the same metadata.
|
|
224
|
+
* with alternatives for payloads sharing the same metadata. A `key` lets {@link replace} and
|
|
225
|
+
* {@link remove} address the case; it has no effect on selection.
|
|
89
226
|
*/
|
|
90
|
-
export const when = <A, E, R>(
|
|
227
|
+
export const when = <A, E, R, const K extends Key | undefined = undefined>(
|
|
91
228
|
predicate: (metadata: Metadata) => boolean,
|
|
92
229
|
body: Body.Decoder<A, E, R>,
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
body.mediaType === undefined ? [] : [body.mediaType],
|
|
97
|
-
);
|
|
230
|
+
options?: { readonly key?: K },
|
|
231
|
+
): Response<A, E, R, Case<K, A, E, R>> =>
|
|
232
|
+
fromCases([{ key: options?.key as K, matches: predicate, decoder: body }]);
|
|
98
233
|
|
|
99
234
|
/**
|
|
100
235
|
* Select a body decoder for one exact HTTP status.
|
|
@@ -105,10 +240,13 @@ export const when = <A, E, R>(
|
|
|
105
240
|
* const health = Response.status(200, Body.text);
|
|
106
241
|
* ```
|
|
107
242
|
*/
|
|
108
|
-
export const status = <A, E, R>(
|
|
109
|
-
code:
|
|
243
|
+
export const status = <A, E, R, const K extends number = number>(
|
|
244
|
+
code: K,
|
|
110
245
|
body: Body.Decoder<A, E, R>,
|
|
111
|
-
): Response<A, E, R
|
|
246
|
+
): Response<A, E, R, Case<K, A, E, R>> =>
|
|
247
|
+
fromCases([
|
|
248
|
+
{ key: code, matches: (info) => info.status === code, decoder: body },
|
|
249
|
+
]);
|
|
112
250
|
|
|
113
251
|
/**
|
|
114
252
|
* Use another response contract when this one has no matching case.
|
|
@@ -118,12 +256,87 @@ export const status = <A, E, R>(
|
|
|
118
256
|
* A selected decoder's failure never tries the fallback.
|
|
119
257
|
*/
|
|
120
258
|
export const orElse =
|
|
121
|
-
<B, E2, R2>(that: Response<B, E2, R2>) =>
|
|
122
|
-
<A, E, R
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
259
|
+
<B, E2, R2, C2 extends AnyCase = AnyCase>(that: Response<B, E2, R2, C2>) =>
|
|
260
|
+
<A, E, R, C extends AnyCase = AnyCase>(
|
|
261
|
+
self: Response<A, E, R, C>,
|
|
262
|
+
): Response<A | B, E | E2, R | R2, C | C2> =>
|
|
263
|
+
fromCases([...self.cases, ...that.cases]);
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Replace the decoder of the case with this key, keeping its position and its match rule.
|
|
267
|
+
*
|
|
268
|
+
* @example
|
|
269
|
+
* ```ts
|
|
270
|
+
* import { Body, Response } from "viell-effect-schema-http";
|
|
271
|
+
* const full = Response.status(200, Body.json).pipe(
|
|
272
|
+
* Response.orElse(Response.status(404, Body.empty)),
|
|
273
|
+
* );
|
|
274
|
+
* const asText = full.pipe(Response.replace(200, Body.text));
|
|
275
|
+
* // A 200 is now text. The 404 case is unchanged, and `full` still reads JSON.
|
|
276
|
+
* ```
|
|
277
|
+
*
|
|
278
|
+
* @remarks
|
|
279
|
+
* Declaration order is priority, so only the decoder changes. If several cases share the key, the
|
|
280
|
+
* first keeps its position and the others go. The result type holds only the cases that can still
|
|
281
|
+
* occur, and the automatic `Accept` follows the new decoder.
|
|
282
|
+
*
|
|
283
|
+
* The key must be one literal the contract declares: a key that is absent, widened to `number` or
|
|
284
|
+
* `string`, or a union is a compile error. One that gets past the types with a cast throws here,
|
|
285
|
+
* when the contract is built. To add a case, use {@link orElse} or place the new case first.
|
|
286
|
+
*/
|
|
287
|
+
export const replace =
|
|
288
|
+
<const K extends Key, B, E2, R2>(key: K, body: Body.Decoder<B, E2, R2>) =>
|
|
289
|
+
<A, E, R, C extends AnyCase>(
|
|
290
|
+
self: Response<A, E, R, C> & Addresses<C, K>,
|
|
291
|
+
): Response<
|
|
292
|
+
CaseValue<Without<C, K>> | B,
|
|
293
|
+
CaseFailure<Without<C, K>> | E2,
|
|
294
|
+
CaseServices<Without<C, K>> | R2,
|
|
295
|
+
Without<C, K> | Case<K, B, E2, R2>
|
|
296
|
+
> => {
|
|
297
|
+
const position = positionOf(self.cases, key);
|
|
298
|
+
return edited(
|
|
299
|
+
self.cases.flatMap((entry, index) =>
|
|
300
|
+
index === position
|
|
301
|
+
? [{ ...entry, decoder: body }]
|
|
302
|
+
: entry.key === key
|
|
303
|
+
? []
|
|
304
|
+
: [entry],
|
|
305
|
+
),
|
|
126
306
|
);
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Remove every case with this key.
|
|
311
|
+
*
|
|
312
|
+
* @example
|
|
313
|
+
* ```ts
|
|
314
|
+
* import { Body, Response } from "viell-effect-schema-http";
|
|
315
|
+
* const full = Response.status(200, Body.json).pipe(
|
|
316
|
+
* Response.orElse(Response.status(404, Body.empty)),
|
|
317
|
+
* );
|
|
318
|
+
* const onlyFound = full.pipe(Response.remove(404));
|
|
319
|
+
* // A 404 now falls through to any later case, or fails with UnexpectedResponse.
|
|
320
|
+
* ```
|
|
321
|
+
*
|
|
322
|
+
* @remarks
|
|
323
|
+
* The result type holds only the cases that can still occur. The key follows the same rules as in
|
|
324
|
+
* {@link replace}: a key that is absent, not literal or a union is a compile error, and one that
|
|
325
|
+
* gets past the types throws here.
|
|
326
|
+
*/
|
|
327
|
+
export const remove =
|
|
328
|
+
<const K extends Key>(key: K) =>
|
|
329
|
+
<A, E, R, C extends AnyCase>(
|
|
330
|
+
self: Response<A, E, R, C> & Addresses<C, K>,
|
|
331
|
+
): Response<
|
|
332
|
+
CaseValue<Without<C, K>>,
|
|
333
|
+
CaseFailure<Without<C, K>>,
|
|
334
|
+
CaseServices<Without<C, K>>,
|
|
335
|
+
Without<C, K>
|
|
336
|
+
> => {
|
|
337
|
+
positionOf(self.cases, key);
|
|
338
|
+
return edited(self.cases.filter((entry) => entry.key !== key));
|
|
339
|
+
};
|
|
127
340
|
|
|
128
341
|
/**
|
|
129
342
|
* A decoded value labelled with its case name and response metadata.
|
package/src/http/UrlEncoding.ts
CHANGED
|
@@ -12,9 +12,18 @@ export type Query = ReadonlyArray<readonly [string, string | null]>;
|
|
|
12
12
|
* A scalar query value before conversion to URL text.
|
|
13
13
|
*
|
|
14
14
|
* @remarks
|
|
15
|
-
* `null` keeps a bare key and `undefined` omits an entry.
|
|
15
|
+
* `null` keeps a bare key and `undefined` omits an entry. A `Date` becomes its ISO text, and other
|
|
16
|
+
* values are converted to strings. An invalid `Date` has no ISO text, so it goes out as
|
|
17
|
+
* `String(value)`, and a schema such as `Schema.Date` refuses it before that.
|
|
16
18
|
*/
|
|
17
|
-
export type QueryValue =
|
|
19
|
+
export type QueryValue =
|
|
20
|
+
string | number | bigint | boolean | Date | null | undefined;
|
|
21
|
+
|
|
22
|
+
/** The URL text of a value that has one. */
|
|
23
|
+
const queryText = (value: Exclude<QueryValue, null | undefined>): string =>
|
|
24
|
+
value instanceof Date && !Number.isNaN(value.getTime())
|
|
25
|
+
? value.toISOString()
|
|
26
|
+
: String(value);
|
|
18
27
|
|
|
19
28
|
/**
|
|
20
29
|
* A record or iterable of query pairs accepted as a schema's encoded output.
|
|
@@ -37,8 +46,8 @@ export type QueryInput =
|
|
|
37
46
|
* ```
|
|
38
47
|
*
|
|
39
48
|
* @remarks
|
|
40
|
-
* Omits `undefined`, keeps `null`, and converts other scalar values to
|
|
41
|
-
* happens later through the query renderer.
|
|
49
|
+
* Omits `undefined`, keeps `null`, writes a `Date` as ISO text, and converts other scalar values to
|
|
50
|
+
* strings. URL escaping happens later through the query renderer.
|
|
42
51
|
*/
|
|
43
52
|
export const queryEntries = (input: QueryInput): Query => {
|
|
44
53
|
const entries =
|
|
@@ -48,7 +57,7 @@ export const queryEntries = (input: QueryInput): Query => {
|
|
|
48
57
|
(Array.isArray(value) ? value : [value]).flatMap((entry: QueryValue) =>
|
|
49
58
|
entry === undefined
|
|
50
59
|
? []
|
|
51
|
-
: [[key, entry === null ? null :
|
|
60
|
+
: [[key, entry === null ? null : queryText(entry)] as const],
|
|
52
61
|
),
|
|
53
62
|
);
|
|
54
63
|
};
|
|
@@ -61,11 +70,25 @@ export const queryEntries = (input: QueryInput): Query => {
|
|
|
61
70
|
* service that needs another URL representation.
|
|
62
71
|
*/
|
|
63
72
|
export interface Service {
|
|
64
|
-
/** Escape one dynamic path value;
|
|
73
|
+
/** Escape one dynamic path value; a template or renderer supplies the text between values. */
|
|
65
74
|
readonly path: (value: string) => string;
|
|
66
|
-
/**
|
|
75
|
+
/**
|
|
76
|
+
* Render ordered query entries without a leading `?`.
|
|
77
|
+
*
|
|
78
|
+
* @remarks
|
|
79
|
+
* Text written in a request's constructor stays as written and is not passed here. Where it
|
|
80
|
+
* stands between other entries, each run of them is rendered by a separate call, keeping the
|
|
81
|
+
* order of the query. A request with no entries gets one call with an empty array, and a query
|
|
82
|
+
* made only of written text gets no call, so add a fixed entry with `Request.setQuery` in a
|
|
83
|
+
* shared transform rather than here.
|
|
84
|
+
*/
|
|
67
85
|
readonly query: (entries: Query) => string;
|
|
68
|
-
/**
|
|
86
|
+
/**
|
|
87
|
+
* Combine the base origin/prefix and the request's rendered path or absolute URL.
|
|
88
|
+
*
|
|
89
|
+
* @remarks
|
|
90
|
+
* Both arrive without a fragment. A fragment in the result is moved after the query.
|
|
91
|
+
*/
|
|
69
92
|
readonly join: (base: string, path: string) => string;
|
|
70
93
|
}
|
|
71
94
|
|
|
@@ -1,22 +1,48 @@
|
|
|
1
1
|
/** A field value, or a computation that stays data until materialization. `undefined` omits the field. */
|
|
2
2
|
export type Value<A = string> = A | (() => A | undefined);
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* One declaration. A query entry written in a request's constructor also keeps that text. An edit
|
|
6
|
+
* makes a new entry, so the text falls away with the old one.
|
|
7
|
+
*/
|
|
8
|
+
export type Field<A = string> = readonly [
|
|
9
|
+
name: string,
|
|
10
|
+
value: Value<A>,
|
|
11
|
+
written?: string,
|
|
12
|
+
];
|
|
13
|
+
|
|
4
14
|
/** Ordered declarations. Entries preserve repetition and their order across names. */
|
|
5
|
-
export type Fields<A = string> = ReadonlyArray<
|
|
15
|
+
export type Fields<A = string> = ReadonlyArray<Field<A>>;
|
|
6
16
|
|
|
7
|
-
/**
|
|
8
|
-
export
|
|
17
|
+
/** The form two names are compared in. Entries keep their own spelling. */
|
|
18
|
+
export type Fold = (name: string) => string;
|
|
19
|
+
|
|
20
|
+
const exact: Fold = (name) => name;
|
|
21
|
+
|
|
22
|
+
/** Put values at a name's first position and drop its later entries, or append new entries. */
|
|
23
|
+
export const replace = <A>(
|
|
9
24
|
fields: Fields<A>,
|
|
10
25
|
name: string,
|
|
11
|
-
|
|
26
|
+
values: ReadonlyArray<Value<A>>,
|
|
27
|
+
fold: Fold = exact,
|
|
12
28
|
): Fields<A> => {
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
29
|
+
const folded = fold(name);
|
|
30
|
+
const position = fields.findIndex(([key]) => fold(key) === folded);
|
|
31
|
+
const entries = values.map((value): Field<A> => [name, value]);
|
|
32
|
+
if (position < 0) return [...fields, ...entries];
|
|
33
|
+
return fields.flatMap((entry, index): ReadonlyArray<Field<A>> =>
|
|
34
|
+
index === position ? entries : fold(entry[0]) === folded ? [] : [entry],
|
|
17
35
|
);
|
|
18
36
|
};
|
|
19
37
|
|
|
38
|
+
/** Replace a name with one value. */
|
|
39
|
+
export const set = <A>(
|
|
40
|
+
fields: Fields<A>,
|
|
41
|
+
name: string,
|
|
42
|
+
value: Value<A>,
|
|
43
|
+
fold: Fold = exact,
|
|
44
|
+
): Fields<A> => replace(fields, name, [value], fold);
|
|
45
|
+
|
|
20
46
|
export const append = <A>(
|
|
21
47
|
fields: Fields<A>,
|
|
22
48
|
name: string,
|
|
@@ -28,9 +54,11 @@ export const remove = <A>(
|
|
|
28
54
|
fields: Fields<A>,
|
|
29
55
|
name: string,
|
|
30
56
|
value?: A,
|
|
57
|
+
fold: Fold = exact,
|
|
31
58
|
): Fields<A> =>
|
|
32
59
|
fields.filter(
|
|
33
|
-
([key, entry]) =>
|
|
60
|
+
([key, entry]) =>
|
|
61
|
+
fold(key) !== fold(name) || (value !== undefined && entry !== value),
|
|
34
62
|
);
|
|
35
63
|
|
|
36
64
|
/** Evaluate every surviving computation once, omitting `undefined` results. */
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { Effect, Schema, SchemaAST } from "effect";
|
|
2
|
+
|
|
3
|
+
/** What a schema's constructor takes. This is the one place that names the `~`-prefixed key. */
|
|
4
|
+
type ConstructorInput<S extends Schema.Top> = S["~type.make.in"];
|
|
5
|
+
|
|
6
|
+
/** A field's type on the encoded side, in whichever union members have it. */
|
|
7
|
+
type EncodedField<B, K> = B extends unknown
|
|
8
|
+
? K extends keyof B
|
|
9
|
+
? B[K]
|
|
10
|
+
: never
|
|
11
|
+
: never;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Either side of a schema, chosen field by field. A list is a value, so it has no fields, and an
|
|
15
|
+
* object whose encoded side is not one, such as a `Date` from text, has none to choose from.
|
|
16
|
+
*/
|
|
17
|
+
type Fieldwise<A, B> =
|
|
18
|
+
A extends ReadonlyArray<unknown>
|
|
19
|
+
? never
|
|
20
|
+
: A extends object
|
|
21
|
+
? B extends object
|
|
22
|
+
? { readonly [K in keyof A]: A[K] | EncodedField<B, K> }
|
|
23
|
+
: never
|
|
24
|
+
: never;
|
|
25
|
+
|
|
26
|
+
/** Every key of every member. `keyof` on a union keeps only the keys all its members share. */
|
|
27
|
+
type KeysOf<T> = T extends unknown ? keyof T : never;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Leave out the sides when the mix takes everything they do, which an editor would show three times.
|
|
31
|
+
*
|
|
32
|
+
* @remarks
|
|
33
|
+
* Assignability is not enough on its own, because a stray key in a literal is an error against the
|
|
34
|
+
* mix even when the value is assignable to it. A renamed field needs its side for that reason, and
|
|
35
|
+
* a field the mix requires and one side leaves out needs its side too.
|
|
36
|
+
*/
|
|
37
|
+
type Merged<Sides, Mix> = [Sides] extends [Mix]
|
|
38
|
+
? [KeysOf<Sides>] extends [KeysOf<Mix>]
|
|
39
|
+
? Mix
|
|
40
|
+
: Sides | Mix
|
|
41
|
+
: Sides | Mix;
|
|
42
|
+
|
|
43
|
+
type EitherSide<A, B> = [A, B] extends [B, A]
|
|
44
|
+
? A
|
|
45
|
+
: Merged<A | B, Fieldwise<A, B>>;
|
|
46
|
+
|
|
47
|
+
/** What a schema-backed input takes: its decoded side, its encoded side, or a mix by field. */
|
|
48
|
+
export type Input<S extends Schema.Top> = EitherSide<
|
|
49
|
+
ConstructorInput<S>,
|
|
50
|
+
S["Encoded"]
|
|
51
|
+
>;
|
|
52
|
+
|
|
53
|
+
/** The fields of a struct or class, as they are declared, with each field's own encoding. */
|
|
54
|
+
const fieldsOf = (
|
|
55
|
+
ast: SchemaAST.AST,
|
|
56
|
+
): ReadonlyArray<{
|
|
57
|
+
readonly name: PropertyKey;
|
|
58
|
+
readonly type: SchemaAST.AST;
|
|
59
|
+
}> =>
|
|
60
|
+
ast._tag === "Objects"
|
|
61
|
+
? ast.propertySignatures
|
|
62
|
+
: ast._tag === "Declaration" && ast.encoding !== undefined
|
|
63
|
+
? fieldsOf(ast.encoding[0].to)
|
|
64
|
+
: [];
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Bring a value on either side of a schema to its decoded side.
|
|
68
|
+
*
|
|
69
|
+
* @remarks
|
|
70
|
+
* A value that fits the decoded side is read as decoded, so it is encoded once. Anything else goes
|
|
71
|
+
* through the decoder as a whole, then field by field. Both routes validate, and a value that fits
|
|
72
|
+
* neither fails with the decoded side's error, so existing failures read the same.
|
|
73
|
+
*/
|
|
74
|
+
export const toDecoded = <S extends Schema.Top>(contract: S) => {
|
|
75
|
+
const make = (input: unknown) =>
|
|
76
|
+
Effect.mapError(
|
|
77
|
+
contract.makeEffect(input),
|
|
78
|
+
(issue) => new Schema.SchemaError(issue),
|
|
79
|
+
);
|
|
80
|
+
const decode = Schema.decodeUnknownEffect(contract);
|
|
81
|
+
const byField = Effect.fnUntraced(function* (input: object) {
|
|
82
|
+
const output: Record<PropertyKey, unknown> = { ...input };
|
|
83
|
+
for (const { name, type } of fieldsOf(contract.ast))
|
|
84
|
+
if (output[name] !== undefined)
|
|
85
|
+
output[name] = yield* fromPart(type, output[name]);
|
|
86
|
+
return yield* make(output);
|
|
87
|
+
});
|
|
88
|
+
const byMember = (input: object) =>
|
|
89
|
+
contract.ast._tag === "Union"
|
|
90
|
+
? Effect.firstSuccessOf(
|
|
91
|
+
contract.ast.types.map((member) => fromPart(member, input)),
|
|
92
|
+
)
|
|
93
|
+
: byField(input);
|
|
94
|
+
return (
|
|
95
|
+
input: Input<S>,
|
|
96
|
+
): Effect.Effect<S["Type"], Schema.SchemaError, S["DecodingServices"]> =>
|
|
97
|
+
Effect.catch(make(input), (failure) =>
|
|
98
|
+
Effect.mapError(
|
|
99
|
+
Effect.catch(decode(input), (encodedFailure) =>
|
|
100
|
+
typeof input === "object" && input !== null
|
|
101
|
+
? byMember(input)
|
|
102
|
+
: Effect.fail(encodedFailure),
|
|
103
|
+
),
|
|
104
|
+
() => failure,
|
|
105
|
+
),
|
|
106
|
+
) as Effect.Effect<S["Type"], Schema.SchemaError, S["DecodingServices"]>;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/** Read a field or union member, which may be on either side of its own schema. */
|
|
110
|
+
const fromPart = (ast: SchemaAST.AST, value: unknown) =>
|
|
111
|
+
toDecoded(Schema.make<Schema.Top>(ast))(value);
|
|
112
|
+
|
|
113
|
+
/** Bring a value to the schema's decoded side, then write it. */
|
|
114
|
+
export const encoder = <S extends Schema.Top, A, R>(
|
|
115
|
+
contract: S,
|
|
116
|
+
write: (value: S["Type"]) => Effect.Effect<A, Schema.SchemaError, R>,
|
|
117
|
+
) => {
|
|
118
|
+
const decoded = toDecoded(contract);
|
|
119
|
+
return (
|
|
120
|
+
input: Input<S>,
|
|
121
|
+
): Effect.Effect<A, Schema.SchemaError, R | S["DecodingServices"]> =>
|
|
122
|
+
Effect.flatMap(decoded(input), write);
|
|
123
|
+
};
|