@zayne-labs/callapi 1.6.12 → 1.6.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.
@@ -117,12 +117,12 @@ type InferSchemaResult<TSchema, TData> = TSchema extends StandardSchemaV1 ? Stan
117
117
 
118
118
  type Params = UnmaskType<Record<string, boolean | number | string> | Array<boolean | number | string>>;
119
119
  type Query = UnmaskType<Record<string, boolean | number | string>>;
120
- type InitURL = UnmaskType<string>;
120
+ type InitURL = UnmaskType<string | URL>;
121
121
  interface UrlOptions<TSchemas extends CallApiSchemas> {
122
122
  /**
123
123
  * URL to be used in the request.
124
124
  */
125
- readonly initURL?: InferSchemaResult<TSchemas["initURL"], InitURL>;
125
+ readonly initURL?: string;
126
126
  /**
127
127
  * Parameters to be appended to the URL (i.e: /:id)
128
128
  */
@@ -176,6 +176,11 @@ interface RetryOptions<TErrorData> {
176
176
  retryStrategy?: "exponential" | "linear";
177
177
  }
178
178
 
179
+ type DefaultDataType = unknown;
180
+ type DefaultMoreOptions = NonNullable<unknown>;
181
+ type DefaultPluginArray = CallApiPlugin[];
182
+ type DefaultThrowOnError = boolean;
183
+
179
184
  type Parser = (responseString: string) => Awaitable<Record<string, unknown>>;
180
185
  declare const getResponseType: <TResponse>(response: Response, parser?: Parser) => {
181
186
  arrayBuffer: () => Promise<ArrayBuffer>;
@@ -193,11 +198,10 @@ type ResponseTypeMap<TResponse> = {
193
198
  type GetResponseType<TResponse, TResponseType extends ResponseTypeUnion, TComputedMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>> = undefined extends TResponseType ? TComputedMap["json"] : TResponseType extends NonNullable<ResponseTypeUnion> ? TComputedMap[TResponseType] : never;
194
199
 
195
200
  type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (param: infer TParam) => void ? TParam : never;
196
- type DefaultPlugins = CallApiPlugin[];
197
201
  type InferSchema<TResult> = TResult extends StandardSchemaV1 ? InferSchemaResult<TResult, NonNullable<unknown>> : TResult;
198
202
  type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<InferSchema<ReturnType<NonNullable<TPluginArray[number]["createExtraOptions"]>>>>;
199
203
  type PluginInitContext<TMoreOptions = DefaultMoreOptions> = WithMoreOptions<TMoreOptions> & {
200
- initURL: string;
204
+ initURL: InitURL | undefined;
201
205
  options: CombinedCallApiExtraOptions;
202
206
  request: CallApiRequestOptionsForHooks;
203
207
  };
@@ -237,7 +241,7 @@ interface CallApiPlugin<TData = never, TErrorData = never> {
237
241
  declare const definePlugin: <TPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>>(plugin: TPlugin) => TPlugin;
238
242
  type Plugins<TPluginArray extends CallApiPlugin[]> = TPluginArray | ((context: PluginInitContext) => TPluginArray);
239
243
 
240
- declare const fetchSpecificKeys: ("body" | "headers" | "method" | "cache" | "credentials" | "integrity" | "keepalive" | "mode" | "priority" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window")[];
244
+ declare const fetchSpecificKeys: ("body" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "priority" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window")[];
241
245
  declare const defaultRetryMethods: ("GET" | "POST")[];
242
246
  declare const defaultRetryStatusCodes: Required<BaseCallApiExtraOptions>["retryStatusCodes"];
243
247
 
@@ -300,6 +304,8 @@ type MetaOption<TSchemas extends CallApiSchemas> = {
300
304
  };
301
305
  type ResultModeOption<TErrorData, TResultMode extends ResultModeUnion> = TErrorData extends false ? {
302
306
  resultMode: "onlySuccessWithException";
307
+ } : TErrorData extends false | undefined ? {
308
+ resultMode?: "onlySuccessWithException";
303
309
  } : undefined extends TResultMode ? {
304
310
  resultMode?: TResultMode;
305
311
  } : {
@@ -311,8 +317,6 @@ type CallApiRequestOptions<TSchemas extends CallApiSchemas = DefaultMoreOptions>
311
317
  type CallApiRequestOptionsForHooks<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<CallApiRequestOptions<TSchemas>, "headers"> & {
312
318
  headers?: Record<string, string | undefined>;
313
319
  };
314
- type DefaultDataType = unknown;
315
- type DefaultMoreOptions = NonNullable<unknown>;
316
320
  type WithMoreOptions<TMoreOptions = DefaultMoreOptions> = {
317
321
  options: CombinedCallApiExtraOptions & Partial<TMoreOptions>;
318
322
  };
@@ -351,7 +355,7 @@ type InterceptorsOrInterceptorArray<TData = DefaultDataType, TErrorData = Defaul
351
355
  [Key in keyof Interceptors<TData, TErrorData, TMoreOptions>]: Interceptors<TData, TErrorData, TMoreOptions>[Key] | Array<Interceptors<TData, TErrorData, TMoreOptions>[Key]>;
352
356
  };
353
357
  type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
354
- type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPlugins> = {
358
+ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = {
355
359
  /**
356
360
  * Authorization header value.
357
361
  */
@@ -436,7 +440,7 @@ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResult
436
440
  * The function is passed the error object and can be used to conditionally throw the error
437
441
  * @default false
438
442
  */
439
- throwOnError?: boolean | ((context: ErrorContext<TErrorData>) => boolean);
443
+ throwOnError?: TThrowOnError | ((context: ErrorContext<TErrorData>) => TThrowOnError);
440
444
  /**
441
445
  * Request timeout in milliseconds
442
446
  */
@@ -447,18 +451,18 @@ type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResult
447
451
  validators?: CallApiValidators<TData, TErrorData>;
448
452
  } & InterceptorsOrInterceptorArray<TData, TErrorData> & Partial<InferPluginOptions<TPluginArray>> & MetaOption<TSchemas> & RetryOptions<TErrorData> & ResultModeOption<TErrorData, TResultMode> & UrlOptions<TSchemas>;
449
453
  declare const optionsEnumToExtendFromBase: ("plugins" | "schemas" | "validators")[];
450
- type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPlugins> = CallApiRequestOptions<TSchemas> & ExtraOptions<TData, TErrorData, TResultMode, TResponseType, TSchemas, TPluginArray> & {
454
+ type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = CallApiRequestOptions<TSchemas> & ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray> & {
451
455
  /**
452
456
  * Options that should extend the base options.
453
457
  */
454
- extend?: Pick<ExtraOptions<TData, TErrorData, TResultMode, TResponseType, TSchemas, TPluginArray>, (typeof optionsEnumToExtendFromBase)[number]>;
458
+ extend?: Pick<ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray>, (typeof optionsEnumToExtendFromBase)[number]>;
455
459
  };
456
460
  declare const optionsEnumToOmitFromBase: ("dedupeKey" | "extend")[];
457
- type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions, TBasePluginArray extends CallApiPlugin[] = DefaultPlugins> = Omit<Partial<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseResponseType, TBaseSchemas, TBasePluginArray>>, (typeof optionsEnumToOmitFromBase)[number]>;
461
+ type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray> = Omit<Partial<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchemas, TBasePluginArray>>, (typeof optionsEnumToOmitFromBase)[number]>;
458
462
  type CombinedCallApiExtraOptions = BaseCallApiExtraOptions & CallApiExtraOptions;
459
- type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPlugins> = [
460
- initURL: UrlOptions<TSchemas>["initURL"],
461
- config?: CallApiExtraOptions<TData, TErrorData, TResultMode, TResponseType, TSchemas, TPluginArray>
463
+ type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TSchemas extends CallApiSchemas = DefaultMoreOptions, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = [
464
+ initURL: InferSchemaResult<TSchemas["initURL"], InitURL>,
465
+ config?: CallApiExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TSchemas, TPluginArray>
462
466
  ];
463
467
  type RequestContext = UnmaskType<{
464
468
  options: CombinedCallApiExtraOptions;
@@ -498,6 +502,7 @@ type RequestErrorContext = UnmaskType<{
498
502
  error: PossibleJavaScriptError;
499
503
  options: CombinedCallApiExtraOptions;
500
504
  request: CallApiRequestOptionsForHooks;
505
+ response: null;
501
506
  }>;
502
507
  type ResponseErrorContext<TErrorData> = UnmaskType<{
503
508
  error: PossibleHTTPError<TErrorData>;
@@ -532,13 +537,15 @@ type CallApiResultErrorVariant<TErrorData> = {
532
537
  };
533
538
  type ResultModeMap<TData = DefaultDataType, TErrorData = DefaultDataType, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TComputedData = GetResponseType<TData, TResponseType>, TComputedErrorData = GetResponseType<TErrorData, TResponseType>> = UnmaskType<{
534
539
  all: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;
540
+ allWithException: CallApiResultSuccessVariant<TComputedData>;
541
+ allWithoutResponse: CallApiResultSuccessVariant<TComputedData>["data" | "error"] | CallApiResultErrorVariant<TComputedErrorData>["data" | "error"];
535
542
  onlyError: CallApiResultSuccessVariant<TComputedData>["error"] | CallApiResultErrorVariant<TComputedErrorData>["error"];
536
543
  onlyResponse: CallApiResultErrorVariant<TComputedErrorData>["response"] | CallApiResultSuccessVariant<TComputedData>["response"];
544
+ onlyResponseWithException: CallApiResultSuccessVariant<TComputedErrorData>["response"];
537
545
  onlySuccess: CallApiResultErrorVariant<TComputedErrorData>["data"] | CallApiResultSuccessVariant<TComputedData>["data"];
538
546
  onlySuccessWithException: CallApiResultSuccessVariant<TComputedData>["data"];
539
547
  }>;
540
548
  type ResultModeUnion = keyof ResultModeMap | undefined;
541
- type GetCallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TResponseType extends ResponseTypeUnion, TComputedMap extends ResultModeMap<TData, TErrorData, TResponseType> = ResultModeMap<TData, TErrorData, TResponseType>> = TErrorData extends false ? TComputedMap["onlySuccessWithException"] : // If TResultMode is the entire ResultModeMap with undefined, we return the "all" variant
542
- ResultModeUnion | undefined extends TResultMode ? TComputedMap["all"] : TResultMode extends NonNullable<ResultModeUnion> ? TComputedMap[TResultMode] : never;
549
+ type GetCallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends boolean, TResponseType extends ResponseTypeUnion> = TErrorData extends false | undefined ? ResultModeMap<TData, TErrorData, TResponseType>["onlySuccessWithException"] : ResultModeUnion | undefined extends TResultMode ? TThrowOnError extends true ? ResultModeMap<TData, TErrorData, TResponseType>["allWithException"] : ResultModeMap<TData, TErrorData, TResponseType>["all"] : TResultMode extends NonNullable<ResultModeUnion> ? ResultModeMap<TData, TErrorData, TResponseType>[TResultMode] : never;
543
550
 
544
- export { type BaseCallApiExtraOptions as B, type CallApiSchemas as C, type DefaultPlugins as D, type ErrorContext as E, type GetCallApiResult as G, type InferSchemaResult as I, type PossibleJavascriptErrorNames as P, type ResultModeUnion as R, type SuccessContext as S, type UrlOptions as U, type ResponseTypeUnion as a, type CallApiPlugin as b, type CallApiExtraOptions as c, type CallApiResultSuccessVariant as d, type CallApiResultErrorVariant as e, definePlugin as f, type PluginInitContext as g, type PossibleJavaScriptError as h, type PossibleHTTPError as i, type CallApiParameters as j, type CallApiRequestOptions as k, type CallApiRequestOptionsForHooks as l, type CombinedCallApiExtraOptions as m, type Interceptors as n, type InterceptorsOrInterceptorArray as o, type Register as p, type RequestContext as q, type RequestErrorContext as r, type ResponseContext as s, type ResponseErrorContext as t, type DefaultDataType as u, defaultRetryMethods as v, defaultRetryStatusCodes as w };
551
+ export { type BaseCallApiExtraOptions as B, type CallApiSchemas as C, type DefaultPluginArray as D, type ErrorContext as E, type GetCallApiResult as G, type InferSchemaResult as I, type PluginInitContext as P, type ResultModeUnion as R, type SuccessContext as S, type ResponseTypeUnion as a, type CallApiPlugin as b, type CallApiExtraOptions as c, type DefaultDataType as d, type DefaultThrowOnError as e, type DefaultMoreOptions as f, definePlugin as g, type PossibleJavaScriptError as h, type PossibleHTTPError as i, type CallApiParameters as j, type CallApiRequestOptions as k, type CallApiRequestOptionsForHooks as l, type CallApiResultErrorVariant as m, type CallApiResultSuccessVariant as n, type CombinedCallApiExtraOptions as o, type Interceptors as p, type InterceptorsOrInterceptorArray as q, type PossibleJavascriptErrorNames as r, type Register as s, type RequestContext as t, type RequestErrorContext as u, type ResponseContext as v, type ResponseErrorContext as w, type InitURL as x, defaultRetryMethods as y, defaultRetryStatusCodes as z };
@@ -1 +1 @@
1
- "use strict";var e,r=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,n={};((e,t)=>{for(var o in t)r(e,o,{get:t[o],enumerable:!0})})(n,{HTTPError:()=>a,callApi:()=>H,createFetchClient:()=>C,definePlugin:()=>T}),module.exports=(e=n,((e,n,a,i)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let l of o(n))s.call(e,l)||l===a||r(e,l,{get:()=>n[l],enumerable:!(i=t(n,l))||i.enumerable});return e})(r({},"__esModule",{value:!0}),e));var a=class extends Error{errorData;isHTTPError=!0;name="HTTPError";response;constructor(e,r){const{defaultErrorMessage:t,errorData:o,response:s}=e;super(o?.message??t,r),this.errorData=o,this.response=s,Error.captureStackTrace(this,this.constructor)}},i=e=>e instanceof a||c(e)&&"HTTPError"===e.name&&!0===e.isHTTPError,l=e=>Array.isArray(e),u=e=>"object"==typeof e&&null!==e,c=e=>{if(!u(e))return!1;const r=Object.getPrototypeOf(e);return(null==r||r===Object.prototype||null===Object.getPrototypeOf(r))&&!(Symbol.toStringTag in e)},d=e=>"function"==typeof e,p=e=>"string"==typeof e,y=e=>d(e)?e():e,f=e=>{if(void 0!==e){if(p(e)||null===e)return{Authorization:`Bearer ${e}`};switch(e.type){case"Basic":{const r=y(e.username),t=y(e.password);if(void 0===r||void 0===t)return;return{Authorization:`Basic ${globalThis.btoa(`${r}:${t}`)}`}}case"Custom":{const r=y(e.value);if(void 0===r)return;return{Authorization:`${y(e.prefix)} ${r}`}}default:{const r=y(e.bearer),t=y(e.token);return"token"in e&&void 0!==t?{Authorization:`Token ${t}`}:void 0!==r&&{Authorization:`Bearer ${r}`}}}}},m=["extend","dedupeKey"],h=["body","integrity","method","headers","signal","cache","redirect","window","credentials","keepalive","referrer","priority","mode","referrerPolicy"],g={408:"Request Timeout",409:"Conflict",425:"Too Early",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},w=["GET","POST"],b=Object.keys(g).map(Number),E=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)||(t[r]=s);return t},R=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)&&(t[r]=s);return t},S=e=>!e||c(e)?e:Object.fromEntries(e),v=e=>{const{auth:r,baseHeaders:t,body:o,headers:s}=e;if(!Boolean(t||s||o||r))return;const n={...f(r),...S(t),...S(s)};return p(a=o)&&a.includes("=")?(n["Content-Type"]="application/x-www-form-urlencoded",n):((c(o)||p(o)&&o.startsWith("{"))&&(n["Content-Type"]="application/json",n.Accept="application/json"),n);var a},O=(...e)=>Promise.all(e),q=e=>{if(0===e)return;const{promise:r,resolve:t}=(()=>{let e,r;return{promise:new Promise(((t,o)=>{r=t,e=o})),reject:e,resolve:r}})();return setTimeout(t,e),r},D=async e=>{const{$RequestInfoCache:r,newFetchController:t,options:o,request:s}=e,n=o.dedupeKey??("cancel"===o.dedupeStrategy||"defer"===o.dedupeStrategy?`${o.fullURL}-${JSON.stringify({options:o,request:s})}`:null),a=null!==n?r:null;null!==n&&await q(.1);const i=a?.get(n);return{handleRequestCancelDedupeStrategy:()=>{if(i&&"cancel"===o.dedupeStrategy){const e=o.dedupeKey?`Duplicate request detected - Aborting previous request with key '${o.dedupeKey}' as a new request was initiated`:`Duplicate request detected - Aborting previous request to '${o.fullURL}' as a new request with identical options was initiated`,r=new DOMException(e,"AbortError");i.controller.abort(r)}},handleRequestDeferDedupeStrategy:()=>{const e=(e=>{if(e)return e;if("undefined"!=typeof globalThis&&d(globalThis.fetch))return globalThis.fetch;throw new Error("No fetch implementation found")})(o.customFetchImpl),r=i&&"defer"===o.dedupeStrategy?i.responsePromise:e(o.fullURL,s);return a?.set(n,{controller:t,responsePromise:r}),r},removeDedupeKeyFromCache:()=>a?.delete(n)}},T=e=>e,M=(e,r)=>async t=>{if("sequential"!==r){if("parallel"===r){const r=[...e];await Promise.all(r.map((e=>e?.(t))))}}else for(const r of e)await(r?.(t))},$={onError:new Set,onRequest:new Set,onRequestError:new Set,onResponse:new Set,onResponseError:new Set,onRetry:new Set,onSuccess:new Set},P=(e,r)=>e?d(e)?e(r):e:[],j=async(e,r,t,o,s)=>{const n=((e,r)=>({arrayBuffer:()=>e.arrayBuffer(),blob:()=>e.blob(),formData:()=>e.formData(),json:async()=>{if(r){const t=await e.text();return r(t)}return e.json()},stream:()=>e.body,text:()=>e.text()}))(e,t);if(!Object.hasOwn(n,r))throw new Error(`Invalid response type: ${r}`);const a=await n[r](),i=s?s(a):a,l=o?await(async(e,r)=>{const t=await e["~standard"].validate(r);if(t.issues)throw new Error(JSON.stringify(t.issues,null,2),{cause:t.issues});return t.value})(o,i):i;return l},x=(e,r)=>{const t=e["~retryCount"]??0;return{getDelay:()=>"exponential"===e.retryStrategy?((e,r)=>{const t=r.retryMaxDelay??1e4,o=(r.retryDelay??1e3)*2**e;return Math.min(o,t)})(t,e):(e=>e.retryDelay??1e3)(e),shouldAttemptRetry:async()=>{const o=await(e.retryCondition?.(r))??!0,s=(e.retryAttempts??0)>t&&o;if("HTTPError"!==r.error.name)return s;const n=!!r.request.method&&e.retryMethods?.includes(r.request.method);return!!r.response?.status&&e.retryStatusCodes?.includes(r.response.status)&&n&&s}}},k=(e,r)=>{if(!r)return e;const t=(o=r)?new URLSearchParams(o).toString():(console.error("toQueryString:","No query params provided!"),null);var o;return 0===t?.length?e:e.endsWith("?")?`${e}${t}`:e.includes("?")?`${e}&${t}`:`${e}?${t}`},A=(e,r,t)=>{const o=((e,r)=>{if(!r)return e;let t=e;if(l(r)){const e=t.split("/").filter((e=>e.startsWith(":")));for(const[o,s]of e.entries()){const e=r[o];t=t.replace(s,e)}return t}for(const[e,o]of Object.entries(r))t=t.replace(`:${e}`,String(o));return t})(e,r);return k(o,t)},C=e=>{const[r,t]=(e=>[R(e,h),E(e,[...h,...m])])(e??{}),o=new Map,s=async(...e)=>{const[n,y={}]=e,[f,m]=(e=>[R(e,h),E(e,h)])(y),g={};for(const e of Object.keys($)){const r=(S=t[e],T=m[e],l(S)?[S,T].flat():T??S);g[e]=r}var S,T;const k={baseURL:"",bodySerializer:JSON.stringify,dedupeStrategy:"cancel",defaultErrorMessage:"Failed to fetch data from server!",mergedHooksExecutionMode:"parallel",mergedHooksExecutionOrder:"mainHooksAfterPlugins",responseType:"json",resultMode:"all",retryAttempts:0,retryDelay:1e3,retryMaxDelay:1e4,retryMethods:w,retryStatusCodes:b,retryStrategy:"linear",...t,...m,...g},C=f.body??r.body,H={body:c(C)?k.bodySerializer(C):C,...r,...f,headers:v({auth:k.auth,baseHeaders:r.headers,body:C,headers:f.headers}),signal:f.signal??r.signal},{resolvedHooks:U,resolvedOptions:L,resolvedRequestOptions:B,url:z}=await(async e=>{const{initURL:r,options:t,request:o}=e,s=structuredClone($),n=()=>{for(const e of Object.keys($)){const r=t[e];s[e].add(r)}},a=e=>{for(const r of Object.keys($)){const t=e[r];s[r].add(t)}};"mainHooksBeforePlugins"===t.mergedHooksExecutionOrder&&n();const i=[...P(t.plugins,e),...P(t.extend?.plugins,e)];let l=r,u=t,d=o;const y=async e=>{if(!e)return;const s=await e({initURL:r,options:t,request:o});c(s)&&(p(s.initURL)&&(l=s.initURL),c(s.request)&&(d=s.request),c(s.options)&&(u=s.options))};for(const e of i)await y(e.init),e.hooks&&a(e.hooks);t.mergedHooksExecutionOrder&&"mainHooksAfterPlugins"!==t.mergedHooksExecutionOrder||n();const f={};for(const[e,r]of Object.entries(s)){const o=[...r].flat(),s=M(o,t.mergedHooksExecutionMode);f[e]=s}return{resolvedHooks:f,resolvedOptions:u,resolvedRequestOptions:d,url:l}})({initURL:n,options:k,request:H}),F=`${L.baseURL}${A(z,L.params,L.query)}`,N={...L,...U,fullURL:F,initURL:n},K=new AbortController,I=null!=N.timeout?(W=N.timeout,AbortSignal.timeout(W)):null;var W;const G=((...e)=>AbortSignal.any(e.filter(Boolean)))(B.signal,I,K.signal),J={...B,signal:G},{handleRequestCancelDedupeStrategy:V,handleRequestDeferDedupeStrategy:_,removeDedupeKeyFromCache:Q}=await D({$RequestInfoCache:o,newFetchController:K,options:N,request:J});V();try{await O(N.onRequest({options:N,request:J})),J.headers=v({auth:N.auth,baseHeaders:r.headers,body:C,headers:J.headers});const e=await _(),t="defer"===N.dedupeStrategy||N.cloneResponse,{schemas:o,validators:s}=(e=>({schemas:e.schemas&&{...e.schemas,...e.extend?.schemas},validators:e.validators&&{...e.validators,...e.extend?.validators}}))(N);if(!e.ok){const r=await j(t?e.clone():e,N.responseType,N.responseParser,o?.errorData,s?.errorData);throw new a({defaultErrorMessage:N.defaultErrorMessage,errorData:r,response:e})}const n={data:await j(t?e.clone():e,N.responseType,N.responseParser,o?.data,s?.data),options:N,request:J,response:N.cloneResponse?e.clone():e};return await O(N.onSuccess(n),N.onResponse({...n,error:null})),await(e=>{const{data:r,response:t,resultMode:o}=e,s={data:r,error:null,response:t};return o?{all:s,onlyError:s.error,onlyResponse:s.response,onlySuccess:s.data,onlySuccessWithException:s.data}[o]:s})({data:n.data,response:n.response,resultMode:N.resultMode})}catch(e){const{errorVariantDetails:r,getErrorResult:t}=(e=>{const{cloneResponse:r,defaultErrorMessage:t,error:o,message:s,resultMode:n}=e;let a={data:null,error:{errorData:o,message:s??o.message,name:o.name},response:null};if(i(o)){const{errorData:e,message:s=t,name:n,response:i}=o;a={data:null,error:{errorData:e,message:s,name:n},response:r?i.clone():i}}const l={all:a,onlyError:a.error,onlyResponse:a.response,onlySuccess:a.data,onlySuccessWithException:a.data};return{errorVariantDetails:a,getErrorResult:e=>{const r=l[n??"all"];return u(e)?{...r,...e}:r}}})({cloneResponse:N.cloneResponse,defaultErrorMessage:N.defaultErrorMessage,error:e,resultMode:N.resultMode}),o={error:r.error,options:N,request:J},a={...o,response:r.response},{getDelay:l,shouldAttemptRetry:c}=x(N,a);if(!G.aborted&&await c()){await O(N.onRetry(a));const e=l();await q(e);const r={...y,"~retryCount":(N["~retryCount"]??0)+1};return await s(n,r)}const p=d(N.throwOnError)?N.throwOnError(a):N.throwOnError,f=()=>{if(p)throw r.error};if(i(e))return await O(N.onResponseError(a),N.onError(a),N.onResponse({...a,data:null})),f(),t();if(e instanceof DOMException&&"AbortError"===e.name){const{message:r,name:o}=e;return console.error(`${o}:`,r),f(),t()}if(e instanceof DOMException&&"TimeoutError"===e.name){const r=`Request timed out after ${N.timeout}ms`;return console.error(`${e.name}:`,r),f(),t({message:r})}return await O(N.onRequestError(o),N.onError(a)),f(),t()}finally{Q()}};return s.create=C,s},H=C();//# sourceMappingURL=index.cjs.map
1
+ "use strict";var e,r=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,n={};((e,t)=>{for(var o in t)r(e,o,{get:t[o],enumerable:!0})})(n,{HTTPError:()=>a,callApi:()=>L,createFetchClient:()=>U,definePlugin:()=>x}),module.exports=(e=n,((e,n,a,i)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let l of o(n))s.call(e,l)||l===a||r(e,l,{get:()=>n[l],enumerable:!(i=t(n,l))||i.enumerable});return e})(r({},"__esModule",{value:!0}),e));var a=class extends Error{errorData;isHTTPError=!0;name="HTTPError";response;constructor(e,r){const{defaultErrorMessage:t,errorData:o,response:s}=e;super(o?.message??t,r),this.errorData=o,this.response=s,Error.captureStackTrace(this,this.constructor)}},i=e=>e instanceof a||d(e)&&"HTTPError"===e.name&&!0===e.isHTTPError,l=e=>Array.isArray(e),u=e=>"object"==typeof e&&null!==e,c=e=>"[object Object]"===Object.prototype.toString.call(e),d=e=>{if(!c(e))return!1;const r=e?.constructor;if(void 0===r)return!0;const t=r.prototype;return!!c(t)&&(!!Object.hasOwn(t,"isPrototypeOf")&&Object.getPrototypeOf(e)===Object.prototype)},p=e=>"function"==typeof e,y=e=>"string"==typeof e,f=e=>p(e)?e():e,h=e=>{if(void 0!==e){if(y(e)||null===e)return{Authorization:`Bearer ${e}`};switch(e.type){case"Basic":{const r=f(e.username),t=f(e.password);if(void 0===r||void 0===t)return;return{Authorization:`Basic ${globalThis.btoa(`${r}:${t}`)}`}}case"Custom":{const r=f(e.value);if(void 0===r)return;return{Authorization:`${f(e.prefix)} ${r}`}}default:{const r=f(e.bearer),t=f(e.token);return"token"in e&&void 0!==t?{Authorization:`Token ${t}`}:void 0!==r&&{Authorization:`Bearer ${r}`}}}}},m=["extend","dedupeKey"],g=["body","integrity","method","headers","signal","cache","redirect","window","credentials","keepalive","referrer","priority","mode","referrerPolicy"],w={408:"Request Timeout",409:"Conflict",425:"Too Early",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},b=["GET","POST"],E=Object.keys(w).map(Number),R=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)||(t[r]=s);return t},S=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)&&(t[r]=s);return t},O=e=>!e||d(e)?e:Object.fromEntries(e),v=e=>{const{auth:r,baseHeaders:t,body:o,headers:s}=e;if(!Boolean(t||s||o||r))return;const n={...h(r),...O(t),...O(s)};return y(a=o)&&a.includes("=")?(n["Content-Type"]="application/x-www-form-urlencoded",n):((d(o)||y(o)&&o.startsWith("{"))&&(n["Content-Type"]="application/json",n.Accept="application/json"),n);var a},q=(...e)=>Promise.all(e),T=e=>{if(0===e)return;const{promise:r,resolve:t}=(()=>{let e,r;return{promise:new Promise(((t,o)=>{r=t,e=o})),reject:e,resolve:r}})();return setTimeout(t,e),r},D=async e=>{const{$RequestInfoCache:r,newFetchController:t,options:o,request:s}=e,n=o.dedupeKey??("cancel"===o.dedupeStrategy||"defer"===o.dedupeStrategy?`${o.fullURL}-${JSON.stringify({options:o,request:s})}`:null),a=null!==n?r:null;null!==n&&await T(.1);const i=a?.get(n);return{handleRequestCancelStrategy:()=>{if(!(i&&"cancel"===o.dedupeStrategy))return;const e=o.dedupeKey?`Duplicate request detected - Aborting previous request with key '${o.dedupeKey}' as a new request was initiated`:`Duplicate request detected - Aborting previous request to '${o.fullURL}' as a new request with identical options was initiated`,r=new DOMException(e,"AbortError");return i.controller.abort(r),Promise.resolve()},handleRequestDeferStrategy:()=>{const e=(e=>{if(e)return e;if("undefined"!=typeof globalThis&&p(globalThis.fetch))return globalThis.fetch;throw new Error("No fetch implementation found")})(o.customFetchImpl),r=i&&"defer"===o.dedupeStrategy?i.responsePromise:e(o.fullURL,s);return a?.set(n,{controller:t,responsePromise:r}),r},removeDedupeKeyFromCache:()=>a?.delete(n)}},x=e=>e,j=(e,r)=>async t=>{if("sequential"!==r){if("parallel"===r){const r=[...e];await Promise.all(r.map((e=>e?.(t))))}}else for(const r of e)await(r?.(t))},M={onError:new Set,onRequest:new Set,onRequestError:new Set,onResponse:new Set,onResponseError:new Set,onRetry:new Set,onSuccess:new Set},P=(e,r)=>e?p(e)?e(r):e:[],$=async(e,r,t)=>{const o=((e,r)=>({arrayBuffer:()=>e.arrayBuffer(),blob:()=>e.blob(),formData:()=>e.formData(),json:async()=>{if(r){const t=await e.text();return r(t)}return e.json()},stream:()=>e.body,text:()=>e.text()}))(e,t);if(!Object.hasOwn(o,r))throw new Error(`Invalid response type: ${r}`);return await o[r]()},k=(e,r)=>{const t=e["~retryCount"]??0;return{getDelay:()=>"exponential"===e.retryStrategy?((e,r)=>{const t=r.retryMaxDelay??1e4,o=(r.retryDelay??1e3)*2**e;return Math.min(o,t)})(t,e):(e=>e.retryDelay??1e3)(e),shouldAttemptRetry:async()=>{const o=await(e.retryCondition?.(r))??!0,s=(e.retryAttempts??0)>t&&o;if("HTTPError"!==r.error.name)return s;const n=!!r.request.method&&e.retryMethods?.includes(r.request.method);return!!r.response?.status&&e.retryStatusCodes?.includes(r.response.status)&&n&&s}}},A=(e,r)=>{if(!r)return e;const t=(o=r)?new URLSearchParams(o).toString():(console.error("toQueryString:","No query params provided!"),null);var o;return 0===t?.length?e:e.endsWith("?")?`${e}${t}`:e.includes("?")?`${e}&${t}`:`${e}?${t}`},C=(e,r,t)=>{if(!e)return;const o=((e,r)=>{if(!r)return e;let t=e;if(l(r)){const e=t.split("/").filter((e=>e.startsWith(":")));for(const[o,s]of e.entries()){const e=r[o];t=t.replace(s,e)}return t}for(const[e,o]of Object.entries(r))t=t.replace(`:${e}`,String(o));return t})(e,r);return A(o,t)},H=async(e,r,t)=>{const o=t?t(e):e,s=r?await(async(e,r)=>{const t=await e["~standard"].validate(r);if(t.issues)throw new Error(JSON.stringify(t.issues,null,2),{cause:t.issues});return t.value})(r,o):o;return s},U=e=>{const[r,t]=(e=>[S(e,g),R(e,[...g,...m])])(e??{}),o=new Map,s=async(...e)=>{const[n,c={}]=e,[f,h]=(e=>[S(e,g),R(e,g)])(c),m={};for(const e of Object.keys(M)){const r=(w=t[e],O=h[e],l(w)?[w,O].flat():O??w);m[e]=r}var w,O;const x={baseURL:"",bodySerializer:JSON.stringify,dedupeStrategy:"cancel",defaultErrorMessage:"Failed to fetch data from server!",mergedHooksExecutionMode:"parallel",mergedHooksExecutionOrder:"mainHooksAfterPlugins",responseType:"json",resultMode:"all",retryAttempts:0,retryDelay:1e3,retryMaxDelay:1e4,retryMethods:b,retryStatusCodes:E,retryStrategy:"linear",...t,...h,...m},A=f.body??r.body,U={...r,...f,body:d(A)?x.bodySerializer(A):A,headers:v({auth:x.auth,baseHeaders:r.headers,body:A,headers:f.headers}),signal:f.signal??r.signal},{resolvedHooks:L,resolvedOptions:W,resolvedRequestOptions:B,url:z}=await(async e=>{const{initURL:r,options:t,request:o}=e,s=structuredClone(M),n=()=>{for(const e of Object.keys(M)){const r=t[e];s[e].add(r)}},a=e=>{for(const r of Object.keys(M)){const t=e[r];s[r].add(t)}};"mainHooksBeforePlugins"===t.mergedHooksExecutionOrder&&n();const i=[...P(t.plugins,e),...P(t.extend?.plugins,e)];let l=r,u=t,c=o;const p=async e=>{if(!e)return;const s=await e({initURL:r,options:t,request:o});d(s)&&(y(s.initURL)&&(l=s.initURL),d(s.request)&&(c=s.request),d(s.options)&&(u=s.options))};for(const e of i)await p(e.init),e.hooks&&a(e.hooks);t.mergedHooksExecutionOrder&&"mainHooksAfterPlugins"!==t.mergedHooksExecutionOrder||n();const f={};for(const[e,r]of Object.entries(s)){const o=[...r].flat(),s=j(o,t.mergedHooksExecutionMode);f[e]=s}return{resolvedHooks:f,resolvedOptions:u,resolvedRequestOptions:c,url:l?.toString()}})({initURL:n,options:x,request:U}),F=`${W.baseURL}${C(z,W.params,W.query)}`,N={...W,...L,fullURL:F,initURL:n.toString()},K=new AbortController,I=null!=N.timeout?(G=N.timeout,AbortSignal.timeout(G)):null;var G;const J=((...e)=>AbortSignal.any(e.filter(Boolean)))(B.signal,I,K.signal),_={...B,signal:J},{handleRequestCancelStrategy:Q,handleRequestDeferStrategy:V,removeDedupeKeyFromCache:X}=await D({$RequestInfoCache:o,newFetchController:K,options:N,request:_});await Q();try{await q(N.onRequest({options:N,request:_})),_.headers=v({auth:N.auth,baseHeaders:r.headers,body:A,headers:_.headers});const e=await V(),t="defer"===N.dedupeStrategy||N.cloneResponse,{schemas:o,validators:s}=(e=>({schemas:e.schemas&&{...e.schemas,...e.extend?.schemas},validators:e.validators&&{...e.validators,...e.extend?.validators}}))(N);if(!e.ok){const r=await $(t?e.clone():e,N.responseType,N.responseParser),n=await H(r,o?.errorData,s?.errorData);throw new a({defaultErrorMessage:N.defaultErrorMessage,errorData:n,response:e})}const n=await $(t?e.clone():e,N.responseType,N.responseParser),i={data:await H(n,o?.data,s?.data),options:N,request:_,response:N.cloneResponse?e.clone():e};return await q(N.onSuccess(i),N.onResponse({...i,error:null})),await(e=>{const{data:r,response:t,resultMode:o}=e,s={data:r,error:null,response:t};return o?{all:s,allWithException:s,allWithoutResponse:R(s,["response"]),onlyError:s.error,onlyResponse:s.response,onlyResponseWithException:s.response,onlySuccess:s.data,onlySuccessWithException:s.data}[o]:s})({data:i.data,response:i.response,resultMode:N.resultMode})}catch(e){const{apiDetails:r,getErrorResult:t}=(e=>{const{cloneResponse:r,defaultErrorMessage:t,error:o,message:s,resultMode:n}=e;let a={data:null,error:{errorData:o,message:s??o.message,name:o.name},response:null};if(i(o)){const{errorData:e,message:s=t,name:n,response:i}=o;a={data:null,error:{errorData:e,message:s,name:n},response:r?i.clone():i}}const l={all:a,allWithException:a,allWithoutResponse:R(a,["response"]),onlyError:a.error,onlyResponse:a.response,onlyResponseWithException:a.response,onlySuccess:a.data,onlySuccessWithException:a.data};return{apiDetails:a,getErrorResult:e=>{const r=l[n??"all"];return u(e)?{...r,...e}:r}}})({cloneResponse:N.cloneResponse,defaultErrorMessage:N.defaultErrorMessage,error:e,resultMode:N.resultMode}),o={error:r.error,options:N,request:_,response:r.response},{getDelay:a,shouldAttemptRetry:l}=k(N,o);if(!J.aborted&&await l()){await q(N.onRetry(o));const e=a();await T(e);const r={...c,"~retryCount":(N["~retryCount"]??0)+1};return await s(n,r)}const d=p(N.throwOnError)?N.throwOnError(o):N.throwOnError,y=()=>{if(d)throw r.error};if(i(e))return await q(N.onResponseError(o),N.onError(o),N.onResponse({...o,data:null})),y(),t();if(e instanceof DOMException&&"AbortError"===e.name){const{message:r,name:o}=e;return console.error(`${o}:`,r),y(),t()}if(e instanceof DOMException&&"TimeoutError"===e.name){const r=`Request timed out after ${N.timeout}ms`;return console.error(`${e.name}:`,r),y(),t({message:r})}return await q(N.onRequestError(o),N.onError(o)),y(),t()}finally{X()}};return s.create=U,s},L=U();//# sourceMappingURL=index.cjs.map