@zayne-labs/callapi 1.11.11 → 1.11.14

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.
@@ -1,8 +1,9 @@
1
- import { $ as GetResponseType, A as RequestStreamContext, C as RetryOptions, D as HooksOrHooksArray, E as Hooks, G as CallApiPlugin, J as PluginSetupContext, K as PluginHooks, M as ResponseErrorContext, N as ResponseStreamContext, O as PluginExtraOptions, P as SuccessContext, Q as GetCallApiResult, S as ThrowOnErrorUnion, St as AnyString, T as ErrorContext, X as CallApiResultSuccessVariant, Y as CallApiResultErrorVariant, Z as CallApiSuccessOrErrorVariant, _ as GetCurrentRouteSchema, _t as CallApiSchema, a as CallApiExtraOptions, at as ResponseTypeUnion, b as InferParamsFromRoute, c as CallApiRequestOptions, d as GetBaseSchemaConfig, dt as DefaultPluginArray, et as PossibleHTTPError, f as GetBaseSchemaRoutes, ft as DefaultThrowOnError, g as ApplyURLBasedConfig, gt as BaseCallApiSchemaRoutes, h as ApplyStrictConfig, ht as BaseCallApiSchemaAndConfig, i as CallApiConfig, it as ResponseTypeMap, j as ResponseContext, k as RequestContext, l as CallApiRequestOptionsForHooks, m as InferExtendSchemaContext, n as BaseCallApiExtraOptions, nt as PossibleJavaScriptOrValidationError, o as CallApiExtraOptionsForHooks, ot as ResultModeMap, p as InferExtendSchemaConfigContext, q as PluginHooksWithMoreOptions, r as BaseInstanceContext, rt as PossibleValidationError, s as CallApiParameters, st as ResultModeUnion, t as BaseCallApiConfig, tt as PossibleJavaScriptError, u as CallApiResult, ut as DefaultDataType, v as GetCurrentRouteSchemaKey, vt as CallApiSchemaConfig, w as DedupeOptions, x as Register, xt as URLOptions, y as InferInitURL, yt as InferSchemaOutputResult } from "./common-7RMbhCz1.js";
1
+ import "./validation-uPnlxhfx.js";
2
+ import { $ as GetResponseType, A as RequestStreamContext, C as RetryOptions, Ct as AnyFunction, D as HooksOrHooksArray, E as Hooks, G as CallApiPlugin, J as PluginSetupContext, K as PluginHooks, M as ResponseErrorContext, N as ResponseStreamContext, O as PluginExtraOptions, P as SuccessContext, Q as GetCallApiResult, S as ThrowOnErrorUnion, T as ErrorContext, X as CallApiResultSuccessVariant, Y as CallApiResultErrorVariant, Z as CallApiSuccessOrErrorVariant, _ as GetCurrentRouteSchema, _t as StandardSchemaV1, a as CallApiExtraOptions, at as ResponseTypeUnion, b as InferParamsFromRoute, bt as DefaultThrowOnError, c as CallApiRequestOptions, d as GetBaseSchemaConfig, dt as BaseCallApiSchemaRoutes, et as PossibleHTTPError, f as GetBaseSchemaRoutes, ft as CallApiSchema, g as ApplyURLBasedConfig, gt as URLOptions, h as ApplyStrictConfig, ht as InferSchemaOutput, i as CallApiConfig, it as ResponseTypeMap, j as ResponseContext, k as RequestContext, l as CallApiRequestOptionsForHooks, m as InferExtendSchemaContext, mt as InferSchemaInput, n as BaseCallApiExtraOptions, nt as PossibleJavaScriptOrValidationError, o as CallApiExtraOptionsForHooks, ot as ResultModeMap, p as InferExtendSchemaConfigContext, pt as CallApiSchemaConfig, q as PluginHooksWithMoreOptions, r as BaseInstanceContext, rt as PossibleValidationError, s as CallApiParameters, st as ResultModeUnion, t as BaseCallApiConfig, tt as PossibleJavaScriptError, u as CallApiResult, ut as BaseCallApiSchemaAndConfig, v as GetCurrentRouteSchemaKey, vt as DefaultDataType, w as DedupeOptions, wt as AnyString, x as Register, y as InferInitURL, yt as DefaultPluginArray } from "./common-Clx7i8bR.js";
2
3
 
3
4
  //#region src/createFetchClient.d.ts
4
5
 
5
- declare const createFetchClient: <TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, const TBaseSchemaAndConfig extends BaseCallApiSchemaAndConfig = BaseCallApiSchemaAndConfig, const TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TComputedBaseSchemaConfig extends CallApiSchemaConfig = GetBaseSchemaConfig<TBaseSchemaAndConfig>, TComputedBaseSchemaRoutes extends BaseCallApiSchemaRoutes = GetBaseSchemaRoutes<TBaseSchemaAndConfig>>(initBaseConfig?: BaseCallApiConfig<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchemaAndConfig, TBasePluginArray>) => <TData = TBaseData, TErrorData = TBaseErrorData, TResultMode extends ResultModeUnion = TBaseResultMode, TThrowOnError extends ThrowOnErrorUnion = TBaseThrowOnError, TResponseType extends ResponseTypeUnion = TBaseResponseType, const TSchemaConfig extends CallApiSchemaConfig = TComputedBaseSchemaConfig, TInitURL extends InferInitURL<TComputedBaseSchemaRoutes, TSchemaConfig> = InferInitURL<TComputedBaseSchemaRoutes, TSchemaConfig>, TCurrentRouteSchemaKey extends GetCurrentRouteSchemaKey<TSchemaConfig, TInitURL> = GetCurrentRouteSchemaKey<TSchemaConfig, TInitURL>, const TSchema extends CallApiSchema = GetCurrentRouteSchema<TComputedBaseSchemaRoutes, TCurrentRouteSchemaKey>, const TPluginArray extends CallApiPlugin[] = TBasePluginArray, TComputedResult = CallApiResult<InferSchemaOutputResult<TSchema["data"], TData>, InferSchemaOutputResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>>(initURL: TInitURL, initConfig?: CallApiConfig<InferSchemaOutputResult<TSchema["data"], GetResponseType<TData, TResponseType>>, InferSchemaOutputResult<TSchema["errorData"], GetResponseType<TErrorData, TResponseType>>, TResultMode, TThrowOnError, TResponseType, TComputedBaseSchemaRoutes, TSchema, TComputedBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, TBasePluginArray, TPluginArray>) => Promise<TComputedResult>;
6
+ declare const createFetchClient: <TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, const TBaseSchemaAndConfig extends BaseCallApiSchemaAndConfig = BaseCallApiSchemaAndConfig, const TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TComputedBaseSchemaConfig extends CallApiSchemaConfig = GetBaseSchemaConfig<TBaseSchemaAndConfig>, TComputedBaseSchemaRoutes extends BaseCallApiSchemaRoutes = GetBaseSchemaRoutes<TBaseSchemaAndConfig>>(initBaseConfig?: BaseCallApiConfig<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchemaAndConfig, TBasePluginArray>) => <TData = TBaseData, TErrorData = TBaseErrorData, TResultMode extends ResultModeUnion = TBaseResultMode, TThrowOnError extends ThrowOnErrorUnion = TBaseThrowOnError, TResponseType extends ResponseTypeUnion = TBaseResponseType, const TSchemaConfig extends CallApiSchemaConfig = TComputedBaseSchemaConfig, TInitURL extends InferInitURL<TComputedBaseSchemaRoutes, TSchemaConfig> = InferInitURL<TComputedBaseSchemaRoutes, TSchemaConfig>, TCurrentRouteSchemaKey extends GetCurrentRouteSchemaKey<TSchemaConfig, TInitURL> = GetCurrentRouteSchemaKey<TSchemaConfig, TInitURL>, const TSchema extends CallApiSchema = GetCurrentRouteSchema<TComputedBaseSchemaRoutes, TCurrentRouteSchemaKey>, const TPluginArray extends CallApiPlugin[] = TBasePluginArray, TComputedResult = CallApiResult<InferSchemaOutput<TSchema["data"], TData>, InferSchemaOutput<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>>(initURL: TInitURL, initConfig?: CallApiConfig<InferSchemaOutput<TSchema["data"], GetResponseType<TData, TResponseType>>, InferSchemaOutput<TSchema["errorData"], GetResponseType<TErrorData, TResponseType>>, TResultMode, TThrowOnError, TResponseType, TComputedBaseSchemaRoutes, TSchema, TComputedBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, TBasePluginArray, TPluginArray>) => Promise<TComputedResult>;
6
7
  declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = boolean, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, const TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends ApplyStrictConfig<TSchemaConfig, ApplyURLBasedConfig<TSchemaConfig, AnyString | "@delete/" | "@get/" | "@patch/" | "@post/" | "@put/">> = ApplyStrictConfig<TSchemaConfig, ApplyURLBasedConfig<TSchemaConfig, AnyString | "@delete/" | "@get/" | "@patch/" | "@post/" | "@put/">>, TCurrentRouteSchemaKey extends GetCurrentRouteSchemaKey<TSchemaConfig, TInitURL> = GetCurrentRouteSchemaKey<TSchemaConfig, TInitURL>, const TSchema extends CallApiSchema = GetCurrentRouteSchema<{
7
8
  [x: AnyString]: CallApiSchema | undefined;
8
9
  "@delete/"?: CallApiSchema | undefined;
@@ -31,11 +32,11 @@ declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode exten
31
32
  "@patch/"?: CallApiSchema | undefined;
32
33
  "@post/"?: CallApiSchema | undefined;
33
34
  "@put/"?: CallApiSchema | undefined;
34
- }[TCurrentRouteSchemaKey]>>, const TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TComputedResult = GetCallApiResult<InferSchemaOutputResult<TSchema["data"], TData>, InferSchemaOutputResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType, {
35
- all: CallApiResultSuccessVariant<GetResponseType<InferSchemaOutputResult<TSchema["data"], TData>, TResponseType, ResponseTypeMap<InferSchemaOutputResult<TSchema["data"], TData>>>>;
36
- onlyData: NoInfer<GetResponseType<InferSchemaOutputResult<TSchema["data"], TData>, TResponseType, ResponseTypeMap<InferSchemaOutputResult<TSchema["data"], TData>>>>;
35
+ }[TCurrentRouteSchemaKey]>>, const TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TComputedResult = GetCallApiResult<undefined extends TSchema["data"] ? TData : TSchema["data"] extends infer T ? T extends TSchema["data"] ? T extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T> : T extends AnyFunction<infer TResult> ? Awaited<TResult> : TData : never : never, undefined extends TSchema["errorData"] ? TErrorData : TSchema["errorData"] extends infer T_1 ? T_1 extends TSchema["errorData"] ? T_1 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_1> : T_1 extends AnyFunction<infer TResult> ? Awaited<TResult> : TErrorData : never : never, TResultMode, TThrowOnError, TResponseType, {
36
+ all: CallApiResultSuccessVariant<GetResponseType<undefined extends TSchema["data"] ? TData : TSchema["data"] extends infer T_2 ? T_2 extends TSchema["data"] ? T_2 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_2> : T_2 extends AnyFunction<infer TResult> ? Awaited<TResult> : TData : never : never, TResponseType, ResponseTypeMap<undefined extends TSchema["data"] ? TData : TSchema["data"] extends infer T_3 ? T_3 extends TSchema["data"] ? T_3 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_3> : T_3 extends AnyFunction<infer TResult> ? Awaited<TResult> : TData : never : never>>>;
37
+ onlyData: NoInfer<GetResponseType<undefined extends TSchema["data"] ? TData : TSchema["data"] extends infer T_4 ? T_4 extends TSchema["data"] ? T_4 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_4> : T_4 extends AnyFunction<infer TResult> ? Awaited<TResult> : TData : never : never, TResponseType, ResponseTypeMap<undefined extends TSchema["data"] ? TData : TSchema["data"] extends infer T_5 ? T_5 extends TSchema["data"] ? T_5 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_5> : T_5 extends AnyFunction<infer TResult> ? Awaited<TResult> : TData : never : never>>>;
37
38
  onlyResponse: Response;
38
- }, ResultModeMap<InferSchemaOutputResult<TSchema["data"], TData>, InferSchemaOutputResult<TSchema["errorData"], TErrorData>, TResponseType, TThrowOnError>>>(initURL: TInitURL, initConfig?: CallApiConfig<InferSchemaOutputResult<TSchema["data"], GetResponseType<TData, TResponseType, ResponseTypeMap<TData>>>, InferSchemaOutputResult<TSchema["errorData"], GetResponseType<TErrorData, TResponseType, ResponseTypeMap<TErrorData>>>, TResultMode, TThrowOnError, TResponseType, {
39
+ }, ResultModeMap<undefined extends TSchema["data"] ? TData : TSchema["data"] extends infer T_6 ? T_6 extends TSchema["data"] ? T_6 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_6> : T_6 extends AnyFunction<infer TResult> ? Awaited<TResult> : TData : never : never, undefined extends TSchema["errorData"] ? TErrorData : TSchema["errorData"] extends infer T_7 ? T_7 extends TSchema["errorData"] ? T_7 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_7> : T_7 extends AnyFunction<infer TResult> ? Awaited<TResult> : TErrorData : never : never, TResponseType, TThrowOnError>>>(initURL: TInitURL, initConfig?: CallApiConfig<undefined extends TSchema["data"] ? GetResponseType<TData, TResponseType, ResponseTypeMap<TData>> : TSchema["data"] extends infer T_8 ? T_8 extends TSchema["data"] ? T_8 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_8> : T_8 extends AnyFunction<infer TResult> ? Awaited<TResult> : GetResponseType<TData, TResponseType, ResponseTypeMap<TData>> : never : never, undefined extends TSchema["errorData"] ? GetResponseType<TErrorData, TResponseType, ResponseTypeMap<TErrorData>> : TSchema["errorData"] extends infer T_9 ? T_9 extends TSchema["errorData"] ? T_9 extends StandardSchemaV1<unknown, unknown> ? StandardSchemaV1.InferOutput<T_9> : T_9 extends AnyFunction<infer TResult> ? Awaited<TResult> : GetResponseType<TErrorData, TResponseType, ResponseTypeMap<TErrorData>> : never : never, TResultMode, TThrowOnError, TResponseType, {
39
40
  [x: AnyString]: CallApiSchema | undefined;
40
41
  "@delete/"?: CallApiSchema | undefined;
41
42
  "@get/"?: CallApiSchema | undefined;
@@ -44,5 +45,5 @@ declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode exten
44
45
  "@put/"?: CallApiSchema | undefined;
45
46
  }, TSchema, CallApiSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, DefaultPluginArray, TPluginArray>) => Promise<TComputedResult>;
46
47
  //#endregion
47
- export { type BaseCallApiConfig, type BaseCallApiExtraOptions, type BaseCallApiSchemaRoutes, type BaseInstanceContext, type CallApiConfig, type CallApiExtraOptions, type CallApiExtraOptionsForHooks, type CallApiParameters, type CallApiPlugin, type CallApiRequestOptions, type CallApiRequestOptionsForHooks, type CallApiResult, type CallApiResultErrorVariant, type CallApiResultSuccessVariant, type CallApiSchema, type CallApiSchemaConfig, type CallApiSuccessOrErrorVariant, type DedupeOptions, type ErrorContext, type Hooks, type HooksOrHooksArray, type InferExtendSchemaConfigContext, type InferExtendSchemaContext, type InferParamsFromRoute, type InferSchemaOutputResult, type PluginExtraOptions, type PluginHooks, type PluginHooksWithMoreOptions, type PluginSetupContext, type PossibleHTTPError, type PossibleJavaScriptError, type PossibleJavaScriptOrValidationError, type PossibleValidationError, type Register, type RequestContext, type RequestStreamContext, type ResponseContext, type ResponseErrorContext, type ResponseStreamContext, type ResponseTypeUnion, type ResultModeUnion, type RetryOptions, type SuccessContext, type URLOptions, callApi, createFetchClient };
48
+ export { type BaseCallApiConfig, type BaseCallApiExtraOptions, type BaseCallApiSchemaRoutes, type BaseInstanceContext, type CallApiConfig, type CallApiExtraOptions, type CallApiExtraOptionsForHooks, type CallApiParameters, type CallApiPlugin, type CallApiRequestOptions, type CallApiRequestOptionsForHooks, type CallApiResult, type CallApiResultErrorVariant, type CallApiResultSuccessVariant, type CallApiSchema, type CallApiSchemaConfig, type CallApiSuccessOrErrorVariant, type DedupeOptions, type ErrorContext, type Hooks, type HooksOrHooksArray, type InferExtendSchemaConfigContext, type InferExtendSchemaContext, type InferParamsFromRoute, type InferSchemaInput, type InferSchemaOutput, type PluginExtraOptions, type PluginHooks, type PluginHooksWithMoreOptions, type PluginSetupContext, type PossibleHTTPError, type PossibleJavaScriptError, type PossibleJavaScriptOrValidationError, type PossibleValidationError, type Register, type RequestContext, type RequestStreamContext, type ResponseContext, type ResponseErrorContext, type ResponseStreamContext, type ResponseTypeUnion, type ResultModeUnion, type RetryOptions, type SuccessContext, type URLOptions, callApi, createFetchClient };
48
49
  //# sourceMappingURL=index.d.ts.map
package/dist/esm/index.js CHANGED
@@ -1,4 +1,6 @@
1
- import { A as isReadableStream, C as HTTPError, D as isFunction, E as isBoolean, M as extraOptionDefaults, O as isObject, S as isValidationErrorInstance, T as isArray, a as getFetchImpl, c as splitBaseConfig, d as getFullAndNormalizedURL, h as handleSchemaValidation, i as getBody, j as isString, k as isPlainObject, l as splitConfig, m as handleConfigValidation, n as createTimeoutSignal, o as getHeaders, p as getCurrentRouteSchemaKeyAndMainInitURL, r as deterministicHashFn, s as getMethod, t as createCombinedSignal, u as waitFor, y as isHTTPErrorInstance } from "./common-CXyKVpND.js";
1
+ import { n as requestOptionDefaults, r as defineEnum, t as extraOptionDefaults } from "./defaults-BD3B1uIH.js";
2
+ import { _ as isReadableStream, b as isValidJsonString, c as HTTPError, d as isBoolean, f as isFunction, g as isQueryString, h as isPromise, i as isHTTPErrorInstance, l as ValidationError, m as isPlainObject, n as toQueryString, p as isObject, s as isValidationErrorInstance, u as isArray, v as isSerializable, y as isString } from "./body-B9WKokQt.js";
3
+ import { n as fetchSpecificKeys, t as fallBackRouteSchemaKey } from "./validation-MjkoG9bG.js";
2
4
 
3
5
  //#region src/result.ts
4
6
  const getResponseType = (response, parser) => ({
@@ -149,9 +151,9 @@ const executeHooksInCatchBlock = async (hookResultsOrPromise, hookInfo) => {
149
151
  await Promise.all(hookResultsOrPromise);
150
152
  return null;
151
153
  } catch (hookError) {
152
- const { errorResult: hookErrorResult } = resolveErrorResult(hookError, errorInfo);
153
154
  if (shouldThrowOnError) throw hookError;
154
- return hookErrorResult;
155
+ const { errorResult } = resolveErrorResult(hookError, errorInfo);
156
+ return errorResult;
155
157
  }
156
158
  };
157
159
 
@@ -262,6 +264,392 @@ const toStreamableResponse = async (context) => {
262
264
  return new Response(stream, response);
263
265
  };
264
266
 
267
+ //#endregion
268
+ //#region src/auth.ts
269
+ const resolveAuthValue = (value) => isFunction(value) ? value() : value;
270
+ const getAuthHeader = async (auth) => {
271
+ if (auth === void 0) return;
272
+ if (isPromise(auth) || isFunction(auth) || !isObject(auth)) {
273
+ const authValue = await resolveAuthValue(auth);
274
+ if (authValue === void 0) return;
275
+ return { Authorization: `Bearer ${authValue}` };
276
+ }
277
+ switch (auth.type) {
278
+ case "Basic": {
279
+ const [username, password] = await Promise.all([resolveAuthValue(auth.username), resolveAuthValue(auth.password)]);
280
+ if (username === void 0 || password === void 0) return;
281
+ return { Authorization: `Basic ${globalThis.btoa(`${username}:${password}`)}` };
282
+ }
283
+ case "Custom": {
284
+ const [prefix, value] = await Promise.all([resolveAuthValue(auth.prefix), resolveAuthValue(auth.value)]);
285
+ if (value === void 0) return;
286
+ return { Authorization: `${prefix} ${value}` };
287
+ }
288
+ default: {
289
+ const [bearer, token] = await Promise.all([resolveAuthValue(auth.bearer), resolveAuthValue(auth.token)]);
290
+ if (bearer !== void 0) return { Authorization: `Bearer ${bearer}` };
291
+ if (token === void 0) return;
292
+ return { Authorization: `Token ${token}` };
293
+ }
294
+ }
295
+ };
296
+
297
+ //#endregion
298
+ //#region src/validation.ts
299
+ const handleValidatorFunction = async (validator, inputData) => {
300
+ try {
301
+ return {
302
+ issues: void 0,
303
+ value: await validator(inputData)
304
+ };
305
+ } catch (error) {
306
+ return {
307
+ issues: toArray(error),
308
+ value: void 0
309
+ };
310
+ }
311
+ };
312
+ const standardSchemaParser = async (fullSchema, schemaName, inputData, response) => {
313
+ const schema = fullSchema?.[schemaName];
314
+ if (!schema) return inputData;
315
+ const result = isFunction(schema) ? await handleValidatorFunction(schema, inputData) : await schema["~standard"].validate(inputData);
316
+ if (result.issues) throw new ValidationError({
317
+ issueCause: schemaName,
318
+ issues: result.issues,
319
+ response: response ?? null
320
+ });
321
+ return result.value;
322
+ };
323
+ const routeKeyMethods = defineEnum([
324
+ "delete",
325
+ "get",
326
+ "patch",
327
+ "post",
328
+ "put"
329
+ ]);
330
+ const handleSchemaValidation = async (fullSchema, schemaName, validationOptions) => {
331
+ const { inputValue, response, schemaConfig } = validationOptions;
332
+ if (schemaConfig?.disableRuntimeValidation) return inputValue;
333
+ return await standardSchemaParser(fullSchema, schemaName, inputValue, response);
334
+ };
335
+ const extraOptionsToBeValidated = [
336
+ "meta",
337
+ "params",
338
+ "query"
339
+ ];
340
+ const handleExtraOptionsValidation = async (validationOptions) => {
341
+ const { options, schema, schemaConfig } = validationOptions;
342
+ const validationResultArray = await Promise.all(extraOptionsToBeValidated.map((schemaName) => handleSchemaValidation(schema, schemaName, {
343
+ inputValue: options[schemaName],
344
+ schemaConfig
345
+ })));
346
+ const validatedResultObject = {};
347
+ for (const [index, schemaName] of extraOptionsToBeValidated.entries()) {
348
+ const validationResult = validationResultArray[index];
349
+ if (validationResult === void 0) continue;
350
+ validatedResultObject[schemaName] = validationResult;
351
+ }
352
+ return validatedResultObject;
353
+ };
354
+ const requestOptionsToBeValidated = [
355
+ "body",
356
+ "headers",
357
+ "method"
358
+ ];
359
+ const handleRequestOptionsValidation = async (validationOptions) => {
360
+ const { requestOptions, schema, schemaConfig } = validationOptions;
361
+ const validationResultArray = await Promise.all(requestOptionsToBeValidated.map((schemaName) => handleSchemaValidation(schema, schemaName, {
362
+ inputValue: requestOptions[schemaName],
363
+ schemaConfig
364
+ })));
365
+ const validatedResultObject = {};
366
+ for (const [index, propertyKey] of requestOptionsToBeValidated.entries()) {
367
+ const validationResult = validationResultArray[index];
368
+ if (validationResult === void 0) continue;
369
+ validatedResultObject[propertyKey] = validationResult;
370
+ }
371
+ return validatedResultObject;
372
+ };
373
+ const handleConfigValidation = async (validationOptions) => {
374
+ const { baseExtraOptions, currentRouteSchemaKey, extraOptions, options, requestOptions } = validationOptions;
375
+ const { currentRouteSchema, resolvedSchema } = getResolvedSchema({
376
+ baseExtraOptions,
377
+ currentRouteSchemaKey,
378
+ extraOptions
379
+ });
380
+ const resolvedSchemaConfig = getResolvedSchemaConfig({
381
+ baseExtraOptions,
382
+ extraOptions
383
+ });
384
+ if (resolvedSchemaConfig?.strict === true && !currentRouteSchema) throw new ValidationError({
385
+ issueCause: "schemaConfig-(strict)",
386
+ issues: [{ message: `Strict Mode - No schema found for route '${currentRouteSchemaKey}' ` }],
387
+ response: null
388
+ });
389
+ if (resolvedSchemaConfig?.disableRuntimeValidation) return {
390
+ extraOptionsValidationResult: null,
391
+ requestOptionsValidationResult: null,
392
+ resolvedSchema,
393
+ resolvedSchemaConfig,
394
+ shouldApplySchemaOutput: false
395
+ };
396
+ const [extraOptionsValidationResult, requestOptionsValidationResult] = await Promise.all([handleExtraOptionsValidation({
397
+ options,
398
+ schema: resolvedSchema,
399
+ schemaConfig: resolvedSchemaConfig
400
+ }), handleRequestOptionsValidation({
401
+ requestOptions,
402
+ schema: resolvedSchema,
403
+ schemaConfig: resolvedSchemaConfig
404
+ })]);
405
+ return {
406
+ extraOptionsValidationResult,
407
+ requestOptionsValidationResult,
408
+ resolvedSchema,
409
+ resolvedSchemaConfig,
410
+ shouldApplySchemaOutput: (Boolean(extraOptionsValidationResult) || Boolean(requestOptionsValidationResult)) && !resolvedSchemaConfig?.disableValidationOutputApplication
411
+ };
412
+ };
413
+ const getResolvedSchema = (context) => {
414
+ const { baseExtraOptions, currentRouteSchemaKey, extraOptions } = context;
415
+ const fallbackRouteSchema = baseExtraOptions.schema?.routes[fallBackRouteSchemaKey];
416
+ const currentRouteSchema = baseExtraOptions.schema?.routes[currentRouteSchemaKey];
417
+ const resolvedRouteSchema = {
418
+ ...fallbackRouteSchema,
419
+ ...currentRouteSchema
420
+ };
421
+ return {
422
+ currentRouteSchema,
423
+ resolvedSchema: isFunction(extraOptions.schema) ? extraOptions.schema({
424
+ baseSchemaRoutes: baseExtraOptions.schema?.routes ?? {},
425
+ currentRouteSchema: resolvedRouteSchema ?? {}
426
+ }) : extraOptions.schema ?? resolvedRouteSchema
427
+ };
428
+ };
429
+ const getResolvedSchemaConfig = (context) => {
430
+ const { baseExtraOptions, extraOptions } = context;
431
+ return isFunction(extraOptions.schemaConfig) ? extraOptions.schemaConfig({ baseSchemaConfig: baseExtraOptions.schema?.config ?? {} }) : extraOptions.schemaConfig ?? baseExtraOptions.schema?.config;
432
+ };
433
+ const getCurrentRouteSchemaKeyAndMainInitURL = (context) => {
434
+ const { baseExtraOptions, extraOptions, initURL } = context;
435
+ const schemaConfig = getResolvedSchemaConfig({
436
+ baseExtraOptions,
437
+ extraOptions
438
+ });
439
+ let currentRouteSchemaKey = initURL;
440
+ let mainInitURL = initURL;
441
+ if (schemaConfig?.prefix && currentRouteSchemaKey.startsWith(schemaConfig.prefix)) {
442
+ currentRouteSchemaKey = currentRouteSchemaKey.replace(schemaConfig.prefix, "");
443
+ mainInitURL = mainInitURL.replace(schemaConfig.prefix, schemaConfig.baseURL ?? "");
444
+ }
445
+ if (schemaConfig?.baseURL && currentRouteSchemaKey.startsWith(schemaConfig.baseURL)) currentRouteSchemaKey = currentRouteSchemaKey.replace(schemaConfig.baseURL, "");
446
+ return {
447
+ currentRouteSchemaKey,
448
+ mainInitURL
449
+ };
450
+ };
451
+
452
+ //#endregion
453
+ //#region src/url.ts
454
+ const slash = "/";
455
+ const colon = ":";
456
+ const openBrace = "{";
457
+ const closeBrace = "}";
458
+ const mergeUrlWithParams = (url, params) => {
459
+ if (!params) return url;
460
+ let newUrl = url;
461
+ if (isArray(params)) {
462
+ const matchedParamsArray = newUrl.split(slash).filter((part) => part.startsWith(colon) || part.startsWith(openBrace) && part.endsWith(closeBrace));
463
+ for (const [paramIndex, matchedParam] of matchedParamsArray.entries()) {
464
+ const stringParamValue = String(params[paramIndex]);
465
+ newUrl = newUrl.replace(matchedParam, stringParamValue);
466
+ }
467
+ return newUrl;
468
+ }
469
+ for (const [paramKey, paramValue] of Object.entries(params)) {
470
+ const colonPattern = `${colon}${paramKey}`;
471
+ const bracePattern = `${openBrace}${paramKey}${closeBrace}`;
472
+ const stringValue = String(paramValue);
473
+ newUrl = newUrl.replace(colonPattern, stringValue);
474
+ newUrl = newUrl.replace(bracePattern, stringValue);
475
+ }
476
+ return newUrl;
477
+ };
478
+ const questionMark = "?";
479
+ const ampersand = "&";
480
+ const mergeUrlWithQuery = (url, query) => {
481
+ if (!query) return url;
482
+ const queryString = toQueryString(query);
483
+ if (queryString?.length === 0) return url;
484
+ if (url.endsWith(questionMark)) return `${url}${queryString}`;
485
+ if (url.includes(questionMark)) return `${url}${ampersand}${queryString}`;
486
+ return `${url}${questionMark}${queryString}`;
487
+ };
488
+ /**
489
+ * @description Extracts the HTTP method from method-prefixed route patterns.
490
+ *
491
+ * Analyzes URLs that start with method modifiers (e.g., "@get/", "@post/") and extracts
492
+ * the HTTP method for use in API requests. This enables method specification directly
493
+ * in route definitions.
494
+ *
495
+ * @param initURL - The URL string to analyze for method modifiers
496
+ * @returns The extracted HTTP method (lowercase) if found, otherwise undefined
497
+ *
498
+ * @example
499
+ * ```typescript
500
+ * // Method extraction from prefixed routes
501
+ * extractMethodFromURL("@get/users"); // Returns: "get"
502
+ * extractMethodFromURL("@post/users"); // Returns: "post"
503
+ * extractMethodFromURL("@put/users/:id"); // Returns: "put"
504
+ * extractMethodFromURL("@delete/users/:id"); // Returns: "delete"
505
+ * extractMethodFromURL("@patch/users/:id"); // Returns: "patch"
506
+ *
507
+ * // No method modifier
508
+ * extractMethodFromURL("/users"); // Returns: undefined
509
+ * extractMethodFromURL("users"); // Returns: undefined
510
+ *
511
+ * // Invalid or unsupported methods
512
+ * extractMethodFromURL("@invalid/users"); // Returns: undefined
513
+ * extractMethodFromURL("@/users"); // Returns: undefined
514
+ *
515
+ * // Edge cases
516
+ * extractMethodFromURL(undefined); // Returns: undefined
517
+ * extractMethodFromURL(""); // Returns: undefined
518
+ * ```
519
+ */
520
+ const extractMethodFromURL = (initURL) => {
521
+ if (!initURL?.startsWith("@")) return;
522
+ const method = initURL.split("@")[1]?.split("/")[0];
523
+ if (!method || !routeKeyMethods.includes(method)) return;
524
+ return method;
525
+ };
526
+ const normalizeURL = (initURL) => {
527
+ const methodFromURL = extractMethodFromURL(initURL);
528
+ if (!methodFromURL) return initURL;
529
+ return initURL.replace(`@${methodFromURL}/`, "/");
530
+ };
531
+ const getFullAndNormalizedURL = (options) => {
532
+ const { baseURL, initURL, params, query } = options;
533
+ const normalizedInitURL = normalizeURL(initURL);
534
+ const urlWithMergedQueryAndParams = mergeUrlWithQuery(mergeUrlWithParams(normalizedInitURL, params), query);
535
+ return {
536
+ fullURL: !urlWithMergedQueryAndParams.startsWith("http") && baseURL ? `${baseURL}${urlWithMergedQueryAndParams}` : urlWithMergedQueryAndParams,
537
+ normalizedInitURL
538
+ };
539
+ };
540
+
541
+ //#endregion
542
+ //#region src/utils/polyfills/combinedSignal.ts
543
+ const createCombinedSignalPolyfill = (signals) => {
544
+ const controller = new AbortController();
545
+ const handleAbort = (actualSignal) => {
546
+ if (controller.signal.aborted) return;
547
+ controller.abort(actualSignal.reason);
548
+ };
549
+ for (const actualSignal of signals) {
550
+ if (actualSignal.aborted) {
551
+ handleAbort(actualSignal);
552
+ break;
553
+ }
554
+ actualSignal.addEventListener("abort", () => handleAbort(actualSignal), { signal: controller.signal });
555
+ }
556
+ return controller.signal;
557
+ };
558
+
559
+ //#endregion
560
+ //#region src/utils/polyfills/timeoutSignal.ts
561
+ const createTimeoutSignalPolyfill = (milliseconds) => {
562
+ const controller = new AbortController();
563
+ const reason = new DOMException("Request timed out", "TimeoutError");
564
+ const timeout = setTimeout(() => controller.abort(reason), milliseconds);
565
+ controller.signal.addEventListener("abort", () => clearTimeout(timeout));
566
+ return controller.signal;
567
+ };
568
+
569
+ //#endregion
570
+ //#region src/utils/common.ts
571
+ const omitKeys = (initialObject, keysToOmit) => {
572
+ const updatedObject = {};
573
+ const keysToOmitSet = new Set(keysToOmit);
574
+ for (const [key, value] of Object.entries(initialObject)) if (!keysToOmitSet.has(key)) updatedObject[key] = value;
575
+ return updatedObject;
576
+ };
577
+ const pickKeys = (initialObject, keysToPick) => {
578
+ const updatedObject = {};
579
+ const keysToPickSet = new Set(keysToPick);
580
+ for (const [key, value] of Object.entries(initialObject)) if (keysToPickSet.has(key)) updatedObject[key] = value;
581
+ return updatedObject;
582
+ };
583
+ const splitBaseConfig = (baseConfig) => [pickKeys(baseConfig, fetchSpecificKeys), omitKeys(baseConfig, fetchSpecificKeys)];
584
+ const splitConfig = (config) => [pickKeys(config, fetchSpecificKeys), omitKeys(config, fetchSpecificKeys)];
585
+ const objectifyHeaders = (headers) => {
586
+ if (!headers || isPlainObject(headers)) return headers;
587
+ return Object.fromEntries(headers);
588
+ };
589
+ const getHeaders = async (options) => {
590
+ const { auth, body, headers } = options;
591
+ if (!(Boolean(headers) || Boolean(body) || Boolean(auth))) return;
592
+ const headersObject = {
593
+ ...await getAuthHeader(auth),
594
+ ...objectifyHeaders(headers)
595
+ };
596
+ if (isQueryString(body)) {
597
+ headersObject["Content-Type"] = "application/x-www-form-urlencoded";
598
+ return headersObject;
599
+ }
600
+ if (isSerializable(body) || isValidJsonString(body)) {
601
+ headersObject["Content-Type"] = "application/json";
602
+ headersObject.Accept = "application/json";
603
+ }
604
+ return headersObject;
605
+ };
606
+ const getMethod = (ctx) => {
607
+ const { initURL, method } = ctx;
608
+ return method?.toUpperCase() ?? extractMethodFromURL(initURL)?.toUpperCase() ?? requestOptionDefaults.method;
609
+ };
610
+ const getBody = (options) => {
611
+ const { body, bodySerializer } = options;
612
+ if (isSerializable(body)) return (bodySerializer ?? extraOptionDefaults.bodySerializer)(body);
613
+ return body;
614
+ };
615
+ const getInitFetchImpl = (customFetchImpl) => {
616
+ if (customFetchImpl) return customFetchImpl;
617
+ if (typeof globalThis !== "undefined" && isFunction(globalThis.fetch)) return globalThis.fetch;
618
+ throw new Error("No fetch implementation found");
619
+ };
620
+ const getFetchImpl = (context) => {
621
+ const { customFetchImpl, fetchMiddleware, requestContext } = context;
622
+ const initFetchImpl = getInitFetchImpl(customFetchImpl);
623
+ return fetchMiddleware ? fetchMiddleware({
624
+ ...requestContext,
625
+ fetchImpl: initFetchImpl
626
+ }) : initFetchImpl;
627
+ };
628
+ const waitFor = (delay) => {
629
+ if (delay === 0) return;
630
+ return new Promise((resolve) => setTimeout(resolve, delay));
631
+ };
632
+ const createCombinedSignal = (...signals) => {
633
+ const cleanedSignals = signals.filter((signal) => signal != null);
634
+ if (!("any" in AbortSignal)) return createCombinedSignalPolyfill(cleanedSignals);
635
+ return AbortSignal.any(cleanedSignals);
636
+ };
637
+ const createTimeoutSignal = (milliseconds) => {
638
+ if (milliseconds == null) return null;
639
+ if (!("timeout" in AbortSignal)) return createTimeoutSignalPolyfill(milliseconds);
640
+ return AbortSignal.timeout(milliseconds);
641
+ };
642
+ const deterministicHashFn = (value) => {
643
+ return JSON.stringify(value, (_, val) => {
644
+ if (!isPlainObject(val)) return val;
645
+ const sortedKeys = Object.keys(val).toSorted();
646
+ const result = {};
647
+ for (const key of sortedKeys) result[key] = val[key];
648
+ return result;
649
+ });
650
+ };
651
+ const toArray = (value) => isArray(value) ? value : [value];
652
+
265
653
  //#endregion
266
654
  //#region src/dedupe.ts
267
655
  const createDedupeStrategy = async (context) => {
@@ -290,11 +678,31 @@ const createDedupeStrategy = async (context) => {
290
678
  if (dedupeCacheScope === "global" && !$GlobalRequestInfoCache$1.has(dedupeCacheScopeKey)) $GlobalRequestInfoCache$1.set(dedupeCacheScopeKey, /* @__PURE__ */ new Map());
291
679
  const $RequestInfoCache = dedupeCacheScope === "global" ? $GlobalRequestInfoCache$1.get(dedupeCacheScopeKey) : $LocalRequestInfoCache;
292
680
  const $RequestInfoCacheOrNull = dedupeKey !== null ? $RequestInfoCache : null;
293
- /******
294
- * == Add a small delay to the execution to ensure proper request deduplication when multiple requests with the same key start simultaneously.
295
- * == This gives time for the cache to be updated with the previous request info before the next request checks it.
296
- ******/
297
- if (dedupeKey !== null) await waitFor(.1);
681
+ /**
682
+ * Force sequential execution of parallel requests to enable proper cache-based deduplication.
683
+ *
684
+ * Problem: When Promise.all([callApi(url), callApi(url)]) executes, both requests
685
+ * start synchronously and reach this point before either can populate the cache.
686
+ *
687
+ * Why `await Promise.resolve()` fails:
688
+ * - All microtasks in a batch resolve together at the next microtask checkpoint
689
+ * - Both requests resume execution simultaneously after the await
690
+ * - Both check `prevRequestInfo` at the same time → both see empty cache
691
+ * - Both proceed to populate cache → deduplication fails
692
+ *
693
+ * Why `wait new Promise(()=> setTimeout(resolve, number))` works:
694
+ * - Each setTimeout creates a separate task in the task queue
695
+ * - Tasks execute sequentially, not simultaneously
696
+ * - Request 1's task runs first: checks cache (empty) → continues → populates cache
697
+ * - Request 2's task runs after: checks cache (populated) → uses cached promise
698
+ * - Deduplication succeeds
699
+ *
700
+ * IMPORTANT: The delay must be non-zero. setTimeout(fn, 0) fails because JavaScript engines
701
+ * may optimize zero-delay timers by batching them together, causing all requests to resume
702
+ * simultaneously (same problem as microtasks). Any non-zero value (even 0.0000000001) forces
703
+ * proper sequential task queue scheduling, ensuring each request gets its own task slot.
704
+ */
705
+ if (dedupeKey !== null) await waitFor(.001);
298
706
  const prevRequestInfo = $RequestInfoCacheOrNull?.get(dedupeKey);
299
707
  const getAbortErrorMessage = () => {
300
708
  if (globalOptions.dedupeKey) return `Duplicate request detected - Aborted previous request with key '${dedupeKey}'`;
@@ -517,7 +925,7 @@ const getExponentialDelay = (currentAttemptCount, options) => {
517
925
  const exponentialDelay = resolvedRetryDelay * 2 ** currentAttemptCount;
518
926
  return Math.min(exponentialDelay, maxDelay);
519
927
  };
520
- const createRetryStrategy = (ctx) => {
928
+ const createRetryManager = (ctx) => {
521
929
  const { options, request } = ctx;
522
930
  const currentAttemptCount = options["~retryAttemptCount"] ?? 1;
523
931
  const retryStrategy = options.retryStrategy ?? options.retry?.strategy ?? extraOptionDefaults.retryStrategy;
@@ -540,9 +948,23 @@ const createRetryStrategy = (ctx) => {
540
948
  const includesStatusCodes = ctx.response != null && retryStatusCodes.size > 0 ? retryStatusCodes.has(ctx.response.status) : true;
541
949
  return includesMethod && includesStatusCodes;
542
950
  };
951
+ const handleRetry = async (context) => {
952
+ const { callApi: callApi$1, callApiArgs, errorContext, hookInfo } = context;
953
+ const retryContext = {
954
+ ...errorContext,
955
+ retryAttemptCount: currentAttemptCount
956
+ };
957
+ const hookError = await executeHooksInCatchBlock([options.onRetry?.(retryContext)], hookInfo);
958
+ if (hookError) return hookError;
959
+ await waitFor(getDelay());
960
+ const updatedOptions = {
961
+ ...callApiArgs.config,
962
+ "~retryAttemptCount": currentAttemptCount + 1
963
+ };
964
+ return callApi$1(callApiArgs.initURL, updatedOptions);
965
+ };
543
966
  return {
544
- currentAttemptCount,
545
- getDelay,
967
+ handleRetry,
546
968
  shouldAttemptRetry
547
969
  };
548
970
  };
@@ -716,21 +1138,17 @@ const createFetchClient = (initBaseConfig = {}) => {
716
1138
  errorInfo,
717
1139
  shouldThrowOnError
718
1140
  };
1141
+ const { handleRetry, shouldAttemptRetry } = createRetryManager(errorContext);
719
1142
  const handleRetryOrGetErrorResult = async () => {
720
- const { currentAttemptCount, getDelay, shouldAttemptRetry } = createRetryStrategy(errorContext);
721
- if (await shouldAttemptRetry()) {
722
- const retryContext = {
723
- ...errorContext,
724
- retryAttemptCount: currentAttemptCount
725
- };
726
- const hookError = await executeHooksInCatchBlock([options.onRetry?.(retryContext)], hookInfo);
727
- if (hookError) return hookError;
728
- await waitFor(getDelay());
729
- return callApi$1(initURL, {
730
- ...config,
731
- "~retryAttemptCount": currentAttemptCount + 1
732
- });
733
- }
1143
+ if (await shouldAttemptRetry()) return handleRetry({
1144
+ callApi: callApi$1,
1145
+ callApiArgs: {
1146
+ config,
1147
+ initURL
1148
+ },
1149
+ errorContext,
1150
+ hookInfo
1151
+ });
734
1152
  if (shouldThrowOnError) throw error;
735
1153
  return errorResult;
736
1154
  };