@defjs/core 0.0.0-test-0014 → 0.0.0-test-001
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/LICENSE +21 -0
- package/{dist/index.d.ts → index.d.ts} +85 -26
- package/{dist/index.js → index.js} +346 -142
- package/index.min.js +1 -0
- package/package.json +14 -14
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 MunMunMiao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -1,15 +1,26 @@
|
|
|
1
|
-
|
|
1
|
+
declare const HTTP_CONTEXT_TOKEN: unique symbol;
|
|
2
|
+
export type HttpContextToken<T> = (() => T) & {
|
|
3
|
+
readonly [HTTP_CONTEXT_TOKEN]: () => T;
|
|
4
|
+
};
|
|
2
5
|
export declare function makeHttpContextToken<T>(defaultValue: () => T): HttpContextToken<T>;
|
|
6
|
+
export declare function isHttpContextToken(value: unknown): value is HttpContextToken<unknown>;
|
|
3
7
|
export type HttpContext = {
|
|
4
8
|
set<T>(token: HttpContextToken<T>, value: T): HttpContext;
|
|
5
9
|
get<T>(token: HttpContextToken<T>): T;
|
|
6
|
-
|
|
10
|
+
del(token: HttpContextToken<unknown>): HttpContext;
|
|
7
11
|
has(token: HttpContextToken<unknown>): boolean;
|
|
8
12
|
keys(): IterableIterator<HttpContextToken<unknown>>;
|
|
9
13
|
};
|
|
10
14
|
export declare function makeHttpContext(): HttpContext;
|
|
11
15
|
export type ValidatorFn<T = unknown> = (value: T) => Error | null | undefined;
|
|
12
16
|
export type AsyncValidatorFn<T = unknown> = (value: T) => Promise<Error | null | undefined>;
|
|
17
|
+
export declare const required: ValidatorFn;
|
|
18
|
+
export declare const requiredTrue: ValidatorFn;
|
|
19
|
+
export declare const minLength: (min: number) => ValidatorFn;
|
|
20
|
+
export declare const maxLength: (max: number) => ValidatorFn;
|
|
21
|
+
export declare const min: (min: number) => ValidatorFn;
|
|
22
|
+
export declare const max: (max: number) => ValidatorFn;
|
|
23
|
+
export declare const pattern: (pattern: string | RegExp) => ValidatorFn;
|
|
13
24
|
declare const FIELD: unique symbol;
|
|
14
25
|
declare enum FieldType {
|
|
15
26
|
Json = 1,
|
|
@@ -38,24 +49,29 @@ export type Field<T = undefined> = (() => T) & {
|
|
|
38
49
|
export declare function field(): Field;
|
|
39
50
|
export declare function field<T>(): Field<T | undefined>;
|
|
40
51
|
export declare function field<T>(defaultValue: T): Field<T>;
|
|
52
|
+
export declare function validatorField(validators: ValidatorFn<any>[], value: unknown): void;
|
|
53
|
+
export declare function asyncValidatorField(asyncValidator: AsyncValidatorFn<any>[], value: unknown): Promise<void>;
|
|
41
54
|
export declare function isField(value: unknown): value is Field;
|
|
42
55
|
export declare function isFieldGroup(value: unknown): value is Record<PropertyKey, Field>;
|
|
56
|
+
declare const HTTP_RESPONSE: unique symbol;
|
|
43
57
|
export type HttpResponseBody = string | ArrayBuffer | Blob | object | null;
|
|
44
|
-
export type HttpResponse<R> = {
|
|
45
|
-
ok: true;
|
|
46
|
-
|
|
47
|
-
statusText: string;
|
|
48
|
-
url: string;
|
|
49
|
-
headers: Headers;
|
|
50
|
-
body: R | null;
|
|
58
|
+
export type HttpResponse<R> = ({
|
|
59
|
+
readonly ok: true;
|
|
60
|
+
readonly error: null;
|
|
51
61
|
} | {
|
|
62
|
+
readonly ok: false;
|
|
63
|
+
readonly error: Error;
|
|
64
|
+
}) & {
|
|
65
|
+
readonly url: string;
|
|
66
|
+
readonly status: number;
|
|
67
|
+
readonly statusText: string;
|
|
68
|
+
readonly headers: Headers;
|
|
69
|
+
readonly body: R | null;
|
|
70
|
+
readonly [HTTP_RESPONSE]: unknown;
|
|
71
|
+
};
|
|
72
|
+
export declare function isHttpResponse<R>(value: unknown): value is HttpResponse<R>;
|
|
73
|
+
export declare function isHttpResponseError<R>(value: unknown): value is HttpResponse<R> & {
|
|
52
74
|
ok: false;
|
|
53
|
-
error: Error;
|
|
54
|
-
status: number;
|
|
55
|
-
statusText: string;
|
|
56
|
-
url: string;
|
|
57
|
-
headers: Headers;
|
|
58
|
-
body: R | null;
|
|
59
75
|
};
|
|
60
76
|
export type MakeResponseOptions<R> = {
|
|
61
77
|
status?: number;
|
|
@@ -67,6 +83,14 @@ export type MakeResponseOptions<R> = {
|
|
|
67
83
|
};
|
|
68
84
|
export declare function makeResponse<R>(options: MakeResponseOptions<R>): HttpResponse<R>;
|
|
69
85
|
export type InterceptorFn = (req: HttpRequest, next: HttpHandler) => Promise<HttpResponse<unknown>>;
|
|
86
|
+
export type BasicCredential = {
|
|
87
|
+
username: string;
|
|
88
|
+
password: string;
|
|
89
|
+
};
|
|
90
|
+
export type BasicAuthInterceptorOptions = {
|
|
91
|
+
encode?: (credential: BasicCredential) => string;
|
|
92
|
+
};
|
|
93
|
+
export declare function basicAuthInterceptor(fn: () => BasicCredential, options?: BasicAuthInterceptorOptions): InterceptorFn;
|
|
70
94
|
export type HttpResponseType = "arraybuffer" | "blob" | "json" | "text";
|
|
71
95
|
export interface HttpProgressEvent {
|
|
72
96
|
/**
|
|
@@ -83,7 +107,7 @@ export interface HttpProgressEvent {
|
|
|
83
107
|
readonly total: number;
|
|
84
108
|
}
|
|
85
109
|
export type HttpProgressFn = (event: HttpProgressEvent) => void;
|
|
86
|
-
export type TransformRequestFn = (request: HttpRequest) => HttpRequest["body"];
|
|
110
|
+
export type TransformRequestFn<Input = unknown> = (input: Input, request: HttpRequest) => HttpRequest["body"];
|
|
87
111
|
export type TransformResponseFn<Output = unknown> = (response: HttpResponse<unknown>) => Output;
|
|
88
112
|
export interface HttpRequest {
|
|
89
113
|
host?: string;
|
|
@@ -100,7 +124,11 @@ export interface HttpRequest {
|
|
|
100
124
|
/** when use fetch handler, no upload progress */
|
|
101
125
|
uploadProgress?: HttpProgressFn;
|
|
102
126
|
downloadProgress?: HttpProgressFn;
|
|
103
|
-
/**
|
|
127
|
+
/**
|
|
128
|
+
* default:body
|
|
129
|
+
*
|
|
130
|
+
* @todo Implement streaming response
|
|
131
|
+
*/
|
|
104
132
|
observe?: "body" | "stream" | "response";
|
|
105
133
|
abort?: AbortSignal;
|
|
106
134
|
}
|
|
@@ -125,7 +153,7 @@ export type RequestOptions<Output = unknown, Input extends Field<any> | Record<P
|
|
|
125
153
|
export type DoRequestOptions = {
|
|
126
154
|
abort?: AbortSignal;
|
|
127
155
|
handler?: HttpHandler;
|
|
128
|
-
client?:
|
|
156
|
+
client?: Client;
|
|
129
157
|
timeout?: number;
|
|
130
158
|
};
|
|
131
159
|
export type DoRequestFn<Input = unknown, Output = unknown> = Input extends undefined ? (options?: DoRequestOptions) => Promise<Output> : (input: RequestInputValue<Input>, options?: DoRequestOptions) => Promise<Output>;
|
|
@@ -150,7 +178,7 @@ export declare function defineRequest<Output = unknown, Input extends Field<any>
|
|
|
150
178
|
context?: HttpContext;
|
|
151
179
|
withCredentials?: boolean;
|
|
152
180
|
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
153
|
-
transformRequest?: TransformRequestFn
|
|
181
|
+
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
154
182
|
transformResponse?: TransformResponseFn<Output>;
|
|
155
183
|
}): UseRequestFn<Output, Input>;
|
|
156
184
|
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
@@ -163,7 +191,7 @@ export declare function defineRequest<Input extends Field<any> | Record<Property
|
|
|
163
191
|
context?: HttpContext;
|
|
164
192
|
withCredentials?: boolean;
|
|
165
193
|
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
166
|
-
transformRequest?: TransformRequestFn
|
|
194
|
+
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
167
195
|
transformResponse?: TransformResponseFn;
|
|
168
196
|
}): UseRequestFn<string, Input>;
|
|
169
197
|
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
@@ -176,7 +204,7 @@ export declare function defineRequest<Input extends Field<any> | Record<Property
|
|
|
176
204
|
context?: HttpContext;
|
|
177
205
|
withCredentials?: boolean;
|
|
178
206
|
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
179
|
-
transformRequest?: TransformRequestFn
|
|
207
|
+
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
180
208
|
transformResponse?: TransformResponseFn;
|
|
181
209
|
}): UseRequestFn<Blob, Input>;
|
|
182
210
|
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
@@ -189,7 +217,7 @@ export declare function defineRequest<Input extends Field<any> | Record<Property
|
|
|
189
217
|
context?: HttpContext;
|
|
190
218
|
withCredentials?: boolean;
|
|
191
219
|
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
192
|
-
transformRequest?: TransformRequestFn
|
|
220
|
+
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
193
221
|
transformResponse?: TransformResponseFn;
|
|
194
222
|
}): UseRequestFn<ArrayBuffer, Input>;
|
|
195
223
|
/** Observe: Response */
|
|
@@ -203,7 +231,7 @@ export declare function defineRequest<Output = unknown, Input extends Field<any>
|
|
|
203
231
|
context?: HttpContext;
|
|
204
232
|
withCredentials?: boolean;
|
|
205
233
|
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
206
|
-
transformRequest?: TransformRequestFn
|
|
234
|
+
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
207
235
|
transformResponse?: TransformResponseFn<Output>;
|
|
208
236
|
}): UseRequestFn<HttpResponse<Output>, Input>;
|
|
209
237
|
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
@@ -216,7 +244,7 @@ export declare function defineRequest<Input extends Field<any> | Record<Property
|
|
|
216
244
|
context?: HttpContext;
|
|
217
245
|
withCredentials?: boolean;
|
|
218
246
|
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
219
|
-
transformRequest?: TransformRequestFn
|
|
247
|
+
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
220
248
|
transformResponse?: TransformResponseFn;
|
|
221
249
|
}): UseRequestFn<HttpResponse<string>, Input>;
|
|
222
250
|
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
@@ -229,7 +257,7 @@ export declare function defineRequest<Input extends Field<any> | Record<Property
|
|
|
229
257
|
context?: HttpContext;
|
|
230
258
|
withCredentials?: boolean;
|
|
231
259
|
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
232
|
-
transformRequest?: TransformRequestFn
|
|
260
|
+
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
233
261
|
transformResponse?: TransformResponseFn;
|
|
234
262
|
}): UseRequestFn<HttpResponse<Blob>, Input>;
|
|
235
263
|
export declare function defineRequest<Input extends Field<any> | Record<PropertyKey, Field<any>> | undefined = undefined>(options: {
|
|
@@ -242,10 +270,28 @@ export declare function defineRequest<Input extends Field<any> | Record<Property
|
|
|
242
270
|
context?: HttpContext;
|
|
243
271
|
withCredentials?: boolean;
|
|
244
272
|
validators?: (ValidatorFn<RequestInputValue<Input>> | AsyncValidatorFn<RequestInputValue<Input>>)[];
|
|
245
|
-
transformRequest?: TransformRequestFn
|
|
273
|
+
transformRequest?: TransformRequestFn<RequestInputValue<Input>>;
|
|
246
274
|
transformResponse?: TransformResponseFn;
|
|
247
275
|
}): UseRequestFn<HttpResponse<ArrayBuffer>, Input>;
|
|
248
276
|
export type HttpHandler = (req: HttpRequest) => Promise<HttpResponse<unknown>>;
|
|
277
|
+
export interface FetchConfig {
|
|
278
|
+
/** A string indicating how the request will interact with the browser's cache to set request's cache. */
|
|
279
|
+
cache?: RequestCache;
|
|
280
|
+
/** A string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. Sets request's credentials. */
|
|
281
|
+
credentials?: RequestCredentials;
|
|
282
|
+
/** A boolean to set request's keepalive. */
|
|
283
|
+
keepalive?: boolean;
|
|
284
|
+
/** A string to indicate whether the request will use CORS, or will be restricted to same-origin URLs. Sets request's mode. */
|
|
285
|
+
mode?: RequestMode;
|
|
286
|
+
priority?: RequestPriority;
|
|
287
|
+
/** A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */
|
|
288
|
+
redirect?: RequestRedirect;
|
|
289
|
+
/** A string whose value is a same-origin URL, "about:client", or the empty string, to set request's referrer. */
|
|
290
|
+
referrer?: string;
|
|
291
|
+
/** A referrer policy to set request's referrerPolicy. */
|
|
292
|
+
referrerPolicy?: ReferrerPolicy;
|
|
293
|
+
}
|
|
294
|
+
export declare const FETCH_CONFIG_KEY: HttpContextToken<FetchConfig>;
|
|
249
295
|
export declare function fetchHandler(httpRequest: HttpRequest): Promise<HttpResponse<unknown>>;
|
|
250
296
|
export interface ClientOptions {
|
|
251
297
|
host: string;
|
|
@@ -263,9 +309,22 @@ export type Client = {} & {
|
|
|
263
309
|
};
|
|
264
310
|
export declare function isClient(value: unknown): value is Client;
|
|
265
311
|
export declare function createClient(options: ClientOptions): Client;
|
|
312
|
+
export declare function cloneClient(client: Client, options: ClientOptions): Client;
|
|
266
313
|
export declare function getGlobalClient(): Client;
|
|
267
314
|
export declare function setGlobalClient(client: Client): void;
|
|
268
315
|
export declare function restGlobalClient(): void;
|
|
269
316
|
export declare function createGlobalClient(options: ClientOptions): void;
|
|
317
|
+
export declare const ERR_ABORTED: Error;
|
|
318
|
+
export declare const ERR_TIMEOUT: Error;
|
|
319
|
+
export declare const ERR_NETWORK: Error;
|
|
320
|
+
export declare const ERR_NOT_FOUND_HANDLER: Error;
|
|
321
|
+
export declare const ERR_TRANSFORM_RESPONSE: Error;
|
|
322
|
+
export declare const ERR_STREAMING_NOT_IMPLEMENTED: Error;
|
|
323
|
+
export declare const ERR_OBSERVE: Error;
|
|
324
|
+
export declare const ERR_NOT_SET_ALIAS: Error;
|
|
325
|
+
export declare const ERR_UNSUPPORTED_FIELD_TYPE: Error;
|
|
326
|
+
export declare const ERR_INVALID_CLIENT: Error;
|
|
327
|
+
export declare const ERR_NOT_FOUND_GLOBAL_CLIENT: Error;
|
|
328
|
+
export declare const ERR_INVALID_HTTP_CONTEXT_TOKEN: Error;
|
|
270
329
|
|
|
271
330
|
export {};
|
|
@@ -1,21 +1,49 @@
|
|
|
1
|
+
// src/error.ts
|
|
2
|
+
function __withErrorCause(err, cause) {
|
|
3
|
+
err.cause = cause;
|
|
4
|
+
return err;
|
|
5
|
+
}
|
|
6
|
+
var ERR_ABORTED = new Error("ERR_ABORTED");
|
|
7
|
+
var ERR_TIMEOUT = new Error("ERR_TIMEOUT");
|
|
8
|
+
var ERR_NETWORK = new Error("ERR_NETWORK");
|
|
9
|
+
var ERR_NOT_FOUND_HANDLER = new Error("ERR_NOT_FOUND_HANDLER");
|
|
10
|
+
var ERR_TRANSFORM_RESPONSE = new Error("ERR_TRANSFORM_RESPONSE");
|
|
11
|
+
var ERR_STREAMING_NOT_IMPLEMENTED = new Error("ERR_STREAMING_NOT_IMPLEMENTED");
|
|
12
|
+
var ERR_OBSERVE = new Error("ERR_OBSERVE");
|
|
13
|
+
var ERR_NOT_SET_ALIAS = new Error("ERR_NOT_SET_ALIAS");
|
|
14
|
+
var ERR_UNSUPPORTED_FIELD_TYPE = new Error("ERR_UNSUPPORTED_FIELD_TYPE");
|
|
15
|
+
var ERR_INVALID_CLIENT = new Error("ERR_INVALID_CLIENT");
|
|
16
|
+
var ERR_NOT_FOUND_GLOBAL_CLIENT = new Error("ERR_NOT_FOUND_GLOBAL_CLIENT");
|
|
17
|
+
var ERR_INVALID_HTTP_CONTEXT_TOKEN = new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN");
|
|
18
|
+
|
|
1
19
|
// src/context.ts
|
|
2
20
|
function makeHttpContextToken(defaultValue) {
|
|
21
|
+
Object.defineProperty(defaultValue, HTTP_CONTEXT_TOKEN, { value: defaultValue });
|
|
3
22
|
return defaultValue;
|
|
4
23
|
}
|
|
24
|
+
function isHttpContextToken(value) {
|
|
25
|
+
return typeof value === "function" && HTTP_CONTEXT_TOKEN in value;
|
|
26
|
+
}
|
|
5
27
|
function makeHttpContext() {
|
|
6
28
|
const ctx = new Map;
|
|
7
29
|
return {
|
|
8
30
|
set(token, value) {
|
|
31
|
+
if (!isHttpContextToken(token)) {
|
|
32
|
+
throw ERR_INVALID_HTTP_CONTEXT_TOKEN;
|
|
33
|
+
}
|
|
9
34
|
ctx.set(token, value);
|
|
10
35
|
return this;
|
|
11
36
|
},
|
|
12
37
|
get(token) {
|
|
38
|
+
if (!isHttpContextToken(token)) {
|
|
39
|
+
throw ERR_INVALID_HTTP_CONTEXT_TOKEN;
|
|
40
|
+
}
|
|
13
41
|
if (!ctx.has(token)) {
|
|
14
42
|
ctx.set(token, token());
|
|
15
43
|
}
|
|
16
44
|
return ctx.get(token);
|
|
17
45
|
},
|
|
18
|
-
|
|
46
|
+
del(token) {
|
|
19
47
|
ctx.delete(token);
|
|
20
48
|
return this;
|
|
21
49
|
},
|
|
@@ -27,6 +55,7 @@ function makeHttpContext() {
|
|
|
27
55
|
}
|
|
28
56
|
};
|
|
29
57
|
}
|
|
58
|
+
var HTTP_CONTEXT_TOKEN = Symbol("HttpContextToken");
|
|
30
59
|
|
|
31
60
|
// src/field.ts
|
|
32
61
|
function field(defaultValue) {
|
|
@@ -73,9 +102,25 @@ function field(defaultValue) {
|
|
|
73
102
|
};
|
|
74
103
|
return getter;
|
|
75
104
|
}
|
|
76
|
-
function
|
|
105
|
+
function __getFieldMetadata(field2) {
|
|
77
106
|
return field2[FIELD];
|
|
78
107
|
}
|
|
108
|
+
function validatorField(validators, value) {
|
|
109
|
+
for (const fn of validators) {
|
|
110
|
+
const err = fn(value);
|
|
111
|
+
if (err) {
|
|
112
|
+
throw err;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
async function asyncValidatorField(asyncValidator, value) {
|
|
117
|
+
for (const fn of asyncValidator) {
|
|
118
|
+
const err = await fn(value);
|
|
119
|
+
if (err) {
|
|
120
|
+
throw err;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
79
124
|
function isField(value) {
|
|
80
125
|
return !!value && typeof value === "function" && FIELD in value;
|
|
81
126
|
}
|
|
@@ -88,15 +133,55 @@ var FIELD = Symbol("field");
|
|
|
88
133
|
var globalHttpHandler = undefined;
|
|
89
134
|
var getGlobalHttpHandler = () => globalHttpHandler;
|
|
90
135
|
|
|
91
|
-
// src/interceptor.ts
|
|
136
|
+
// src/interceptor/interceptor.ts
|
|
92
137
|
function makeInterceptorChain(interceptors) {
|
|
93
138
|
return interceptors.reduceRight((fn, interceptor) => {
|
|
94
139
|
return (initReq, finalHandlerFn) => interceptor(initReq, (req) => fn(req, finalHandlerFn));
|
|
95
140
|
}, (req, fn) => fn(req));
|
|
96
141
|
}
|
|
97
142
|
|
|
143
|
+
// src/response.ts
|
|
144
|
+
function isHttpResponse(value) {
|
|
145
|
+
return typeof value === "object" && value !== null && HTTP_RESPONSE in value;
|
|
146
|
+
}
|
|
147
|
+
function isHttpResponseError(value) {
|
|
148
|
+
return isHttpResponse(value) && !value.ok;
|
|
149
|
+
}
|
|
150
|
+
function makeResponse(options) {
|
|
151
|
+
const status = options.status ?? 0;
|
|
152
|
+
const statusText = options.statusText ?? "";
|
|
153
|
+
const ok = status >= 200 && status < 300;
|
|
154
|
+
const url = options.url ?? "";
|
|
155
|
+
const headers = options.headers ?? new Headers;
|
|
156
|
+
const body = options.body ?? null;
|
|
157
|
+
if (!ok || options.error) {
|
|
158
|
+
const error2 = options.error || new Error(`Http failure response for ${options.url}: ${status} ${statusText}`);
|
|
159
|
+
return {
|
|
160
|
+
ok: false,
|
|
161
|
+
error: error2,
|
|
162
|
+
status,
|
|
163
|
+
statusText,
|
|
164
|
+
url,
|
|
165
|
+
headers,
|
|
166
|
+
body,
|
|
167
|
+
[HTTP_RESPONSE]: null
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
ok: true,
|
|
172
|
+
error: null,
|
|
173
|
+
status,
|
|
174
|
+
statusText,
|
|
175
|
+
url,
|
|
176
|
+
headers,
|
|
177
|
+
body,
|
|
178
|
+
[HTTP_RESPONSE]: null
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
var HTTP_RESPONSE = Symbol("HTTP_RESPONSE");
|
|
182
|
+
|
|
98
183
|
// src/request.ts
|
|
99
|
-
function
|
|
184
|
+
function __serializeBody(body) {
|
|
100
185
|
switch (true) {
|
|
101
186
|
case body instanceof FormData:
|
|
102
187
|
case body instanceof Blob:
|
|
@@ -112,7 +197,7 @@ function serializeBody(body) {
|
|
|
112
197
|
return null;
|
|
113
198
|
}
|
|
114
199
|
}
|
|
115
|
-
function
|
|
200
|
+
function __detectContentTypeHeader(body) {
|
|
116
201
|
switch (true) {
|
|
117
202
|
case body instanceof FormData:
|
|
118
203
|
return "multipart/form-data";
|
|
@@ -134,7 +219,7 @@ function detectContentTypeHeader(body) {
|
|
|
134
219
|
return null;
|
|
135
220
|
}
|
|
136
221
|
}
|
|
137
|
-
function
|
|
222
|
+
function __buildFieldValue(input) {
|
|
138
223
|
if (isField(input)) {
|
|
139
224
|
return input();
|
|
140
225
|
}
|
|
@@ -163,17 +248,34 @@ function defineRequest(options) {
|
|
|
163
248
|
const setDownloadProgress = (fn) => {
|
|
164
249
|
downloadProgress = fn;
|
|
165
250
|
};
|
|
166
|
-
const doRequest = async (
|
|
251
|
+
const doRequest = async (...args) => {
|
|
252
|
+
let input;
|
|
253
|
+
let doRequestOptions;
|
|
254
|
+
switch (args.length) {
|
|
255
|
+
case 1: {
|
|
256
|
+
doRequestOptions = args[0];
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
case 2: {
|
|
260
|
+
input = args[0];
|
|
261
|
+
doRequestOptions = args[1];
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
167
265
|
if (requiredInput && !input) {
|
|
168
|
-
throw new Error(
|
|
266
|
+
throw new Error(`Because the request has input, the first argument must be the input value`);
|
|
169
267
|
}
|
|
170
|
-
|
|
171
|
-
|
|
268
|
+
const timeout = doRequestOptions?.timeout || 0;
|
|
269
|
+
if (doRequestOptions?.abort) {
|
|
270
|
+
abortSignal = doRequestOptions.abort;
|
|
271
|
+
} else if (timeout > 0) {
|
|
272
|
+
abortSignal = AbortSignal.timeout(timeout);
|
|
172
273
|
} else {
|
|
173
274
|
abortController = new AbortController;
|
|
174
275
|
abortSignal = abortController.signal;
|
|
175
276
|
}
|
|
176
|
-
const
|
|
277
|
+
const client2 = isClient(doRequestOptions?.client) ? doRequestOptions.client : getGlobalClient();
|
|
278
|
+
const clientOptions = getClientConfig(client2);
|
|
177
279
|
const req = {
|
|
178
280
|
host: clientOptions?.host,
|
|
179
281
|
method: requestOptions.method,
|
|
@@ -187,59 +289,75 @@ function defineRequest(options) {
|
|
|
187
289
|
observe: requestOptions.observe ?? "body",
|
|
188
290
|
uploadProgress,
|
|
189
291
|
downloadProgress,
|
|
190
|
-
timeout
|
|
292
|
+
timeout,
|
|
191
293
|
abort: abortSignal
|
|
192
294
|
};
|
|
193
|
-
const handler2 =
|
|
295
|
+
const handler2 = doRequestOptions?.handler || clientOptions?.handler || getGlobalHttpHandler();
|
|
194
296
|
if (!handler2) {
|
|
195
|
-
throw
|
|
297
|
+
throw ERR_NOT_FOUND_HANDLER;
|
|
196
298
|
}
|
|
197
299
|
if (requiredInput) {
|
|
198
|
-
await
|
|
300
|
+
await __fillRequestFromField(req, requestOptions.input, input);
|
|
199
301
|
}
|
|
200
302
|
if (typeof requestOptions.transformRequest === "function") {
|
|
201
|
-
req.body = requestOptions.transformRequest(req);
|
|
303
|
+
req.body = requestOptions.transformRequest(input, req);
|
|
202
304
|
}
|
|
203
305
|
const chain = makeInterceptorChain([...clientOptions?.interceptors || [], ...requestOptions?.interceptors || []]);
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
306
|
+
let res;
|
|
307
|
+
try {
|
|
308
|
+
res = await chain(req, handler2);
|
|
309
|
+
} catch (error3) {
|
|
310
|
+
if (error3 instanceof DOMException) {
|
|
311
|
+
switch (true) {
|
|
312
|
+
case (error3.name === "AbortError" || error3.code === error3.ABORT_ERR):
|
|
313
|
+
throw ERR_ABORTED;
|
|
314
|
+
case (error3.name === "TimeoutError" || error3.code === error3.TIMEOUT_ERR):
|
|
315
|
+
throw ERR_TIMEOUT;
|
|
208
316
|
}
|
|
209
|
-
}
|
|
317
|
+
}
|
|
318
|
+
throw makeResponse({
|
|
319
|
+
error: __withErrorCause(ERR_NETWORK, error3)
|
|
320
|
+
});
|
|
210
321
|
}
|
|
211
|
-
const res = await chain(req, handler2);
|
|
212
322
|
if (typeof requestOptions.transformResponse === "function") {
|
|
213
|
-
|
|
323
|
+
try {
|
|
324
|
+
res = makeResponse({
|
|
325
|
+
...res,
|
|
326
|
+
body: requestOptions.transformResponse(res),
|
|
327
|
+
error: undefined
|
|
328
|
+
});
|
|
329
|
+
} catch (error3) {
|
|
330
|
+
throw makeResponse({
|
|
331
|
+
...res,
|
|
332
|
+
error: __withErrorCause(ERR_TRANSFORM_RESPONSE, error3)
|
|
333
|
+
});
|
|
334
|
+
}
|
|
214
335
|
}
|
|
215
336
|
switch (req.observe) {
|
|
216
337
|
case "body":
|
|
217
338
|
return res.body;
|
|
218
339
|
case "stream":
|
|
219
|
-
throw
|
|
340
|
+
throw ERR_STREAMING_NOT_IMPLEMENTED;
|
|
220
341
|
case "response":
|
|
221
342
|
return res;
|
|
222
343
|
default:
|
|
223
|
-
throw
|
|
344
|
+
throw ERR_OBSERVE;
|
|
224
345
|
}
|
|
225
346
|
};
|
|
226
347
|
return {
|
|
227
348
|
doRequest,
|
|
228
|
-
inputValue:
|
|
349
|
+
inputValue: __buildFieldValue(requestOptions.input),
|
|
229
350
|
setUploadProgress,
|
|
230
351
|
setDownloadProgress
|
|
231
352
|
};
|
|
232
353
|
};
|
|
233
354
|
}
|
|
234
|
-
function
|
|
235
|
-
throw new Error("alias not set");
|
|
236
|
-
}
|
|
237
|
-
function fillUrl(endpoint, params) {
|
|
355
|
+
function __fillUrl(endpoint, params) {
|
|
238
356
|
return endpoint.replace(/:([^\/]+)/g, (_, p1) => {
|
|
239
357
|
return params.get(p1) ?? "undefined";
|
|
240
358
|
});
|
|
241
359
|
}
|
|
242
|
-
async function
|
|
360
|
+
async function __fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
243
361
|
async function doValid(validators, value) {
|
|
244
362
|
for (const validator of validators) {
|
|
245
363
|
const err = await validator(value);
|
|
@@ -278,7 +396,7 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
278
396
|
let headers;
|
|
279
397
|
let body = undefined;
|
|
280
398
|
const fieldValue = input ?? fieldOrFieldGroup();
|
|
281
|
-
const meta =
|
|
399
|
+
const meta = __getFieldMetadata(fieldOrFieldGroup);
|
|
282
400
|
const err = await doValid([...meta.validators, ...meta.asyncValidator], fieldValue);
|
|
283
401
|
if (err) {
|
|
284
402
|
throw err;
|
|
@@ -287,28 +405,28 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
287
405
|
switch (type) {
|
|
288
406
|
case 2 /* Query */: {
|
|
289
407
|
if (!aliasName) {
|
|
290
|
-
|
|
408
|
+
throw ERR_NOT_SET_ALIAS;
|
|
291
409
|
}
|
|
292
410
|
queryParams = appendValue(new URLSearchParams, aliasName, fieldValue);
|
|
293
411
|
break;
|
|
294
412
|
}
|
|
295
413
|
case 3 /* Param */: {
|
|
296
414
|
if (!aliasName) {
|
|
297
|
-
|
|
415
|
+
throw ERR_NOT_SET_ALIAS;
|
|
298
416
|
}
|
|
299
417
|
params = setValue(new Map, aliasName, fieldValue);
|
|
300
418
|
break;
|
|
301
419
|
}
|
|
302
420
|
case 4 /* Header */: {
|
|
303
421
|
if (!aliasName) {
|
|
304
|
-
|
|
422
|
+
throw ERR_NOT_SET_ALIAS;
|
|
305
423
|
}
|
|
306
424
|
headers = appendValue(new Headers, aliasName, fieldValue);
|
|
307
425
|
break;
|
|
308
426
|
}
|
|
309
427
|
case 5 /* Form */: {
|
|
310
428
|
if (!aliasName) {
|
|
311
|
-
|
|
429
|
+
throw ERR_NOT_SET_ALIAS;
|
|
312
430
|
}
|
|
313
431
|
body = appendValue(new FormData, aliasName, fieldValue);
|
|
314
432
|
break;
|
|
@@ -320,7 +438,7 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
320
438
|
}
|
|
321
439
|
}
|
|
322
440
|
if (params) {
|
|
323
|
-
request.endpoint =
|
|
441
|
+
request.endpoint = __fillUrl(request.endpoint, params);
|
|
324
442
|
}
|
|
325
443
|
request.queryParams = queryParams;
|
|
326
444
|
request.headers = headers;
|
|
@@ -335,7 +453,7 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
335
453
|
const json = {};
|
|
336
454
|
let body = undefined;
|
|
337
455
|
for (const [propertyKey, field3] of Object.entries(fieldOrFieldGroup)) {
|
|
338
|
-
const meta =
|
|
456
|
+
const meta = __getFieldMetadata(field3);
|
|
339
457
|
for (const [type, aliasName] of meta.alias) {
|
|
340
458
|
const valueKey = aliasName || propertyKey;
|
|
341
459
|
const value = input[propertyKey] || field3();
|
|
@@ -369,7 +487,7 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
369
487
|
}
|
|
370
488
|
}
|
|
371
489
|
}
|
|
372
|
-
request.endpoint =
|
|
490
|
+
request.endpoint = __fillUrl(request.endpoint, params);
|
|
373
491
|
request.queryParams = queryParams;
|
|
374
492
|
request.headers = headers;
|
|
375
493
|
if (body) {
|
|
@@ -381,78 +499,27 @@ async function fillRequestFromField(request, fieldOrFieldGroup, input) {
|
|
|
381
499
|
}
|
|
382
500
|
return;
|
|
383
501
|
}
|
|
384
|
-
throw
|
|
502
|
+
throw ERR_UNSUPPORTED_FIELD_TYPE;
|
|
385
503
|
}
|
|
386
504
|
|
|
387
|
-
// src/
|
|
388
|
-
function
|
|
389
|
-
const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
const url = options.url ?? "";
|
|
393
|
-
const headers = options.headers ?? new Headers;
|
|
394
|
-
const body = options.body ?? null;
|
|
395
|
-
if (!ok || options.error) {
|
|
396
|
-
const error = options.error || new Error(`Http failure response for ${options.url}: ${status} ${statusText}`);
|
|
397
|
-
return {
|
|
398
|
-
ok: false,
|
|
399
|
-
error,
|
|
400
|
-
status,
|
|
401
|
-
statusText,
|
|
402
|
-
url,
|
|
403
|
-
headers,
|
|
404
|
-
body
|
|
405
|
-
};
|
|
406
|
-
}
|
|
407
|
-
return {
|
|
408
|
-
ok: true,
|
|
409
|
-
status,
|
|
410
|
-
statusText,
|
|
411
|
-
url,
|
|
412
|
-
headers,
|
|
413
|
-
body
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
// src/handler/fetch/fetch.ts
|
|
418
|
-
function createRequest(request2) {
|
|
419
|
-
const url = new URL(request2.endpoint, request2.host);
|
|
420
|
-
if (request2.queryParams) {
|
|
421
|
-
url.search = request2.queryParams.toString();
|
|
505
|
+
// src/handler/util.ts
|
|
506
|
+
function getContentLength(headers) {
|
|
507
|
+
const value = headers.get("Content-Length");
|
|
508
|
+
if (!value) {
|
|
509
|
+
return 0;
|
|
422
510
|
}
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
if (detectedType) {
|
|
427
|
-
request2.headers.set("Content-Type", detectedType);
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
if (!request2.headers.has("Accept")) {
|
|
431
|
-
request2.headers.set("Accept", "application/json, text/plain, */*");
|
|
432
|
-
}
|
|
511
|
+
const num = Number(value);
|
|
512
|
+
if (isNaN(num)) {
|
|
513
|
+
return 0;
|
|
433
514
|
}
|
|
434
|
-
|
|
435
|
-
const fetchConfig = request2.context?.get(FETCH_CONFIG_KEY) || {};
|
|
436
|
-
return new Request(url, {
|
|
437
|
-
...fetchConfig,
|
|
438
|
-
headers: request2.headers,
|
|
439
|
-
method: request2.method,
|
|
440
|
-
body: serializeBody(request2.body),
|
|
441
|
-
signal: request2.abort,
|
|
442
|
-
credentials
|
|
443
|
-
});
|
|
515
|
+
return num;
|
|
444
516
|
}
|
|
445
|
-
function
|
|
446
|
-
|
|
447
|
-
let position = 0;
|
|
448
|
-
for (const chunk of chunks) {
|
|
449
|
-
chunksAll.set(chunk, position);
|
|
450
|
-
position += chunk.length;
|
|
451
|
-
}
|
|
452
|
-
return chunksAll;
|
|
517
|
+
function getContentType(headers) {
|
|
518
|
+
return headers.get("Content-Type") || "";
|
|
453
519
|
}
|
|
454
|
-
function parseBody(
|
|
455
|
-
const
|
|
520
|
+
function parseBody(params) {
|
|
521
|
+
const { request, content, contentType } = params;
|
|
522
|
+
const responseType = request.responseType;
|
|
456
523
|
if (!responseType) {
|
|
457
524
|
return null;
|
|
458
525
|
}
|
|
@@ -467,7 +534,6 @@ function parseBody(request2, response2, content) {
|
|
|
467
534
|
case "text":
|
|
468
535
|
return new TextDecoder().decode(content);
|
|
469
536
|
case "blob": {
|
|
470
|
-
const contentType = response2.headers.get("Content-Type") || undefined;
|
|
471
537
|
return new Blob([content], { type: contentType });
|
|
472
538
|
}
|
|
473
539
|
case "arraybuffer":
|
|
@@ -476,35 +542,54 @@ function parseBody(request2, response2, content) {
|
|
|
476
542
|
return null;
|
|
477
543
|
}
|
|
478
544
|
}
|
|
479
|
-
function
|
|
480
|
-
const
|
|
481
|
-
|
|
482
|
-
|
|
545
|
+
function concatChunks(chunks, totalLength) {
|
|
546
|
+
const chunksAll = new Uint8Array(totalLength);
|
|
547
|
+
let position = 0;
|
|
548
|
+
for (const chunk of chunks) {
|
|
549
|
+
chunksAll.set(chunk, position);
|
|
550
|
+
position += chunk.length;
|
|
483
551
|
}
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
552
|
+
return chunksAll;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// src/handler/fetch/fetch.ts
|
|
556
|
+
function __createRequest(request2) {
|
|
557
|
+
const url = new URL(request2.endpoint, request2.host);
|
|
558
|
+
if (request2.queryParams) {
|
|
559
|
+
url.search = request2.queryParams.toString();
|
|
487
560
|
}
|
|
488
|
-
|
|
561
|
+
const headers = request2.headers ?? new Headers;
|
|
562
|
+
if (!headers.has("Content-Type")) {
|
|
563
|
+
const detectedType = __detectContentTypeHeader(request2.body);
|
|
564
|
+
if (detectedType) {
|
|
565
|
+
headers.set("Content-Type", detectedType);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
if (!headers.has("Accept")) {
|
|
569
|
+
headers.set("Accept", "application/json, text/plain, */*");
|
|
570
|
+
}
|
|
571
|
+
const credentials = request2.withCredentials ? "include" : undefined;
|
|
572
|
+
const fetchConfig = request2.context?.get(FETCH_CONFIG_KEY) || {};
|
|
573
|
+
return new Request(url, {
|
|
574
|
+
...fetchConfig,
|
|
575
|
+
headers,
|
|
576
|
+
method: request2.method,
|
|
577
|
+
body: __serializeBody(request2.body),
|
|
578
|
+
signal: request2.abort,
|
|
579
|
+
credentials
|
|
580
|
+
});
|
|
489
581
|
}
|
|
490
582
|
async function fetchHandler(httpRequest) {
|
|
491
|
-
const
|
|
492
|
-
const request2 =
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
response2 = await (globalThis || window).fetch(request2);
|
|
496
|
-
} catch (error) {
|
|
497
|
-
throw makeResponse({
|
|
498
|
-
error: error instanceof Error ? error : new Error("Network Error"),
|
|
499
|
-
url: request2.url
|
|
500
|
-
});
|
|
501
|
-
}
|
|
502
|
-
const { headers, status, statusText, url } = response2;
|
|
583
|
+
const downloadProgress = httpRequest.downloadProgress;
|
|
584
|
+
const request2 = __createRequest(httpRequest);
|
|
585
|
+
const response3 = await (globalThis || window).fetch(request2);
|
|
586
|
+
const { headers, status, statusText, url } = response3;
|
|
503
587
|
const contentLength = getContentLength(headers);
|
|
588
|
+
const contentType = getContentType(headers);
|
|
504
589
|
let body = null;
|
|
505
|
-
if (
|
|
590
|
+
if (response3.body) {
|
|
506
591
|
const chunks = [];
|
|
507
|
-
const reader =
|
|
592
|
+
const reader = response3.body.getReader();
|
|
508
593
|
let receivedLength = 0;
|
|
509
594
|
while (true) {
|
|
510
595
|
const { done, value } = await reader.read();
|
|
@@ -520,17 +605,11 @@ async function fetchHandler(httpRequest) {
|
|
|
520
605
|
});
|
|
521
606
|
}
|
|
522
607
|
const chunksAll = concatChunks(chunks, receivedLength);
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
url,
|
|
529
|
-
status,
|
|
530
|
-
statusText,
|
|
531
|
-
headers
|
|
532
|
-
});
|
|
533
|
-
}
|
|
608
|
+
body = parseBody({
|
|
609
|
+
request: httpRequest,
|
|
610
|
+
content: chunksAll,
|
|
611
|
+
contentType
|
|
612
|
+
});
|
|
534
613
|
}
|
|
535
614
|
return makeResponse({
|
|
536
615
|
url,
|
|
@@ -547,7 +626,7 @@ function isClient(value) {
|
|
|
547
626
|
}
|
|
548
627
|
function getClientConfig(client2) {
|
|
549
628
|
if (!isClient(client2)) {
|
|
550
|
-
|
|
629
|
+
throw ERR_INVALID_CLIENT;
|
|
551
630
|
}
|
|
552
631
|
return client2[CLIENT];
|
|
553
632
|
}
|
|
@@ -561,9 +640,19 @@ function createClient(options) {
|
|
|
561
640
|
[CLIENT]: conf
|
|
562
641
|
};
|
|
563
642
|
}
|
|
643
|
+
function cloneClient(client2, options) {
|
|
644
|
+
const preConf = getClientConfig(client2);
|
|
645
|
+
const conf = {
|
|
646
|
+
...preConf,
|
|
647
|
+
...options
|
|
648
|
+
};
|
|
649
|
+
return {
|
|
650
|
+
[CLIENT]: conf
|
|
651
|
+
};
|
|
652
|
+
}
|
|
564
653
|
function getGlobalClient() {
|
|
565
654
|
if (!globalClient) {
|
|
566
|
-
throw
|
|
655
|
+
throw ERR_NOT_FOUND_GLOBAL_CLIENT;
|
|
567
656
|
}
|
|
568
657
|
return globalClient;
|
|
569
658
|
}
|
|
@@ -578,12 +667,111 @@ function createGlobalClient(options) {
|
|
|
578
667
|
}
|
|
579
668
|
var CLIENT = Symbol("Client");
|
|
580
669
|
var globalClient;
|
|
670
|
+
// src/interceptor/authorization/basic_auth_interceptor.ts
|
|
671
|
+
function basicAuthInterceptor(fn, options) {
|
|
672
|
+
let encode = options?.encode;
|
|
673
|
+
if (!encode) {
|
|
674
|
+
const btoa = (globalThis || window).btoa;
|
|
675
|
+
if (typeof btoa !== "function") {
|
|
676
|
+
throw new Error("BasicAuthInterceptor is not supported in this environment");
|
|
677
|
+
}
|
|
678
|
+
encode = (data) => btoa(`${data.username}:${data.password}`);
|
|
679
|
+
}
|
|
680
|
+
return (req, next) => {
|
|
681
|
+
const headers = req.headers || new Headers;
|
|
682
|
+
headers.set("Authorization", `Basic ${encode(fn())}`);
|
|
683
|
+
req.headers = headers;
|
|
684
|
+
return next(req);
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
// src/validator.ts
|
|
688
|
+
var required = (value) => {
|
|
689
|
+
if (!value) {
|
|
690
|
+
return new Error("required");
|
|
691
|
+
}
|
|
692
|
+
return null;
|
|
693
|
+
};
|
|
694
|
+
var requiredTrue = (value) => {
|
|
695
|
+
if (typeof value !== "boolean" || !value) {
|
|
696
|
+
return new Error("requiredTrue");
|
|
697
|
+
}
|
|
698
|
+
return null;
|
|
699
|
+
};
|
|
700
|
+
var minLength = (min) => {
|
|
701
|
+
return (value) => {
|
|
702
|
+
if (typeof value !== "string") {
|
|
703
|
+
return new Error("invalid string");
|
|
704
|
+
}
|
|
705
|
+
if (value.length < min) {
|
|
706
|
+
return new Error(`minLength ${min}`);
|
|
707
|
+
}
|
|
708
|
+
return null;
|
|
709
|
+
};
|
|
710
|
+
};
|
|
711
|
+
var maxLength = (max) => {
|
|
712
|
+
return (value) => {
|
|
713
|
+
if (typeof value !== "string") {
|
|
714
|
+
return new Error("invalid string");
|
|
715
|
+
}
|
|
716
|
+
if (value.length > max) {
|
|
717
|
+
return new Error(`maxLength ${max}`);
|
|
718
|
+
}
|
|
719
|
+
return null;
|
|
720
|
+
};
|
|
721
|
+
};
|
|
722
|
+
var min = (min2) => {
|
|
723
|
+
return (value) => {
|
|
724
|
+
if (typeof value !== "number" || isNaN(value)) {
|
|
725
|
+
return new Error("invalid number");
|
|
726
|
+
}
|
|
727
|
+
if (value < min2) {
|
|
728
|
+
return new Error(`minLength ${min2}`);
|
|
729
|
+
}
|
|
730
|
+
return null;
|
|
731
|
+
};
|
|
732
|
+
};
|
|
733
|
+
var max = (max2) => {
|
|
734
|
+
return (value) => {
|
|
735
|
+
if (typeof value !== "number" || isNaN(value)) {
|
|
736
|
+
return new Error("invalid number");
|
|
737
|
+
}
|
|
738
|
+
if (value > max2) {
|
|
739
|
+
return new Error(`maxLength ${max2}`);
|
|
740
|
+
}
|
|
741
|
+
return null;
|
|
742
|
+
};
|
|
743
|
+
};
|
|
744
|
+
var pattern = (pattern2) => {
|
|
745
|
+
return (value) => {
|
|
746
|
+
if (typeof value !== "string") {
|
|
747
|
+
return new Error("invalid string");
|
|
748
|
+
}
|
|
749
|
+
if (typeof pattern2 === "string") {
|
|
750
|
+
pattern2 = new RegExp(pattern2);
|
|
751
|
+
}
|
|
752
|
+
if (!pattern2.test(value)) {
|
|
753
|
+
return new Error("pattern");
|
|
754
|
+
}
|
|
755
|
+
return null;
|
|
756
|
+
};
|
|
757
|
+
};
|
|
581
758
|
export {
|
|
759
|
+
validatorField,
|
|
582
760
|
setGlobalClient,
|
|
583
761
|
restGlobalClient,
|
|
762
|
+
requiredTrue,
|
|
763
|
+
required,
|
|
764
|
+
pattern,
|
|
765
|
+
minLength,
|
|
766
|
+
min,
|
|
767
|
+
maxLength,
|
|
768
|
+
max,
|
|
584
769
|
makeResponse,
|
|
585
770
|
makeHttpContextToken,
|
|
586
771
|
makeHttpContext,
|
|
772
|
+
isHttpResponseError,
|
|
773
|
+
isHttpResponse,
|
|
774
|
+
isHttpContextToken,
|
|
587
775
|
isFieldGroup,
|
|
588
776
|
isField,
|
|
589
777
|
isClient,
|
|
@@ -592,5 +780,21 @@ export {
|
|
|
592
780
|
fetchHandler,
|
|
593
781
|
defineRequest,
|
|
594
782
|
createGlobalClient,
|
|
595
|
-
createClient
|
|
783
|
+
createClient,
|
|
784
|
+
cloneClient,
|
|
785
|
+
basicAuthInterceptor,
|
|
786
|
+
asyncValidatorField,
|
|
787
|
+
FETCH_CONFIG_KEY,
|
|
788
|
+
ERR_UNSUPPORTED_FIELD_TYPE,
|
|
789
|
+
ERR_TRANSFORM_RESPONSE,
|
|
790
|
+
ERR_TIMEOUT,
|
|
791
|
+
ERR_STREAMING_NOT_IMPLEMENTED,
|
|
792
|
+
ERR_OBSERVE,
|
|
793
|
+
ERR_NOT_SET_ALIAS,
|
|
794
|
+
ERR_NOT_FOUND_HANDLER,
|
|
795
|
+
ERR_NOT_FOUND_GLOBAL_CLIENT,
|
|
796
|
+
ERR_NETWORK,
|
|
797
|
+
ERR_INVALID_HTTP_CONTEXT_TOKEN,
|
|
798
|
+
ERR_INVALID_CLIENT,
|
|
799
|
+
ERR_ABORTED
|
|
596
800
|
};
|
package/index.min.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function U(t,n){return t.cause=n,t}var l=new Error("ERR_ABORTED"),h=new Error("ERR_TIMEOUT"),L=new Error("ERR_NETWORK"),P=new Error("ERR_NOT_FOUND_HANDLER"),D=new Error("ERR_TRANSFORM_RESPONSE"),M=new Error("ERR_STREAMING_NOT_IMPLEMENTED"),d=new Error("ERR_OBSERVE"),m=new Error("ERR_NOT_SET_ALIAS"),O=new Error("ERR_UNSUPPORTED_FIELD_TYPE"),g=new Error("ERR_INVALID_CLIENT"),S=new Error("ERR_NOT_FOUND_GLOBAL_CLIENT"),u=new Error("ERR_INVALID_HTTP_CONTEXT_TOKEN");function X(t){return Object.defineProperty(t,z,{value:t}),t}function $(t){return typeof t==="function"&&z in t}function J(){const t=new Map;return{set(n,r){if(!$(n))throw u;return t.set(n,r),this},get(n){if(!$(n))throw u;if(!t.has(n))t.set(n,n());return t.get(n)},del(n){return t.delete(n),this},has(n){return t.has(n)},keys(){return t.keys()}}}var z=Symbol("HttpContextToken");function it(t){const n={alias:new Map,validators:[],asyncValidator:[]},r=()=>t;return Object.defineProperty(r,K,{value:n}),r.withJson=(o)=>{return n.alias.set(1,o),r},r.withForm=(o)=>{return n.alias.set(5,o),r},r.withQuery=(o)=>{return n.alias.set(2,o),r},r.withParam=(o)=>{return n.alias.set(3,o),r},r.withHeader=(o)=>{return n.alias.set(4,o),r},r.withBody=()=>{return n.alias.set(6,void 0),r},r.withValidators=(...o)=>{return n.validators=o,r},r.withAsyncValidators=(...o)=>{return n.asyncValidator=o,r},r}function Q(t){return t[K]}function pt(t,n){for(let r of t){const o=r(n);if(o)throw o}}async function ct(t,n){for(let r of t){const o=await r(n);if(o)throw o}}function A(t){return!!t&&typeof t==="function"&&K in t}function y(t){return!!t&&typeof t==="object"&&Object.entries(t).every(([,n])=>A(n))}var K=Symbol("field");var ft=void 0;var G=()=>ft;function b(t){return t.reduceRight((n,r)=>{return(o,T)=>r(o,(x)=>n(x,T))},(n,r)=>r(n))}function v(t){return typeof t==="object"&&t!==null&&j in t}function Rt(t){return v(t)&&!t.ok}function _(t){const n=t.status??0,r=t.statusText??"",o=n>=200&&n<300,T=t.url??"",x=t.headers??new Headers,a=t.body??null;if(!o||t.error)return{ok:!1,error:t.error||new Error(`Http failure response for ${t.url}: ${n} ${r}`),status:n,statusText:r,url:T,headers:x,body:a,[j]:null};return{ok:!0,error:null,status:n,statusText:r,url:T,headers:x,body:a,[j]:null}}var j=Symbol("HTTP_RESPONSE");function tt(t){switch(!0){case t instanceof FormData:case t instanceof Blob:case t instanceof ArrayBuffer: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 nt(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 Ht(t){if(A(t))return t();if(y(t)){const n={};for(let[r,o]of Object.entries(t))n[r]=o();return n}return}function wt(t){const n={...t},r=!!n.input;return()=>{let o,T,x,a;const E=(e)=>{o=e},i=(e)=>{T=e};return{doRequest:async(...e)=>{let c,f;switch(e.length){case 1:{f=e[0];break}case 2:{c=e[0],f=e[1];break}}if(r&&!c)throw new Error("Because the request has input, the first argument must be the input value");const w=f?.timeout||0;if(f?.abort)a=f.abort;else if(w>0)a=AbortSignal.timeout(w);else x=new AbortController,a=x.signal;const F=B(f?.client)?f.client:Y(),R=W(F),k={host:R?.host,method:n.method,endpoint:n.endpoint,queryParams:new URLSearchParams,headers:new Headers,body:void 0,withCredentials:n.withCredentials,responseType:n.responseType??"json",context:n.context||J(),observe:n.observe??"body",uploadProgress:o,downloadProgress:T,timeout:w,abort:a},I=f?.handler||R?.handler||G();if(!I)throw P;if(r)await st(k,n.input,c);if(typeof n.transformRequest==="function")k.body=n.transformRequest(c,k);const N=b([...R?.interceptors||[],...n?.interceptors||[]]);let H;try{H=await N(k,I)}catch(s){if(s instanceof DOMException)switch(!0){case(s.name==="AbortError"||s.code===s.ABORT_ERR):throw l;case(s.name==="TimeoutError"||s.code===s.TIMEOUT_ERR):throw h}throw _({error:U(L,s)})}if(typeof n.transformResponse==="function")try{H=_({...H,body:n.transformResponse(H),error:void 0})}catch(s){throw _({...H,error:U(D,s)})}switch(k.observe){case"body":return H.body;case"stream":throw M;case"response":return H;default:throw d}},inputValue:Ht(n.input),setUploadProgress:E,setDownloadProgress:i}}}function q(t,n){return t.replace(/:([^\/]+)/g,(r,o)=>{return n.get(o)??"undefined"})}async function st(t,n,r){async function o(E,i){for(let p of E){const e=await p(i);if(e)return e}return}function T(E){return typeof E==="object"&&E!==null}function x(E,i,p){if(Array.isArray(p))for(let e of p)E.append(i,String(e));else E.set(i,String(p));return E}function a(E,i,p){if(Array.isArray(p))for(let e of p)E.set(i,String(e));else E.set(i,String(p));return E}if(A(n)){let E,i,p,e=void 0;const c=r??n(),f=Q(n),w=await o([...f.validators,...f.asyncValidator],c);if(w)throw w;for(let[F,R]of f.alias)switch(F){case 2:{if(!R)throw m;i=x(new URLSearchParams,R,c);break}case 3:{if(!R)throw m;E=a(new Map,R,c);break}case 4:{if(!R)throw m;p=x(new Headers,R,c);break}case 5:{if(!R)throw m;e=x(new FormData,R,c);break}case 1:case 6:e=c;break}if(E)t.endpoint=q(t.endpoint,E);t.queryParams=i,t.headers=p,t.body=e;return}if(y(n)&&T(r)){let E=new Map,i=new URLSearchParams,p=new Headers,e=new FormData;const c={};let f=void 0;for(let[w,F]of Object.entries(n)){const R=Q(F);for(let[k,I]of R.alias){const N=I||w,H=r[w]||F(),s=await o([...R.validators,...R.asyncValidator],H);if(s)throw s;switch(k){case 1:Object.defineProperty(c,N,{value:H,writable:!0,enumerable:!0});break;case 2:i=x(i,N,H);break;case 3:E=a(E,N,H);break;case 4:p=x(p,N,H);break;case 5:e=x(e,N,H);break;case 6:f=H;break}}}if(t.endpoint=q(t.endpoint,E),t.queryParams=i,t.headers=p,f)t.body=f;else if(Array.from(e.keys()).length>0)t.body=e;else if(Object.keys(c).length)t.body=c;return}throw O}function rt(t){const n=t.get("Content-Length");if(!n)return 0;const r=Number(n);if(isNaN(r))return 0;return r}function ot(t){return t.get("Content-Type")||""}function et(t){const{request:n,content:r,contentType:o}=t,T=n.responseType;if(!T)return null;switch(T){case"json":{const x=new TextDecoder().decode(r);if(x==="")return null;return JSON.parse(x)}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 at(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 x=nt(t.body);if(x)r.set("Content-Type",x)}if(!r.has("Accept"))r.set("Accept","application/json, text/plain, */*");const o=t.withCredentials?"include":void 0,T=t.context?.get(xt)||{};return new Request(n,{...T,headers:r,method:t.method,body:tt(t.body),signal:t.abort,credentials:o})}async function Z(t){const n=t.downloadProgress,r=at(t),o=await(globalThis||window).fetch(r),{headers:T,status:x,statusText:a,url:E}=o,i=rt(T),p=ot(T);let e=null;if(o.body){const c=[],f=o.body.getReader();let w=0;while(!0){const{done:R,value:k}=await f.read();if(R)break;c.push(k),w+=k.length,n?.({lengthComputable:i>0,loaded:w,total:i})}const F=Tt(c,w);e=et({request:t,content:F,contentType:p})}return _({url:E,status:x,statusText:a,headers:T,body:e})}var xt=X(()=>({}));function B(t){return typeof t==="object"&&t!==null&&V in t}function W(t){if(!B(t))throw g;return t[V]}function Et(t){const n={host:t.host,interceptors:t.interceptors??[],handler:t.handler||Z};return{[V]:n}}function kt(t,n){const o={...W(t),...n};return{[V]:o}}function Y(){if(!C)throw S;return C}function Ft(t){C=t}function Nt(){C=void 0}function _t(t){C=Et(t)}var V=Symbol("Client"),C;function mt(t,n){let r=n?.encode;if(!r){const o=(globalThis||window).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 x=o.headers||new Headers;return x.set("Authorization",`Basic ${r(t())}`),o.headers=x,T(o)}}var At=(t)=>{if(!t)return new Error("required");return null},Ct=(t)=>{if(typeof t!=="boolean"||!t)return new Error("requiredTrue");return null},It=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length<t)return new Error(`minLength ${t}`);return null}},ut=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(n.length>t)return new Error(`maxLength ${t}`);return null}},yt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n<t)return new Error(`minLength ${t}`);return null}},Bt=(t)=>{return(n)=>{if(typeof n!=="number"||isNaN(n))return new Error("invalid number");if(n>t)return new Error(`maxLength ${t}`);return null}},Vt=(t)=>{return(n)=>{if(typeof n!=="string")return new Error("invalid string");if(typeof t==="string")t=new RegExp(t);if(!t.test(n))return new Error("pattern");return null}};export{pt as validatorField,Ft as setGlobalClient,Nt as restGlobalClient,Ct as requiredTrue,At as required,Vt as pattern,It as minLength,yt as min,ut as maxLength,Bt as max,_ as makeResponse,X as makeHttpContextToken,J as makeHttpContext,Rt as isHttpResponseError,v as isHttpResponse,$ as isHttpContextToken,y as isFieldGroup,A as isField,B as isClient,Y as getGlobalClient,it as field,Z as fetchHandler,wt as defineRequest,_t as createGlobalClient,Et as createClient,kt as cloneClient,mt as basicAuthInterceptor,ct as asyncValidatorField,xt as FETCH_CONFIG_KEY,O as ERR_UNSUPPORTED_FIELD_TYPE,D as ERR_TRANSFORM_RESPONSE,h as ERR_TIMEOUT,M as ERR_STREAMING_NOT_IMPLEMENTED,d as ERR_OBSERVE,m as ERR_NOT_SET_ALIAS,P as ERR_NOT_FOUND_HANDLER,S as ERR_NOT_FOUND_GLOBAL_CLIENT,L as ERR_NETWORK,u as ERR_INVALID_HTTP_CONTEXT_TOKEN,g as ERR_INVALID_CLIENT,l as ERR_ABORTED};
|
package/package.json
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@defjs/core",
|
|
3
|
-
"version": "0.0.0-test-
|
|
3
|
+
"version": "0.0.0-test-001",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
"
|
|
10
|
-
"
|
|
5
|
+
"module": "index.js",
|
|
6
|
+
"typings": "index.d.ts",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/defjs/defjs.git"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/defjs/defjs/issues"
|
|
11
14
|
},
|
|
12
15
|
"peerDependencies": {
|
|
13
|
-
"typescript": "^5.0"
|
|
16
|
+
"typescript": "^5.0.0"
|
|
14
17
|
},
|
|
15
|
-
"files": ["dist"],
|
|
16
|
-
"module": "dist/index.js",
|
|
17
|
-
"typings": "dist/index.d.ts",
|
|
18
18
|
"exports": {
|
|
19
19
|
"./package.json": "./package.json",
|
|
20
20
|
".": {
|
|
21
|
-
"types": "./
|
|
22
|
-
"default": "./
|
|
21
|
+
"types": "./index.d.ts",
|
|
22
|
+
"default": "./index.js"
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
|
-
}
|
|
25
|
+
}
|