-
Notifications
You must be signed in to change notification settings - Fork 0
/
Codec.ts
81 lines (78 loc) · 1.96 KB
/
Codec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import type { Result } from './Result.js';
import type { JSONValue } from './JSON.js';
import { DecodeError } from './DecodeError.js';
import { decode } from './Codec/decode.js';
import { encode } from './Codec/encode.js';
import { lazy } from './Codec/lazy.js';
import { schema } from './Codec/schema.js';
export interface Codec<T> {
/**
* Returns the decoded `input`, `Result.Ok` or `Result.Error()`
*
* @example
* ```typescript
* interface SomeObject {
* foo: string
* }
* const someCodec: Codec<SomeObject> = ...;
* const input: unknown = ...;
* const decoded = Codec.decode(someCodec, input);
* ```
* @category Codec
* @param input - The value to decode
*/
codecDecode(this: void, input: unknown, context: Codec.Context<T>): Result<T, DecodeError>;
/**
* Returns the encoded `input`
*
* @example
* ```typescript
* interface SomeObject {
* foo: string
* }
* const someCodec: Codec<SomeObject> = ...;
* const someObject: SomeObject = { foo: "bar" }
* const encoded = Codec.decode(someCodec, someObject);
* ```
* @category Codec
* @param input - The value to encode
*/
codecEncode(this: void, input: T): unknown;
/**
* Returns the JSONSchema corresponding to the decoded type
*
* @example
* ```typescript
* const someCodec: Codec<unknown> = ...;
* const jsonSchema = Codec.schema(someCodec);
* ```
* @category Codec
*/
codecSchema(this: void): JSONValue;
}
/**
* @namespace
*/
export const Codec = {
decode,
encode,
lazy,
schema,
};
export namespace Codec {
export type TypeOf<V> = V extends Codec<infer Type> ? Type : never;
export interface Context<T> {
/**
* Helper that returns a new Ok result
*
* @param value
*/
ok: (value: T) => Result<T, DecodeError>;
/**
* Helper that returns a new Error result
*
* @param message
*/
error: (input: unknown, asType?: string) => Result<T, DecodeError>;
}
}