@jutsustack/api-codegen 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 +574 -141
- package/dist/cache/manifest.d.ts +0 -1
- package/dist/cache/manifest.d.ts.map +1 -1
- package/dist/cache/manifest.js +1 -1
- package/dist/cache/manifest.js.map +1 -1
- package/dist/cjs/cache/manifest.d.ts +34 -0
- package/dist/cjs/cache/manifest.js +45 -0
- package/dist/cjs/cli.d.ts +8 -0
- package/dist/cjs/cli.js +245 -0
- package/dist/cjs/codegen/emit-api.d.ts +6 -0
- package/dist/cjs/codegen/emit-api.js +108 -0
- package/dist/cjs/codegen/emit-bindings.d.ts +8 -0
- package/dist/cjs/codegen/emit-bindings.js +115 -0
- package/dist/cjs/codegen/emit-types.d.ts +10 -0
- package/dist/cjs/codegen/emit-types.js +232 -0
- package/dist/cjs/codegen/emit.d.ts +28 -0
- package/dist/cjs/codegen/emit.js +180 -0
- package/dist/cjs/codegen/files.d.ts +14 -0
- package/dist/cjs/codegen/files.js +66 -0
- package/dist/cjs/codegen/plan.d.ts +32 -0
- package/dist/cjs/codegen/plan.js +84 -0
- package/dist/cjs/codegen/print.d.ts +10 -0
- package/dist/cjs/codegen/print.js +65 -0
- package/dist/cjs/codegen/templates/bindings.d.ts +13 -0
- package/dist/cjs/codegen/templates/bindings.js +707 -0
- package/dist/cjs/codegen/templates/runtime.d.ts +2 -0
- package/dist/cjs/codegen/templates/runtime.js +1401 -0
- package/dist/cjs/codegen/templates/transports.d.ts +1 -0
- package/dist/cjs/codegen/templates/transports.js +272 -0
- package/dist/cjs/codegen/tsType.d.ts +15 -0
- package/dist/cjs/codegen/tsType.js +114 -0
- package/dist/cjs/collect/collect.d.ts +16 -0
- package/dist/cjs/collect/collect.js +472 -0
- package/dist/cjs/collect/naming.d.ts +25 -0
- package/dist/cjs/collect/naming.js +149 -0
- package/dist/cjs/collect/path.d.ts +10 -0
- package/dist/cjs/collect/path.js +67 -0
- package/dist/cjs/config/init.d.ts +37 -0
- package/dist/cjs/config/init.js +143 -0
- package/dist/cjs/config/load.d.ts +11 -0
- package/dist/cjs/config/load.js +121 -0
- package/dist/cjs/config/types.d.ts +88 -0
- package/dist/cjs/config/types.js +2 -0
- package/dist/cjs/config/validate.d.ts +8 -0
- package/dist/cjs/config/validate.js +200 -0
- package/dist/cjs/generate.d.ts +55 -0
- package/dist/cjs/generate.js +263 -0
- package/dist/cjs/index.d.ts +23 -0
- package/dist/cjs/index.js +48 -0
- package/dist/cjs/model/collection.d.ts +83 -0
- package/dist/cjs/model/collection.js +16 -0
- package/dist/cjs/model/infer.d.ts +7 -0
- package/dist/cjs/model/infer.js +95 -0
- package/dist/cjs/model/merge.d.ts +3 -0
- package/dist/cjs/model/merge.js +131 -0
- package/dist/cjs/model/reserved.d.ts +2 -0
- package/dist/cjs/model/reserved.js +128 -0
- package/dist/cjs/model/schema.d.ts +54 -0
- package/dist/cjs/model/schema.js +2 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/parsers/openapi-schema.d.ts +30 -0
- package/dist/cjs/parsers/openapi-schema.js +241 -0
- package/dist/cjs/parsers/openapi.d.ts +8 -0
- package/dist/cjs/parsers/openapi.js +435 -0
- package/dist/cjs/parsers/postman.d.ts +20 -0
- package/dist/cjs/parsers/postman.js +493 -0
- package/dist/cjs/parsers/types.d.ts +52 -0
- package/dist/cjs/parsers/types.js +2 -0
- package/dist/cjs/sources/load.d.ts +25 -0
- package/dist/cjs/sources/load.js +296 -0
- package/dist/cjs/sources/parse.d.ts +4 -0
- package/dist/cjs/sources/parse.js +50 -0
- package/dist/cjs/util/errors.d.ts +9 -0
- package/dist/cjs/util/errors.js +23 -0
- package/dist/cjs/util/fs.d.ts +7 -0
- package/dist/cjs/util/fs.js +44 -0
- package/dist/cjs/util/hash.d.ts +3 -0
- package/dist/cjs/util/hash.js +26 -0
- package/dist/cjs/util/json.d.ts +10 -0
- package/dist/cjs/util/json.js +31 -0
- package/dist/cjs/util/log.d.ts +22 -0
- package/dist/cjs/util/log.js +45 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cli.d.ts +3 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +42 -12
- package/dist/cli.js.map +1 -1
- package/dist/codegen/emit-api.d.ts +3 -1
- package/dist/codegen/emit-api.d.ts.map +1 -1
- package/dist/codegen/emit-api.js +32 -7
- package/dist/codegen/emit-api.js.map +1 -1
- package/dist/codegen/emit-bindings.d.ts +9 -0
- package/dist/codegen/emit-bindings.d.ts.map +1 -0
- package/dist/codegen/emit-bindings.js +112 -0
- package/dist/codegen/emit-bindings.js.map +1 -0
- package/dist/codegen/emit-types.d.ts +8 -1
- package/dist/codegen/emit-types.d.ts.map +1 -1
- package/dist/codegen/emit-types.js +10 -8
- package/dist/codegen/emit-types.js.map +1 -1
- package/dist/codegen/emit.d.ts +10 -1
- package/dist/codegen/emit.d.ts.map +1 -1
- package/dist/codegen/emit.js +142 -37
- package/dist/codegen/emit.js.map +1 -1
- package/dist/codegen/files.d.ts +3 -12
- package/dist/codegen/files.d.ts.map +1 -1
- package/dist/codegen/files.js +3 -12
- package/dist/codegen/files.js.map +1 -1
- package/dist/codegen/print.d.ts +1 -4
- package/dist/codegen/print.d.ts.map +1 -1
- package/dist/codegen/print.js +1 -4
- package/dist/codegen/print.js.map +1 -1
- package/dist/codegen/templates/bindings.d.ts +14 -0
- package/dist/codegen/templates/bindings.d.ts.map +1 -0
- package/dist/codegen/templates/bindings.js +705 -0
- package/dist/codegen/templates/bindings.js.map +1 -0
- package/dist/codegen/templates/runtime.d.ts +2 -1
- package/dist/codegen/templates/runtime.d.ts.map +1 -1
- package/dist/codegen/templates/runtime.js +1192 -279
- package/dist/codegen/templates/runtime.js.map +1 -1
- package/dist/codegen/templates/transports.d.ts +2 -0
- package/dist/codegen/templates/transports.d.ts.map +1 -0
- package/dist/codegen/templates/transports.js +270 -0
- package/dist/codegen/templates/transports.js.map +1 -0
- package/dist/collect/collect.d.ts +1 -11
- package/dist/collect/collect.d.ts.map +1 -1
- package/dist/collect/collect.js +21 -28
- package/dist/collect/collect.js.map +1 -1
- package/dist/collect/naming.d.ts +1 -4
- package/dist/collect/naming.d.ts.map +1 -1
- package/dist/collect/naming.js +1 -4
- package/dist/collect/naming.js.map +1 -1
- package/dist/collect/path.d.ts +2 -9
- package/dist/collect/path.d.ts.map +1 -1
- package/dist/collect/path.js +2 -9
- package/dist/collect/path.js.map +1 -1
- package/dist/config/init.d.ts +11 -2
- package/dist/config/init.d.ts.map +1 -1
- package/dist/config/init.js +55 -7
- package/dist/config/init.js.map +1 -1
- package/dist/config/load.d.ts.map +1 -1
- package/dist/config/load.js +26 -1
- package/dist/config/load.js.map +1 -1
- package/dist/config/types.d.ts +13 -5
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/validate.d.ts +2 -6
- package/dist/config/validate.d.ts.map +1 -1
- package/dist/config/validate.js +18 -7
- package/dist/config/validate.js.map +1 -1
- package/dist/generate.d.ts +2 -8
- package/dist/generate.d.ts.map +1 -1
- package/dist/generate.js +13 -12
- package/dist/generate.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/model/infer.d.ts +2 -9
- package/dist/model/infer.d.ts.map +1 -1
- package/dist/model/infer.js +2 -9
- package/dist/model/infer.js.map +1 -1
- package/dist/model/merge.d.ts +1 -5
- package/dist/model/merge.d.ts.map +1 -1
- package/dist/model/merge.js +1 -5
- package/dist/model/merge.js.map +1 -1
- package/dist/model/reserved.d.ts +1 -4
- package/dist/model/reserved.d.ts.map +1 -1
- package/dist/model/reserved.js +63 -4
- package/dist/model/reserved.js.map +1 -1
- package/dist/model/schema.d.ts +1 -4
- package/dist/model/schema.d.ts.map +1 -1
- package/dist/parsers/openapi-schema.d.ts +1 -5
- package/dist/parsers/openapi-schema.d.ts.map +1 -1
- package/dist/parsers/openapi-schema.js +2 -5
- package/dist/parsers/openapi-schema.js.map +1 -1
- package/dist/parsers/postman.d.ts +0 -3
- package/dist/parsers/postman.d.ts.map +1 -1
- package/dist/parsers/postman.js +2 -5
- package/dist/parsers/postman.js.map +1 -1
- package/dist/sources/load.d.ts +0 -6
- package/dist/sources/load.d.ts.map +1 -1
- package/dist/sources/load.js +4 -7
- package/dist/sources/load.js.map +1 -1
- package/dist/sources/parse.d.ts +0 -2
- package/dist/sources/parse.d.ts.map +1 -1
- package/dist/sources/parse.js +1 -1
- package/dist/sources/parse.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +40 -12
- package/schema/config.schema.json +58 -12
- package/dist/codegen/emit-hooks.d.ts +0 -5
- package/dist/codegen/emit-hooks.d.ts.map +0 -1
- package/dist/codegen/emit-hooks.js +0 -67
- package/dist/codegen/emit-hooks.js.map +0 -1
- package/dist/codegen/templates/hooks.d.ts +0 -11
- package/dist/codegen/templates/hooks.d.ts.map +0 -1
- package/dist/codegen/templates/hooks.js +0 -272
- package/dist/codegen/templates/hooks.js.map +0 -1
|
@@ -1,157 +1,35 @@
|
|
|
1
|
-
// Source of the generated
|
|
2
|
-
|
|
3
|
-
const
|
|
4
|
-
type Call<A, R> = {} extends A ? (args?: A) => Promise<R> : (args: A) => Promise<R>;
|
|
5
|
-
|
|
6
|
-
/** \`{ status: 401; data: AuthError } | …\` for the documented error responses of an endpoint. */
|
|
7
|
-
export type ErrorOf<E, D = never> =
|
|
8
|
-
| { [S in keyof E]: { status: S; data: E[S] } }[keyof E]
|
|
9
|
-
| ([D] extends [never] ? never : { status: number; data: D });
|
|
10
|
-
|
|
11
|
-
/** A generated endpoint: call it for the data, \`.raw()\` for the whole response. */
|
|
12
|
-
export type Endpoint<A, R, E = {}, D = never> = Call<A, R> & {
|
|
13
|
-
/** same call, resolving the full response (status, headers, …) */
|
|
14
|
-
raw: Call<A, ApiResponse<R>>;
|
|
15
|
-
/** typed body of a documented error response; undefined for any other failure */
|
|
16
|
-
errorOf(error: unknown): ErrorOf<E, D> | undefined;
|
|
17
|
-
readonly method: HttpMethod;
|
|
18
|
-
readonly path: string;
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
export interface EndpointSpec {
|
|
22
|
-
method: HttpMethod;
|
|
23
|
-
path: string;
|
|
24
|
-
/** applied before the caller's options (headers are merged) */
|
|
25
|
-
defaults?: CallOptions;
|
|
26
|
-
/** documented error statuses */
|
|
27
|
-
errors?: readonly number[];
|
|
28
|
-
/** documented error classes: 4 for \`4XX\`, 5 for \`5XX\` */
|
|
29
|
-
errorRanges?: readonly number[];
|
|
30
|
-
/** a catch-all (\`default\`) error response is documented */
|
|
31
|
-
defaultError?: boolean;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** Bind one endpoint to a transport. Used by the generated \`createApi\`. */
|
|
35
|
-
export function endpoint<A, R, E = {}, D = never>(
|
|
36
|
-
client: ApiTransport,
|
|
37
|
-
spec: EndpointSpec
|
|
38
|
-
): Endpoint<A, R, E, D> {
|
|
39
|
-
const raw = (args?: A) => {
|
|
40
|
-
const options = { ...spec.defaults, ...(args as RequestOptions | undefined) };
|
|
41
|
-
if (spec.defaults?.headers && (args as RequestOptions | undefined)?.headers) {
|
|
42
|
-
options.headers = { ...spec.defaults.headers, ...(args as RequestOptions).headers };
|
|
43
|
-
}
|
|
44
|
-
return client.request<R>(spec.method, spec.path, options);
|
|
45
|
-
};
|
|
46
|
-
const call = (args?: A) => raw(args).then((response) => response.data);
|
|
47
|
-
const errorOf = (error: unknown) => {
|
|
48
|
-
const details = httpErrorDetails(error);
|
|
49
|
-
if (!details) return undefined;
|
|
50
|
-
const documented =
|
|
51
|
-
(spec.errors !== undefined && spec.errors.indexOf(details.status) !== -1) ||
|
|
52
|
-
(spec.errorRanges !== undefined &&
|
|
53
|
-
spec.errorRanges.indexOf(Math.floor(details.status / 100)) !== -1) ||
|
|
54
|
-
(spec.defaultError === true && details.status >= 400);
|
|
55
|
-
return documented ? details : undefined;
|
|
56
|
-
};
|
|
57
|
-
return Object.assign(call, {
|
|
58
|
-
raw,
|
|
59
|
-
errorOf,
|
|
60
|
-
method: spec.method,
|
|
61
|
-
path: spec.path,
|
|
62
|
-
}) as unknown as Endpoint<A, R, E, D>;
|
|
63
|
-
}
|
|
64
|
-
`;
|
|
65
|
-
const REACT_NATIVE = `import { isJutsuError } from '@jutsustack/react-native-fetch';
|
|
66
|
-
import type {
|
|
67
|
-
HttpMethod,
|
|
68
|
-
JutsuClient,
|
|
69
|
-
JutsuFileInput,
|
|
70
|
-
JutsuFormData,
|
|
71
|
-
JutsuResponse,
|
|
72
|
-
RequestOptions as JutsuRequestOptions,
|
|
73
|
-
} from '@jutsustack/react-native-fetch';
|
|
74
|
-
|
|
75
|
-
export type { HttpMethod };
|
|
76
|
-
|
|
77
|
-
/** Anything with \`request()\`: a client from \`createJutsuClient()\`, or a test double. */
|
|
78
|
-
export type ApiTransport = Pick<JutsuClient, 'request'>;
|
|
79
|
-
|
|
80
|
-
/** Per-call options: every react-native-fetch request option except path params and query. */
|
|
81
|
-
export type CallOptions = Omit<JutsuRequestOptions, 'params' | 'query'>;
|
|
82
|
-
|
|
83
|
-
export type RequestOptions = JutsuRequestOptions & { body?: unknown };
|
|
84
|
-
|
|
85
|
-
export type ApiResponse<T> = JutsuResponse<T>;
|
|
1
|
+
// Source of the generated runtime.ts. Inside String.raw: no backticks, no dollar braces.
|
|
2
|
+
import { TRANSPORTS } from './transports.js';
|
|
3
|
+
export const RUNTIME = String.raw `// ─── Basics ─────────────────────────────────────────────────────────────────
|
|
86
4
|
|
|
87
|
-
|
|
88
|
-
export type MultipartBody = JutsuFormData;
|
|
89
|
-
|
|
90
|
-
/** A file part (\`file://\` / \`content://\` uri, streamed natively). */
|
|
91
|
-
export type FileInput = JutsuFileInput;
|
|
92
|
-
|
|
93
|
-
export type BinaryBody = ArrayBuffer | ArrayBufferView | JutsuFileInput;
|
|
94
|
-
|
|
95
|
-
function httpErrorDetails(error: unknown): { status: number; data: unknown } | undefined {
|
|
96
|
-
return isJutsuError(error) && error.kind === 'HTTP'
|
|
97
|
-
? { status: error.status, data: error.data }
|
|
98
|
-
: undefined;
|
|
99
|
-
}
|
|
100
|
-
` + ENDPOINT;
|
|
101
|
-
const WEB = `export type HttpMethod = 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
5
|
+
export type HttpMethod = 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
102
6
|
export type QueryValue = string | number | boolean | Date | null | undefined;
|
|
103
7
|
export type Query = Record<string, QueryValue | readonly QueryValue[]>;
|
|
104
8
|
export type BodyEncoding = 'json' | 'urlencoded' | 'multipart' | 'text' | 'binary';
|
|
105
9
|
export type ResponseKind = 'json' | 'text' | 'blob' | 'arraybuffer';
|
|
10
|
+
export type HeaderValues = Record<string, string | undefined>;
|
|
106
11
|
|
|
107
|
-
/**
|
|
108
|
-
export interface
|
|
109
|
-
|
|
12
|
+
/** A file part on React Native: a file:// or content:// uri. */
|
|
13
|
+
export interface NativeFile {
|
|
14
|
+
uri: string;
|
|
15
|
+
name: string;
|
|
16
|
+
type: string;
|
|
110
17
|
}
|
|
111
18
|
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
signal?: AbortSignal;
|
|
115
|
-
/** overrides the client timeout; 0 disables it */
|
|
116
|
-
timeoutMs?: number;
|
|
117
|
-
/** body encoding; inferred when omitted (FormData → multipart, string → text, object → json) */
|
|
118
|
-
contentType?: BodyEncoding;
|
|
119
|
-
/** response decoding; inferred from Content-Type when omitted */
|
|
120
|
-
responseType?: ResponseKind;
|
|
121
|
-
/** do not attach the bearer token from \`getToken\` */
|
|
122
|
-
skipAuth?: boolean;
|
|
123
|
-
/** extra fetch() options for this call */
|
|
124
|
-
init?: FetchInit;
|
|
125
|
-
}
|
|
19
|
+
/** A file part: a Blob / File on the web, a NativeFile on React Native. */
|
|
20
|
+
export type FileInput = Blob | NativeFile;
|
|
126
21
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
query?: Query;
|
|
130
|
-
body?: unknown;
|
|
131
|
-
}
|
|
22
|
+
/** Multipart body: a FormData, or a plain fields object (encoded by the transport). */
|
|
23
|
+
export type MultipartBody = FormData;
|
|
132
24
|
|
|
133
|
-
export
|
|
134
|
-
data: T;
|
|
135
|
-
status: number;
|
|
136
|
-
headers: Record<string, string>;
|
|
137
|
-
url: string;
|
|
138
|
-
}
|
|
25
|
+
export type BinaryBody = Blob | ArrayBuffer | ArrayBufferView | NativeFile;
|
|
139
26
|
|
|
140
|
-
/**
|
|
141
|
-
export interface
|
|
142
|
-
|
|
143
|
-
method: HttpMethod,
|
|
144
|
-
path: string,
|
|
145
|
-
options?: RequestOptions
|
|
146
|
-
): Promise<ApiResponse<T>>;
|
|
27
|
+
/** Extra fetch() options: cache, credentials, mode… and Next.js next: { revalidate, tags }. */
|
|
28
|
+
export interface FetchInit extends Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'> {
|
|
29
|
+
next?: { revalidate?: number | false; tags?: string[] };
|
|
147
30
|
}
|
|
148
31
|
|
|
149
|
-
|
|
150
|
-
export type MultipartBody = FormData;
|
|
151
|
-
|
|
152
|
-
export type FileInput = Blob;
|
|
153
|
-
|
|
154
|
-
export type BinaryBody = Blob | ArrayBuffer | ArrayBufferView;
|
|
32
|
+
// ─── Errors ─────────────────────────────────────────────────────────────────
|
|
155
33
|
|
|
156
34
|
export type ApiErrorKind = 'HTTP' | 'NETWORK' | 'TIMEOUT' | 'ABORTED' | 'PARSE';
|
|
157
35
|
|
|
@@ -165,9 +43,14 @@ export class ApiError<TData = unknown> extends Error {
|
|
|
165
43
|
readonly data: TData | undefined;
|
|
166
44
|
readonly headers: Record<string, string>;
|
|
167
45
|
readonly method: HttpMethod;
|
|
46
|
+
/** full request URL, query included */
|
|
168
47
|
readonly url: string;
|
|
48
|
+
/** endpoint id ('users.getUser') when the call came from the generated api */
|
|
49
|
+
readonly endpoint: string | undefined;
|
|
169
50
|
/** underlying error (network failure, JSON syntax error, …) */
|
|
170
51
|
readonly originalError: unknown;
|
|
52
|
+
/** message for people, from the configured error messages; never server internals by default */
|
|
53
|
+
userMessage: string;
|
|
171
54
|
|
|
172
55
|
constructor(
|
|
173
56
|
kind: ApiErrorKind,
|
|
@@ -177,12 +60,14 @@ export class ApiError<TData = unknown> extends Error {
|
|
|
177
60
|
status?: number;
|
|
178
61
|
data?: TData;
|
|
179
62
|
headers?: Record<string, string>;
|
|
63
|
+
endpoint?: string | undefined;
|
|
180
64
|
message?: string;
|
|
181
65
|
originalError?: unknown;
|
|
182
66
|
}
|
|
183
67
|
) {
|
|
184
68
|
const status = init.status ?? 0;
|
|
185
|
-
|
|
69
|
+
const where = init.method + ' ' + stripQuery(init.url);
|
|
70
|
+
super(init.message ?? (status ? kind + ' ' + status + ' ' + where : kind + ' ' + where));
|
|
186
71
|
Object.setPrototypeOf(this, new.target.prototype);
|
|
187
72
|
this.name = 'ApiError';
|
|
188
73
|
this.kind = kind;
|
|
@@ -191,9 +76,25 @@ export class ApiError<TData = unknown> extends Error {
|
|
|
191
76
|
this.headers = init.headers ?? {};
|
|
192
77
|
this.method = init.method;
|
|
193
78
|
this.url = init.url;
|
|
79
|
+
this.endpoint = init.endpoint;
|
|
194
80
|
this.originalError = init.originalError;
|
|
81
|
+
this.userMessage = '';
|
|
195
82
|
Object.defineProperty(this, API_ERROR, { value: true });
|
|
196
83
|
}
|
|
84
|
+
|
|
85
|
+
/** Safe for logs: no body, headers or query string. */
|
|
86
|
+
toJSON(): Record<string, unknown> {
|
|
87
|
+
return {
|
|
88
|
+
name: this.name,
|
|
89
|
+
kind: this.kind,
|
|
90
|
+
status: this.status,
|
|
91
|
+
method: this.method,
|
|
92
|
+
url: stripQuery(this.url),
|
|
93
|
+
endpoint: this.endpoint,
|
|
94
|
+
message: this.message,
|
|
95
|
+
userMessage: this.userMessage,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
197
98
|
}
|
|
198
99
|
|
|
199
100
|
/** Works across bundles (e.g. Next.js server and client copies of this module). */
|
|
@@ -204,66 +105,567 @@ export function isApiError(error: unknown): error is ApiError {
|
|
|
204
105
|
);
|
|
205
106
|
}
|
|
206
107
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
108
|
+
/** 'https://api.example.com' (lower case) for an absolute URL, undefined for a relative one. */
|
|
109
|
+
function originOf(url: string): string | undefined {
|
|
110
|
+
const match = /^([a-z][a-z\d+\-.]*:\/\/[^/?#]*)/i.exec(url);
|
|
111
|
+
return match ? (match[1] as string).toLowerCase() : undefined;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function stripQuery(url: string): string {
|
|
115
|
+
const i = url.indexOf('?');
|
|
116
|
+
return i === -1 ? url : url.slice(0, i);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ─── Error messages ─────────────────────────────────────────────────────────
|
|
120
|
+
|
|
121
|
+
export type ErrorMessage = string | ((error: ApiError) => string | undefined);
|
|
122
|
+
|
|
123
|
+
/** Messages by status, status class, failure kind or 'default'; the most specific key wins. */
|
|
124
|
+
export interface ErrorMessages {
|
|
125
|
+
[status: number]: ErrorMessage | undefined;
|
|
126
|
+
'4XX'?: ErrorMessage;
|
|
127
|
+
'5XX'?: ErrorMessage;
|
|
128
|
+
'NETWORK'?: ErrorMessage;
|
|
129
|
+
'TIMEOUT'?: ErrorMessage;
|
|
130
|
+
'ABORTED'?: ErrorMessage;
|
|
131
|
+
'PARSE'?: ErrorMessage;
|
|
132
|
+
'default'?: ErrorMessage;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Built-in English messages; override any of them with the messages option. */
|
|
136
|
+
export const defaultErrorMessages: ErrorMessages = {
|
|
137
|
+
400: 'The request was not valid.',
|
|
138
|
+
401: 'Please sign in to continue.',
|
|
139
|
+
403: 'You do not have permission to do that.',
|
|
140
|
+
404: 'We could not find what you were looking for.',
|
|
141
|
+
408: 'The server took too long to respond. Please try again.',
|
|
142
|
+
409: 'This conflicts with the current state. Refresh and try again.',
|
|
143
|
+
413: 'That is too large to send.',
|
|
144
|
+
422: 'Some of the information is not valid.',
|
|
145
|
+
429: 'Too many requests. Please wait a moment and try again.',
|
|
146
|
+
'4XX': 'The request could not be completed.',
|
|
147
|
+
'5XX': 'Something went wrong on our side. Please try again later.',
|
|
148
|
+
'NETWORK': 'Cannot reach the server. Check your connection and try again.',
|
|
149
|
+
'TIMEOUT': 'The server took too long to respond. Please try again.',
|
|
150
|
+
'ABORTED': 'The request was cancelled.',
|
|
151
|
+
'PARSE': 'The server sent a response that could not be read.',
|
|
152
|
+
'default': 'Something went wrong. Please try again.',
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
function messageKeys(error: ApiError): Array<keyof ErrorMessages> {
|
|
156
|
+
if (error.kind !== 'HTTP') return [error.kind, 'default'];
|
|
157
|
+
const keys: Array<keyof ErrorMessages> = [error.status];
|
|
158
|
+
if (error.status >= 400 && error.status < 500) keys.push('4XX');
|
|
159
|
+
if (error.status >= 500 && error.status < 600) keys.push('5XX');
|
|
160
|
+
keys.push('default');
|
|
161
|
+
return keys;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function resolveMessage(error: ApiError, layers: ReadonlyArray<ErrorMessages | undefined>): string {
|
|
165
|
+
const keys = messageKeys(error);
|
|
166
|
+
for (const layer of layers) {
|
|
167
|
+
if (!layer) continue;
|
|
168
|
+
for (const key of keys) {
|
|
169
|
+
const entry = layer[key as number];
|
|
170
|
+
if (entry === undefined) continue;
|
|
171
|
+
let text: string | undefined;
|
|
172
|
+
try {
|
|
173
|
+
text = typeof entry === 'function' ? entry(error) : entry;
|
|
174
|
+
} catch {
|
|
175
|
+
text = undefined;
|
|
176
|
+
}
|
|
177
|
+
if (text) return text;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
return defaultErrorMessages.default as string;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** A message for people for anything a call can throw; other errors get the generic message. */
|
|
184
|
+
export function getErrorMessage(error: unknown, messages?: ErrorMessages): string {
|
|
185
|
+
if (isApiError(error)) {
|
|
186
|
+
if (!messages && error.userMessage) return error.userMessage;
|
|
187
|
+
return resolveMessage(error, [messages, defaultErrorMessages]);
|
|
188
|
+
}
|
|
189
|
+
return (messages && typeof messages.default === 'string' && messages.default) || (defaultErrorMessages.default as string);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ─── Retry ──────────────────────────────────────────────────────────────────
|
|
193
|
+
|
|
194
|
+
export interface RetryPolicy {
|
|
195
|
+
/** retries after the first attempt (default 2, max 10) */
|
|
196
|
+
attempts?: number;
|
|
197
|
+
/** delay before retry n (1-based); default 300 ms · 2^(n-1) with jitter */
|
|
198
|
+
delayMs?: number | ((attempt: number, error: ApiError) => number);
|
|
199
|
+
/** cap for every delay, Retry-After included (default 30000) */
|
|
200
|
+
maxDelayMs?: number;
|
|
201
|
+
/** default: network errors, timeouts, 408/429/500/502/503/504; only idempotent calls retry */
|
|
202
|
+
retryOn?: (error: ApiError, attempt: number) => boolean;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** false / 0: off (default) · true: the default policy · n: n retries · or a policy. */
|
|
206
|
+
export type RetryOption = boolean | number | RetryPolicy;
|
|
207
|
+
|
|
208
|
+
interface Retry {
|
|
209
|
+
attempts: number;
|
|
210
|
+
policy: RetryPolicy;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const IDEMPOTENT: readonly HttpMethod[] = ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE'];
|
|
214
|
+
const RETRY_STATUS: readonly number[] = [408, 429, 500, 502, 503, 504];
|
|
215
|
+
|
|
216
|
+
function normalizeRetry(option: RetryOption | undefined): Retry {
|
|
217
|
+
if (option === undefined || option === false) return { attempts: 0, policy: {} };
|
|
218
|
+
if (option === true) return { attempts: 2, policy: {} };
|
|
219
|
+
const policy = typeof option === 'number' ? {} : option;
|
|
220
|
+
const wanted = typeof option === 'number' ? option : (option.attempts ?? 2);
|
|
221
|
+
const attempts = Number.isFinite(wanted) ? Math.min(10, Math.max(0, Math.floor(wanted))) : 0;
|
|
222
|
+
return { attempts, policy };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function shouldRetry(error: ApiError, attempt: number, retry: Retry, idempotent: boolean): boolean {
|
|
226
|
+
if (!idempotent || error.kind === 'ABORTED' || attempt > retry.attempts) return false;
|
|
227
|
+
if (retry.policy.retryOn) {
|
|
228
|
+
try {
|
|
229
|
+
return retry.policy.retryOn(error, attempt);
|
|
230
|
+
} catch {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return error.kind === 'NETWORK' || error.kind === 'TIMEOUT' || (error.kind === 'HTTP' && RETRY_STATUS.indexOf(error.status) !== -1);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Largest delay setTimeout honours. */
|
|
238
|
+
const MAX_DELAY = 2147483647;
|
|
239
|
+
|
|
240
|
+
function delayOr(value: unknown, fallback: number): number {
|
|
241
|
+
if (typeof value !== 'number' || Number.isNaN(value) || value < 0) return fallback;
|
|
242
|
+
return Math.min(value, MAX_DELAY);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function retryDelay(error: ApiError, attempt: number, policy: RetryPolicy): number {
|
|
246
|
+
const max = delayOr(policy.maxDelayMs, 30000);
|
|
247
|
+
let delay: number;
|
|
248
|
+
if (typeof policy.delayMs === 'function') delay = policy.delayMs(attempt, error);
|
|
249
|
+
else if (typeof policy.delayMs === 'number') delay = policy.delayMs;
|
|
250
|
+
else delay = 300 * Math.pow(2, attempt - 1) * (0.75 + Math.random() * 0.5);
|
|
251
|
+
const after = retryAfterMs(error.headers['retry-after']);
|
|
252
|
+
if (after !== undefined && after > delay) delay = after;
|
|
253
|
+
return Math.min(max, Math.max(0, Number.isFinite(delay) ? delay : 0));
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function retryAfterMs(value: string | undefined): number | undefined {
|
|
257
|
+
if (!value) return undefined;
|
|
258
|
+
const seconds = Number(value);
|
|
259
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
|
|
260
|
+
const date = Date.parse(value);
|
|
261
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ─── Transport ──────────────────────────────────────────────────────────────
|
|
265
|
+
|
|
266
|
+
/** What a transport is asked to send. Headers are lower-case. */
|
|
267
|
+
export interface TransportRequest {
|
|
268
|
+
method: HttpMethod;
|
|
269
|
+
/** path params filled in and query appended; absolute when baseURL is set */
|
|
270
|
+
url: string;
|
|
271
|
+
/** endpoint path template, e.g. /users/:id */
|
|
272
|
+
path: string;
|
|
273
|
+
/** endpoint id, e.g. users.getUser */
|
|
274
|
+
endpoint: string | undefined;
|
|
275
|
+
headers: Record<string, string>;
|
|
276
|
+
/** the body as the caller passed it; encode it with encodeBody() if needed */
|
|
277
|
+
body: unknown;
|
|
278
|
+
contentType: BodyEncoding | undefined;
|
|
279
|
+
responseType: ResponseKind | undefined;
|
|
280
|
+
/** aborted on timeout or when the caller cancels */
|
|
281
|
+
signal: AbortSignal;
|
|
282
|
+
timeoutMs: number;
|
|
283
|
+
skipAuth: boolean;
|
|
284
|
+
idempotencyKey: string | undefined;
|
|
285
|
+
/** 1 for the first try */
|
|
286
|
+
attempt: number;
|
|
287
|
+
init: FetchInit | undefined;
|
|
288
|
+
/** passed through to the HTTP library untouched */
|
|
289
|
+
adapterOptions: Record<string, unknown> | undefined;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** A response as middleware sees it: lower-case headers, data decoded. */
|
|
293
|
+
export interface TransportResponse {
|
|
294
|
+
status: number;
|
|
295
|
+
headers: Record<string, string>;
|
|
296
|
+
data: unknown;
|
|
297
|
+
url?: string;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Response headers as a plain object (any case) or a Headers-like object. */
|
|
301
|
+
export type ResponseHeaders =
|
|
302
|
+
| Record<string, string | number | readonly string[] | null | undefined>
|
|
303
|
+
| { forEach(callback: (value: string, key: string) => void): void };
|
|
304
|
+
|
|
305
|
+
/** What a transport or middleware resolves with; headers and JSON text are normalised. */
|
|
306
|
+
export interface RawResponse {
|
|
307
|
+
status: number;
|
|
308
|
+
headers?: ResponseHeaders | null | undefined;
|
|
309
|
+
data?: unknown;
|
|
310
|
+
url?: string | null | undefined;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** Sends one request. Resolve for every HTTP status; reject only when no response arrived. */
|
|
314
|
+
export type Transport = (request: TransportRequest) => Promise<RawResponse>;
|
|
315
|
+
|
|
316
|
+
export type MiddlewareNext = (request: TransportRequest) => Promise<TransportResponse>;
|
|
317
|
+
|
|
318
|
+
function headerRecord(source: unknown): Record<string, string> {
|
|
319
|
+
const out: Record<string, string> = {};
|
|
320
|
+
if (!source || typeof source !== 'object') return out;
|
|
321
|
+
const add = (key: string, value: unknown) => {
|
|
322
|
+
if (value === undefined || value === null) return;
|
|
323
|
+
out[String(key).toLowerCase()] = Array.isArray(value) ? value.join(', ') : String(value);
|
|
324
|
+
};
|
|
325
|
+
// AxiosHeaders has toJSON; Headers and Map have forEach
|
|
326
|
+
const json = (source as { toJSON?: unknown }).toJSON;
|
|
327
|
+
const value = typeof json === 'function' ? (json.call(source) as unknown) : source;
|
|
328
|
+
if (!value || typeof value !== 'object') return out;
|
|
329
|
+
const each = (value as { forEach?: unknown }).forEach;
|
|
330
|
+
if (typeof each === 'function' && !Array.isArray(value)) {
|
|
331
|
+
each.call(value, (v: unknown, k: unknown) => add(String(k), v));
|
|
332
|
+
} else {
|
|
333
|
+
for (const key of Object.keys(value)) add(key, (value as Record<string, unknown>)[key]);
|
|
334
|
+
}
|
|
335
|
+
return out;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function toResponse(raw: unknown, request: TransportRequest): TransportResponse {
|
|
339
|
+
const r = raw as RawResponse | null | undefined;
|
|
340
|
+
if (!r || typeof r.status !== 'number') {
|
|
341
|
+
throw new ApiError('PARSE', {
|
|
342
|
+
method: request.method,
|
|
343
|
+
url: request.url,
|
|
344
|
+
endpoint: request.endpoint,
|
|
345
|
+
message: 'PARSE ' + request.method + ' ' + stripQuery(request.url) + ': the transport returned no response',
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
const headers = headerRecord(r.headers);
|
|
349
|
+
let data = r.data;
|
|
350
|
+
const type = headers['content-type'] || '';
|
|
351
|
+
const wantsJson = request.responseType === undefined || request.responseType === 'json';
|
|
352
|
+
if (typeof data === 'string' && wantsJson && type.indexOf('json') !== -1) {
|
|
353
|
+
if (data.trim() === '') data = undefined;
|
|
354
|
+
else {
|
|
355
|
+
try {
|
|
356
|
+
data = JSON.parse(data);
|
|
357
|
+
} catch (error) {
|
|
358
|
+
// an unreadable error body stays text
|
|
359
|
+
if (r.status >= 200 && r.status < 300) {
|
|
360
|
+
throw new ApiError('PARSE', {
|
|
361
|
+
method: request.method,
|
|
362
|
+
url: request.url,
|
|
363
|
+
status: r.status,
|
|
364
|
+
headers,
|
|
365
|
+
endpoint: request.endpoint,
|
|
366
|
+
originalError: error,
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const response: TransportResponse = { status: r.status, headers, data };
|
|
373
|
+
if (typeof r.url === 'string') response.url = r.url;
|
|
374
|
+
return response;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Wraps every attempt: call next(request) to continue, or return a response yourself. */
|
|
378
|
+
export type Middleware = (request: TransportRequest, next: MiddlewareNext) => Promise<RawResponse>;
|
|
379
|
+
|
|
380
|
+
function checkMiddleware(middleware: readonly Middleware[] | undefined, where: string): readonly Middleware[] {
|
|
381
|
+
if (middleware === undefined) return [];
|
|
382
|
+
if (!Array.isArray(middleware)) throw new TypeError(where + ': "middleware" must be an array of functions');
|
|
383
|
+
middleware.forEach((m, i) => {
|
|
384
|
+
if (typeof m !== 'function') throw new TypeError(where + ': middleware[' + i + '] is not a function');
|
|
385
|
+
});
|
|
386
|
+
return middleware;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function chain(middleware: readonly Middleware[], last: MiddlewareNext): MiddlewareNext {
|
|
390
|
+
return middleware.reduceRight<MiddlewareNext>(
|
|
391
|
+
(next, m) => (request) => Promise.resolve(m(request, next)).then((raw) => toResponse(raw, request)),
|
|
392
|
+
last
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function normalised(transport: Transport): MiddlewareNext {
|
|
397
|
+
return (request) => Promise.resolve(transport(request)).then((raw) => toResponse(raw, request));
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Wraps a transport in middleware (first = outermost). */
|
|
401
|
+
export function applyMiddleware(transport: Transport, middleware: readonly Middleware[]): Transport {
|
|
402
|
+
if (typeof transport !== 'function') throw new TypeError('applyMiddleware: "transport" must be a function');
|
|
403
|
+
return chain(checkMiddleware(middleware, 'applyMiddleware'), normalised(transport));
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// ─── Client ─────────────────────────────────────────────────────────────────
|
|
407
|
+
|
|
408
|
+
export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
|
|
409
|
+
|
|
410
|
+
export interface ApiLogger {
|
|
411
|
+
debug?(message: string, details?: Record<string, unknown>): void;
|
|
412
|
+
info?(message: string, details?: Record<string, unknown>): void;
|
|
413
|
+
warn?(message: string, details?: Record<string, unknown>): void;
|
|
414
|
+
error?(message: string, details?: Record<string, unknown>): void;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** One finished call, for performance monitoring. */
|
|
418
|
+
export interface RequestMetric {
|
|
419
|
+
endpoint: string | undefined;
|
|
420
|
+
method: HttpMethod;
|
|
421
|
+
/** path template: no ids, no query (safe to send to analytics) */
|
|
422
|
+
path: string;
|
|
423
|
+
/** 0 when no response was received */
|
|
424
|
+
status: number;
|
|
425
|
+
ok: boolean;
|
|
426
|
+
errorKind: ApiErrorKind | undefined;
|
|
427
|
+
durationMs: number;
|
|
428
|
+
attempts: number;
|
|
429
|
+
fromFallback: boolean;
|
|
430
|
+
/** slower than slowRequestMs */
|
|
431
|
+
slow: boolean;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
export interface ApiResponse<T> {
|
|
435
|
+
data: T;
|
|
436
|
+
status: number;
|
|
437
|
+
headers: Record<string, string>;
|
|
438
|
+
url: string;
|
|
439
|
+
durationMs: number;
|
|
440
|
+
attempts: number;
|
|
441
|
+
/** data came from a fallback, not from the server */
|
|
442
|
+
fromFallback: boolean;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** Options every generated endpoint accepts (in its args object). */
|
|
446
|
+
export interface CallOptions<R = unknown> {
|
|
447
|
+
headers?: HeaderValues;
|
|
448
|
+
/** cancels the call; the hooks pass their own */
|
|
449
|
+
signal?: AbortSignal;
|
|
450
|
+
/** per attempt; overrides the client timeout; 0 disables it */
|
|
451
|
+
timeoutMs?: number;
|
|
452
|
+
/** body encoding; inferred when omitted (FormData → multipart, string → text, object → json) */
|
|
453
|
+
contentType?: BodyEncoding;
|
|
454
|
+
/** response decoding; inferred from Content-Type when omitted */
|
|
455
|
+
responseType?: ResponseKind;
|
|
456
|
+
/** do not attach the bearer token from getToken */
|
|
457
|
+
skipAuth?: boolean;
|
|
458
|
+
/** sent as Idempotency-Key; also makes non-idempotent methods eligible for retry */
|
|
459
|
+
idempotencyKey?: string;
|
|
460
|
+
retry?: RetryOption;
|
|
461
|
+
/** value to resolve with instead of throwing (not for cancelled calls) */
|
|
462
|
+
fallback?: (error: ApiError) => R | Promise<R>;
|
|
463
|
+
/** messages for this call; override endpoint and client messages */
|
|
464
|
+
messages?: ErrorMessages;
|
|
465
|
+
/** true when the call starts, false when it settles */
|
|
466
|
+
onLoading?: (loading: boolean) => void;
|
|
467
|
+
/** false keeps this call out of the logs (e.g. a login body) */
|
|
468
|
+
log?: boolean;
|
|
469
|
+
/** extra fetch() options (fetchTransport) */
|
|
470
|
+
init?: FetchInit;
|
|
471
|
+
/** options for the HTTP library (axios config, Angular HttpClient options, …) */
|
|
472
|
+
adapterOptions?: Record<string, unknown>;
|
|
473
|
+
/** runs inside the client and endpoint middleware, for this call only */
|
|
474
|
+
middleware?: readonly Middleware[];
|
|
211
475
|
}
|
|
212
476
|
|
|
213
|
-
|
|
477
|
+
/** Per-endpoint defaults, set with createApi(client, { endpoints }). */
|
|
478
|
+
export type EndpointOptions<R = unknown> = Pick<
|
|
479
|
+
CallOptions<R>,
|
|
480
|
+
'headers' | 'timeoutMs' | 'skipAuth' | 'retry' | 'fallback' | 'messages' | 'log' | 'responseType' | 'init' | 'adapterOptions' | 'middleware'
|
|
481
|
+
>;
|
|
482
|
+
|
|
483
|
+
export interface RequestOptions<R = unknown> extends CallOptions<R> {
|
|
484
|
+
params?: Record<string, string | number>;
|
|
485
|
+
query?: Query;
|
|
486
|
+
body?: unknown;
|
|
487
|
+
/** endpoint id, for logs, metrics and errors */
|
|
488
|
+
endpoint?: string;
|
|
489
|
+
}
|
|
214
490
|
|
|
215
|
-
export interface
|
|
216
|
-
/**
|
|
491
|
+
export interface ClientConfig {
|
|
492
|
+
/** fetch (default), axios, Angular HttpClient or a react-native-fetch client */
|
|
493
|
+
http?: HttpLibrary;
|
|
494
|
+
/** instead of http: your own function that sends a request (see Transport) */
|
|
495
|
+
transport?: Transport;
|
|
496
|
+
/** prepended to relative endpoint paths, e.g. 'https://api.example.com/v1' */
|
|
217
497
|
baseURL?: string;
|
|
218
|
-
/** headers for every call
|
|
498
|
+
/** headers for every call to a trusted origin; an object or a function */
|
|
219
499
|
headers?: HeaderValues | (() => HeaderValues | Promise<HeaderValues>);
|
|
220
|
-
/** bearer token for every call
|
|
500
|
+
/** bearer token for every call to a trusted origin */
|
|
221
501
|
getToken?: () => string | null | undefined | Promise<string | null | undefined>;
|
|
222
|
-
/**
|
|
502
|
+
/** origins besides baseURL's that receive the token and client headers */
|
|
503
|
+
trustedOrigins?: readonly string[];
|
|
504
|
+
/** per attempt; default 30000 ms; 0 disables */
|
|
223
505
|
timeoutMs?: number;
|
|
224
|
-
/** custom fetch (tests, polyfills, instrumentation) */
|
|
225
|
-
fetch?: typeof fetch;
|
|
226
|
-
/** fetch() options for every call */
|
|
227
|
-
init?: FetchInit;
|
|
228
506
|
/** query arrays: 'repeat' (a=1&a=2, default), 'comma' (a=1,2), 'brackets' (a[]=1&a[]=2) */
|
|
229
507
|
arrayFormat?: 'repeat' | 'comma' | 'brackets';
|
|
230
|
-
/**
|
|
508
|
+
/** default retry policy (off unless set) */
|
|
509
|
+
retry?: RetryOption;
|
|
510
|
+
/** messages for people for every call */
|
|
511
|
+
messages?: ErrorMessages;
|
|
512
|
+
/** read a message from an error body; off by default to hide server internals */
|
|
513
|
+
messageFromResponse?: (error: ApiError) => string | undefined;
|
|
514
|
+
/** true logs to the console; or your logger */
|
|
515
|
+
logger?: boolean | ApiLogger;
|
|
516
|
+
/** default 'info' */
|
|
517
|
+
logLevel?: LogLevel;
|
|
518
|
+
/** include request and response bodies in debug / info logs (default false) */
|
|
519
|
+
logBodies?: boolean;
|
|
520
|
+
/** headers logged as [redacted] */
|
|
521
|
+
redactHeaders?: readonly string[];
|
|
522
|
+
/** log a warning and flag the metric when a call takes longer (ms) */
|
|
523
|
+
slowRequestMs?: number;
|
|
524
|
+
/** around every attempt, first = outermost; endpoint and call middleware run inside */
|
|
525
|
+
middleware?: readonly Middleware[];
|
|
526
|
+
/** before each attempt; may change request.headers (e.g. add a trace id) */
|
|
527
|
+
onRequest?: (request: TransportRequest) => void | Promise<void>;
|
|
528
|
+
/** after each successful call */
|
|
529
|
+
onResponse?: (response: ApiResponse<unknown>, request: TransportRequest) => void;
|
|
530
|
+
/** after each failed call (before any fallback); the error is still thrown */
|
|
231
531
|
onError?: (error: ApiError) => void;
|
|
532
|
+
/** after every call, for performance monitoring */
|
|
533
|
+
onMetrics?: (metric: RequestMetric) => void;
|
|
534
|
+
/** whenever the number of calls in flight changes (global spinner) */
|
|
535
|
+
onLoadingChange?: (pending: number) => void;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export interface ApiClient {
|
|
539
|
+
request<T = unknown>(method: HttpMethod, path: string, options?: RequestOptions<T>): Promise<ApiResponse<T>>;
|
|
540
|
+
/** calls in flight */
|
|
541
|
+
readonly pending: number;
|
|
542
|
+
/** listener runs whenever pending changes; returns unsubscribe */
|
|
543
|
+
subscribe(listener: (pending: number) => void): () => void;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** Anything with request(): a client from createClient(), or a test double. */
|
|
547
|
+
export type ApiRequester = Pick<ApiClient, 'request'>;
|
|
548
|
+
|
|
549
|
+
const DEFAULT_REDACT = [
|
|
550
|
+
'authorization',
|
|
551
|
+
'cookie',
|
|
552
|
+
'set-cookie',
|
|
553
|
+
'proxy-authorization',
|
|
554
|
+
'x-api-key',
|
|
555
|
+
'x-auth-token',
|
|
556
|
+
'x-csrf-token',
|
|
557
|
+
];
|
|
558
|
+
|
|
559
|
+
const LEVELS: Record<LogLevel, number> = { debug: 10, info: 20, warn: 30, error: 40, silent: 100 };
|
|
560
|
+
|
|
561
|
+
function now(): number {
|
|
562
|
+
const perf = (globalThis as { performance?: { now(): number } }).performance;
|
|
563
|
+
return perf && typeof perf.now === 'function' ? perf.now() : Date.now();
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** Runs an observer; a throwing observer must not break the call. */
|
|
567
|
+
function safely(fn: () => void): void {
|
|
568
|
+
try {
|
|
569
|
+
fn();
|
|
570
|
+
} catch {
|
|
571
|
+
// observers only observe
|
|
572
|
+
}
|
|
232
573
|
}
|
|
233
574
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
575
|
+
export function createClient(config: ClientConfig = {}): ApiClient {
|
|
576
|
+
if (config.transport !== undefined && config.http !== undefined) {
|
|
577
|
+
throw new TypeError('createClient: pass "http" (a library) or "transport" (your own function), not both');
|
|
578
|
+
}
|
|
579
|
+
if (config.transport !== undefined && typeof config.transport !== 'function') {
|
|
580
|
+
throw new TypeError('createClient: "transport" must be a function');
|
|
581
|
+
}
|
|
582
|
+
const transport: Transport = config.transport ?? toTransport(config.http);
|
|
583
|
+
const sendNormalised = normalised(transport);
|
|
584
|
+
const clientMiddleware = checkMiddleware(config.middleware, 'createClient');
|
|
585
|
+
const redact = (config.redactHeaders ?? DEFAULT_REDACT).map((h) => h.toLowerCase());
|
|
586
|
+
const trusted = (config.trustedOrigins ?? []).map((o) => originOf(o) ?? o.toLowerCase());
|
|
587
|
+
const baseOrigin = originOf(config.baseURL ?? '');
|
|
588
|
+
if (baseOrigin) trusted.push(baseOrigin);
|
|
589
|
+
const mayReceiveCredentials = (url: string): boolean => {
|
|
590
|
+
const origin = originOf(url);
|
|
591
|
+
return origin === undefined || trusted.indexOf(origin) !== -1;
|
|
240
592
|
};
|
|
593
|
+
const logger: ApiLogger | undefined = config.logger === true ? console : config.logger || undefined;
|
|
594
|
+
const minLevel = LEVELS[config.logLevel ?? 'info'];
|
|
595
|
+
const listeners = new Set<(pending: number) => void>();
|
|
596
|
+
let pending = 0;
|
|
241
597
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
598
|
+
const log = (level: Exclude<LogLevel, 'silent'>, enabled: boolean, message: string, details: Record<string, unknown>) => {
|
|
599
|
+
if (!logger || !enabled || LEVELS[level] < minLevel) return;
|
|
600
|
+
const write = logger[level];
|
|
601
|
+
if (typeof write === 'function') safely(() => write.call(logger, message, details));
|
|
602
|
+
};
|
|
603
|
+
const setPending = (delta: number) => {
|
|
604
|
+
pending += delta;
|
|
605
|
+
const count = pending;
|
|
606
|
+
if (config.onLoadingChange) safely(() => config.onLoadingChange!(count));
|
|
607
|
+
listeners.forEach((listener) => safely(() => listener(count)));
|
|
608
|
+
};
|
|
609
|
+
const redacted = (headers: Record<string, string>) => {
|
|
610
|
+
const out: Record<string, string> = {};
|
|
611
|
+
for (const key of Object.keys(headers)) out[key] = redact.indexOf(key) !== -1 ? '[redacted]' : (headers[key] as string);
|
|
612
|
+
return out;
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
async function request<T = unknown>(
|
|
616
|
+
method: HttpMethod,
|
|
617
|
+
path: string,
|
|
618
|
+
options: RequestOptions<T> = {}
|
|
619
|
+
): Promise<ApiResponse<T>> {
|
|
620
|
+
const started = now();
|
|
621
|
+
const endpointId = options.endpoint;
|
|
622
|
+
const logged = options.log !== false;
|
|
623
|
+
const label = method + ' ' + path;
|
|
624
|
+
const url = buildUrl(config.baseURL ?? '', path, options.params, options.query, config.arrayFormat ?? 'repeat');
|
|
625
|
+
const retry = normalizeRetry(options.retry !== undefined ? options.retry : config.retry);
|
|
626
|
+
const idempotent = IDEMPOTENT.indexOf(method) !== -1 || !!options.idempotencyKey;
|
|
627
|
+
const timeoutMs = delayOr(options.timeoutMs ?? config.timeoutMs, 30000);
|
|
628
|
+
const middleware = clientMiddleware.concat(checkMiddleware(options.middleware, 'request'));
|
|
629
|
+
/** token and config.headers: only trusted origins get them */
|
|
630
|
+
const credentialHeaders: Record<string, string> = {};
|
|
631
|
+
let credentials = false;
|
|
632
|
+
let attempt = 0;
|
|
633
|
+
let lastRequest: TransportRequest | undefined;
|
|
634
|
+
|
|
635
|
+
const failure = (kind: ApiErrorKind, originalError?: unknown) =>
|
|
636
|
+
new ApiError(kind, { method, url, endpoint: endpointId, originalError });
|
|
637
|
+
|
|
638
|
+
const finish = (status: number, ok: boolean, kind: ApiErrorKind | undefined, fromFallback: boolean): number => {
|
|
639
|
+
const durationMs = Math.round(now() - started);
|
|
640
|
+
const slow = config.slowRequestMs !== undefined && durationMs > config.slowRequestMs;
|
|
641
|
+
if (slow) log('warn', logged, 'slow request: ' + label + ' took ' + durationMs + ' ms', { endpoint: endpointId, durationMs });
|
|
642
|
+
if (config.onMetrics) {
|
|
643
|
+
const metric: RequestMetric = {
|
|
644
|
+
endpoint: endpointId,
|
|
645
|
+
method,
|
|
646
|
+
path,
|
|
647
|
+
status,
|
|
648
|
+
ok,
|
|
649
|
+
errorKind: kind,
|
|
650
|
+
durationMs,
|
|
651
|
+
attempts: attempt,
|
|
652
|
+
fromFallback,
|
|
653
|
+
slow,
|
|
654
|
+
};
|
|
655
|
+
safely(() => config.onMetrics!(metric));
|
|
255
656
|
}
|
|
256
|
-
|
|
657
|
+
return durationMs;
|
|
658
|
+
};
|
|
257
659
|
|
|
660
|
+
const attemptOnce = async (headers: Record<string, string>): Promise<TransportResponse> => {
|
|
258
661
|
const controller = new AbortController();
|
|
259
662
|
const external = options.signal;
|
|
663
|
+
let timedOut = false;
|
|
260
664
|
const onAbort = () => controller.abort();
|
|
261
665
|
if (external) {
|
|
262
666
|
if (external.aborted) controller.abort();
|
|
263
667
|
else external.addEventListener('abort', onAbort);
|
|
264
668
|
}
|
|
265
|
-
const timeoutMs = options.timeoutMs ?? config.timeoutMs ?? 30000;
|
|
266
|
-
let timedOut = false;
|
|
267
669
|
const timer =
|
|
268
670
|
timeoutMs > 0
|
|
269
671
|
? setTimeout(() => {
|
|
@@ -271,78 +673,232 @@ export function createFetchClient(config: FetchClientConfig = {}): ApiTransport
|
|
|
271
673
|
controller.abort();
|
|
272
674
|
}, timeoutMs)
|
|
273
675
|
: undefined;
|
|
274
|
-
const abortKind = (): ApiErrorKind => (timedOut ? 'TIMEOUT' : 'ABORTED');
|
|
275
|
-
|
|
276
676
|
try {
|
|
277
|
-
|
|
677
|
+
if (controller.signal.aborted) throw failure('ABORTED');
|
|
678
|
+
const req: TransportRequest = {
|
|
679
|
+
method,
|
|
680
|
+
url,
|
|
681
|
+
path,
|
|
682
|
+
endpoint: endpointId,
|
|
683
|
+
headers: { ...headers },
|
|
684
|
+
body: options.body,
|
|
685
|
+
contentType: options.contentType,
|
|
686
|
+
responseType: options.responseType,
|
|
687
|
+
signal: controller.signal,
|
|
688
|
+
timeoutMs,
|
|
689
|
+
skipAuth: !!options.skipAuth,
|
|
690
|
+
idempotencyKey: options.idempotencyKey,
|
|
691
|
+
attempt,
|
|
692
|
+
init: options.init,
|
|
693
|
+
adapterOptions: options.adapterOptions,
|
|
694
|
+
};
|
|
695
|
+
lastRequest = req;
|
|
696
|
+
if (config.onRequest) await config.onRequest(req);
|
|
697
|
+
log('debug', logged, '→ ' + label, {
|
|
698
|
+
endpoint: endpointId,
|
|
699
|
+
url: stripQuery(url),
|
|
700
|
+
attempt,
|
|
701
|
+
headers: redacted(req.headers),
|
|
702
|
+
...(config.logBodies ? { body: options.body } : {}),
|
|
703
|
+
});
|
|
704
|
+
// settles on abort even when the transport ignores the signal
|
|
705
|
+
const aborted = new Promise<never>((_resolve, reject) => {
|
|
706
|
+
const fail = () => reject(failure(timedOut ? 'TIMEOUT' : 'ABORTED'));
|
|
707
|
+
if (controller.signal.aborted) fail();
|
|
708
|
+
else controller.signal.addEventListener('abort', fail);
|
|
709
|
+
});
|
|
710
|
+
aborted.catch(() => undefined);
|
|
711
|
+
// a request redirected by middleware loses the credentials
|
|
712
|
+
const send: MiddlewareNext = (sent) => {
|
|
713
|
+
if (sent && credentials && sent.url !== url && !mayReceiveCredentials(String(sent.url))) {
|
|
714
|
+
const stripped = { ...sent.headers };
|
|
715
|
+
for (const key of Object.keys(credentialHeaders)) {
|
|
716
|
+
if (stripped[key] === credentialHeaders[key]) delete stripped[key];
|
|
717
|
+
}
|
|
718
|
+
sent = { ...sent, headers: stripped };
|
|
719
|
+
}
|
|
720
|
+
checkHeaderValues(sent.headers);
|
|
721
|
+
return sendNormalised(sent);
|
|
722
|
+
};
|
|
723
|
+
const run = middleware.length ? chain(middleware, send) : send;
|
|
724
|
+
// called in this tick; a synchronous throw becomes a rejection
|
|
725
|
+
let sending: Promise<TransportResponse>;
|
|
278
726
|
try {
|
|
279
|
-
|
|
280
|
-
...config.init,
|
|
281
|
-
...options.init,
|
|
282
|
-
method,
|
|
283
|
-
headers,
|
|
284
|
-
signal: controller.signal,
|
|
285
|
-
};
|
|
286
|
-
if (body !== undefined) init.body = body;
|
|
287
|
-
response = await doFetch(url, init);
|
|
727
|
+
sending = Promise.resolve(run(req));
|
|
288
728
|
} catch (error) {
|
|
289
|
-
|
|
290
|
-
new ApiError(controller.signal.aborted ? abortKind() : 'NETWORK', { method, url, originalError: error })
|
|
291
|
-
);
|
|
729
|
+
sending = Promise.reject(error);
|
|
292
730
|
}
|
|
293
|
-
|
|
294
|
-
response.headers.forEach((value, key) => {
|
|
295
|
-
responseHeaders[key.toLowerCase()] = value;
|
|
296
|
-
});
|
|
297
|
-
let data: unknown;
|
|
731
|
+
let response: TransportResponse;
|
|
298
732
|
try {
|
|
299
|
-
|
|
300
|
-
data = await readBody(response, method, response.ok ? options.responseType : undefined);
|
|
733
|
+
response = await Promise.race([sending, aborted]);
|
|
301
734
|
} catch (error) {
|
|
302
|
-
if (controller.signal.aborted)
|
|
303
|
-
|
|
304
|
-
throw
|
|
305
|
-
new ApiError('PARSE', {
|
|
306
|
-
method,
|
|
307
|
-
url,
|
|
308
|
-
status: response.status,
|
|
309
|
-
headers: responseHeaders,
|
|
310
|
-
originalError: error,
|
|
311
|
-
})
|
|
312
|
-
);
|
|
735
|
+
if (controller.signal.aborted) {
|
|
736
|
+
if (isApiError(error) && (error.kind === 'TIMEOUT' || error.kind === 'ABORTED')) throw error;
|
|
737
|
+
throw failure(timedOut ? 'TIMEOUT' : 'ABORTED', error);
|
|
313
738
|
}
|
|
314
|
-
|
|
739
|
+
if (isApiError(error) || error instanceof InvalidHeaderError) throw error;
|
|
740
|
+
throw failure('NETWORK', error);
|
|
315
741
|
}
|
|
316
|
-
if (
|
|
317
|
-
throw
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
);
|
|
742
|
+
if (response.status < 200 || response.status >= 300) {
|
|
743
|
+
throw new ApiError('HTTP', {
|
|
744
|
+
method,
|
|
745
|
+
url,
|
|
746
|
+
status: response.status,
|
|
747
|
+
data: response.data,
|
|
748
|
+
headers: response.headers,
|
|
749
|
+
endpoint: endpointId,
|
|
750
|
+
});
|
|
326
751
|
}
|
|
327
|
-
return
|
|
752
|
+
return response;
|
|
328
753
|
} finally {
|
|
329
754
|
if (timer !== undefined) clearTimeout(timer);
|
|
330
755
|
external?.removeEventListener('abort', onAbort);
|
|
331
756
|
}
|
|
757
|
+
};
|
|
758
|
+
|
|
759
|
+
setPending(1);
|
|
760
|
+
if (options.onLoading) safely(() => options.onLoading!(true));
|
|
761
|
+
try {
|
|
762
|
+
const headers: Record<string, string> = { accept: 'application/json, text/plain, */*' };
|
|
763
|
+
credentials = mayReceiveCredentials(url);
|
|
764
|
+
if (credentials) {
|
|
765
|
+
assignHeaders(credentialHeaders, typeof config.headers === 'function' ? await config.headers() : config.headers);
|
|
766
|
+
Object.assign(headers, credentialHeaders);
|
|
767
|
+
}
|
|
768
|
+
assignHeaders(headers, options.headers);
|
|
769
|
+
for (const key of Object.keys(credentialHeaders)) {
|
|
770
|
+
if (headers[key] !== credentialHeaders[key]) delete credentialHeaders[key];
|
|
771
|
+
}
|
|
772
|
+
if (credentials && config.getToken && !options.skipAuth && headers.authorization === undefined) {
|
|
773
|
+
const token = await config.getToken();
|
|
774
|
+
if (token) headers.authorization = credentialHeaders.authorization = 'Bearer ' + token;
|
|
775
|
+
}
|
|
776
|
+
if (options.idempotencyKey && headers['idempotency-key'] === undefined) {
|
|
777
|
+
headers['idempotency-key'] = options.idempotencyKey;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
for (;;) {
|
|
781
|
+
attempt++;
|
|
782
|
+
try {
|
|
783
|
+
const response = await attemptOnce(headers);
|
|
784
|
+
const durationMs = finish(response.status, true, undefined, false);
|
|
785
|
+
const result: ApiResponse<T> = {
|
|
786
|
+
data: response.data as T,
|
|
787
|
+
status: response.status,
|
|
788
|
+
headers: response.headers,
|
|
789
|
+
url: response.url ?? url,
|
|
790
|
+
durationMs,
|
|
791
|
+
attempts: attempt,
|
|
792
|
+
fromFallback: false,
|
|
793
|
+
};
|
|
794
|
+
log('info', logged, '← ' + response.status + ' ' + label + ' (' + durationMs + ' ms)', {
|
|
795
|
+
endpoint: endpointId,
|
|
796
|
+
status: response.status,
|
|
797
|
+
durationMs,
|
|
798
|
+
attempts: attempt,
|
|
799
|
+
...(config.logBodies ? { data: response.data } : {}),
|
|
800
|
+
});
|
|
801
|
+
const sent = lastRequest;
|
|
802
|
+
if (config.onResponse && sent) safely(() => config.onResponse!(result, sent));
|
|
803
|
+
return result;
|
|
804
|
+
} catch (error) {
|
|
805
|
+
if (!isApiError(error) || !shouldRetry(error, attempt, retry, idempotent)) throw error;
|
|
806
|
+
const delay = retryDelay(error, attempt, retry.policy);
|
|
807
|
+
log('warn', logged, 'retry ' + attempt + '/' + retry.attempts + ' ' + label + ' in ' + Math.round(delay) + ' ms (' + (error.status || error.kind) + ')', {
|
|
808
|
+
endpoint: endpointId,
|
|
809
|
+
kind: error.kind,
|
|
810
|
+
status: error.status,
|
|
811
|
+
});
|
|
812
|
+
await sleep(delay, options.signal, () => failure('ABORTED'));
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
} catch (thrown) {
|
|
816
|
+
if (!isApiError(thrown)) {
|
|
817
|
+
finish(0, false, undefined, false);
|
|
818
|
+
throw thrown;
|
|
819
|
+
}
|
|
820
|
+
const error = thrown;
|
|
821
|
+
const fromResponse: ErrorMessages | undefined =
|
|
822
|
+
config.messageFromResponse && error.kind === 'HTTP'
|
|
823
|
+
? { default: config.messageFromResponse }
|
|
824
|
+
: undefined;
|
|
825
|
+
error.userMessage = resolveMessage(error, [options.messages, fromResponse, config.messages, defaultErrorMessages]);
|
|
826
|
+
log(error.kind === 'ABORTED' ? 'debug' : 'error', logged, '✖ ' + (error.status || error.kind) + ' ' + label, {
|
|
827
|
+
endpoint: endpointId,
|
|
828
|
+
kind: error.kind,
|
|
829
|
+
status: error.status,
|
|
830
|
+
attempts: attempt,
|
|
831
|
+
userMessage: error.userMessage,
|
|
832
|
+
...(config.logBodies ? { data: error.data } : {}),
|
|
833
|
+
});
|
|
834
|
+
if (config.onError) safely(() => config.onError!(error));
|
|
835
|
+
if (options.fallback && error.kind !== 'ABORTED') {
|
|
836
|
+
const data = await options.fallback(error);
|
|
837
|
+
log('warn', logged, 'fallback used for ' + label + ' after ' + (error.status || error.kind), { endpoint: endpointId });
|
|
838
|
+
const durationMs = finish(error.status, false, error.kind, true);
|
|
839
|
+
return { data, status: error.status, headers: error.headers, url, durationMs, attempts: attempt, fromFallback: true };
|
|
840
|
+
}
|
|
841
|
+
finish(error.status, false, error.kind, false);
|
|
842
|
+
throw error;
|
|
843
|
+
} finally {
|
|
844
|
+
setPending(-1);
|
|
845
|
+
if (options.onLoading) safely(() => options.onLoading!(false));
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
return {
|
|
850
|
+
request,
|
|
851
|
+
get pending() {
|
|
852
|
+
return pending;
|
|
853
|
+
},
|
|
854
|
+
subscribe(listener) {
|
|
855
|
+
listeners.add(listener);
|
|
856
|
+
return () => {
|
|
857
|
+
listeners.delete(listener);
|
|
858
|
+
};
|
|
332
859
|
},
|
|
333
860
|
};
|
|
334
861
|
}
|
|
335
862
|
|
|
863
|
+
function sleep(ms: number, signal: AbortSignal | undefined, aborted: () => ApiError): Promise<void> {
|
|
864
|
+
ms = delayOr(ms, 0);
|
|
865
|
+
return new Promise<void>((resolve, reject) => {
|
|
866
|
+
if (signal?.aborted) return reject(aborted());
|
|
867
|
+
const onAbort = () => {
|
|
868
|
+
clearTimeout(timer);
|
|
869
|
+
reject(aborted());
|
|
870
|
+
};
|
|
871
|
+
const timer = setTimeout(() => {
|
|
872
|
+
signal?.removeEventListener('abort', onAbort);
|
|
873
|
+
resolve();
|
|
874
|
+
}, ms);
|
|
875
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
/** Thrown as is: not retried, not wrapped in an ApiError. */
|
|
880
|
+
class InvalidHeaderError extends TypeError {}
|
|
881
|
+
|
|
882
|
+
function checkHeaderValues(headers: Record<string, string>): void {
|
|
883
|
+
for (const key of Object.keys(headers)) {
|
|
884
|
+
if (/[\r\n]/.test(String(headers[key]))) throw new InvalidHeaderError('Header "' + key + '" contains a line break');
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
336
888
|
function assignHeaders(target: Record<string, string>, source: HeaderValues | undefined): void {
|
|
337
889
|
if (!source) return;
|
|
338
890
|
for (const key of Object.keys(source)) {
|
|
339
891
|
const value = source[key];
|
|
340
|
-
|
|
341
|
-
|
|
892
|
+
const name = key.toLowerCase();
|
|
893
|
+
if (value === undefined) delete target[name];
|
|
894
|
+
else target[name] = value;
|
|
342
895
|
}
|
|
343
896
|
}
|
|
344
897
|
|
|
345
|
-
|
|
898
|
+
// ─── URL and body encoding ──────────────────────────────────────────────────
|
|
899
|
+
|
|
900
|
+
const PARAM = /\/:([A-Za-z_]\w*)/g;
|
|
901
|
+
const ABSOLUTE = /^[a-z][a-z\d+\-.]*:\/\//i;
|
|
346
902
|
|
|
347
903
|
function buildUrl(
|
|
348
904
|
baseURL: string,
|
|
@@ -353,14 +909,17 @@ function buildUrl(
|
|
|
353
909
|
): string {
|
|
354
910
|
const filled = path.replace(PARAM, (_match, name: string) => {
|
|
355
911
|
const value = params ? params[name] : undefined;
|
|
356
|
-
if (value === undefined || value === null) {
|
|
357
|
-
throw new
|
|
912
|
+
if (value === undefined || value === null || value === '') {
|
|
913
|
+
throw new TypeError('Missing path param ":' + name + '" for "' + path + '"');
|
|
358
914
|
}
|
|
359
|
-
|
|
915
|
+
const text = String(value);
|
|
916
|
+
// ".." would walk up the server path
|
|
917
|
+
if (text === '.' || text === '..') throw new TypeError('Invalid path param ":' + name + '" for "' + path + '"');
|
|
918
|
+
return '/' + encodeURIComponent(text);
|
|
360
919
|
});
|
|
361
920
|
let url = filled;
|
|
362
|
-
if (baseURL &&
|
|
363
|
-
url = baseURL.replace(
|
|
921
|
+
if (baseURL && !ABSOLUTE.test(filled)) {
|
|
922
|
+
url = baseURL.replace(/\/+$/, '') + '/' + filled.replace(/^\/+/, '');
|
|
364
923
|
}
|
|
365
924
|
const qs = encodeQuery(query, arrayFormat);
|
|
366
925
|
return qs ? url + (url.indexOf('?') === -1 ? '?' : '&') + qs : url;
|
|
@@ -370,7 +929,7 @@ function stringify(value: QueryValue): string {
|
|
|
370
929
|
return value instanceof Date ? value.toISOString() : String(value);
|
|
371
930
|
}
|
|
372
931
|
|
|
373
|
-
function encodeQuery(query: Query | undefined, arrayFormat: 'repeat' | 'comma' | 'brackets'): string {
|
|
932
|
+
export function encodeQuery(query: Query | undefined, arrayFormat: 'repeat' | 'comma' | 'brackets' = 'repeat'): string {
|
|
374
933
|
if (!query) return '';
|
|
375
934
|
const parts: string[] = [];
|
|
376
935
|
for (const key of Object.keys(query)) {
|
|
@@ -393,32 +952,37 @@ function encodeQuery(query: Query | undefined, arrayFormat: 'repeat' | 'comma' |
|
|
|
393
952
|
return parts.join('&');
|
|
394
953
|
}
|
|
395
954
|
|
|
955
|
+
function isNativeFile(value: unknown): value is NativeFile {
|
|
956
|
+
return typeof value === 'object' && value !== null && typeof (value as NativeFile).uri === 'string';
|
|
957
|
+
}
|
|
958
|
+
|
|
396
959
|
function isBinary(body: unknown): boolean {
|
|
397
960
|
return (
|
|
398
961
|
(typeof Blob !== 'undefined' && body instanceof Blob) ||
|
|
399
962
|
body instanceof ArrayBuffer ||
|
|
400
963
|
ArrayBuffer.isView(body) ||
|
|
401
|
-
(typeof
|
|
964
|
+
(typeof body === 'object' && body !== null && typeof (body as { getReader?: unknown }).getReader === 'function')
|
|
402
965
|
);
|
|
403
966
|
}
|
|
404
967
|
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
encoding
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
if (
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
const kind: BodyEncoding =
|
|
414
|
-
encoding ??
|
|
415
|
-
(isFormData ? 'multipart' : isParams ? 'urlencoded' : typeof body === 'string' ? 'text' : isBinary(body) ? 'binary' : 'json');
|
|
968
|
+
/** The encoding a body is sent with when the call does not say. */
|
|
969
|
+
export function bodyEncoding(body: unknown, encoding?: BodyEncoding): BodyEncoding {
|
|
970
|
+
if (encoding) return encoding;
|
|
971
|
+
if (typeof FormData !== 'undefined' && body instanceof FormData) return 'multipart';
|
|
972
|
+
if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return 'urlencoded';
|
|
973
|
+
if (typeof body === 'string') return 'text';
|
|
974
|
+
return isBinary(body) ? 'binary' : 'json';
|
|
975
|
+
}
|
|
416
976
|
|
|
977
|
+
/** Encodes a body for fetch-like libraries and sets its content-type in headers. */
|
|
978
|
+
export function encodeBody(body: unknown, encoding: BodyEncoding | undefined, headers: Record<string, string>): unknown {
|
|
979
|
+
if (body === undefined || body === null) return undefined;
|
|
980
|
+
const kind = bodyEncoding(body, encoding);
|
|
417
981
|
switch (kind) {
|
|
418
982
|
case 'multipart': {
|
|
419
|
-
// the
|
|
983
|
+
// the platform sets the boundary; a hand-written multipart header would break it
|
|
420
984
|
if (headers['content-type'] && headers['content-type'].indexOf('boundary=') === -1) delete headers['content-type'];
|
|
421
|
-
if (
|
|
985
|
+
if (typeof FormData !== 'undefined' && body instanceof FormData) return body;
|
|
422
986
|
const form = new FormData();
|
|
423
987
|
const fields = body as Record<string, unknown>;
|
|
424
988
|
for (const key of Object.keys(fields)) {
|
|
@@ -427,59 +991,408 @@ function encodeBody(
|
|
|
427
991
|
for (const v of values) {
|
|
428
992
|
if (v === undefined || v === null) continue;
|
|
429
993
|
if (typeof Blob !== 'undefined' && v instanceof Blob) form.append(key, v);
|
|
994
|
+
// React Native's FormData sends { uri, name, type } as a file part
|
|
995
|
+
else if (isNativeFile(v)) form.append(key, v as unknown as Blob);
|
|
430
996
|
else form.append(key, typeof v === 'object' && !(v instanceof Date) ? JSON.stringify(v) : stringify(v as QueryValue));
|
|
431
997
|
}
|
|
432
998
|
}
|
|
433
999
|
return form;
|
|
434
1000
|
}
|
|
435
1001
|
case 'urlencoded':
|
|
436
|
-
if (
|
|
437
|
-
if (
|
|
438
|
-
|
|
439
|
-
return body;
|
|
440
|
-
}
|
|
441
|
-
return new URLSearchParams(encodeQuery(body as Query, 'repeat'));
|
|
1002
|
+
if (typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams) return body;
|
|
1003
|
+
if (!headers['content-type']) headers['content-type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
|
|
1004
|
+
return typeof body === 'string' ? body : encodeQuery(body as Query, 'repeat');
|
|
442
1005
|
case 'text':
|
|
443
1006
|
if (!headers['content-type']) headers['content-type'] = 'text/plain;charset=UTF-8';
|
|
444
1007
|
return typeof body === 'string' ? body : JSON.stringify(body);
|
|
445
1008
|
case 'binary':
|
|
1009
|
+
if (isNativeFile(body)) {
|
|
1010
|
+
throw new TypeError('A { uri } file body needs a transport that streams files (e.g. reactNativeFetchTransport)');
|
|
1011
|
+
}
|
|
446
1012
|
if (!headers['content-type'] && !(typeof Blob !== 'undefined' && body instanceof Blob && body.type)) {
|
|
447
1013
|
headers['content-type'] = 'application/octet-stream';
|
|
448
1014
|
}
|
|
449
|
-
return body
|
|
1015
|
+
return body;
|
|
450
1016
|
default:
|
|
451
1017
|
if (!headers['content-type']) headers['content-type'] = 'application/json';
|
|
452
1018
|
return typeof body === 'string' ? body : JSON.stringify(body);
|
|
453
1019
|
}
|
|
454
1020
|
}
|
|
455
1021
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
1022
|
+
// ─── Endpoints ──────────────────────────────────────────────────────────────
|
|
1023
|
+
|
|
1024
|
+
type Call<A, R> = {} extends A ? (args?: A) => Promise<R> : (args: A) => Promise<R>;
|
|
1025
|
+
|
|
1026
|
+
/** { status: 401; data: AuthError } | … for the documented error responses of an endpoint. */
|
|
1027
|
+
export type ErrorOf<E, D = never> =
|
|
1028
|
+
| { [S in keyof E]: { status: S; data: E[S] } }[keyof E]
|
|
1029
|
+
| ([D] extends [never] ? never : { status: number; data: D });
|
|
1030
|
+
|
|
1031
|
+
/** A generated endpoint: call it for the data, .raw() for the whole response. */
|
|
1032
|
+
export type Endpoint<A, R, E = {}, D = never> = Call<A, R> & {
|
|
1033
|
+
/** same call, resolving the full response (status, headers, timing, fromFallback) */
|
|
1034
|
+
raw: Call<A, ApiResponse<R>>;
|
|
1035
|
+
/** typed body of a documented error response; undefined for any other failure */
|
|
1036
|
+
errorOf(error: unknown): ErrorOf<E, D> | undefined;
|
|
1037
|
+
readonly id: string;
|
|
1038
|
+
readonly method: HttpMethod;
|
|
1039
|
+
readonly path: string;
|
|
1040
|
+
};
|
|
1041
|
+
|
|
1042
|
+
export interface EndpointSpec {
|
|
1043
|
+
/** 'group.name' */
|
|
1044
|
+
id: string;
|
|
1045
|
+
method: HttpMethod;
|
|
1046
|
+
path: string;
|
|
1047
|
+
/** applied before endpoint options and the caller's options */
|
|
1048
|
+
defaults?: CallOptions;
|
|
1049
|
+
/** documented error statuses */
|
|
1050
|
+
errors?: readonly number[];
|
|
1051
|
+
/** documented error classes: 4 for 4XX, 5 for 5XX */
|
|
1052
|
+
errorRanges?: readonly number[];
|
|
1053
|
+
/** a catch-all (default) error response is documented */
|
|
1054
|
+
defaultError?: boolean;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
function mergeRecords<V>(...records: Array<Record<string, V> | undefined>): Record<string, V> | undefined {
|
|
1058
|
+
let out: Record<string, V> | undefined;
|
|
1059
|
+
for (const record of records) if (record) out = { ...out, ...record };
|
|
1060
|
+
return out;
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/** Bind one endpoint to a client. Used by the generated createApi. */
|
|
1064
|
+
export function endpoint<A, R, E = {}, D = never>(
|
|
1065
|
+
client: ApiRequester,
|
|
1066
|
+
spec: EndpointSpec,
|
|
1067
|
+
overrides?: EndpointOptions<R>
|
|
1068
|
+
): Endpoint<A, R, E, D> {
|
|
1069
|
+
const raw = (args?: A) => {
|
|
1070
|
+
const call = (args ?? {}) as RequestOptions<R>;
|
|
1071
|
+
const options: RequestOptions<R> = { ...(spec.defaults as RequestOptions<R>), ...overrides, ...call, endpoint: spec.id };
|
|
1072
|
+
const headers = mergeRecords(spec.defaults?.headers, overrides?.headers, call.headers);
|
|
1073
|
+
if (headers) options.headers = headers;
|
|
1074
|
+
const messages = mergeRecords<ErrorMessage | undefined>(
|
|
1075
|
+
spec.defaults?.messages as Record<string, ErrorMessage | undefined> | undefined,
|
|
1076
|
+
overrides?.messages as Record<string, ErrorMessage | undefined> | undefined,
|
|
1077
|
+
call.messages as Record<string, ErrorMessage | undefined> | undefined
|
|
1078
|
+
);
|
|
1079
|
+
if (messages) options.messages = messages as ErrorMessages;
|
|
1080
|
+
const middleware = ([] as Middleware[]).concat(
|
|
1081
|
+
spec.defaults?.middleware ?? [],
|
|
1082
|
+
overrides?.middleware ?? [],
|
|
1083
|
+
call.middleware ?? []
|
|
1084
|
+
);
|
|
1085
|
+
if (middleware.length) options.middleware = middleware;
|
|
1086
|
+
else delete options.middleware;
|
|
1087
|
+
return client.request<R>(spec.method, spec.path, options);
|
|
1088
|
+
};
|
|
1089
|
+
const call = (args?: A) => raw(args).then((response) => response.data);
|
|
1090
|
+
const errorOf = (error: unknown) => {
|
|
1091
|
+
if (!isApiError(error) || error.kind !== 'HTTP') return undefined;
|
|
1092
|
+
const status = error.status;
|
|
1093
|
+
const documented =
|
|
1094
|
+
(spec.errors !== undefined && spec.errors.indexOf(status) !== -1) ||
|
|
1095
|
+
(spec.errorRanges !== undefined && spec.errorRanges.indexOf(Math.floor(status / 100)) !== -1) ||
|
|
1096
|
+
(spec.defaultError === true && status >= 400);
|
|
1097
|
+
return documented ? { status, data: error.data } : undefined;
|
|
1098
|
+
};
|
|
1099
|
+
return Object.assign(call, {
|
|
1100
|
+
raw,
|
|
1101
|
+
errorOf,
|
|
1102
|
+
id: spec.id,
|
|
1103
|
+
method: spec.method,
|
|
1104
|
+
path: spec.path,
|
|
1105
|
+
}) as unknown as Endpoint<A, R, E, D>;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// ─── Request state for UI bindings (React, Vue, Angular, Svelte, Solid, …) ──
|
|
1109
|
+
|
|
1110
|
+
export type RequestStatus = 'idle' | 'loading' | 'success' | 'error';
|
|
1111
|
+
|
|
1112
|
+
export interface RequestState<T> {
|
|
1113
|
+
readonly status: RequestStatus;
|
|
1114
|
+
/** last successful data (kept while reloading and after an error) */
|
|
1115
|
+
readonly data: T | undefined;
|
|
1116
|
+
readonly error: ApiError | Error | undefined;
|
|
1117
|
+
readonly isIdle: boolean;
|
|
1118
|
+
readonly isLoading: boolean;
|
|
1119
|
+
readonly isSuccess: boolean;
|
|
1120
|
+
readonly isError: boolean;
|
|
1121
|
+
/** Date.now() of the last success */
|
|
1122
|
+
readonly updatedAt: number | undefined;
|
|
1123
|
+
/** data came from a fallback, not the server: show it as stale / offline */
|
|
1124
|
+
readonly fromFallback: boolean;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
/** Lets a controller's function say where its data came from (e.g. from .raw()). */
|
|
1128
|
+
export type FallbackReporter = (response: { fromFallback: boolean }) => void;
|
|
1129
|
+
|
|
1130
|
+
function snapshot<T>(
|
|
1131
|
+
status: RequestStatus,
|
|
1132
|
+
data: T | undefined,
|
|
1133
|
+
error: ApiError | Error | undefined,
|
|
1134
|
+
updatedAt: number | undefined,
|
|
1135
|
+
fromFallback = false
|
|
1136
|
+
): RequestState<T> {
|
|
1137
|
+
return {
|
|
1138
|
+
status,
|
|
1139
|
+
data,
|
|
1140
|
+
error,
|
|
1141
|
+
isIdle: status === 'idle',
|
|
1142
|
+
isLoading: status === 'loading',
|
|
1143
|
+
isSuccess: status === 'success',
|
|
1144
|
+
isError: status === 'error',
|
|
1145
|
+
updatedAt,
|
|
1146
|
+
fromFallback,
|
|
1147
|
+
};
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
export interface QueryOptions<T> {
|
|
1151
|
+
/** default true; false keeps the query idle (and cancels a running one) */
|
|
1152
|
+
enabled?: boolean;
|
|
1153
|
+
/** default true: keep the last data while reloading */
|
|
1154
|
+
keepPreviousData?: boolean;
|
|
1155
|
+
onSuccess?: (data: T) => void;
|
|
1156
|
+
onError?: (error: ApiError | Error) => void;
|
|
1157
|
+
onSettled?: () => void;
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
export interface MutationOptions<T, V> {
|
|
1161
|
+
onSuccess?: (data: T, vars: V) => void;
|
|
1162
|
+
onError?: (error: ApiError | Error, vars: V) => void;
|
|
1163
|
+
/** after success or error (e.g. refetch a list) */
|
|
1164
|
+
onSettled?: (vars: V) => void;
|
|
1165
|
+
/** true: while a call is running, run() returns it instead of sending again (double submit) */
|
|
1166
|
+
dedupe?: boolean;
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
interface Store<T> {
|
|
1170
|
+
getState(): RequestState<T>;
|
|
1171
|
+
/** listener runs on every state change; returns unsubscribe */
|
|
1172
|
+
subscribe(listener: () => void): () => void;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
export interface QueryController<A, T> extends Store<T> {
|
|
1176
|
+
/** start when args (by value) or enabled changed; a no-op otherwise */
|
|
1177
|
+
update(args: A, enabled?: boolean): void;
|
|
1178
|
+
/** run again with the last args */
|
|
1179
|
+
refetch(): void;
|
|
1180
|
+
/** abort the call in flight; the next update() starts again */
|
|
1181
|
+
cancel(): void;
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
export interface MutationController<V, T> extends Store<T> {
|
|
1185
|
+
/** rejects with the error (also passed to onError) */
|
|
1186
|
+
runAsync(vars: V): Promise<T>;
|
|
1187
|
+
/** never rejects: resolves the data, or undefined after an error */
|
|
1188
|
+
run(vars: V): Promise<T | undefined>;
|
|
1189
|
+
reset(): void;
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
function createStore<T>(initial: RequestState<T>) {
|
|
1193
|
+
let state = initial;
|
|
1194
|
+
const listeners = new Set<() => void>();
|
|
1195
|
+
return {
|
|
1196
|
+
get: () => state,
|
|
1197
|
+
set(next: RequestState<T>) {
|
|
1198
|
+
state = next;
|
|
1199
|
+
listeners.forEach((listener) => listener());
|
|
1200
|
+
},
|
|
1201
|
+
subscribe(listener: () => void) {
|
|
1202
|
+
listeners.add(listener);
|
|
1203
|
+
return () => {
|
|
1204
|
+
listeners.delete(listener);
|
|
1205
|
+
};
|
|
1206
|
+
},
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
function isAbort(error: unknown): boolean {
|
|
1211
|
+
return (
|
|
1212
|
+
(isApiError(error) && error.kind === 'ABORTED') ||
|
|
1213
|
+
(typeof error === 'object' && error !== null && (error as { name?: unknown }).name === 'AbortError')
|
|
1214
|
+
);
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/** Refetch key: path params, query, body and headers (not signal or callbacks). */
|
|
1218
|
+
export function argsKey(args: unknown): string {
|
|
1219
|
+
if (!args || typeof args !== 'object') return '';
|
|
1220
|
+
const a = args as { params?: unknown; query?: unknown; body?: unknown; headers?: unknown };
|
|
1221
|
+
try {
|
|
1222
|
+
return JSON.stringify([a.params, a.query, a.body, a.headers]) ?? '';
|
|
1223
|
+
} catch {
|
|
1224
|
+
// circular or BigInt
|
|
1225
|
+
return '?';
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/** A signal aborted when either input is. */
|
|
1230
|
+
export function linkSignals(signal: AbortSignal, other: AbortSignal | undefined): AbortSignal {
|
|
1231
|
+
if (!other) return signal;
|
|
1232
|
+
if (other.aborted) return other;
|
|
1233
|
+
const controller = new AbortController();
|
|
1234
|
+
const abort = () => controller.abort();
|
|
1235
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
1236
|
+
other.addEventListener('abort', abort, { once: true });
|
|
1237
|
+
return controller.signal;
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
/** Framework-neutral query: aborts stale calls and keeps the last data. */
|
|
1241
|
+
export function createQueryController<A, T>(
|
|
1242
|
+
fn: (args: A, signal: AbortSignal, report: FallbackReporter) => Promise<T>,
|
|
1243
|
+
getOptions: () => QueryOptions<T> = () => ({})
|
|
1244
|
+
): QueryController<A, T> {
|
|
1245
|
+
const store = createStore<T>(snapshot<T>(getOptions().enabled === false ? 'idle' : 'loading', undefined, undefined, undefined));
|
|
1246
|
+
let key: string | undefined;
|
|
1247
|
+
let args: A | undefined;
|
|
1248
|
+
let hasArgs = false;
|
|
1249
|
+
let enabled = true;
|
|
1250
|
+
let runId = 0;
|
|
1251
|
+
let controller: AbortController | undefined;
|
|
1252
|
+
|
|
1253
|
+
const stop = () => {
|
|
1254
|
+
runId++;
|
|
1255
|
+
controller?.abort();
|
|
1256
|
+
controller = undefined;
|
|
1257
|
+
};
|
|
1258
|
+
|
|
1259
|
+
const start = () => {
|
|
1260
|
+
stop();
|
|
1261
|
+
const id = runId;
|
|
1262
|
+
const own = new AbortController();
|
|
1263
|
+
controller = own;
|
|
1264
|
+
const options = getOptions();
|
|
1265
|
+
const s = store.get();
|
|
1266
|
+
const keep = options.keepPreviousData !== false;
|
|
1267
|
+
store.set(snapshot<T>('loading', keep ? s.data : undefined, undefined, s.updatedAt, keep && s.fromFallback));
|
|
1268
|
+
let fromFallback = false;
|
|
1269
|
+
const report: FallbackReporter = (response) => {
|
|
1270
|
+
fromFallback = !!response.fromFallback;
|
|
1271
|
+
};
|
|
1272
|
+
let promise: Promise<T>;
|
|
1273
|
+
try {
|
|
1274
|
+
promise = fn(args as A, own.signal, report);
|
|
1275
|
+
} catch (error) {
|
|
1276
|
+
promise = Promise.reject(error);
|
|
1277
|
+
}
|
|
1278
|
+
promise.then(
|
|
1279
|
+
(data) => {
|
|
1280
|
+
if (id !== runId) return;
|
|
1281
|
+
controller = undefined;
|
|
1282
|
+
store.set(snapshot<T>('success', data, undefined, Date.now(), fromFallback));
|
|
1283
|
+
safely(() => options.onSuccess?.(data));
|
|
1284
|
+
safely(() => options.onSettled?.());
|
|
1285
|
+
},
|
|
1286
|
+
(error: unknown) => {
|
|
1287
|
+
if (id !== runId) return;
|
|
1288
|
+
controller = undefined;
|
|
1289
|
+
const s = store.get();
|
|
1290
|
+
if (isAbort(error)) {
|
|
1291
|
+
store.set(snapshot<T>('idle', s.data, undefined, s.updatedAt, s.fromFallback));
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1295
|
+
store.set(snapshot<T>('error', s.data, err, s.updatedAt, s.fromFallback));
|
|
1296
|
+
safely(() => options.onError?.(err));
|
|
1297
|
+
safely(() => options.onSettled?.());
|
|
1298
|
+
}
|
|
1299
|
+
);
|
|
1300
|
+
};
|
|
1301
|
+
|
|
1302
|
+
return {
|
|
1303
|
+
getState: store.get,
|
|
1304
|
+
subscribe: store.subscribe,
|
|
1305
|
+
update(nextArgs, nextEnabled = true) {
|
|
1306
|
+
const nextKey = argsKey(nextArgs);
|
|
1307
|
+
args = nextArgs;
|
|
1308
|
+
hasArgs = true;
|
|
1309
|
+
if (!nextEnabled) {
|
|
1310
|
+
enabled = false;
|
|
1311
|
+
key = undefined;
|
|
1312
|
+
stop();
|
|
1313
|
+
const s = store.get();
|
|
1314
|
+
if (s.status === 'loading') store.set(snapshot<T>('idle', s.data, s.error, s.updatedAt, s.fromFallback));
|
|
1315
|
+
return;
|
|
475
1316
|
}
|
|
1317
|
+
if (enabled && nextKey === key) return;
|
|
1318
|
+
enabled = true;
|
|
1319
|
+
key = nextKey;
|
|
1320
|
+
start();
|
|
1321
|
+
},
|
|
1322
|
+
refetch() {
|
|
1323
|
+
if (hasArgs && enabled) start();
|
|
1324
|
+
},
|
|
1325
|
+
cancel() {
|
|
1326
|
+
stop();
|
|
1327
|
+
key = undefined;
|
|
1328
|
+
},
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/** Framework-neutral mutation: tracks the latest call; callbacks run for every call. */
|
|
1333
|
+
export function createMutationController<V, T>(
|
|
1334
|
+
fn: (vars: V, report: FallbackReporter) => Promise<T>,
|
|
1335
|
+
getOptions: () => MutationOptions<T, V> = () => ({})
|
|
1336
|
+
): MutationController<V, T> {
|
|
1337
|
+
const store = createStore<T>(snapshot<T>('idle', undefined, undefined, undefined));
|
|
1338
|
+
let runId = 0;
|
|
1339
|
+
let inFlight: Promise<T> | undefined;
|
|
1340
|
+
|
|
1341
|
+
const runAsync = (vars: V): Promise<T> => {
|
|
1342
|
+
const options = getOptions();
|
|
1343
|
+
if (options.dedupe && inFlight) return inFlight;
|
|
1344
|
+
const id = ++runId;
|
|
1345
|
+
const s = store.get();
|
|
1346
|
+
store.set(snapshot<T>('loading', s.data, undefined, s.updatedAt, s.fromFallback));
|
|
1347
|
+
let fromFallback = false;
|
|
1348
|
+
let promise: Promise<T>;
|
|
1349
|
+
try {
|
|
1350
|
+
promise = fn(vars, (response) => {
|
|
1351
|
+
fromFallback = !!response.fromFallback;
|
|
1352
|
+
});
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
promise = Promise.reject(error);
|
|
476
1355
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
1356
|
+
const tracked = promise.then(
|
|
1357
|
+
(data) => {
|
|
1358
|
+
if (id === runId) store.set(snapshot<T>('success', data, undefined, Date.now(), fromFallback));
|
|
1359
|
+
safely(() => options.onSuccess?.(data, vars));
|
|
1360
|
+
safely(() => options.onSettled?.(vars));
|
|
1361
|
+
return data;
|
|
1362
|
+
},
|
|
1363
|
+
(error: unknown) => {
|
|
1364
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1365
|
+
if (id === runId) {
|
|
1366
|
+
const current = store.get();
|
|
1367
|
+
store.set(snapshot<T>('error', current.data, err, current.updatedAt, current.fromFallback));
|
|
1368
|
+
}
|
|
1369
|
+
safely(() => options.onError?.(err, vars));
|
|
1370
|
+
safely(() => options.onSettled?.(vars));
|
|
1371
|
+
throw err;
|
|
1372
|
+
}
|
|
1373
|
+
);
|
|
1374
|
+
inFlight = tracked;
|
|
1375
|
+
const clear = () => {
|
|
1376
|
+
if (inFlight === tracked) inFlight = undefined;
|
|
1377
|
+
};
|
|
1378
|
+
tracked.then(clear, clear);
|
|
1379
|
+
return tracked;
|
|
1380
|
+
};
|
|
1381
|
+
|
|
1382
|
+
return {
|
|
1383
|
+
getState: store.get,
|
|
1384
|
+
subscribe: store.subscribe,
|
|
1385
|
+
runAsync,
|
|
1386
|
+
run: (vars) => runAsync(vars).catch(() => undefined),
|
|
1387
|
+
reset() {
|
|
1388
|
+
runId++;
|
|
1389
|
+
inFlight = undefined;
|
|
1390
|
+
store.set(snapshot<T>('idle', undefined, undefined, undefined));
|
|
1391
|
+
},
|
|
1392
|
+
};
|
|
480
1393
|
}
|
|
481
|
-
|
|
482
|
-
export function runtimeSource(
|
|
483
|
-
return
|
|
1394
|
+
`;
|
|
1395
|
+
export function runtimeSource() {
|
|
1396
|
+
return RUNTIME + '\n' + TRANSPORTS;
|
|
484
1397
|
}
|
|
485
1398
|
//# sourceMappingURL=runtime.js.map
|