@defjs/core 0.2.0 → 0.3.1
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/index.d.ts +24 -37
- package/index.js +144 -243
- package/index.min.js +1 -1
- package/package.json +1 -1
package/index.d.ts
CHANGED
|
@@ -63,6 +63,16 @@ export declare function field<T>(defaultValue: T): Field<T>;
|
|
|
63
63
|
export declare function doValid<T>(validators: (ValidatorFn<T> | AsyncValidatorFn<T>)[], value: T): Promise<void>;
|
|
64
64
|
export declare function isField(value: unknown): value is Field;
|
|
65
65
|
export declare function isFieldGroup(value: unknown): value is Record<PropertyKey, Field>;
|
|
66
|
+
export declare const ERR_ABORTED: Error;
|
|
67
|
+
export declare const ERR_TIMEOUT: Error;
|
|
68
|
+
export declare const ERR_NETWORK: Error;
|
|
69
|
+
export declare const ERR_NOT_FOUND_HANDLER: Error;
|
|
70
|
+
export declare const ERR_OBSERVE: Error;
|
|
71
|
+
export declare const ERR_UNSUPPORTED_FIELD_TYPE: Error;
|
|
72
|
+
export declare const ERR_INVALID_CLIENT: Error;
|
|
73
|
+
export declare const ERR_NOT_FOUND_GLOBAL_CLIENT: Error;
|
|
74
|
+
export declare const ERR_INVALID_HTTP_CONTEXT_TOKEN: Error;
|
|
75
|
+
export declare const ERR_UNKNOWN: Error;
|
|
66
76
|
export type HttpResponseBody = string | ArrayBuffer | Blob | object | null;
|
|
67
77
|
export type HttpResponse<R> = {
|
|
68
78
|
readonly url: string;
|
|
@@ -70,6 +80,7 @@ export type HttpResponse<R> = {
|
|
|
70
80
|
readonly statusText: string;
|
|
71
81
|
readonly headers: Headers;
|
|
72
82
|
readonly body: R | null;
|
|
83
|
+
readonly error?: Error | string | unknown;
|
|
73
84
|
};
|
|
74
85
|
export type MakeResponseOptions<R> = {
|
|
75
86
|
status?: number;
|
|
@@ -77,6 +88,7 @@ export type MakeResponseOptions<R> = {
|
|
|
77
88
|
url?: string;
|
|
78
89
|
headers?: Headers;
|
|
79
90
|
body?: R | null;
|
|
91
|
+
error?: Error | string | unknown;
|
|
80
92
|
};
|
|
81
93
|
export type InterceptorFn = (req: HttpRequest, next: HttpHandler) => Promise<HttpResponse<unknown>>;
|
|
82
94
|
export type BasicCredential = {
|
|
@@ -103,6 +115,10 @@ export interface HttpProgressEvent {
|
|
|
103
115
|
readonly total: number;
|
|
104
116
|
}
|
|
105
117
|
export type HttpProgressFn = (event: HttpProgressEvent) => void;
|
|
118
|
+
/**
|
|
119
|
+
* No suitable scenario was found.
|
|
120
|
+
* export type TransformRequestFn<Input = unknown> = (input: Input, request: HttpRequest) => HttpRequest['body']
|
|
121
|
+
*/
|
|
106
122
|
export type TransformResponseFn<Output = unknown> = (response: HttpResponse<unknown>) => Output;
|
|
107
123
|
export interface HttpRequest {
|
|
108
124
|
host?: string;
|
|
@@ -121,10 +137,10 @@ export interface HttpRequest {
|
|
|
121
137
|
downloadProgress?: HttpProgressFn;
|
|
122
138
|
abort?: AbortSignal;
|
|
123
139
|
}
|
|
124
|
-
export type RequestInputValue<T> = T extends
|
|
140
|
+
export type RequestInputValue<T> = T extends {
|
|
125
141
|
[K in keyof T]: Field<any>;
|
|
126
142
|
} ? {
|
|
127
|
-
[K in keyof T]:
|
|
143
|
+
[K in keyof T]: T[K] extends Field<infer V> ? V : never;
|
|
128
144
|
} : never;
|
|
129
145
|
export type UseRequestOptions = {
|
|
130
146
|
abort?: AbortSignal;
|
|
@@ -132,24 +148,21 @@ export type UseRequestOptions = {
|
|
|
132
148
|
client?: Client;
|
|
133
149
|
timeout?: number;
|
|
134
150
|
};
|
|
151
|
+
export type IsOptionalObject<T> = Partial<T> extends T ? true : false;
|
|
135
152
|
export type UseRequestFn<Input, Output> = {
|
|
136
|
-
doRequest:
|
|
153
|
+
doRequest: IsOptionalObject<Input> extends true ? (input?: RequestInputValue<Input>) => Promise<HttpResponse<Output>> : (input: RequestInputValue<Input>) => Promise<HttpResponse<Output>>;
|
|
137
154
|
cancel: () => void;
|
|
138
|
-
getInitValue: () =>
|
|
139
|
-
[K in keyof Input]: Field<any>;
|
|
140
|
-
} ? {
|
|
141
|
-
[K in keyof Input]: RequestInputValue<Input[K]>;
|
|
142
|
-
} : undefined;
|
|
155
|
+
getInitValue: () => RequestInputValue<Input>;
|
|
143
156
|
setUploadProgress: (fn: HttpProgressFn) => void;
|
|
144
157
|
setDownloadProgress: (fn: HttpProgressFn) => void;
|
|
145
158
|
};
|
|
146
|
-
export interface DefineRequest<Input extends
|
|
159
|
+
export interface DefineRequest<Input extends Record<PropertyKey, Field<any>> | undefined = undefined, Output = unknown> {
|
|
147
160
|
(options?: UseRequestOptions): UseRequestFn<Input, Output>;
|
|
148
|
-
withField<I extends
|
|
161
|
+
withField<I extends Record<PropertyKey, Field<any>>>(value: I): DefineRequest<I, Output>;
|
|
149
162
|
withInterceptors(value: InterceptorFn[]): DefineRequest<Input, Output>;
|
|
150
163
|
withContext(value: HttpContext): DefineRequest<Input, Output>;
|
|
151
164
|
withCredentials(value: boolean): DefineRequest<Input, Output>;
|
|
152
|
-
withValidators(
|
|
165
|
+
withValidators(...fn: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[]): DefineRequest<Input, Output>;
|
|
153
166
|
withTransformResponse<O>(fn: TransformResponseFn<O>): DefineRequest<Input, O>;
|
|
154
167
|
withResponseType(value: "json"): DefineRequest<Input, Output>;
|
|
155
168
|
withResponseType(value: "text"): DefineRequest<Input, string>;
|
|
@@ -181,31 +194,5 @@ export declare function getGlobalClient(): Client;
|
|
|
181
194
|
export declare function setGlobalClient(client: Client): void;
|
|
182
195
|
export declare function restGlobalClient(): void;
|
|
183
196
|
export declare function createGlobalClient(options: ClientOptions): void;
|
|
184
|
-
export declare const ERR_ABORTED: Error;
|
|
185
|
-
export declare const ERR_TIMEOUT: Error;
|
|
186
|
-
export declare const ERR_NETWORK: Error;
|
|
187
|
-
export declare const ERR_NOT_FOUND_HANDLER: Error;
|
|
188
|
-
export declare const ERR_OBSERVE: Error;
|
|
189
|
-
export declare const ERR_NOT_SET_ALIAS: Error;
|
|
190
|
-
export declare const ERR_UNSUPPORTED_FIELD_TYPE: Error;
|
|
191
|
-
export declare const ERR_INVALID_CLIENT: Error;
|
|
192
|
-
export declare const ERR_NOT_FOUND_GLOBAL_CLIENT: Error;
|
|
193
|
-
export declare const ERR_INVALID_HTTP_CONTEXT_TOKEN: Error;
|
|
194
|
-
export declare const ERR_UNKNOWN: Error;
|
|
195
|
-
export declare class HttpErrorResponse extends Error {
|
|
196
|
-
readonly status: number;
|
|
197
|
-
readonly statusText: string;
|
|
198
|
-
readonly url: string;
|
|
199
|
-
readonly headers: Headers;
|
|
200
|
-
readonly body: unknown;
|
|
201
|
-
constructor(init?: {
|
|
202
|
-
error?: Error | string | unknown;
|
|
203
|
-
status?: number;
|
|
204
|
-
statusText?: string;
|
|
205
|
-
url?: string;
|
|
206
|
-
headers?: Headers;
|
|
207
|
-
body?: unknown;
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
197
|
|
|
211
198
|
export {};
|
package/index.js
CHANGED
|
@@ -1,96 +1,41 @@
|
|
|
1
|
-
// src/
|
|
1
|
+
// src/response.ts
|
|
2
2
|
var ERR_ABORTED = new Error("ERR_ABORTED");
|
|
3
3
|
var ERR_TIMEOUT = new Error("ERR_TIMEOUT");
|
|
4
4
|
var ERR_NETWORK = new Error("ERR_NETWORK");
|
|
5
5
|
var ERR_NOT_FOUND_HANDLER = new Error("ERR_NOT_FOUND_HANDLER");
|
|
6
6
|
var ERR_OBSERVE = new Error("ERR_OBSERVE");
|
|
7
|
-
var ERR_NOT_SET_ALIAS = new Error("ERR_NOT_SET_ALIAS");
|
|
8
7
|
var ERR_UNSUPPORTED_FIELD_TYPE = new Error("ERR_UNSUPPORTED_FIELD_TYPE");
|
|
9
8
|
var ERR_INVALID_CLIENT = new Error("ERR_INVALID_CLIENT");
|
|
10
9
|
var ERR_NOT_FOUND_GLOBAL_CLIENT = new Error("ERR_NOT_FOUND_GLOBAL_CLIENT");
|
|
11
10
|
var ERR_INVALID_HTTP_CONTEXT_TOKEN = new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN");
|
|
12
11
|
var ERR_UNKNOWN = new Error("ERR_UNKNOWN");
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
status;
|
|
16
|
-
statusText;
|
|
17
|
-
url;
|
|
18
|
-
headers;
|
|
19
|
-
body;
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const url = init?.url ?? "";
|
|
26
|
-
const body = init?.body ?? null;
|
|
27
|
-
let message;
|
|
28
|
-
if (ok) {
|
|
29
|
-
message = `Http failure during parsing for ${url}`;
|
|
30
|
-
} else {
|
|
31
|
-
message = `Http failure response for ${url || "(unknown url)"}: ${status}`;
|
|
32
|
-
if (statusText) {
|
|
33
|
-
message += ` - ${statusText}`;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
super(message, { cause: init?.error });
|
|
37
|
-
super.name = "HttpErrorResponse";
|
|
38
|
-
this.statusText = statusText;
|
|
39
|
-
this.url = url;
|
|
40
|
-
this.headers = headers;
|
|
41
|
-
this.status = status;
|
|
42
|
-
this.body = body;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// src/handler/util.ts
|
|
47
|
-
function __getContentLength(headers) {
|
|
48
|
-
const value = headers.get("Content-Length");
|
|
49
|
-
if (!value) {
|
|
50
|
-
return 0;
|
|
51
|
-
}
|
|
52
|
-
const num = Number(value);
|
|
53
|
-
if (isNaN(num)) {
|
|
54
|
-
return 0;
|
|
55
|
-
}
|
|
56
|
-
return num;
|
|
57
|
-
}
|
|
58
|
-
function __getContentType(headers) {
|
|
59
|
-
return headers.get("Content-Type") || "";
|
|
60
|
-
}
|
|
61
|
-
function __parseBody(params) {
|
|
62
|
-
const { request, content, contentType } = params;
|
|
63
|
-
const responseType = request.responseType;
|
|
64
|
-
switch (responseType) {
|
|
65
|
-
case "json": {
|
|
66
|
-
const text = new TextDecoder().decode(content);
|
|
67
|
-
if (text === "") {
|
|
68
|
-
return null;
|
|
69
|
-
}
|
|
70
|
-
return JSON.parse(text);
|
|
71
|
-
}
|
|
72
|
-
case "text":
|
|
73
|
-
return new TextDecoder().decode(content);
|
|
74
|
-
case "blob": {
|
|
75
|
-
return new Blob([content], { type: contentType });
|
|
12
|
+
function __makeResponse(options) {
|
|
13
|
+
const status = options?.status ?? 0;
|
|
14
|
+
const ok = status >= 200 && status < 300;
|
|
15
|
+
const statusText = options?.statusText ?? "";
|
|
16
|
+
const url = options?.url ?? "";
|
|
17
|
+
const headers = options?.headers ?? new Headers;
|
|
18
|
+
const body = options?.body ?? null;
|
|
19
|
+
let error = options?.error;
|
|
20
|
+
if (!error && !ok) {
|
|
21
|
+
let message = `Http failure response for ${url || "(unknown url)"}: ${status}`;
|
|
22
|
+
if (statusText) {
|
|
23
|
+
message += ` - ${statusText}`;
|
|
76
24
|
}
|
|
77
|
-
|
|
78
|
-
return content.buffer;
|
|
79
|
-
default:
|
|
80
|
-
return null;
|
|
25
|
+
error = new Error(message);
|
|
81
26
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
}
|
|
90
|
-
return chunksAll;
|
|
27
|
+
return {
|
|
28
|
+
status,
|
|
29
|
+
statusText,
|
|
30
|
+
url,
|
|
31
|
+
headers,
|
|
32
|
+
body,
|
|
33
|
+
error
|
|
34
|
+
};
|
|
91
35
|
}
|
|
92
36
|
|
|
93
37
|
// src/context.ts
|
|
38
|
+
var HTTP_CONTEXT_TOKEN = Symbol("HttpContextToken");
|
|
94
39
|
function makeHttpContextToken(defaultValue) {
|
|
95
40
|
Object.defineProperty(defaultValue, HTTP_CONTEXT_TOKEN, { value: defaultValue });
|
|
96
41
|
return defaultValue;
|
|
@@ -98,6 +43,7 @@ function makeHttpContextToken(defaultValue) {
|
|
|
98
43
|
function isHttpContextToken(value) {
|
|
99
44
|
return typeof value === "function" && HTTP_CONTEXT_TOKEN in value;
|
|
100
45
|
}
|
|
46
|
+
var HTTP_CONTEXT = Symbol("HttpContext");
|
|
101
47
|
function isHttpContext(value) {
|
|
102
48
|
return typeof value === "object" && value !== null && HTTP_CONTEXT in value;
|
|
103
49
|
}
|
|
@@ -152,10 +98,9 @@ function makeHttpContext(entries) {
|
|
|
152
98
|
[HTTP_CONTEXT]: ctx
|
|
153
99
|
};
|
|
154
100
|
}
|
|
155
|
-
var HTTP_CONTEXT_TOKEN = Symbol("HttpContextToken");
|
|
156
|
-
var HTTP_CONTEXT = Symbol("HttpContext");
|
|
157
101
|
|
|
158
102
|
// src/field.ts
|
|
103
|
+
var FIELD = Symbol("field");
|
|
159
104
|
function field(defaultValue) {
|
|
160
105
|
const meta = {
|
|
161
106
|
required: typeof defaultValue !== "undefined",
|
|
@@ -217,7 +162,6 @@ function isField(value) {
|
|
|
217
162
|
function isFieldGroup(value) {
|
|
218
163
|
return !!value && typeof value === "object" && Object.entries(value).every(([, v]) => isField(v));
|
|
219
164
|
}
|
|
220
|
-
var FIELD = Symbol("field");
|
|
221
165
|
|
|
222
166
|
// src/handler/handler.ts
|
|
223
167
|
var globalHttpHandler = undefined;
|
|
@@ -230,22 +174,6 @@ function makeInterceptorChain(interceptors) {
|
|
|
230
174
|
}, (req, fn) => fn(req));
|
|
231
175
|
}
|
|
232
176
|
|
|
233
|
-
// src/response.ts
|
|
234
|
-
function __makeResponse(options) {
|
|
235
|
-
const status = options?.status ?? 0;
|
|
236
|
-
const statusText = options?.statusText ?? "";
|
|
237
|
-
const url = options?.url ?? "";
|
|
238
|
-
const headers = options?.headers ?? new Headers;
|
|
239
|
-
const body = options?.body ?? null;
|
|
240
|
-
return {
|
|
241
|
-
status,
|
|
242
|
-
statusText,
|
|
243
|
-
url,
|
|
244
|
-
headers,
|
|
245
|
-
body
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
|
|
249
177
|
// src/request.ts
|
|
250
178
|
function __serializeBody(body) {
|
|
251
179
|
switch (true) {
|
|
@@ -287,13 +215,10 @@ function __detectContentTypeHeader(body) {
|
|
|
287
215
|
}
|
|
288
216
|
}
|
|
289
217
|
function __buildFieldDefaultValue(input) {
|
|
290
|
-
if (isField(input)) {
|
|
291
|
-
return input();
|
|
292
|
-
}
|
|
293
218
|
if (isFieldGroup(input)) {
|
|
294
219
|
const obj = {};
|
|
295
|
-
for (const [key,
|
|
296
|
-
obj[key] =
|
|
220
|
+
for (const [key, field2] of Object.entries(input)) {
|
|
221
|
+
obj[key] = field2();
|
|
297
222
|
}
|
|
298
223
|
return obj;
|
|
299
224
|
}
|
|
@@ -302,11 +227,10 @@ function __buildFieldDefaultValue(input) {
|
|
|
302
227
|
function defineRequest(...args) {
|
|
303
228
|
let method;
|
|
304
229
|
let endpoint;
|
|
305
|
-
let
|
|
306
|
-
let field3;
|
|
230
|
+
let field2;
|
|
307
231
|
let interceptors = [];
|
|
308
232
|
let responseType = "json";
|
|
309
|
-
let
|
|
233
|
+
let context;
|
|
310
234
|
let withCredentials = false;
|
|
311
235
|
let validators = [];
|
|
312
236
|
let transformResponse;
|
|
@@ -326,10 +250,10 @@ function defineRequest(...args) {
|
|
|
326
250
|
}
|
|
327
251
|
const fn = (options) => {
|
|
328
252
|
const timeout = options?.timeout || 0;
|
|
329
|
-
const
|
|
330
|
-
const clientOptions = getClientConfig(
|
|
331
|
-
const
|
|
332
|
-
if (!
|
|
253
|
+
const client = options?.client || getGlobalClient();
|
|
254
|
+
const clientOptions = getClientConfig(client);
|
|
255
|
+
const handler = options?.handler || clientOptions?.handler || getGlobalHttpHandler();
|
|
256
|
+
if (!handler) {
|
|
333
257
|
throw ERR_NOT_FOUND_HANDLER;
|
|
334
258
|
}
|
|
335
259
|
let uploadProgress;
|
|
@@ -348,7 +272,7 @@ function defineRequest(...args) {
|
|
|
348
272
|
const cancel = () => {
|
|
349
273
|
abortController?.abort();
|
|
350
274
|
};
|
|
351
|
-
const getInitValue = () => __buildFieldDefaultValue(
|
|
275
|
+
const getInitValue = () => __buildFieldDefaultValue(field2);
|
|
352
276
|
const setUploadProgress = (fn2) => {
|
|
353
277
|
uploadProgress = fn2;
|
|
354
278
|
};
|
|
@@ -357,12 +281,9 @@ function defineRequest(...args) {
|
|
|
357
281
|
};
|
|
358
282
|
const doRequest = async (...args2) => {
|
|
359
283
|
let input;
|
|
360
|
-
if (
|
|
284
|
+
if (args2.length === 1) {
|
|
361
285
|
input = args2[0];
|
|
362
286
|
}
|
|
363
|
-
if (requiredInput && !input) {
|
|
364
|
-
throw new Error(`Because the request has input, the argument must be the input value`);
|
|
365
|
-
}
|
|
366
287
|
if (validators.length > 0) {
|
|
367
288
|
for (const fn2 of validators) {
|
|
368
289
|
fn2(input);
|
|
@@ -377,28 +298,28 @@ function defineRequest(...args) {
|
|
|
377
298
|
body: undefined,
|
|
378
299
|
withCredentials,
|
|
379
300
|
responseType,
|
|
380
|
-
context:
|
|
301
|
+
context: context || makeHttpContext(),
|
|
381
302
|
uploadProgress,
|
|
382
303
|
downloadProgress,
|
|
383
304
|
timeout,
|
|
384
305
|
abort: AbortSignal.any(abortSignal)
|
|
385
306
|
};
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
307
|
+
try {
|
|
308
|
+
if (input && field2) {
|
|
309
|
+
await __fillRequestFromField(req, field2, input);
|
|
310
|
+
}
|
|
311
|
+
const chain = makeInterceptorChain([...clientOptions.interceptors, ...interceptors]);
|
|
312
|
+
let res = await chain(req, handler);
|
|
313
|
+
if (typeof transformResponse === "function") {
|
|
393
314
|
res = __makeResponse({
|
|
394
315
|
...res,
|
|
395
316
|
body: transformResponse(res)
|
|
396
317
|
});
|
|
397
|
-
} catch (error3) {
|
|
398
|
-
throw new HttpErrorResponse({ error: error3 });
|
|
399
318
|
}
|
|
319
|
+
return res;
|
|
320
|
+
} catch (error) {
|
|
321
|
+
return __makeResponse({ error });
|
|
400
322
|
}
|
|
401
|
-
return res;
|
|
402
323
|
};
|
|
403
324
|
return {
|
|
404
325
|
doRequest,
|
|
@@ -409,8 +330,7 @@ function defineRequest(...args) {
|
|
|
409
330
|
};
|
|
410
331
|
};
|
|
411
332
|
fn.withField = (value) => {
|
|
412
|
-
|
|
413
|
-
requiredInput = true;
|
|
333
|
+
field2 = value;
|
|
414
334
|
return fn;
|
|
415
335
|
};
|
|
416
336
|
fn.withInterceptors = (value) => {
|
|
@@ -418,15 +338,15 @@ function defineRequest(...args) {
|
|
|
418
338
|
return fn;
|
|
419
339
|
};
|
|
420
340
|
fn.withContext = (value) => {
|
|
421
|
-
|
|
341
|
+
context = value;
|
|
422
342
|
return fn;
|
|
423
343
|
};
|
|
424
344
|
fn.withCredentials = (value) => {
|
|
425
345
|
withCredentials = value;
|
|
426
346
|
return fn;
|
|
427
347
|
};
|
|
428
|
-
fn.withValidators = (
|
|
429
|
-
validators =
|
|
348
|
+
fn.withValidators = (...fns) => {
|
|
349
|
+
validators = fns;
|
|
430
350
|
return fn;
|
|
431
351
|
};
|
|
432
352
|
fn.withTransformResponse = (value) => {
|
|
@@ -444,7 +364,7 @@ function __fillUrl(endpoint, params) {
|
|
|
444
364
|
return params.get(p1) ?? "undefined";
|
|
445
365
|
});
|
|
446
366
|
}
|
|
447
|
-
async function __fillRequestFromField(request,
|
|
367
|
+
async function __fillRequestFromField(request, fieldGroup, input) {
|
|
448
368
|
function inputIsObject(input2) {
|
|
449
369
|
return typeof input2 === "object" && input2 !== null;
|
|
450
370
|
}
|
|
@@ -457,9 +377,10 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
457
377
|
case typeof value === "boolean":
|
|
458
378
|
case typeof value === "number":
|
|
459
379
|
case typeof value === "string":
|
|
380
|
+
case typeof value === "undefined":
|
|
460
381
|
return String(value);
|
|
461
382
|
default:
|
|
462
|
-
throw new Error(
|
|
383
|
+
throw new Error(`Unsupported value type: ${typeof value}`);
|
|
463
384
|
}
|
|
464
385
|
}
|
|
465
386
|
function appendValue(sp, key, value) {
|
|
@@ -467,7 +388,9 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
467
388
|
for (const v of value) {
|
|
468
389
|
sp.append(key, serializeToString(v));
|
|
469
390
|
}
|
|
470
|
-
|
|
391
|
+
return sp;
|
|
392
|
+
}
|
|
393
|
+
if (typeof value !== "undefined") {
|
|
471
394
|
sp.set(key, serializeToString(value));
|
|
472
395
|
}
|
|
473
396
|
return sp;
|
|
@@ -477,8 +400,11 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
477
400
|
for (const v of value) {
|
|
478
401
|
setValue(sp, key, serializeToString(v));
|
|
479
402
|
}
|
|
403
|
+
return sp;
|
|
404
|
+
}
|
|
405
|
+
if (typeof value !== "undefined") {
|
|
406
|
+
sp.set(key, serializeToString(value));
|
|
480
407
|
}
|
|
481
|
-
sp.set(key, serializeToString(value));
|
|
482
408
|
return sp;
|
|
483
409
|
}
|
|
484
410
|
function getValidValue(value, defaultValue) {
|
|
@@ -491,66 +417,7 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
491
417
|
return value;
|
|
492
418
|
}
|
|
493
419
|
}
|
|
494
|
-
if (
|
|
495
|
-
let params;
|
|
496
|
-
let queryParams;
|
|
497
|
-
let headers;
|
|
498
|
-
let body = undefined;
|
|
499
|
-
const validValue = getValidValue(input, fieldOrFieldGroup());
|
|
500
|
-
const meta = __getFieldMetadata(fieldOrFieldGroup);
|
|
501
|
-
await doValid([...meta.validators, ...meta.asyncValidator], validValue);
|
|
502
|
-
for (const [type, aliasName] of meta.alias) {
|
|
503
|
-
switch (type) {
|
|
504
|
-
case 1 /* Query */: {
|
|
505
|
-
if (!aliasName) {
|
|
506
|
-
throw ERR_NOT_SET_ALIAS;
|
|
507
|
-
}
|
|
508
|
-
queryParams = appendValue(new URLSearchParams, aliasName, validValue);
|
|
509
|
-
break;
|
|
510
|
-
}
|
|
511
|
-
case 2 /* Param */: {
|
|
512
|
-
if (!aliasName) {
|
|
513
|
-
throw ERR_NOT_SET_ALIAS;
|
|
514
|
-
}
|
|
515
|
-
params = setValue(new Map, aliasName, validValue);
|
|
516
|
-
break;
|
|
517
|
-
}
|
|
518
|
-
case 3 /* Header */: {
|
|
519
|
-
if (!aliasName) {
|
|
520
|
-
throw ERR_NOT_SET_ALIAS;
|
|
521
|
-
}
|
|
522
|
-
headers = appendValue(new Headers, aliasName, validValue);
|
|
523
|
-
break;
|
|
524
|
-
}
|
|
525
|
-
case 4 /* Form */: {
|
|
526
|
-
if (!aliasName) {
|
|
527
|
-
throw ERR_NOT_SET_ALIAS;
|
|
528
|
-
}
|
|
529
|
-
body = appendValue(new FormData, aliasName, validValue);
|
|
530
|
-
break;
|
|
531
|
-
}
|
|
532
|
-
case 6 /* UrlForm */: {
|
|
533
|
-
if (!aliasName) {
|
|
534
|
-
throw ERR_NOT_SET_ALIAS;
|
|
535
|
-
}
|
|
536
|
-
body = appendValue(new URLSearchParams, aliasName, validValue);
|
|
537
|
-
break;
|
|
538
|
-
}
|
|
539
|
-
case 0 /* Json */:
|
|
540
|
-
case 5 /* Body */:
|
|
541
|
-
body = validValue;
|
|
542
|
-
break;
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
if (params) {
|
|
546
|
-
request.endpoint = __fillUrl(request.endpoint, params);
|
|
547
|
-
}
|
|
548
|
-
request.queryParams = queryParams;
|
|
549
|
-
request.headers = headers;
|
|
550
|
-
request.body = body;
|
|
551
|
-
return;
|
|
552
|
-
}
|
|
553
|
-
if (isFieldGroup(fieldOrFieldGroup) && inputIsObject(input)) {
|
|
420
|
+
if (isFieldGroup(fieldGroup) && inputIsObject(input)) {
|
|
554
421
|
let params = new Map;
|
|
555
422
|
let queryParams = new URLSearchParams;
|
|
556
423
|
let headers = new Headers;
|
|
@@ -559,11 +426,11 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
559
426
|
const json = {};
|
|
560
427
|
let body = undefined;
|
|
561
428
|
let lastBodyField;
|
|
562
|
-
for (const [propertyKey,
|
|
563
|
-
const meta = __getFieldMetadata(
|
|
429
|
+
for (const [propertyKey, field2] of Object.entries(fieldGroup)) {
|
|
430
|
+
const meta = __getFieldMetadata(field2);
|
|
564
431
|
for (const [type, aliasName] of meta.alias) {
|
|
565
432
|
const valueKey = aliasName || propertyKey;
|
|
566
|
-
const value = getValidValue(input[propertyKey],
|
|
433
|
+
const value = getValidValue(input[propertyKey], field2());
|
|
567
434
|
await doValid([...meta.validators, ...meta.asyncValidator], value);
|
|
568
435
|
switch (type) {
|
|
569
436
|
case 0 /* Json */: {
|
|
@@ -619,20 +486,65 @@ async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
619
486
|
request.body = json;
|
|
620
487
|
break;
|
|
621
488
|
}
|
|
622
|
-
return;
|
|
623
489
|
}
|
|
624
|
-
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
// src/handler/util.ts
|
|
493
|
+
function __getContentLength(headers) {
|
|
494
|
+
const value = headers.get("Content-Length");
|
|
495
|
+
if (!value) {
|
|
496
|
+
return 0;
|
|
497
|
+
}
|
|
498
|
+
const num = Number(value);
|
|
499
|
+
if (isNaN(num)) {
|
|
500
|
+
return 0;
|
|
501
|
+
}
|
|
502
|
+
return num;
|
|
503
|
+
}
|
|
504
|
+
function __getContentType(headers) {
|
|
505
|
+
return headers.get("Content-Type") || "";
|
|
506
|
+
}
|
|
507
|
+
function __parseBody(params) {
|
|
508
|
+
const { request, content, contentType } = params;
|
|
509
|
+
const responseType = request.responseType;
|
|
510
|
+
switch (responseType) {
|
|
511
|
+
case "json": {
|
|
512
|
+
const text = new TextDecoder().decode(content);
|
|
513
|
+
if (text === "") {
|
|
514
|
+
return null;
|
|
515
|
+
}
|
|
516
|
+
return JSON.parse(text);
|
|
517
|
+
}
|
|
518
|
+
case "text":
|
|
519
|
+
return new TextDecoder().decode(content);
|
|
520
|
+
case "blob": {
|
|
521
|
+
return new Blob([content], { type: contentType });
|
|
522
|
+
}
|
|
523
|
+
case "arraybuffer":
|
|
524
|
+
return content.buffer;
|
|
525
|
+
default:
|
|
526
|
+
return null;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function __concatChunks(chunks, totalLength) {
|
|
530
|
+
const chunksAll = new Uint8Array(totalLength);
|
|
531
|
+
let position = 0;
|
|
532
|
+
for (const chunk of chunks) {
|
|
533
|
+
chunksAll.set(chunk, position);
|
|
534
|
+
position += chunk.length;
|
|
535
|
+
}
|
|
536
|
+
return chunksAll;
|
|
625
537
|
}
|
|
626
538
|
|
|
627
539
|
// src/handler/fetch/fetch.ts
|
|
628
|
-
function __createRequest(
|
|
629
|
-
const url = new URL(
|
|
630
|
-
if (
|
|
631
|
-
url.search =
|
|
540
|
+
function __createRequest(request) {
|
|
541
|
+
const url = new URL(request.endpoint, request.host);
|
|
542
|
+
if (request.queryParams) {
|
|
543
|
+
url.search = request.queryParams.toString();
|
|
632
544
|
}
|
|
633
|
-
const headers =
|
|
545
|
+
const headers = request.headers ?? new Headers;
|
|
634
546
|
if (!headers.has("Content-Type")) {
|
|
635
|
-
const detectedType = __detectContentTypeHeader(
|
|
547
|
+
const detectedType = __detectContentTypeHeader(request.body);
|
|
636
548
|
if (detectedType) {
|
|
637
549
|
headers.set("Content-Type", detectedType);
|
|
638
550
|
}
|
|
@@ -640,40 +552,40 @@ function __createRequest(request2) {
|
|
|
640
552
|
if (!headers.has("Accept")) {
|
|
641
553
|
headers.set("Accept", "application/json, text/plain, */*");
|
|
642
554
|
}
|
|
643
|
-
const credentials =
|
|
555
|
+
const credentials = request.withCredentials ? "include" : undefined;
|
|
644
556
|
return new Request(url, {
|
|
645
557
|
headers,
|
|
646
|
-
method:
|
|
647
|
-
body: __serializeBody(
|
|
648
|
-
signal:
|
|
558
|
+
method: request.method,
|
|
559
|
+
body: __serializeBody(request.body),
|
|
560
|
+
signal: request.abort,
|
|
649
561
|
credentials
|
|
650
562
|
});
|
|
651
563
|
}
|
|
652
564
|
async function fetchHandler(httpRequest) {
|
|
653
565
|
const downloadProgress = httpRequest.downloadProgress;
|
|
654
|
-
const
|
|
566
|
+
const request = __createRequest(httpRequest);
|
|
655
567
|
const abortSignal = httpRequest.abort;
|
|
656
|
-
let
|
|
568
|
+
let response;
|
|
657
569
|
try {
|
|
658
|
-
|
|
659
|
-
} catch (
|
|
570
|
+
response = await globalThis.fetch(request);
|
|
571
|
+
} catch (error) {
|
|
660
572
|
if (abortSignal?.aborted && abortSignal.reason instanceof Error) {
|
|
661
573
|
switch (true) {
|
|
662
574
|
case abortSignal.reason.name === "AbortError":
|
|
663
|
-
|
|
575
|
+
return __makeResponse({ error: ERR_ABORTED });
|
|
664
576
|
case abortSignal.reason.name === "TimeoutError":
|
|
665
|
-
|
|
577
|
+
return __makeResponse({ error: ERR_TIMEOUT });
|
|
666
578
|
}
|
|
667
579
|
}
|
|
668
|
-
|
|
580
|
+
return __makeResponse({ error });
|
|
669
581
|
}
|
|
670
|
-
const {
|
|
582
|
+
const { headers, status, statusText, url } = response;
|
|
671
583
|
const contentLength = __getContentLength(headers);
|
|
672
584
|
const contentType = __getContentType(headers);
|
|
673
585
|
let body = null;
|
|
674
|
-
if (
|
|
586
|
+
if (response.body) {
|
|
675
587
|
const chunks = [];
|
|
676
|
-
const reader =
|
|
588
|
+
const reader = response.body.getReader();
|
|
677
589
|
let receivedLength = 0;
|
|
678
590
|
while (true) {
|
|
679
591
|
const { done, value } = await reader.read();
|
|
@@ -695,9 +607,9 @@ async function fetchHandler(httpRequest) {
|
|
|
695
607
|
content: chunksAll,
|
|
696
608
|
contentType
|
|
697
609
|
});
|
|
698
|
-
} catch (
|
|
699
|
-
|
|
700
|
-
error
|
|
610
|
+
} catch (error) {
|
|
611
|
+
return __makeResponse({
|
|
612
|
+
error,
|
|
701
613
|
status,
|
|
702
614
|
statusText,
|
|
703
615
|
headers,
|
|
@@ -705,32 +617,25 @@ async function fetchHandler(httpRequest) {
|
|
|
705
617
|
});
|
|
706
618
|
}
|
|
707
619
|
}
|
|
708
|
-
if (!ok) {
|
|
709
|
-
throw new HttpErrorResponse({
|
|
710
|
-
status,
|
|
711
|
-
statusText,
|
|
712
|
-
headers,
|
|
713
|
-
url,
|
|
714
|
-
body
|
|
715
|
-
});
|
|
716
|
-
}
|
|
717
620
|
return __makeResponse({
|
|
718
|
-
url,
|
|
719
621
|
status,
|
|
720
622
|
statusText,
|
|
721
623
|
headers,
|
|
624
|
+
url,
|
|
722
625
|
body
|
|
723
626
|
});
|
|
724
627
|
}
|
|
725
628
|
// src/client.ts
|
|
629
|
+
var CLIENT = Symbol("Client");
|
|
630
|
+
var globalClient;
|
|
726
631
|
function isClient(value) {
|
|
727
632
|
return typeof value === "object" && value !== null && CLIENT in value;
|
|
728
633
|
}
|
|
729
|
-
function getClientConfig(
|
|
730
|
-
if (!isClient(
|
|
634
|
+
function getClientConfig(client) {
|
|
635
|
+
if (!isClient(client)) {
|
|
731
636
|
throw ERR_INVALID_CLIENT;
|
|
732
637
|
}
|
|
733
|
-
return
|
|
638
|
+
return client[CLIENT];
|
|
734
639
|
}
|
|
735
640
|
function createClient(options) {
|
|
736
641
|
const conf = {
|
|
@@ -742,8 +647,8 @@ function createClient(options) {
|
|
|
742
647
|
[CLIENT]: conf
|
|
743
648
|
};
|
|
744
649
|
}
|
|
745
|
-
function cloneClient(
|
|
746
|
-
const preConf = getClientConfig(
|
|
650
|
+
function cloneClient(client, options) {
|
|
651
|
+
const preConf = getClientConfig(client);
|
|
747
652
|
const conf = {
|
|
748
653
|
...preConf,
|
|
749
654
|
...options
|
|
@@ -758,8 +663,8 @@ function getGlobalClient() {
|
|
|
758
663
|
}
|
|
759
664
|
return globalClient;
|
|
760
665
|
}
|
|
761
|
-
function setGlobalClient(
|
|
762
|
-
globalClient =
|
|
666
|
+
function setGlobalClient(client) {
|
|
667
|
+
globalClient = client;
|
|
763
668
|
}
|
|
764
669
|
function restGlobalClient() {
|
|
765
670
|
globalClient = undefined;
|
|
@@ -767,8 +672,6 @@ function restGlobalClient() {
|
|
|
767
672
|
function createGlobalClient(options) {
|
|
768
673
|
globalClient = createClient(options);
|
|
769
674
|
}
|
|
770
|
-
var CLIENT = Symbol("Client");
|
|
771
|
-
var globalClient;
|
|
772
675
|
// src/interceptor/authorization/basic_auth_interceptor.ts
|
|
773
676
|
function basicAuthInterceptor(fn, options) {
|
|
774
677
|
let encode = options?.encode;
|
|
@@ -879,12 +782,10 @@ export {
|
|
|
879
782
|
createClient,
|
|
880
783
|
cloneClient,
|
|
881
784
|
basicAuthInterceptor,
|
|
882
|
-
HttpErrorResponse,
|
|
883
785
|
ERR_UNSUPPORTED_FIELD_TYPE,
|
|
884
786
|
ERR_UNKNOWN,
|
|
885
787
|
ERR_TIMEOUT,
|
|
886
788
|
ERR_OBSERVE,
|
|
887
|
-
ERR_NOT_SET_ALIAS,
|
|
888
789
|
ERR_NOT_FOUND_HANDLER,
|
|
889
790
|
ERR_NOT_FOUND_GLOBAL_CLIENT,
|
|
890
791
|
ERR_NETWORK,
|
package/index.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var K=new Error("ERR_ABORTED"),X=new Error("ERR_TIMEOUT"),Ht=new Error("ERR_NETWORK"),W=new Error("ERR_NOT_FOUND_HANDLER"),pt=new Error("ERR_OBSERVE"),A=new Error("ERR_NOT_SET_ALIAS"),J=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),j=new Error("ERR_INVALID_CLIENT"),Q=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),y=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),Et=new Error("ERR_UNKNOWN");class f extends Error{status;statusText;url;headers;body;constructor(t){const n=t?.status??0,r=t?.statusText??"",o=n>=200&&n<300,T=t?.headers??new Headers,s=t?.url??"",i=t?.body??null;let R;if(o)R=`Http failure during parsing for ${s}`;else if(R=`Http failure response for ${s||"(unknown url)"}: ${n}`,r)R+=` - ${r}`;super(R,{cause:t?.error});super.name="HttpErrorResponse",this.statusText=r,this.url=s,this.headers=T,this.status=n,this.body=i}}function q(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function l(t){return t.get("Content-Type")||""}function v(t){const{request:n,content:r,contentType:o}=t;switch(n.responseType){case"json":{const s=new TextDecoder().decode(r);if(s==="")return null;return JSON.parse(s)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function tt(t,n){const r=new Uint8Array(n);let o=0;for(let T of t)r.set(T,o),o+=T.length;return r}function wt(t){return Object.defineProperty(t,nt,{value:t}),t}function P(t){return typeof t==="function"&&nt in t}function it(t){return typeof t==="object"&&t!==null&&Y in t}function Z(t){const n=new Map;switch(!0){case Array.isArray(t):{for(let[r,o]of t)if(P(r))n.set(r,o);break}case it(t):{for(let[r,o]of t[Y])n.set(r,o);break}}return{set(r,o){if(!P(r))throw y;return n.set(r,o),this},get(r){if(!P(r))throw y;if(!n.has(r))n.set(r,r());return n.get(r)},del(r){return n.delete(r),this},has(r){return n.has(r)},keys(){return n.keys()},get length(){return Array.from(n.keys()).length},[Y]:n}}var nt=Symbol("HttpContextToken"),Y=Symbol("HttpContext");function Rt(t){const n={required:typeof t!=="undefined",alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,a,{value:n}),r.withJson=(o)=>{return n.alias.set(0,o),r},r.withForm=(o)=>{return n.alias.set(4,o),r},r.withQuery=(o)=>{return n.alias.set(1,o),r},r.withParam=(o)=>{return n.alias.set(2,o),r},r.withHeader=(o)=>{return n.alias.set(3,o),r},r.withUrlForm=(o)=>{return n.alias.set(6,o),r},r.withBody=()=>{return n.alias.set(5,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function G(t){return t[a]}async function g(t,n){await Promise.all(t.map((r)=>r(n)))}function U(t){return!!t&&typeof t==="function"&&a in t}function V(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>U(n))}var a=Symbol("field");var ft=void 0;var rt=()=>ft;function ot(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(s)=>n(s,T))},(n,r)=>r(n))}function M(t){const n=t?.status??0,r=t?.statusText??"",o=t?.url??"",T=t?.headers??new Headers,s=t?.body??null;return{status:n,statusText:r,url:o,headers:T,body:s}}function xt(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer:case t instanceof URLSearchParams:case typeof t==="string":return t;case typeof t==="object":case typeof t==="boolean":case typeof t==="number":case Array.isArray(t):return JSON.stringify(t);default:return null}}function Tt(t){switch(!0){case t instanceof FormData:return"multipart/form-data";case t instanceof ArrayBuffer:return"application/octet-stream";case t instanceof Blob:return t.type||"application/octet-stream";case t instanceof URLSearchParams:return"application/x-www-form-urlencoded;charset=UTF-8";case typeof t==="string":return"text/plain";case(typeof t==="object"&&t!==null):case typeof t==="number":case typeof t==="boolean":return"application/json";default:return null}}function kt(t){if(U(t))return t();if(V(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function mt(...t){let n,r,o=!1,T,s=[],i="json",R,e=!1,p=[],E;switch(t.length){case 1:{n="GET",r=t[0];break}case 2:{n=t[0],r=t[1];break}default:throw new Error("Invalid arguments")}const c=(x)=>{const w=x?.timeout||0,N=x?.client||z(),H=d(N),_=x?.handler||H?.handler||rt();if(!_)throw W;let k,m,F;const h=[];if(x?.abort)h.push(x.abort);else F=new AbortController,h.push(F.signal);if(w>0)h.push(AbortSignal.timeout(w));return{doRequest:async(...I)=>{let D;if(o&&I.length===1)D=I[0];if(o&&!D)throw new Error("Because the request has input, the argument must be the input value");if(p.length>0)for(let u of p)u(D);const b={host:H?.host,method:n,endpoint:r,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:e,responseType:i,context:R||Z(),uploadProgress:k,downloadProgress:m,timeout:w,abort:AbortSignal.any(h)};if(o&&T)await Ct(b,T,D);let L=await ot([...H.interceptors,...s])(b,_);if(typeof E==="function")try{L=M({...L,body:E(L)})}catch(u){throw new f({error:u})}return L},cancel:()=>{F?.abort()},getInitValue:()=>kt(T),setUploadProgress:(I)=>{k=I},setDownloadProgress:(I)=>{m=I}}};return c.withField=(x)=>{return T=x,o=!0,c},c.withInterceptors=(x)=>{return s=x,c},c.withContext=(x)=>{return R=x,c},c.withCredentials=(x)=>{return e=x,c},c.withValidators=(x)=>{return p=x,c},c.withTransformResponse=(x)=>{return E=x,c},c.withResponseType=(x)=>{return i=x,c},c}function et(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function Ct(t,n,r){function o(e){return typeof e==="object"&&e!==null}function T(e){switch(!0){case Array.isArray(e):case(typeof e==="object"&&e!==null):return JSON.stringify(e);case(typeof e==="object"&&e===null):case typeof e==="boolean":case typeof e==="number":case typeof e==="string":return String(e);default:throw new Error("Unsupported value type")}}function s(e,p,E){if(Array.isArray(E))for(let c of E)e.append(p,T(c));else e.set(p,T(E));return e}function i(e,p,E){if(Array.isArray(E))for(let c of E)i(e,p,T(c));return e.set(p,T(E)),e}function R(e,p){switch(!0){case typeof e==="undefined":return p;case(typeof e==="object"&&e===null):return e;default:return e}}if(U(n)){let e,p,E,c=void 0;const x=R(r,n()),w=G(n);await g([...w.validators,...w.asyncValidator],x);for(let[N,H]of w.alias)switch(N){case 1:{if(!H)throw A;p=s(new URLSearchParams,H,x);break}case 2:{if(!H)throw A;e=i(new Map,H,x);break}case 3:{if(!H)throw A;E=s(new Headers,H,x);break}case 4:{if(!H)throw A;c=s(new FormData,H,x);break}case 6:{if(!H)throw A;c=s(new URLSearchParams,H,x);break}case 0:case 5:c=x;break}if(e)t.endpoint=et(t.endpoint,e);t.queryParams=p,t.headers=E,t.body=c;return}if(V(n)&&o(r)){let e=new Map,p=new URLSearchParams,E=new Headers,c=new URLSearchParams,x=new FormData;const w={};let N=void 0,H;for(let[_,k]of Object.entries(n)){const m=G(k);for(let[F,h]of m.alias){const O=h||_,C=R(r[_],k());switch(await g([...m.validators,...m.asyncValidator],C),F){case 0:{Object.defineProperty(w,O,{value:C,writable:!0,enumerable:!0}),H=0;break}case 1:p=s(p,O,C);break;case 2:e=i(e,O,C);break;case 3:E=s(E,O,C);break;case 4:{x=s(x,O,C),H=4;break}case 6:{c=s(c,O,C),H=6;break}case 5:{N=C,H=5;break}}}}switch(t.endpoint=et(t.endpoint,e),t.queryParams=p,t.headers=E,H){case 5:t.body=N;break;case 4:t.body=x;break;case 6:t.body=c;break;case 0:t.body=w;break}return}throw J}function Nt(t){const n=new URL(t.endpoint,t.host);if(t.queryParams)n.search=t.queryParams.toString();const r=t.headers??new Headers;if(!r.has("Content-Type")){const T=Tt(t.body);if(T)r.set("Content-Type",T)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0;return new Request(n,{headers:r,method:t.method,body:xt(t.body),signal:t.abort,credentials:o})}async function S(t){const n=t.downloadProgress,r=Nt(t),o=t.abort;let T;try{T=await globalThis.fetch(r)}catch(w){if(o?.aborted&&o.reason instanceof Error)switch(!0){case o.reason.name==="AbortError":throw new f({error:K});case o.reason.name==="TimeoutError":throw new f({error:X})}throw new f({error:w})}const{ok:s,headers:i,status:R,statusText:e,url:p}=T,E=q(i),c=l(i);let x=null;if(T.body){const w=[],N=T.body.getReader();let H=0;while(!0){const{done:k,value:m}=await N.read();if(k)break;w.push(m),H+=m.length,n?.({lengthComputable:E>0,loaded:H,total:E})}const _=tt(w,H);try{x=v({request:t,content:_,contentType:c})}catch(k){throw new f({error:k,status:R,statusText:e,headers:i,url:p})}}if(!s)throw new f({status:R,statusText:e,headers:i,url:p,body:x});return M({url:p,status:R,statusText:e,headers:i,body:x})}function ct(t){return typeof t==="object"&&t!==null&&$ in t}function d(t){if(!ct(t))throw j;return t[$]}function st(t){const n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||S};return{[$]:n}}function _t(t,n){const o={...d(t),...n};return{[$]:o}}function z(){if(!B)throw Q;return B}function Ot(t){B=t}function At(){B=void 0}function ht(t){B=st(t)}var $=Symbol("Client"),B;function It(t,n){let r=n?.encode;if(!r){const o=globalThis.btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(T)=>o(`${T.username}:${T.password}`)}return(o,T)=>{const s=o.headers||new Headers;return s.set("Authorization",`Basic ${r(t())}`),o.headers=s,T(o)}}var Ft=(t)=>{if(!t)return new Error("required");return null},Ut=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},Bt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},Dt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},Lt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},yt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Pt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Ot as setGlobalClient,At as restGlobalClient,Ut as requiredTrue,Ft as required,Pt as pattern,Bt as minLength,Lt as min,Dt as maxLength,yt as max,wt as makeHttpContextToken,Z as makeHttpContext,P as isHttpContextToken,V as isFieldGroup,U as isField,ct as isClient,z as getGlobalClient,Rt as field,S as fetchHandler,g as doValid,mt as defineRequest,ht as createGlobalClient,st as createClient,_t as cloneClient,It as basicAuthInterceptor,f as HttpErrorResponse,J as ERR_UNSUPPORTED_FIELD_TYPE,Et as ERR_UNKNOWN,X as ERR_TIMEOUT,pt as ERR_OBSERVE,A as ERR_NOT_SET_ALIAS,W as ERR_NOT_FOUND_HANDLER,Q as ERR_NOT_FOUND_GLOBAL_CLIENT,Ht as ERR_NETWORK,y as ERR_INVALID_HTTP_CONTEXT_TOKEN,j as ERR_INVALID_CLIENT,K as ERR_ABORTED};
|
|
1
|
+
var L=new Error("ERR_ABORTED"),h=new Error("ERR_TIMEOUT"),Tt=new Error("ERR_NETWORK"),B=new Error("ERR_NOT_FOUND_HANDLER"),it=new Error("ERR_OBSERVE"),xt=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),D=new Error("ERR_INVALID_CLIENT"),M=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),U=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN"),pt=new Error("ERR_UNKNOWN");function k(t){let n=t?.status??0,r=n>=200&&n<300,o=t?.statusText??"",x=t?.url??"",p=t?.headers??new Headers,w=t?.body??null,H=t?.error;if(!H&&!r){let e=`Http failure response for ${x||"(unknown url)"}: ${n}`;if(o)e+=` - ${o}`;H=new Error(e)}return{status:n,statusText:o,url:x,headers:p,body:w,error:H}}var G=Symbol("HttpContextToken");function ct(t){return Object.defineProperty(t,G,{value:t}),t}function y(t){return typeof t==="function"&&G in t}var g=Symbol("HttpContext");function Et(t){return typeof t==="object"&&t!==null&&g in t}function $(t){let n=new Map;switch(!0){case Array.isArray(t):{for(let[r,o]of t)if(y(r))n.set(r,o);break}case Et(t):{for(let[r,o]of t[g])n.set(r,o);break}}return{set(r,o){if(!y(r))throw U;return n.set(r,o),this},get(r){if(!y(r))throw U;if(!n.has(r))n.set(r,r());return n.get(r)},del(r){return n.delete(r),this},has(r){return n.has(r)},keys(){return n.keys()},get length(){return Array.from(n.keys()).length},[g]:n}}var K=Symbol("field");function Ht(t){let n={required:typeof t!=="undefined",alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,K,{value:n}),r.withJson=(o)=>{return n.alias.set(0,o),r},r.withForm=(o)=>{return n.alias.set(4,o),r},r.withQuery=(o)=>{return n.alias.set(1,o),r},r.withParam=(o)=>{return n.alias.set(2,o),r},r.withHeader=(o)=>{return n.alias.set(3,o),r},r.withUrlForm=(o)=>{return n.alias.set(6,o),r},r.withBody=()=>{return n.alias.set(5,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function Z(t){return t[K]}async function X(t,n){await Promise.all(t.map((r)=>r(n)))}function S(t){return!!t&&typeof t==="function"&&K in t}function u(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>S(n))}var wt=void 0;var z=()=>wt;function b(t){return t.reduceRight((n,r)=>{return(o,x)=>r(o,(p)=>n(p,x))},(n,r)=>r(n))}function l(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer:case t instanceof URLSearchParams:case typeof t==="string":return t;case typeof t==="object":case typeof t==="boolean":case typeof t==="number":case Array.isArray(t):return JSON.stringify(t);default:return null}}function q(t){switch(!0){case t instanceof FormData:return"multipart/form-data";case t instanceof ArrayBuffer:return"application/octet-stream";case t instanceof Blob:return t.type||"application/octet-stream";case t instanceof URLSearchParams:return"application/x-www-form-urlencoded;charset=UTF-8";case typeof t==="string":return"text/plain";case(typeof t==="object"&&t!==null):case typeof t==="number":case typeof t==="boolean":return"application/json";default:return null}}function Rt(t){if(u(t)){let n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function ft(...t){let n,r,o,x=[],p="json",w,H=!1,e=[],c;switch(t.length){case 1:{n="GET",r=t[0];break}case 2:{n=t[0],r=t[1];break}default:throw new Error("Invalid arguments")}let T=(i)=>{let E=i?.timeout||0,F=i?.client||J(),R=W(F),f=i?.handler||R?.handler||z();if(!f)throw B;let s,N,C,_=[];if(i?.abort)_.push(i.abort);else C=new AbortController,_.push(C.signal);if(E>0)_.push(AbortSignal.timeout(E));return{doRequest:async(...a)=>{let d;if(a.length===1)d=a[0];if(e.length>0)for(let I of e)I(d);let Y={host:R?.host,method:n,endpoint:r,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:H,responseType:p,context:w||$(),uploadProgress:s,downloadProgress:N,timeout:E,abort:AbortSignal.any(_)};try{if(d&&o)await mt(Y,o,d);let V=await b([...R.interceptors,...x])(Y,f);if(typeof c==="function")V=k({...V,body:c(V)});return V}catch(I){return k({error:I})}},cancel:()=>{C?.abort()},getInitValue:()=>Rt(o),setUploadProgress:(a)=>{s=a},setDownloadProgress:(a)=>{N=a}}};return T.withField=(i)=>{return o=i,T},T.withInterceptors=(i)=>{return x=i,T},T.withContext=(i)=>{return w=i,T},T.withCredentials=(i)=>{return H=i,T},T.withValidators=(...i)=>{return e=i,T},T.withTransformResponse=(i)=>{return c=i,T},T.withResponseType=(i)=>{return p=i,T},T}function st(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function mt(t,n,r){function o(e){return typeof e==="object"&&e!==null}function x(e){switch(!0){case Array.isArray(e):case(typeof e==="object"&&e!==null):return JSON.stringify(e);case(typeof e==="object"&&e===null):case typeof e==="boolean":case typeof e==="number":case typeof e==="string":case typeof e==="undefined":return String(e);default:throw new Error(`Unsupported value type: ${typeof e}`)}}function p(e,c,T){if(Array.isArray(T)){for(let i of T)e.append(c,x(i));return e}if(typeof T!=="undefined")e.set(c,x(T));return e}function w(e,c,T){if(Array.isArray(T)){for(let i of T)w(e,c,x(i));return e}if(typeof T!=="undefined")e.set(c,x(T));return e}function H(e,c){switch(!0){case typeof e==="undefined":return c;case(typeof e==="object"&&e===null):return e;default:return e}}if(u(n)&&o(r)){let e=new Map,c=new URLSearchParams,T=new Headers,i=new URLSearchParams,E=new FormData,F={},R=void 0,f;for(let[s,N]of Object.entries(n)){let C=Z(N);for(let[_,Q]of C.alias){let O=Q||s,m=H(r[s],N());switch(await X([...C.validators,...C.asyncValidator],m),_){case 0:{Object.defineProperty(F,O,{value:m,writable:!0,enumerable:!0}),f=0;break}case 1:c=p(c,O,m);break;case 2:e=w(e,O,m);break;case 3:T=p(T,O,m);break;case 4:{E=p(E,O,m),f=4;break}case 6:{i=p(i,O,m),f=6;break}case 5:{R=m,f=5;break}}}}switch(t.endpoint=st(t.endpoint,e),t.queryParams=c,t.headers=T,f){case 5:t.body=R;break;case 4:t.body=E;break;case 6:t.body=i;break;case 0:t.body=F;break}}}function v(t){let n=t.get("Content-Length");if(!n)return 0;let r=Number(n);if(isNaN(r))return 0;return r}function tt(t){return t.get("Content-Type")||""}function nt(t){let{request:n,content:r,contentType:o}=t;switch(n.responseType){case"json":{let p=new TextDecoder().decode(r);if(p==="")return null;return JSON.parse(p)}case"text":return new TextDecoder().decode(r);case"blob":return new Blob([r],{type:o});case"arraybuffer":return r.buffer;default:return null}}function rt(t,n){let r=new Uint8Array(n),o=0;for(let x of t)r.set(x,o),o+=x.length;return r}function kt(t){let n=new URL(t.endpoint,t.host);if(t.queryParams)n.search=t.queryParams.toString();let r=t.headers??new Headers;if(!r.has("Content-Type")){let x=q(t.body);if(x)r.set("Content-Type",x)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");let o=t.withCredentials?"include":void 0;return new Request(n,{headers:r,method:t.method,body:l(t.body),signal:t.abort,credentials:o})}async function j(t){let n=t.downloadProgress,r=kt(t),o=t.abort,x;try{x=await globalThis.fetch(r)}catch(E){if(o?.aborted&&o.reason instanceof Error)switch(!0){case o.reason.name==="AbortError":return k({error:L});case o.reason.name==="TimeoutError":return k({error:h})}return k({error:E})}let{headers:p,status:w,statusText:H,url:e}=x,c=v(p),T=tt(p),i=null;if(x.body){let E=[],F=x.body.getReader(),R=0;while(!0){let{done:s,value:N}=await F.read();if(s)break;E.push(N),R+=N.length,n?.({lengthComputable:c>0,loaded:R,total:c})}let f=rt(E,R);try{i=nt({request:t,content:f,contentType:T})}catch(s){return k({error:s,status:w,statusText:H,headers:p,url:e})}}return k({status:w,statusText:H,headers:p,url:e,body:i})}var P=Symbol("Client"),A;function ot(t){return typeof t==="object"&&t!==null&&P in t}function W(t){if(!ot(t))throw D;return t[P]}function et(t){let n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||j};return{[P]:n}}function Nt(t,n){let o={...W(t),...n};return{[P]:o}}function J(){if(!A)throw M;return A}function Ct(t){A=t}function Ot(){A=void 0}function Ft(t){A=et(t)}function _t(t,n){let r=n?.encode;if(!r){let o=globalThis.btoa;if(typeof o!=="function")throw new Error("BasicAuthInterceptor is not supported in this environment");r=(x)=>o(`${x.username}:${x.password}`)}return(o,x)=>{let p=o.headers||new Headers;return p.set("Authorization",`Basic ${r(t())}`),o.headers=p,x(o)}}var at=(t)=>{if(!t)return new Error("required");return null},At=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},dt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},It=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},Vt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},Ut=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},yt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(!t.test(n))return new Error("pattern");return null}};export{Ct as setGlobalClient,Ot as restGlobalClient,At as requiredTrue,at as required,yt as pattern,dt as minLength,Vt as min,It as maxLength,Ut as max,ct as makeHttpContextToken,$ as makeHttpContext,y as isHttpContextToken,u as isFieldGroup,S as isField,ot as isClient,J as getGlobalClient,Ht as field,j as fetchHandler,X as doValid,ft as defineRequest,Ft as createGlobalClient,et as createClient,Nt as cloneClient,_t as basicAuthInterceptor,xt as ERR_UNSUPPORTED_FIELD_TYPE,pt as ERR_UNKNOWN,h as ERR_TIMEOUT,it as ERR_OBSERVE,B as ERR_NOT_FOUND_HANDLER,M as ERR_NOT_FOUND_GLOBAL_CLIENT,Tt as ERR_NETWORK,U as ERR_INVALID_HTTP_CONTEXT_TOKEN,D as ERR_INVALID_CLIENT,L as ERR_ABORTED};
|