@zayne-labs/callapi 1.10.3 → 1.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/esm/common-BFea9qeg.js +577 -0
- package/dist/esm/common-BFea9qeg.js.map +1 -0
- package/dist/esm/{common-Bk1Hh1hR.d.ts → common-BqnzZD5r.d.ts} +10 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +10 -255
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/utils/index.d.ts +1 -1
- package/dist/esm/utils/index.js +1 -1
- package/package.json +7 -8
- package/dist/esm/utils-BCsnh8UI.js +0 -296
- package/dist/esm/utils-BCsnh8UI.js.map +0 -1
package/README.md
CHANGED
@@ -57,6 +57,6 @@ To do this, you first need to set your `script`'s type to `module`, then import
|
|
57
57
|
|
58
58
|
<!-- Locked to a specific version -->
|
59
59
|
<script type="module">
|
60
|
-
import { callApi } from "https://esm.run/@zayne-labs/callapi@1.
|
60
|
+
import { callApi } from "https://esm.run/@zayne-labs/callapi@1.10.3";
|
61
61
|
</script>
|
62
62
|
```
|
@@ -0,0 +1,577 @@
|
|
1
|
+
//#region src/types/type-helpers.ts
|
2
|
+
const defineEnum = (value) => value;
|
3
|
+
|
4
|
+
//#endregion
|
5
|
+
//#region src/constants/default-options.ts
|
6
|
+
const extraOptionDefaults = () => {
|
7
|
+
return defineEnum({
|
8
|
+
bodySerializer: JSON.stringify,
|
9
|
+
defaultHTTPErrorMessage: "An unexpected error occurred during the HTTP request.",
|
10
|
+
dedupeCacheScope: "local",
|
11
|
+
dedupeCacheScopeKey: "default",
|
12
|
+
dedupeStrategy: "cancel",
|
13
|
+
hooksExecutionMode: "parallel",
|
14
|
+
hooksRegistrationOrder: "pluginsFirst",
|
15
|
+
responseParser: JSON.parse,
|
16
|
+
responseType: "json",
|
17
|
+
resultMode: "all",
|
18
|
+
retryAttempts: 0,
|
19
|
+
retryCondition: () => true,
|
20
|
+
retryDelay: 1e3,
|
21
|
+
retryMaxDelay: 1e4,
|
22
|
+
retryMethods: ["GET", "POST"],
|
23
|
+
retryStatusCodes: [],
|
24
|
+
retryStrategy: "linear"
|
25
|
+
});
|
26
|
+
};
|
27
|
+
const requestOptionDefaults = () => {
|
28
|
+
return defineEnum({ method: "GET" });
|
29
|
+
};
|
30
|
+
|
31
|
+
//#endregion
|
32
|
+
//#region src/error.ts
|
33
|
+
const httpErrorSymbol = Symbol("HTTPError");
|
34
|
+
var HTTPError = class HTTPError extends Error {
|
35
|
+
errorData;
|
36
|
+
httpErrorSymbol = httpErrorSymbol;
|
37
|
+
name = "HTTPError";
|
38
|
+
response;
|
39
|
+
constructor(errorDetails, errorOptions) {
|
40
|
+
const { defaultHTTPErrorMessage, errorData, response } = errorDetails;
|
41
|
+
const selectedDefaultErrorMessage = (isString(defaultHTTPErrorMessage) ? defaultHTTPErrorMessage : defaultHTTPErrorMessage?.({
|
42
|
+
errorData,
|
43
|
+
response
|
44
|
+
})) ?? (response.statusText || extraOptionDefaults().defaultHTTPErrorMessage);
|
45
|
+
const message = errorData?.message ?? selectedDefaultErrorMessage;
|
46
|
+
super(message, errorOptions);
|
47
|
+
this.errorData = errorData;
|
48
|
+
this.response = response;
|
49
|
+
}
|
50
|
+
/**
|
51
|
+
* @description Checks if the given error is an instance of HTTPError
|
52
|
+
* @param error - The error to check
|
53
|
+
* @returns true if the error is an instance of HTTPError, false otherwise
|
54
|
+
*/
|
55
|
+
static isError(error) {
|
56
|
+
if (!isObject(error)) return false;
|
57
|
+
if (error instanceof HTTPError) return true;
|
58
|
+
const actualError = error;
|
59
|
+
return actualError.httpErrorSymbol === httpErrorSymbol && actualError.name === "HTTPError";
|
60
|
+
}
|
61
|
+
};
|
62
|
+
const prettifyPath = (path) => {
|
63
|
+
if (!path || path.length === 0) return "";
|
64
|
+
return ` → at ${path.map((segment) => isObject(segment) ? segment.key : segment).join(".")}`;
|
65
|
+
};
|
66
|
+
const prettifyValidationIssues = (issues) => {
|
67
|
+
return issues.map((issue) => `✖ ${issue.message}${prettifyPath(issue.path)}`).join(" | ");
|
68
|
+
};
|
69
|
+
const validationErrorSymbol = Symbol("ValidationErrorSymbol");
|
70
|
+
var ValidationError = class ValidationError extends Error {
|
71
|
+
errorData;
|
72
|
+
issueCause;
|
73
|
+
name = "ValidationError";
|
74
|
+
response;
|
75
|
+
validationErrorSymbol = validationErrorSymbol;
|
76
|
+
constructor(details, errorOptions) {
|
77
|
+
const { issueCause, issues, response } = details;
|
78
|
+
const message = prettifyValidationIssues(issues);
|
79
|
+
super(message, errorOptions);
|
80
|
+
this.errorData = issues;
|
81
|
+
this.response = response;
|
82
|
+
this.issueCause = issueCause;
|
83
|
+
}
|
84
|
+
/**
|
85
|
+
* @description Checks if the given error is an instance of ValidationError
|
86
|
+
* @param error - The error to check
|
87
|
+
* @returns true if the error is an instance of ValidationError, false otherwise
|
88
|
+
*/
|
89
|
+
static isError(error) {
|
90
|
+
if (!isObject(error)) return false;
|
91
|
+
if (error instanceof ValidationError) return true;
|
92
|
+
const actualError = error;
|
93
|
+
return actualError.validationErrorSymbol === validationErrorSymbol && actualError.name === "ValidationError";
|
94
|
+
}
|
95
|
+
};
|
96
|
+
|
97
|
+
//#endregion
|
98
|
+
//#region src/utils/guards.ts
|
99
|
+
const isHTTPError = (error) => {
|
100
|
+
return isObject(error) && error.name === "HTTPError";
|
101
|
+
};
|
102
|
+
const isHTTPErrorInstance = (error) => {
|
103
|
+
return HTTPError.isError(error);
|
104
|
+
};
|
105
|
+
const isValidationError = (error) => {
|
106
|
+
return isObject(error) && error.name === "ValidationError";
|
107
|
+
};
|
108
|
+
const isValidationErrorInstance = (error) => {
|
109
|
+
return ValidationError.isError(error);
|
110
|
+
};
|
111
|
+
const isJavascriptError = (error) => {
|
112
|
+
return isObject(error) && !isHTTPError(error) && !isValidationError(error);
|
113
|
+
};
|
114
|
+
const isArray = (value) => Array.isArray(value);
|
115
|
+
const isBoolean = (value) => typeof value === "boolean";
|
116
|
+
const isObject = (value) => {
|
117
|
+
return typeof value === "object" && value !== null;
|
118
|
+
};
|
119
|
+
const hasObjectPrototype = (value) => {
|
120
|
+
return Object.prototype.toString.call(value) === "[object Object]";
|
121
|
+
};
|
122
|
+
/**
|
123
|
+
* @description Copied from TanStack Query's isPlainObject
|
124
|
+
* @see https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L321
|
125
|
+
*/
|
126
|
+
const isPlainObject = (value) => {
|
127
|
+
if (!hasObjectPrototype(value)) return false;
|
128
|
+
const constructor = value?.constructor;
|
129
|
+
if (constructor === void 0) return true;
|
130
|
+
const prototype = constructor.prototype;
|
131
|
+
if (!hasObjectPrototype(prototype)) return false;
|
132
|
+
if (!Object.hasOwn(prototype, "isPrototypeOf")) return false;
|
133
|
+
if (Object.getPrototypeOf(value) !== Object.prototype) return false;
|
134
|
+
return true;
|
135
|
+
};
|
136
|
+
const isValidJsonString = (value) => {
|
137
|
+
if (!isString(value)) return false;
|
138
|
+
try {
|
139
|
+
JSON.parse(value);
|
140
|
+
return true;
|
141
|
+
} catch {
|
142
|
+
return false;
|
143
|
+
}
|
144
|
+
};
|
145
|
+
const isSerializable = (value) => {
|
146
|
+
return isPlainObject(value) || isArray(value) || typeof value?.toJSON === "function";
|
147
|
+
};
|
148
|
+
const isFunction = (value) => typeof value === "function";
|
149
|
+
const isQueryString = (value) => isString(value) && value.includes("=");
|
150
|
+
const isString = (value) => typeof value === "string";
|
151
|
+
const isPromise = (value) => value instanceof Promise;
|
152
|
+
const isReadableStream = (value) => {
|
153
|
+
return value instanceof ReadableStream;
|
154
|
+
};
|
155
|
+
|
156
|
+
//#endregion
|
157
|
+
//#region src/auth.ts
|
158
|
+
const resolveAuthValue = (value) => isFunction(value) ? value() : value;
|
159
|
+
const getAuthHeader = async (auth) => {
|
160
|
+
if (auth === void 0) return;
|
161
|
+
if (isPromise(auth) || isFunction(auth) || !isObject(auth)) {
|
162
|
+
const authValue = await resolveAuthValue(auth);
|
163
|
+
if (authValue === void 0) return;
|
164
|
+
return { Authorization: `Bearer ${authValue}` };
|
165
|
+
}
|
166
|
+
switch (auth.type) {
|
167
|
+
case "Basic": {
|
168
|
+
const [username, password] = await Promise.all([resolveAuthValue(auth.username), resolveAuthValue(auth.password)]);
|
169
|
+
if (username === void 0 || password === void 0) return;
|
170
|
+
return { Authorization: `Basic ${globalThis.btoa(`${username}:${password}`)}` };
|
171
|
+
}
|
172
|
+
case "Custom": {
|
173
|
+
const [prefix, value] = await Promise.all([resolveAuthValue(auth.prefix), resolveAuthValue(auth.value)]);
|
174
|
+
if (value === void 0) return;
|
175
|
+
return { Authorization: `${prefix} ${value}` };
|
176
|
+
}
|
177
|
+
default: {
|
178
|
+
const [bearer, token] = await Promise.all([resolveAuthValue(auth.bearer), resolveAuthValue(auth.token)]);
|
179
|
+
if (bearer !== void 0) return { Authorization: `Bearer ${bearer}` };
|
180
|
+
if (token === void 0) return;
|
181
|
+
return { Authorization: `Token ${token}` };
|
182
|
+
}
|
183
|
+
}
|
184
|
+
};
|
185
|
+
|
186
|
+
//#endregion
|
187
|
+
//#region src/constants/common.ts
|
188
|
+
const fetchSpecificKeys = defineEnum([
|
189
|
+
"body",
|
190
|
+
"integrity",
|
191
|
+
"duplex",
|
192
|
+
"method",
|
193
|
+
"headers",
|
194
|
+
"signal",
|
195
|
+
"cache",
|
196
|
+
"redirect",
|
197
|
+
"window",
|
198
|
+
"credentials",
|
199
|
+
"keepalive",
|
200
|
+
"referrer",
|
201
|
+
"priority",
|
202
|
+
"mode",
|
203
|
+
"referrerPolicy"
|
204
|
+
]);
|
205
|
+
|
206
|
+
//#endregion
|
207
|
+
//#region src/validation.ts
|
208
|
+
const handleValidatorFunction = async (validator, inputData) => {
|
209
|
+
try {
|
210
|
+
return {
|
211
|
+
issues: void 0,
|
212
|
+
value: await validator(inputData)
|
213
|
+
};
|
214
|
+
} catch (error) {
|
215
|
+
return {
|
216
|
+
issues: toArray(error),
|
217
|
+
value: void 0
|
218
|
+
};
|
219
|
+
}
|
220
|
+
};
|
221
|
+
const standardSchemaParser = async (fullSchema, schemaName, inputData, response) => {
|
222
|
+
const schema = fullSchema?.[schemaName];
|
223
|
+
if (!schema) return inputData;
|
224
|
+
const result = isFunction(schema) ? await handleValidatorFunction(schema, inputData) : await schema["~standard"].validate(inputData);
|
225
|
+
if (result.issues) throw new ValidationError({
|
226
|
+
issueCause: schemaName,
|
227
|
+
issues: result.issues,
|
228
|
+
response: response ?? null
|
229
|
+
});
|
230
|
+
return result.value;
|
231
|
+
};
|
232
|
+
const routeKeyMethods = defineEnum([
|
233
|
+
"delete",
|
234
|
+
"get",
|
235
|
+
"patch",
|
236
|
+
"post",
|
237
|
+
"put"
|
238
|
+
]);
|
239
|
+
const handleSchemaValidation = async (fullSchema, schemaName, validationOptions) => {
|
240
|
+
const { inputValue, response, schemaConfig } = validationOptions;
|
241
|
+
if (schemaConfig?.disableRuntimeValidation) return inputValue;
|
242
|
+
return await standardSchemaParser(fullSchema, schemaName, inputValue, response);
|
243
|
+
};
|
244
|
+
const extraOptionsToBeValidated = [
|
245
|
+
"meta",
|
246
|
+
"params",
|
247
|
+
"query"
|
248
|
+
];
|
249
|
+
const handleExtraOptionsValidation = async (validationOptions) => {
|
250
|
+
const { options, schema, schemaConfig } = validationOptions;
|
251
|
+
const validationResultArray = await Promise.all(extraOptionsToBeValidated.map((schemaName) => handleSchemaValidation(schema, schemaName, {
|
252
|
+
inputValue: options[schemaName],
|
253
|
+
schemaConfig
|
254
|
+
})));
|
255
|
+
const validatedResultObject = {};
|
256
|
+
for (const [index, schemaName] of extraOptionsToBeValidated.entries()) {
|
257
|
+
const validationResult = validationResultArray[index];
|
258
|
+
if (validationResult === void 0) continue;
|
259
|
+
validatedResultObject[schemaName] = validationResult;
|
260
|
+
}
|
261
|
+
return validatedResultObject;
|
262
|
+
};
|
263
|
+
const requestOptionsToBeValidated = [
|
264
|
+
"body",
|
265
|
+
"headers",
|
266
|
+
"method"
|
267
|
+
];
|
268
|
+
const handleRequestOptionsValidation = async (validationOptions) => {
|
269
|
+
const { requestOptions, schema, schemaConfig } = validationOptions;
|
270
|
+
const validationResultArray = await Promise.all(requestOptionsToBeValidated.map((schemaName) => handleSchemaValidation(schema, schemaName, {
|
271
|
+
inputValue: requestOptions[schemaName],
|
272
|
+
schemaConfig
|
273
|
+
})));
|
274
|
+
const validatedResultObject = {};
|
275
|
+
for (const [index, propertyKey] of requestOptionsToBeValidated.entries()) {
|
276
|
+
const validationResult = validationResultArray[index];
|
277
|
+
if (validationResult === void 0) continue;
|
278
|
+
validatedResultObject[propertyKey] = validationResult;
|
279
|
+
}
|
280
|
+
return validatedResultObject;
|
281
|
+
};
|
282
|
+
const handleConfigValidation = async (validationOptions) => {
|
283
|
+
const { baseExtraOptions, currentRouteSchemaKey, extraOptions, options, requestOptions } = validationOptions;
|
284
|
+
const { currentRouteSchema, resolvedSchema } = getResolvedSchema({
|
285
|
+
baseExtraOptions,
|
286
|
+
currentRouteSchemaKey,
|
287
|
+
extraOptions
|
288
|
+
});
|
289
|
+
const resolvedSchemaConfig = getResolvedSchemaConfig({
|
290
|
+
baseExtraOptions,
|
291
|
+
extraOptions
|
292
|
+
});
|
293
|
+
if (resolvedSchemaConfig?.strict === true && !currentRouteSchema) throw new ValidationError({
|
294
|
+
issueCause: "schemaConfig-(strict)",
|
295
|
+
issues: [{ message: `Strict Mode - No schema found for route '${currentRouteSchemaKey}' ` }],
|
296
|
+
response: null
|
297
|
+
});
|
298
|
+
if (resolvedSchemaConfig?.disableRuntimeValidation) return {
|
299
|
+
extraOptionsValidationResult: null,
|
300
|
+
requestOptionsValidationResult: null,
|
301
|
+
resolvedSchema,
|
302
|
+
resolvedSchemaConfig,
|
303
|
+
shouldApplySchemaOutput: false
|
304
|
+
};
|
305
|
+
const [extraOptionsValidationResult, requestOptionsValidationResult] = await Promise.all([handleExtraOptionsValidation({
|
306
|
+
options,
|
307
|
+
schema: resolvedSchema,
|
308
|
+
schemaConfig: resolvedSchemaConfig
|
309
|
+
}), handleRequestOptionsValidation({
|
310
|
+
requestOptions,
|
311
|
+
schema: resolvedSchema,
|
312
|
+
schemaConfig: resolvedSchemaConfig
|
313
|
+
})]);
|
314
|
+
const shouldApplySchemaOutput = (Boolean(extraOptionsValidationResult) || Boolean(requestOptionsValidationResult)) && !resolvedSchemaConfig?.disableValidationOutputApplication;
|
315
|
+
return {
|
316
|
+
extraOptionsValidationResult,
|
317
|
+
requestOptionsValidationResult,
|
318
|
+
resolvedSchema,
|
319
|
+
resolvedSchemaConfig,
|
320
|
+
shouldApplySchemaOutput
|
321
|
+
};
|
322
|
+
};
|
323
|
+
const fallBackRouteSchemaKey = ".";
|
324
|
+
const getResolvedSchema = (context) => {
|
325
|
+
const { baseExtraOptions, currentRouteSchemaKey, extraOptions } = context;
|
326
|
+
const fallbackRouteSchema = baseExtraOptions.schema?.routes[fallBackRouteSchemaKey];
|
327
|
+
const currentRouteSchema = baseExtraOptions.schema?.routes[currentRouteSchemaKey];
|
328
|
+
const resolvedRouteSchema = {
|
329
|
+
...fallbackRouteSchema,
|
330
|
+
...currentRouteSchema
|
331
|
+
};
|
332
|
+
const resolvedSchema = isFunction(extraOptions.schema) ? extraOptions.schema({
|
333
|
+
baseSchemaRoutes: baseExtraOptions.schema?.routes ?? {},
|
334
|
+
currentRouteSchema: resolvedRouteSchema ?? {}
|
335
|
+
}) : extraOptions.schema ?? resolvedRouteSchema;
|
336
|
+
return {
|
337
|
+
currentRouteSchema,
|
338
|
+
resolvedSchema
|
339
|
+
};
|
340
|
+
};
|
341
|
+
const getResolvedSchemaConfig = (context) => {
|
342
|
+
const { baseExtraOptions, extraOptions } = context;
|
343
|
+
return isFunction(extraOptions.schemaConfig) ? extraOptions.schemaConfig({ baseSchemaConfig: baseExtraOptions.schema?.config ?? {} }) : extraOptions.schemaConfig ?? baseExtraOptions.schema?.config;
|
344
|
+
};
|
345
|
+
const getCurrentRouteSchemaKeyAndMainInitURL = (context) => {
|
346
|
+
const { baseExtraOptions, extraOptions, initURL } = context;
|
347
|
+
const schemaConfig = getResolvedSchemaConfig({
|
348
|
+
baseExtraOptions,
|
349
|
+
extraOptions
|
350
|
+
});
|
351
|
+
let currentRouteSchemaKey = initURL;
|
352
|
+
let mainInitURL = initURL;
|
353
|
+
if (schemaConfig?.prefix && currentRouteSchemaKey.startsWith(schemaConfig.prefix)) {
|
354
|
+
currentRouteSchemaKey = currentRouteSchemaKey.replace(schemaConfig.prefix, "");
|
355
|
+
mainInitURL = mainInitURL.replace(schemaConfig.prefix, schemaConfig.baseURL ?? "");
|
356
|
+
}
|
357
|
+
if (schemaConfig?.baseURL && currentRouteSchemaKey.startsWith(schemaConfig.baseURL)) currentRouteSchemaKey = currentRouteSchemaKey.replace(schemaConfig.baseURL, "");
|
358
|
+
return {
|
359
|
+
currentRouteSchemaKey,
|
360
|
+
mainInitURL
|
361
|
+
};
|
362
|
+
};
|
363
|
+
|
364
|
+
//#endregion
|
365
|
+
//#region src/url.ts
|
366
|
+
const slash = "/";
|
367
|
+
const colon = ":";
|
368
|
+
const openBrace = "{";
|
369
|
+
const closeBrace = "}";
|
370
|
+
const mergeUrlWithParams = (url, params) => {
|
371
|
+
if (!params) return url;
|
372
|
+
let newUrl = url;
|
373
|
+
if (isArray(params)) {
|
374
|
+
const matchedParamsArray = newUrl.split(slash).filter((part) => part.startsWith(colon) || part.startsWith(openBrace) && part.endsWith(closeBrace));
|
375
|
+
for (const [paramIndex, matchedParam] of matchedParamsArray.entries()) {
|
376
|
+
const stringParamValue = String(params[paramIndex]);
|
377
|
+
newUrl = newUrl.replace(matchedParam, stringParamValue);
|
378
|
+
}
|
379
|
+
return newUrl;
|
380
|
+
}
|
381
|
+
for (const [paramKey, paramValue] of Object.entries(params)) {
|
382
|
+
const colonPattern = `${colon}${paramKey}`;
|
383
|
+
const bracePattern = `${openBrace}${paramKey}${closeBrace}`;
|
384
|
+
const stringValue = String(paramValue);
|
385
|
+
newUrl = newUrl.replace(colonPattern, stringValue);
|
386
|
+
newUrl = newUrl.replace(bracePattern, stringValue);
|
387
|
+
}
|
388
|
+
return newUrl;
|
389
|
+
};
|
390
|
+
const questionMark = "?";
|
391
|
+
const ampersand = "&";
|
392
|
+
const mergeUrlWithQuery = (url, query) => {
|
393
|
+
if (!query) return url;
|
394
|
+
const queryString = toQueryString(query);
|
395
|
+
if (queryString?.length === 0) return url;
|
396
|
+
if (url.endsWith(questionMark)) return `${url}${queryString}`;
|
397
|
+
if (url.includes(questionMark)) return `${url}${ampersand}${queryString}`;
|
398
|
+
return `${url}${questionMark}${queryString}`;
|
399
|
+
};
|
400
|
+
/**
|
401
|
+
* @description Extracts the HTTP method from method-prefixed route patterns.
|
402
|
+
*
|
403
|
+
* Analyzes URLs that start with method modifiers (e.g., "@get/", "@post/") and extracts
|
404
|
+
* the HTTP method for use in API requests. This enables method specification directly
|
405
|
+
* in route definitions.
|
406
|
+
*
|
407
|
+
* @param initURL - The URL string to analyze for method modifiers
|
408
|
+
* @returns The extracted HTTP method (lowercase) if found, otherwise undefined
|
409
|
+
*
|
410
|
+
* @example
|
411
|
+
* ```typescript
|
412
|
+
* // Method extraction from prefixed routes
|
413
|
+
* extractMethodFromURL("@get/users"); // Returns: "get"
|
414
|
+
* extractMethodFromURL("@post/users"); // Returns: "post"
|
415
|
+
* extractMethodFromURL("@put/users/:id"); // Returns: "put"
|
416
|
+
* extractMethodFromURL("@delete/users/:id"); // Returns: "delete"
|
417
|
+
* extractMethodFromURL("@patch/users/:id"); // Returns: "patch"
|
418
|
+
*
|
419
|
+
* // No method modifier
|
420
|
+
* extractMethodFromURL("/users"); // Returns: undefined
|
421
|
+
* extractMethodFromURL("users"); // Returns: undefined
|
422
|
+
*
|
423
|
+
* // Invalid or unsupported methods
|
424
|
+
* extractMethodFromURL("@invalid/users"); // Returns: undefined
|
425
|
+
* extractMethodFromURL("@/users"); // Returns: undefined
|
426
|
+
*
|
427
|
+
* // Edge cases
|
428
|
+
* extractMethodFromURL(undefined); // Returns: undefined
|
429
|
+
* extractMethodFromURL(""); // Returns: undefined
|
430
|
+
* ```
|
431
|
+
*/
|
432
|
+
const extractMethodFromURL = (initURL) => {
|
433
|
+
if (!initURL?.startsWith("@")) return;
|
434
|
+
const method = initURL.split("@")[1]?.split("/")[0];
|
435
|
+
if (!method || !routeKeyMethods.includes(method)) return;
|
436
|
+
return method;
|
437
|
+
};
|
438
|
+
const normalizeURL = (initURL) => {
|
439
|
+
const methodFromURL = extractMethodFromURL(initURL);
|
440
|
+
if (!methodFromURL) return initURL;
|
441
|
+
return initURL.replace(`@${methodFromURL}/`, "/");
|
442
|
+
};
|
443
|
+
const getFullAndNormalizedURL = (options) => {
|
444
|
+
const { baseURL, initURL, params, query } = options;
|
445
|
+
const normalizedInitURL = normalizeURL(initURL);
|
446
|
+
const urlWithMergedParams = mergeUrlWithParams(normalizedInitURL, params);
|
447
|
+
const urlWithMergedQueryAndParams = mergeUrlWithQuery(urlWithMergedParams, query);
|
448
|
+
return {
|
449
|
+
fullURL: !urlWithMergedQueryAndParams.startsWith("http") && baseURL ? `${baseURL}${urlWithMergedQueryAndParams}` : urlWithMergedQueryAndParams,
|
450
|
+
normalizedInitURL
|
451
|
+
};
|
452
|
+
};
|
453
|
+
|
454
|
+
//#endregion
|
455
|
+
//#region src/utils/polyfills.ts
|
456
|
+
const createCombinedSignalPolyfill = (signals) => {
|
457
|
+
const controller = new AbortController();
|
458
|
+
const handleAbort = (actualSignal) => {
|
459
|
+
if (controller.signal.aborted) return;
|
460
|
+
controller.abort(actualSignal.reason);
|
461
|
+
};
|
462
|
+
for (const actualSignal of signals) {
|
463
|
+
if (actualSignal.aborted) {
|
464
|
+
handleAbort(actualSignal);
|
465
|
+
break;
|
466
|
+
}
|
467
|
+
actualSignal.addEventListener("abort", () => handleAbort(actualSignal), { signal: controller.signal });
|
468
|
+
}
|
469
|
+
return controller.signal;
|
470
|
+
};
|
471
|
+
const createTimeoutSignalPolyfill = (milliseconds) => {
|
472
|
+
const controller = new AbortController();
|
473
|
+
const reason = new DOMException("Request timed out", "TimeoutError");
|
474
|
+
const timeout = setTimeout(() => controller.abort(reason), milliseconds);
|
475
|
+
controller.signal.addEventListener("abort", () => clearTimeout(timeout));
|
476
|
+
return controller.signal;
|
477
|
+
};
|
478
|
+
|
479
|
+
//#endregion
|
480
|
+
//#region src/utils/common.ts
|
481
|
+
const omitKeys = (initialObject, keysToOmit) => {
|
482
|
+
const updatedObject = {};
|
483
|
+
const keysToOmitSet = new Set(keysToOmit);
|
484
|
+
for (const [key, value] of Object.entries(initialObject)) if (!keysToOmitSet.has(key)) updatedObject[key] = value;
|
485
|
+
return updatedObject;
|
486
|
+
};
|
487
|
+
const pickKeys = (initialObject, keysToPick) => {
|
488
|
+
const updatedObject = {};
|
489
|
+
const keysToPickSet = new Set(keysToPick);
|
490
|
+
for (const [key, value] of Object.entries(initialObject)) if (keysToPickSet.has(key)) updatedObject[key] = value;
|
491
|
+
return updatedObject;
|
492
|
+
};
|
493
|
+
const splitBaseConfig = (baseConfig) => [pickKeys(baseConfig, fetchSpecificKeys), omitKeys(baseConfig, fetchSpecificKeys)];
|
494
|
+
const splitConfig = (config) => [pickKeys(config, fetchSpecificKeys), omitKeys(config, fetchSpecificKeys)];
|
495
|
+
const toQueryString = (params) => {
|
496
|
+
if (!params) {
|
497
|
+
console.error("toQueryString:", "No query params provided!");
|
498
|
+
return null;
|
499
|
+
}
|
500
|
+
return new URLSearchParams(params).toString();
|
501
|
+
};
|
502
|
+
const objectifyHeaders = (headers) => {
|
503
|
+
if (!headers || isPlainObject(headers)) return headers;
|
504
|
+
return Object.fromEntries(headers);
|
505
|
+
};
|
506
|
+
const getHeaders = async (options) => {
|
507
|
+
const { auth, body, headers } = options;
|
508
|
+
if (!(Boolean(headers) || Boolean(body) || Boolean(auth))) return;
|
509
|
+
const headersObject = {
|
510
|
+
...await getAuthHeader(auth),
|
511
|
+
...objectifyHeaders(headers)
|
512
|
+
};
|
513
|
+
if (isQueryString(body)) {
|
514
|
+
headersObject["Content-Type"] = "application/x-www-form-urlencoded";
|
515
|
+
return headersObject;
|
516
|
+
}
|
517
|
+
if (isSerializable(body) || isValidJsonString(body)) {
|
518
|
+
headersObject["Content-Type"] = "application/json";
|
519
|
+
headersObject.Accept = "application/json";
|
520
|
+
}
|
521
|
+
return headersObject;
|
522
|
+
};
|
523
|
+
const getMethod = (ctx) => {
|
524
|
+
const { initURL, method } = ctx;
|
525
|
+
return method?.toUpperCase() ?? extractMethodFromURL(initURL)?.toUpperCase() ?? requestOptionDefaults().method;
|
526
|
+
};
|
527
|
+
const getBody = (options) => {
|
528
|
+
const { body, bodySerializer } = options;
|
529
|
+
if (isSerializable(body)) return (bodySerializer ?? extraOptionDefaults().bodySerializer)(body);
|
530
|
+
return body;
|
531
|
+
};
|
532
|
+
const getFetchImpl = (customFetchImpl) => {
|
533
|
+
if (customFetchImpl) return customFetchImpl;
|
534
|
+
if (typeof globalThis !== "undefined" && isFunction(globalThis.fetch)) return globalThis.fetch;
|
535
|
+
throw new Error("No fetch implementation found");
|
536
|
+
};
|
537
|
+
const PromiseWithResolvers = () => {
|
538
|
+
let reject;
|
539
|
+
let resolve;
|
540
|
+
return {
|
541
|
+
promise: new Promise((res, rej) => {
|
542
|
+
resolve = res;
|
543
|
+
reject = rej;
|
544
|
+
}),
|
545
|
+
reject,
|
546
|
+
resolve
|
547
|
+
};
|
548
|
+
};
|
549
|
+
const waitFor = (delay) => {
|
550
|
+
if (delay === 0) return;
|
551
|
+
const { promise, resolve } = PromiseWithResolvers();
|
552
|
+
setTimeout(resolve, delay);
|
553
|
+
return promise;
|
554
|
+
};
|
555
|
+
const createCombinedSignal = (...signals) => {
|
556
|
+
const cleanedSignals = signals.filter((signal) => signal != null);
|
557
|
+
if (!("any" in AbortSignal)) return createCombinedSignalPolyfill(cleanedSignals);
|
558
|
+
return AbortSignal.any(cleanedSignals);
|
559
|
+
};
|
560
|
+
const createTimeoutSignal = (milliseconds) => {
|
561
|
+
if (!("timeout" in AbortSignal)) return createTimeoutSignalPolyfill(milliseconds);
|
562
|
+
return AbortSignal.timeout(milliseconds);
|
563
|
+
};
|
564
|
+
const deterministicHashFn = (value) => {
|
565
|
+
return JSON.stringify(value, (_, val) => {
|
566
|
+
if (!isPlainObject(val)) return val;
|
567
|
+
const sortedKeys = Object.keys(val).toSorted();
|
568
|
+
const result = {};
|
569
|
+
for (const key of sortedKeys) result[key] = val[key];
|
570
|
+
return result;
|
571
|
+
});
|
572
|
+
};
|
573
|
+
const toArray = (value) => isArray(value) ? value : [value];
|
574
|
+
|
575
|
+
//#endregion
|
576
|
+
export { HTTPError, ValidationError, createCombinedSignal, createTimeoutSignal, deterministicHashFn, extraOptionDefaults, fallBackRouteSchemaKey, getBody, getCurrentRouteSchemaKeyAndMainInitURL, getFetchImpl, getFullAndNormalizedURL, getHeaders, getMethod, handleConfigValidation, handleSchemaValidation, isArray, isBoolean, isFunction, isHTTPError, isHTTPErrorInstance, isJavascriptError, isObject, isPlainObject, isReadableStream, isString, isValidationError, isValidationErrorInstance, splitBaseConfig, splitConfig, toQueryString, waitFor };
|
577
|
+
//# sourceMappingURL=common-BFea9qeg.js.map
|