@hyper-fetch/core 3.2.1 → 3.3.0

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.
@@ -29,8 +29,6 @@ export const getAdapterBindings = async <ConfigType = any>(cmd: RequestInstance,
29
29
  // Request Setup
30
30
  const { client, abortKey, queueKey, endpoint, data } = request;
31
31
 
32
- requestManager.addAbortController(abortKey, requestId);
33
-
34
32
  const fullUrl = url + endpoint;
35
33
  const effects = client.effects.filter((effect) => request.effectKey === effect.getEffectKey());
36
34
  const headers = headerMapper(request);
@@ -171,7 +169,6 @@ export const getAdapterBindings = async <ConfigType = any>(cmd: RequestInstance,
171
169
  }
172
170
 
173
171
  const progressTimestamp = +new Date();
174
- requestManager.removeAbortController(abortKey, requestId);
175
172
  handleResponseProgress(responseStartTimestamp, progressTimestamp, {
176
173
  total: responseTotal,
177
174
  loaded: responseTotal,
@@ -260,6 +257,12 @@ export const getAdapterBindings = async <ConfigType = any>(cmd: RequestInstance,
260
257
  requestManager.events.emitAbort(abortKey, requestId, request);
261
258
  };
262
259
 
260
+ // Instant abort when we stack many requests triggered at once and we receive aborted controller
261
+ if (controller.signal.aborted) {
262
+ fn();
263
+ }
264
+
265
+ // Abort during the request
263
266
  controller.signal.addEventListener("abort", fn);
264
267
 
265
268
  return () => controller.signal.removeEventListener("abort", fn);
@@ -1,7 +1,7 @@
1
1
  import { getAdapterBindings, defaultTimeout, ResponseType, AdapterType } from "adapter";
2
2
  import { parseErrorResponse, parseResponse } from "./adapter.utils";
3
3
 
4
- export const browserAdapter: AdapterType = async (request, requestId) => {
4
+ export const adapter: AdapterType = async (request, requestId) => {
5
5
  const {
6
6
  fullUrl,
7
7
  headers,
@@ -1,15 +1,11 @@
1
+ import http, { OutgoingHttpHeaders } from "http";
2
+ import https from "https";
3
+ import stream from "stream";
4
+
1
5
  import { getAdapterBindings, defaultTimeout, ResponseType, AdapterType, AdapterOptionsType } from "adapter";
2
6
  import { parseErrorResponse, parseResponse, getUploadSize, getStreamPayload } from "./adapter.utils";
3
7
 
4
- export const serverAdapter: AdapterType = async (request, requestId) => {
5
- /**
6
- * Prevent issues related to the missing Node.js polyfills
7
- */
8
- // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
9
- const http = require("http");
10
- // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
11
- const stream = require("stream");
12
-
8
+ export const adapter: AdapterType = async (request, requestId) => {
13
9
  const {
14
10
  fullUrl,
15
11
  headers,
@@ -27,14 +23,15 @@ export const serverAdapter: AdapterType = async (request, requestId) => {
27
23
  onError,
28
24
  onResponseEnd,
29
25
  } = await getAdapterBindings<AdapterOptionsType>(request, requestId);
30
- const { method } = request;
26
+ const { method, client } = request;
27
+ const httpClient = client.url.includes("https://") ? https : http;
31
28
 
32
29
  return new Promise<ResponseType<unknown, unknown>>((resolve) => {
33
30
  const execute = async () => {
34
31
  const options = {
35
32
  path: fullUrl,
36
33
  method,
37
- headers,
34
+ headers: headers as OutgoingHttpHeaders,
38
35
  timeout: defaultTimeout,
39
36
  };
40
37
 
@@ -51,7 +48,7 @@ export const serverAdapter: AdapterType = async (request, requestId) => {
51
48
 
52
49
  const payloadChunks = await getStreamPayload(payload);
53
50
 
54
- const httpRequest = http.request(options, (response) => {
51
+ const httpRequest = httpClient.request(options, (response) => {
55
52
  response.setEncoding("utf8");
56
53
 
57
54
  let chunks = "";
@@ -1,8 +1,16 @@
1
- import { browserAdapter, serverAdapter, AdapterType } from "adapter";
1
+ import * as browser from "@browser-adapter";
2
+ import * as server from "@server-adapter";
3
+
4
+ import { AdapterType } from "adapter";
2
5
 
3
6
  export const adapter: AdapterType = async (request, requestId) => {
4
- if (!window?.XMLHttpRequest) {
5
- return serverAdapter(request, requestId);
7
+ if (typeof XMLHttpRequest !== "undefined") {
8
+ return browser.adapter(request, requestId);
9
+ }
10
+ if (typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]") {
11
+ return server.adapter(request, requestId);
6
12
  }
7
- return browserAdapter(request, requestId);
13
+ return (() => {
14
+ return [null, new Error("Cannot find the right environment for http adapter"), 0];
15
+ }) as unknown as ReturnType<AdapterType>;
8
16
  };
@@ -1,7 +1,5 @@
1
1
  export * from "./adapter";
2
2
  export * from "./adapter.types";
3
3
  export * from "./adapter.utils";
4
- export * from "./adapter.server";
5
- export * from "./adapter.browser";
6
4
  export * from "./adapter.bindings";
7
5
  export * from "./adapter.constants";
@@ -1,9 +1,6 @@
1
- import { Cache } from "cache";
2
1
  import { RequestInstance } from "request";
3
- import { Dispatcher } from "dispatcher";
4
2
  import { ResponseType, AdapterType, QueryParamsType } from "adapter";
5
3
  import { Client } from "client";
6
- import { AppManager } from "managers";
7
4
  import { NegativeTypes } from "types";
8
5
 
9
6
  export type ClientErrorType = Record<string, any> | string;
@@ -24,19 +21,19 @@ export type ClientOptionsType = {
24
21
  /**
25
22
  * Custom cache initialization prop
26
23
  */
27
- cache?: <B extends ClientInstance, C extends Cache>(client: B) => C;
24
+ cache?: <B extends ClientInstance>(client: B) => B["cache"];
28
25
  /**
29
26
  * Custom app manager initialization prop
30
27
  */
31
- appManager?: <B extends ClientInstance, A extends AppManager>(client: B) => A;
28
+ appManager?: <B extends ClientInstance>(client: B) => B["appManager"];
32
29
  /**
33
30
  * Custom fetch dispatcher initialization prop
34
31
  */
35
- fetchDispatcher?: <B extends ClientInstance, D extends Dispatcher>(client: B) => D;
32
+ fetchDispatcher?: <B extends ClientInstance>(client: B) => B["submitDispatcher"];
36
33
  /**
37
34
  * Custom submit dispatcher initialization prop
38
35
  */
39
- submitDispatcher?: <B extends ClientInstance, D extends Dispatcher>(client: B) => D;
36
+ submitDispatcher?: <B extends ClientInstance>(client: B) => B["fetchDispatcher"];
40
37
  };
41
38
 
42
39
  // Interceptors
@@ -428,7 +428,7 @@ export class Dispatcher {
428
428
  return requestId;
429
429
  }
430
430
  case DispatcherRequestType.deduplicated: {
431
- // Return the running requestId to fullfil the events
431
+ // Return the running requestId to fulfill the events
432
432
  return queue.requests[0].requestId;
433
433
  }
434
434
  default: {
@@ -508,9 +508,13 @@ export class Dispatcher {
508
508
 
509
509
  // Trigger Request
510
510
  this.incrementQueueRequestCount(queueKey);
511
+ // Listen for aborting
512
+ requestManager.addAbortController(abortKey, requestId);
511
513
 
512
514
  const response = await adapter(request, requestId);
513
515
 
516
+ // Stop listening for aborting
517
+ requestManager.removeAbortController(abortKey, requestId);
514
518
  // Do not continue the request handling when it got stopped and request was unsuccessful
515
519
  // Or when the request was aborted/canceled
516
520
  const isOfflineResponseStatus = !appManager.isOnline;
@@ -417,12 +417,20 @@ export class Request<
417
417
  >
418
418
  >,
419
419
  ) => {
420
- const { adapter } = this.client;
420
+ const { adapter, requestManager } = this.client;
421
421
  const request = this.clone(options as any);
422
422
 
423
423
  const requestId = getUniqueRequestId(this.queueKey);
424
424
 
425
- return adapter(request, requestId);
425
+ // Listen for aborting
426
+ requestManager.addAbortController(this.abortKey, requestId);
427
+
428
+ const response = await adapter(request, requestId);
429
+
430
+ // Stop listening for aborting
431
+ requestManager.removeAbortController(this.abortKey, requestId);
432
+
433
+ return response;
426
434
  };
427
435
 
428
436
  /**
@@ -271,10 +271,10 @@ export type RequestSendType<Request extends RequestInstance> =
271
271
  options?: RequestSendOptionsType<Request>,
272
272
  ) => Promise<ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>>>
273
273
  : (
274
- options: RequestSendOptionsType<Request>,
274
+ options?: RequestSendOptionsType<Request>,
275
275
  ) => Promise<ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>>>
276
276
  : (
277
- options: RequestSendOptionsType<Request>,
277
+ options?: RequestSendOptionsType<Request>,
278
278
  ) => Promise<ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>>>;
279
279
 
280
280
  // Instance
package/tsconfig.json CHANGED
@@ -2,7 +2,11 @@
2
2
  "extends": "../../tsconfig.json",
3
3
  "compilerOptions": {
4
4
  "rootDir": "./src",
5
- "baseUrl": "./src"
5
+ "baseUrl": "./src",
6
+ "paths": {
7
+ "@browser-adapter": ["./adapter/adapter.browser.ts"],
8
+ "@server-adapter": ["./adapter/adapter.browser.ts"]
9
+ }
6
10
  },
7
11
  "include": ["./src/index.ts"],
8
12
  "exclude": ["dist", "__tests__", "jest.config.ts"]
@@ -0,0 +1,13 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "rootDir": "./src",
5
+ "baseUrl": "./src",
6
+ "paths": {
7
+ "@browser-adapter": ["./adapter/adapter.browser.ts"],
8
+ "@server-adapter": ["./adapter/adapter.server.ts"]
9
+ }
10
+ },
11
+ "include": ["./src/index.ts"],
12
+ "exclude": ["dist", "__tests__", "jest.config.ts"]
13
+ }
package/dist/index.cjs.js DELETED
@@ -1,2 +0,0 @@
1
- var Ht=Object.create;var te=Object.defineProperty,Bt=Object.defineProperties,kt=Object.getOwnPropertyDescriptor,Ut=Object.getOwnPropertyDescriptors,Nt=Object.getOwnPropertyNames,$e=Object.getOwnPropertySymbols,zt=Object.getPrototypeOf,je=Object.prototype.hasOwnProperty,St=Object.prototype.propertyIsEnumerable;var At=(r,e,t)=>e in r?te(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,V=(r,e)=>{for(var t in e||(e={}))je.call(e,t)&&At(r,t,e[t]);if($e)for(var t of $e(e))St.call(e,t)&&At(r,t,e[t]);return r},_e=(r,e)=>Bt(r,Ut(e));var Ct=(r,e)=>{var t={};for(var s in r)je.call(r,s)&&e.indexOf(s)<0&&(t[s]=r[s]);if(r!=null&&$e)for(var s of $e(r))e.indexOf(s)<0&&St.call(r,s)&&(t[s]=r[s]);return t};var jt=(r,e)=>{for(var t in e)te(r,t,{get:e[t],enumerable:!0})},wt=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Nt(e))!je.call(r,n)&&n!==t&&te(r,n,{get:()=>e[n],enumerable:!(s=kt(e,n))||s.enumerable});return r};var se=(r,e,t)=>(t=r!=null?Ht(zt(r)):{},wt(e||!r||!r.__esModule?te(t,"default",{value:r,enumerable:!0}):t,r)),Wt=r=>wt(te({},"__esModule",{value:!0}),r);var d=(r,e,t)=>new Promise((s,n)=>{var o=a=>{try{p(t.next(a))}catch(i){n(i)}},u=a=>{try{p(t.throw(a))}catch(i){n(i)}},p=a=>a.done?s(a.value):Promise.resolve(a.value).then(o,u);p((t=t.apply(r,e)).next())});var es={};jt(es,{AppEvents:()=>lt,AppManager:()=>J,Cache:()=>W,Client:()=>bt,DateInterval:()=>Ve,Dispatcher:()=>H,DispatcherRequestType:()=>He,HttpMethodsEnum:()=>Ge,LoggerManager:()=>Ie,Request:()=>_,RequestEffect:()=>We,RequestManager:()=>ye,adapter:()=>Je,appManagerInitialOptions:()=>N,browserAdapter:()=>Ye,canRetryRequest:()=>le,defaultTimeout:()=>oe,fileToBuffer:()=>Ot,getAbortByIdEventKey:()=>Ee,getAbortEventKey:()=>Te,getAdapterBindings:()=>ne,getAdapterHeaders:()=>Rt,getAdapterPayload:()=>mt,getAppManagerEvents:()=>pt,getCacheData:()=>at,getCacheEvents:()=>it,getCacheIdKey:()=>Xt,getCacheKey:()=>ge,getDispatcherChangeEventKey:()=>ce,getDispatcherDrainedEventKey:()=>pe,getDispatcherEvents:()=>rt,getDispatcherStatusEventKey:()=>ue,getDownloadProgressEventKey:()=>we,getDownloadProgressIdEventKey:()=>Oe,getErrorMessage:()=>$,getIsEqualTimestamp:()=>Jt,getLoadingEventKey:()=>he,getLoadingIdEventKey:()=>fe,getProgressData:()=>Be,getProgressValue:()=>Qt,getRemoveEventKey:()=>Re,getRemoveIdEventKey:()=>me,getRequestDispatcher:()=>Mt,getRequestEta:()=>Lt,getRequestKey:()=>tt,getRequestManagerEvents:()=>dt,getRequestStartEventKey:()=>qe,getRequestStartIdEventKey:()=>xe,getRequestType:()=>nt,getResponseEventKey:()=>be,getResponseIdEventKey:()=>ve,getResponseStartEventKey:()=>Pe,getResponseStartIdEventKey:()=>Ae,getRevalidateEventKey:()=>de,getSimpleKey:()=>ie,getStreamPayload:()=>et,getTime:()=>_t,getUniqueRequestId:()=>ae,getUploadProgressEventKey:()=>Se,getUploadProgressIdEventKey:()=>Ce,getUploadSize:()=>Ze,hasDocument:()=>ke,hasWindow:()=>ut,interceptRequest:()=>Ne,interceptResponse:()=>Qe,isFailedRequest:()=>U,logger:()=>gt,loggerIconLevels:()=>ht,loggerStyles:()=>yt,onDocumentEvent:()=>ct,onWindowEvent:()=>X,parseErrorResponse:()=>re,parseResponse:()=>j,requestSendRequest:()=>st,serverAdapter:()=>Xe,severity:()=>ft,stringifyDefaultOptions:()=>Et,stringifyKey:()=>ot,stringifyQueryParams:()=>Tt,stringifyValue:()=>Vt});module.exports=Wt(es);var We=class{constructor(e){this.config=e;this.getEffectKey=()=>this.config.effectKey;this.onTrigger=e=>{var t,s;(s=(t=this.config).onTrigger)==null||s.call(t,e)};this.onStart=e=>{var t,s;(s=(t=this.config).onStart)==null||s.call(t,e)};this.onSuccess=(e,t)=>{var s,n;(n=(s=this.config).onSuccess)==null||n.call(s,e,t)};this.onError=(e,t)=>{var s,n;(n=(s=this.config).onError)==null||n.call(s,e,t)};this.onFinished=(e,t)=>{var s,n;(n=(s=this.config).onFinished)==null||n.call(s,e,t)}}};var Je=(r,e)=>d(void 0,null,function*(){return window!=null&&window.XMLHttpRequest?Ye(r,e):Xe(r,e)});var $=r=>r==="timeout"?new Error("Request timeout"):r==="abort"?new Error("Request cancelled"):new Error("Unexpected error"),j=r=>{try{return JSON.parse(r)}catch(e){return r}},re=r=>r?j(r):$(),Ze=r=>r instanceof FormData?Array.from(r.values()).map(e=>typeof e=="string"?e.length:e.size).reduce((e,t)=>e+t,0):r.length,Ot=r=>new Promise(e=>{let t=new FileReader;t.onload=()=>{e(new Uint8Array(t.result))},t.readAsArrayBuffer(r)}),et=r=>{if(r instanceof FormData){let e=Array.from(r.values()).map(t=>typeof t=="string"?t:Ot(t));return Promise.all(e)}return r};var Xe=(r,e)=>d(void 0,null,function*(){let t=require("http"),s=require("stream"),{fullUrl:n,headers:o,payload:u,config:p,createAbortListener:a,onBeforeRequest:i,onRequestStart:c,onRequestProgress:E,onRequestEnd:f,onResponseStart:S,onResponseProgress:R,onSuccess:h,onTimeoutError:x,onError:C,onResponseEnd:m}=yield ne(r,e),{method:T}=r;return new Promise(w=>{(()=>d(void 0,null,function*(){let M={path:n,method:T,headers:o,timeout:oe};Object.entries(p).forEach(([q,Q])=>{M[q]=Q});let v=()=>null;i();let P=u?Number(Ze(u)):0,I=0,F=yield et(u),b=t.request(M,q=>{q.setEncoding("utf8");let Q="",z=Number(q.headers["content-length"]),B=0;q.on("data",K=>{Q||S(),B+=K.length,Q+=K,R({total:z,loaded:B})}),q.on("end",()=>{let{statusCode:K}=q;if(String(K).startsWith("2")||String(K).startsWith("3")){let G=j(Q);h(G,K,w)}else{let G=re(Q);C(G,K,w)}v(),m()})});v=a(b.destroy,w),b.on("timeout",()=>x(w)),b.on("error",q=>C(q,0,w)),F?s.Readable.from(F,{objectMode:!1}).on("data",Q=>{I||c(),I+=Q.length,E({total:P,loaded:I})}).on("end",()=>{f()}).pipe(b):b.end()}))()})});var Ye=(r,e)=>d(void 0,null,function*(){let{fullUrl:t,headers:s,payload:n,config:o,createAbortListener:u,onBeforeRequest:p,onRequestStart:a,onRequestProgress:i,onRequestEnd:c,onResponseStart:E,onResponseProgress:f,onSuccess:S,onError:R,onResponseEnd:h,onTimeoutError:x}=yield ne(r,e),{method:C}=r,m=new XMLHttpRequest;m.timeout=oe;let T=()=>m.abort();return new Promise(w=>{Object.entries(o).forEach(([M,v])=>{m[M]=v}),m.open(C,t,!0),Object.entries(s).forEach(([M,v])=>m.setRequestHeader(M,v));let O=u(T,w);m.upload.onprogress=i,m.onloadstart=()=>{c(),E()},m.onprogress=f,m.onloadend=()=>{h(),O()},m.ontimeout=()=>x,m.onreadystatechange=M=>{let v=M,P=4;if(v.target&&v.target.readyState===P){let{status:I}=v.target;if(String(I).startsWith("2")||String(I).startsWith("3")){let b=j(v.target.response);S(b,I,w)}else{let b=re(v.target.response);R(b,I,w)}}},p(),a(),m.send(n)})});var ae=r=>`${r}_${Date.now().toString(36)}_${Math.random().toString(36).substring(2)}`;var Ve=(i=>(i[i.second=1e3]="second",i[i.minute=6e4]="minute",i[i.hour=36e5]="hour",i[i.day=864e5]="day",i[i.week=6048e5]="week",i[i.month30=2592e6]="month30",i[i.month31=26784e5]="month31",i[i.year=31536e6]="year",i[i.yearLeap=316224e5]="yearLeap",i))(Ve||{});var Ge=(o=>(o.get="GET",o.post="POST",o.put="PUT",o.patch="PATCH",o.delete="DELETE",o))(Ge||{});var _=class{constructor(e,t,s,n){this.client=e;this.requestOptions=t;this.requestDump=s;this.dataMapper=n;this.setHeaders=e=>this.clone({headers:e});this.setAuth=e=>this.clone({auth:e});this.setParams=e=>this.clone({params:e});this.setData=e=>{var s;let t=((s=this.dataMapper)==null?void 0:s.call(this,e))||e;return this.clone({data:t})};this.setQueryParams=e=>this.clone({queryParams:e});this.setOptions=e=>this.clone({options:e});this.setCancelable=e=>this.clone({cancelable:e});this.setRetry=e=>this.clone({retry:e});this.setRetryTime=e=>this.clone({retryTime:e});this.setGarbageCollection=e=>this.clone({garbageCollection:e});this.setCache=e=>this.clone({cache:e});this.setCacheTime=e=>this.clone({cacheTime:e});this.setQueued=e=>this.clone({queued:e});this.setAbortKey=e=>(this.updatedAbortKey=!0,this.clone({abortKey:e}));this.setCacheKey=e=>(this.updatedCacheKey=!0,this.clone({cacheKey:e}));this.setQueueKey=e=>(this.updatedQueueKey=!0,this.clone({queueKey:e}));this.setEffectKey=e=>(this.updatedEffectKey=!0,this.clone({effectKey:e}));this.setDeduplicate=e=>this.clone({deduplicate:e});this.setDeduplicateTime=e=>this.clone({deduplicateTime:e});this.setUsed=e=>this.clone({used:e});this.setOffline=e=>this.clone({offline:e});this.setDataMapper=e=>this.clone(void 0,e);this.paramsMapper=(e,t)=>{let s=this.requestOptions.endpoint;return e&&Object.entries(e).forEach(([n,o])=>{s=s.replace(new RegExp(`:${n}`,"g"),String(o))}),t&&(s+=this.client.stringifyQueryParams(t)),s};this.abort=()=>{let{requestManager:e}=this.client;return e.abortByKey(this.abortKey),this.clone()};this.exec=e=>d(this,null,function*(){let{adapter:t}=this.client,s=this.clone(e),n=ae(this.queueKey);return t(s,n)});this.send=e=>d(this,null,function*(){let o=e||{},{dispatcherType:t}=o,s=Ct(o,["dispatcherType"]),n=this.clone(s);return st(n,e)});var P,I,F,b,q,Q,z,B,K,Y,G,Le,Me,Ke,k,Z,Fe,De,ee,ze,l,g,A,y,D,vt,qt,xt,Pt;let{endpoint:o,headers:u,auth:p=!0,method:a="GET",options:i,cancelable:c=!1,retry:E=0,retryTime:f=500,garbageCollection:S=6e4*5,cache:R=!0,cacheTime:h=6e4*5,queued:x=!1,offline:C=!0,abortKey:m,cacheKey:T,queueKey:w,effectKey:O,deduplicate:M=!1,deduplicateTime:v=10}=V(V({},(I=(P=this.client).requestDefaultOptions)==null?void 0:I.call(P,t)),t);this.endpoint=(F=s==null?void 0:s.endpoint)!=null?F:o,this.headers=(b=s==null?void 0:s.headers)!=null?b:u,this.auth=(q=s==null?void 0:s.auth)!=null?q:p,this.method=a,this.params=s==null?void 0:s.params,this.data=s==null?void 0:s.data,this.queryParams=s==null?void 0:s.queryParams,this.options=(Q=s==null?void 0:s.options)!=null?Q:i,this.cancelable=(z=s==null?void 0:s.cancelable)!=null?z:c,this.retry=(B=s==null?void 0:s.retry)!=null?B:E,this.retryTime=(K=s==null?void 0:s.retryTime)!=null?K:f,this.garbageCollection=(Y=s==null?void 0:s.garbageCollection)!=null?Y:S,this.cache=(G=s==null?void 0:s.cache)!=null?G:R,this.cacheTime=(Le=s==null?void 0:s.cacheTime)!=null?Le:h,this.queued=(Me=s==null?void 0:s.queued)!=null?Me:x,this.offline=(Ke=s==null?void 0:s.offline)!=null?Ke:C,this.abortKey=(Z=(k=s==null?void 0:s.abortKey)!=null?k:m)!=null?Z:ie(this),this.cacheKey=(De=(Fe=s==null?void 0:s.cacheKey)!=null?Fe:T)!=null?De:tt(this),this.queueKey=(ze=(ee=s==null?void 0:s.queueKey)!=null?ee:w)!=null?ze:ie(this),this.effectKey=(g=(l=s==null?void 0:s.effectKey)!=null?l:O)!=null?g:ie(this),this.used=(A=s==null?void 0:s.used)!=null?A:!1,this.deduplicate=(y=s==null?void 0:s.deduplicate)!=null?y:M,this.deduplicateTime=(D=s==null?void 0:s.deduplicateTime)!=null?D:v,this.updatedAbortKey=(vt=s==null?void 0:s.updatedAbortKey)!=null?vt:!1,this.updatedCacheKey=(qt=s==null?void 0:s.updatedCacheKey)!=null?qt:!1,this.updatedQueueKey=(xt=s==null?void 0:s.updatedQueueKey)!=null?xt:!1,this.updatedEffectKey=(Pt=s==null?void 0:s.updatedEffectKey)!=null?Pt:!1}dump(){return{requestOptions:this.requestOptions,endpoint:this.endpoint,headers:this.headers,auth:this.auth,method:this.method,params:this.params,data:this.data,queryParams:this.queryParams,options:this.options,cancelable:this.cancelable,retry:this.retry,retryTime:this.retryTime,garbageCollection:this.garbageCollection,cache:this.cache,cacheTime:this.cacheTime,queued:this.queued,offline:this.offline,abortKey:this.abortKey,cacheKey:this.cacheKey,queueKey:this.queueKey,effectKey:this.effectKey,used:this.used,disableResponseInterceptors:this.requestOptions.disableResponseInterceptors,disableRequestInterceptors:this.requestOptions.disableRequestInterceptors,updatedAbortKey:this.updatedAbortKey,updatedCacheKey:this.updatedCacheKey,updatedQueueKey:this.updatedQueueKey,updatedEffectKey:this.updatedEffectKey,deduplicate:this.deduplicate,deduplicateTime:this.deduplicateTime}}clone(e,t){let s=this.dump(),n=_e(V(V({},s),e),{abortKey:this.updatedAbortKey?(e==null?void 0:e.abortKey)||this.abortKey:void 0,cacheKey:this.updatedCacheKey?(e==null?void 0:e.cacheKey)||this.cacheKey:void 0,queueKey:this.updatedQueueKey?(e==null?void 0:e.queueKey)||this.queueKey:void 0,endpoint:this.paramsMapper((e==null?void 0:e.params)||this.params,(e==null?void 0:e.queryParams)||this.queryParams),queryParams:(e==null?void 0:e.queryParams)||this.queryParams,data:(e==null?void 0:e.data)||this.data}),o=t||this.dataMapper;return new _(this.client,this.requestOptions,n,o)}};var He=(n=>(n.oneByOne="one-by-one",n.allAtOnce="all-at-once",n.previousCanceled="previous-canceled",n.deduplicated="deduplicated",n))(He||{});var rt=r=>({setDrained:(e,t)=>{r.emit(pe(e),t)},setQueueStatus:(e,t)=>{r.emit(ue(e),t)},setQueueChanged:(e,t)=>{r.emit(ce(e),t)},onDrained:(e,t)=>(r.on(pe(e),t),()=>r.removeListener(pe(e),t)),onQueueStatus:(e,t)=>(r.on(ue(e),t),()=>r.removeListener(ue(e),t)),onQueueChange:(e,t)=>(r.on(ce(e),t),()=>r.removeListener(ce(e),t))});var It=se(require("events"));var H=class{constructor(e,t){this.client=e;this.options=t;this.emitter=new It.default;this.events=rt(this.emitter);this.storage=new Map;this.requestCount=new Map;this.runningRequests=new Map;this.start=e=>{let t=this.getQueue(e);t.stopped=!1,this.setQueue(e,t),this.flushQueue(e),this.events.setQueueStatus(e,t)};this.pause=e=>{let t=this.getQueue(e);t.stopped=!0,this.setQueue(e,t),this.events.setQueueStatus(e,t)};this.stop=e=>{let t=this.getQueue(e);t.stopped=!0,this.setQueue(e,t),this.cancelRunningRequests(e),this.events.setQueueStatus(e,t)};this.getQueuesKeys=()=>Array.from(this.storage.keys());this.getQueue=e=>{let t={requests:[],stopped:!1};return this.storage.get(e)||t};this.getRequest=(e,t)=>{let s={requests:[],stopped:!1};return(this.storage.get(e)||s).requests.find(o=>o.requestId===t)};this.getIsActiveQueue=e=>{let t=this.getQueue(e),s=t.requests.some(o=>!o.stopped),n=!t.stopped;return s&&n};this.addQueueElement=(e,t)=>{let s=this.getQueue(e);s.requests.push(t),this.setQueue(e,s)};this.setQueue=(e,t)=>{var s,n;return this.storage.set(e,t),(n=(s=this.options)==null?void 0:s.onUpdateStorage)==null||n.call(s,e,t),this.events.setQueueChanged(e,t),t};this.clearQueue=e=>{var n,o;let t=this.getQueue(e),s={requests:[],stopped:t.stopped};return this.storage.set(e,s),(o=(n=this.options)==null?void 0:n.onDeleteFromStorage)==null||o.call(n,e,s),this.events.setQueueChanged(e,s),s};this.flushQueue=e=>d(this,null,function*(){let t=this.getQueue(e),s=this.getRunningRequests(e),n=t.requests.find(c=>!c.stopped),o=t&&t.stopped,u=!this.client.appManager.isOnline,p=!(n!=null&&n.requestDump.queued),a=!s.length,i=!n;o||u||i?this.logger.debug("Skipping queue trigger",{isStopped:o,isOffline:u,isEmpty:i}):p?t.requests.forEach(c=>{this.hasRunningRequest(e,c.requestId)||this.performRequest(c)}):a&&(yield this.performRequest(n),this.flushQueue(e))});this.flush=()=>d(this,null,function*(){let e=this.getQueuesKeys();for(let t of e)this.getQueue(t)&&this.flushQueue(t)});this.clear=()=>{var t,s;this.getQueuesKeys().forEach(n=>this.cancelRunningRequests(n)),this.runningRequests.clear(),this.storage.clear(),(s=(t=this.options)==null?void 0:t.onClearStorage)==null||s.call(t,this)};this.startRequest=(e,t)=>{let s=this.getQueue(e),n=s.requests.find(o=>o.requestId===t);n&&(n.stopped=!1,this.setQueue(e,s),this.flushQueue(e),this.events.setQueueStatus(e,s))};this.stopRequest=(e,t)=>{let s=this.getQueue(e),n=s.requests.find(o=>o.requestId===t);n&&(n.stopped=!0,this.setQueue(e,s),this.cancelRunningRequest(e,t),this.events.setQueueStatus(e,s))};this.getAllRunningRequest=()=>Array.from(this.runningRequests.values()).flat();this.getRunningRequests=e=>this.runningRequests.get(e)||[];this.getRunningRequest=(e,t)=>this.getRunningRequests(e).find(n=>n.requestId===t);this.addRunningRequest=(e,t,s)=>{let n=this.getRunningRequests(e);n.push({requestId:t,request:s}),this.runningRequests.set(e,n)};this.hasRunningRequests=e=>!!this.getRunningRequests(e).length;this.hasRunningRequest=(e,t)=>!!this.getRunningRequests(e).find(n=>n.requestId===t);this.cancelRunningRequests=e=>{var t;(t=this.runningRequests.get(e))==null||t.forEach(s=>{this.client.requestManager.abortByRequestId(s.request.abortKey,s.requestId)}),this.deleteRunningRequests(e)};this.cancelRunningRequest=(e,t)=>{let s=this.getRunningRequests(e).filter(n=>n.requestId===t?(this.client.requestManager.abortByRequestId(n.request.abortKey,n.requestId),!1):!0);this.runningRequests.set(e,s)};this.deleteRunningRequests=e=>{this.runningRequests.set(e,[])};this.deleteRunningRequest=(e,t)=>{let s=this.getRunningRequests(e);this.runningRequests.set(e,s.filter(n=>n.requestId!==t))};this.getQueueRequestCount=e=>this.requestCount.get(e)||0;this.incrementQueueRequestCount=e=>{let t=this.requestCount.get(e)||0;this.requestCount.set(e,t+1)};this.createStorageElement=e=>({requestId:ae(e.queueKey),timestamp:+new Date,requestDump:e.dump(),retries:0,stopped:!1});this.add=e=>{let{queueKey:t}=e,s=this.createStorageElement(e),{requestId:n}=s,o=this.getQueue(t),[u]=o.requests.slice(-1),p=nt(e,u);switch(this.logger.debug("Adding request to queue",{requestType:p,request:e,requestId:n}),p){case"one-by-one":return this.addQueueElement(t,s),this.flushQueue(t),n;case"previous-canceled":return this.cancelRunningRequests(t),this.clearQueue(t),this.addQueueElement(t,s),this.flushQueue(t),n;case"deduplicated":return o.requests[0].requestId;default:return this.addQueueElement(t,s),this.flushQueue(t),n}};this.delete=(e,t,s)=>{var p,a;this.logger.debug("Deleting request",{queueKey:e,requestId:t,abortKey:s});let n=this.getQueue(e),o=n.requests.find(i=>i.requestId===t);if(!o)return;let u=new _(this.client,o.requestDump.requestOptions,o.requestDump);return n.requests=n.requests.filter(i=>i.requestId!==t),this.storage.set(e,n),this.hasRunningRequest(e,t)&&(this.deleteRunningRequest(e,t),this.client.requestManager.abortByRequestId(s,t)),(a=(p=this.options)==null?void 0:p.onDeleteFromStorage)==null||a.call(p,e,n),this.events.setQueueChanged(e,n),this.client.requestManager.events.emitRemove(e,t,{requestId:t,request:u}),n.requests.length||this.events.setDrained(e,n),n};this.performRequest=e=>d(this,null,function*(){var I;let t=new _(this.client,e.requestDump.requestOptions,e.requestDump),{requestDump:s,requestId:n}=e;this.logger.info("Performing request",{request:t,requestId:n});let{retry:o,retryTime:u,queueKey:p,cacheKey:a,abortKey:i,offline:c}=s,{adapter:E,requestManager:f,cache:S,appManager:R}=this.client,h=le(e.retries,o),x=!R.isOnline&&c,C=this.hasRunningRequest(p,n),m=e.stopped;if(x||C||m)return this.logger.warning("Unable to perform request",{isOffline:x,isAlreadyRunning:C,isStopped:m});this.addRunningRequest(p,n,t),f.events.emitLoading(p,n,{queueKey:p,requestId:n,loading:!0,isRetry:!!e.retries,isOffline:x}),this.incrementQueueRequestCount(p);let T=yield E(t,n),w=!R.isOnline,O=U(T),M=$("abort").message===((I=T[1])==null?void 0:I.message),v=!this.hasRunningRequest(p,n)||M;this.deleteRunningRequest(p,n);let P={isFailed:O,isCanceled:v,isOffline:w,retries:e.retries,timestamp:+new Date};if(f.events.emitLoading(p,n,{queueKey:p,requestId:n,loading:!1,isRetry:!!e.retries,isOffline:x}),f.events.emitResponse(a,n,T,P),S.set(t,T,P),this.logger.info("Request finished",{requestId:n,request:t,response:T,requestDetails:P}),v){let F=this.getQueue(p),b=F.requests.find(q=>q.requestId===n);return!F.stopped&&!(b!=null&&b.stopped)?(this.logger.debug("Request paused",{response:T,requestDetails:P,request:t}),this.delete(p,n,i)):this.logger.debug("Request canceled",{response:T,requestDetails:P,request:t})}if(O&&w)return c?this.logger.debug("Awaiting for network restoration",{response:T,requestDetails:P,request:t}):(this.logger.warning("Removing non-offline request",{response:T,requestDetails:P,request:t}),this.delete(p,n,i));if(!O)return this.delete(p,n,i),this.logger.debug("Successful response, removing request from queue.",{response:T,requestDetails:P,request:t});O&&h?(this.logger.debug("Waiting for retry",{response:T,requestDetails:P,request:t}),setTimeout(()=>{this.logger.warning("Error response, performing retry"),this.performRequest(_e(V({},e),{retries:e.retries+1}))},u||0)):(this.logger.error("All retries have been used. Removing request from queue."),this.delete(p,n,i))});var s,n,o;this.logger=e.loggerManager.init("Dispatcher"),(s=this.options)!=null&&s.storage&&(this.storage=this.options.storage),this.client.appManager.events.onOnline(()=>{this.flush()}),(o=(n=this.options)==null?void 0:n.onInitialization)==null||o.call(n,this)}};var pe=r=>`${r}-drained-event`,ue=r=>`${r}-status-event`,ce=r=>`${r}-change-event`,Jt=(r,e,t)=>t?t-r<=e:!1,le=(r,e)=>!!(e&&r<e),nt=(r,e)=>{let{queued:t,cancelable:s,deduplicate:n}=r,o=e?+new Date-e.timestamp<=r.deduplicateTime:!1;return t?"one-by-one":s?"previous-canceled":o&&n?"deduplicated":"all-at-once"},U=r=>{let[,,e]=r;return!e||e>=400};var ot=r=>{try{if(typeof r=="string")return r;if(r==null)return"";let e=JSON.stringify(r);if(typeof e!="string")throw new Error;return e}catch(e){return""}},Qt=({loaded:r,total:e})=>!r||!e?0:Number((r*100/e).toFixed(0)),Lt=(r,e,{total:t,loaded:s})=>{let n=+e-+r||1,o=s/n,u=Math.max(t,s),p=u-s,a=o?p/o:null;return{timeLeft:u===s?0:a,sizeLeft:p}},Be=(r,e,t)=>{let{total:s,loaded:n}=t;if(Number.isNaN(s)||Number.isNaN(n))return{progress:0,timeLeft:0,sizeLeft:0,total:0,loaded:0,startTimestamp:+r};let{timeLeft:o,sizeLeft:u}=Lt(r,e,t);return{progress:Qt(t),timeLeft:o,sizeLeft:u,total:s,loaded:n,startTimestamp:+r}},ie=r=>`${r.method}_${r.requestOptions.endpoint}_${r.cancelable}`,tt=(r,e)=>{let t=ot(r.method),s=e?r.requestOptions.endpoint:ot(r.endpoint);return`${t}_${s}`},Mt=(r,e="auto")=>{let{fetchDispatcher:t,submitDispatcher:s}=r.client,n=r.method==="GET",o=e==="auto"&&n||e==="fetch";return[o?t:s,o]},st=(r,e)=>{let{requestManager:t}=r.client,[s]=Mt(r,e==null?void 0:e.dispatcherType);return new Promise(n=>{var S;let o=s.add(r);(S=e==null?void 0:e.onSettle)==null||S.call(e,o,r);let u=t.events.onRequestStartById(o,(...R)=>{var h;return(h=e==null?void 0:e.onRequestStart)==null?void 0:h.call(e,...R)}),p=t.events.onResponseStartById(o,(...R)=>{var h;return(h=e==null?void 0:e.onResponseStart)==null?void 0:h.call(e,...R)}),a=t.events.onUploadProgressById(o,(...R)=>{var h;return(h=e==null?void 0:e.onUploadProgress)==null?void 0:h.call(e,...R)}),i=t.events.onDownloadProgressById(o,(...R)=>{var h;return(h=e==null?void 0:e.onDownloadProgress)==null?void 0:h.call(e,...R)}),c=t.events.onResponseById(o,(R,h)=>{var T;let x=U(R),C=r.offline&&h.isOffline,m=le(h.retries,r.retry);x&&C||x&&m||((T=e==null?void 0:e.onResponse)==null||T.call(e,R,h),n(R),f())}),E=t.events.onRemoveById(o,(...R)=>{var h;(h=e.onRemove)==null||h.call(e,...R),n([null,$("deleted"),0]),f()});function f(){u(),p(),a(),i(),c(),E()}})};var ne=(r,e)=>d(void 0,null,function*(){let{url:t,requestManager:s,loggerManager:n,headerMapper:o,payloadMapper:u}=r.client,p=n.init("Adapter"),a=null,i=null,c=r,E=1,f=1,S=0,R=0;p.debug("Starting request middleware callbacks"),c=yield c.client.__modifyRequest(r),c.auth&&(c=yield c.client.__modifyAuth(r));let{client:h,abortKey:x,queueKey:C,endpoint:m,data:T}=c;s.addAbortController(x,e);let w=t+m,O=h.effects.filter(l=>c.effectKey===l.getEffectKey()),M=o(c),v=u(T),P=V({},c.requestOptions.options),I=()=>a,F=()=>i,b=(l,g)=>{if(!g)return l;let A=Number(g.total||0),y=Number(g.loaded||0);return Math.max(A,y,l)},q=(l,g,A)=>{let y=Be(new Date(l),new Date(g),A);S!==100&&(S=y.total,s.events.emitUploadProgress(C,e,y,{requestId:e,request:c}))},Q=(l,g,A)=>{let y=Be(new Date(l),new Date(g),A);R!==100&&(R=y.total,s.events.emitDownloadProgress(C,e,y,{requestId:e,request:c}))},z=()=>{O.forEach(l=>l.onTrigger(c))},B=l=>{O.forEach(A=>A.onStart(c)),l!=null&&l.total&&(E=b(E,l));let g={total:E,loaded:(l==null?void 0:l.loaded)||0};return a=+new Date,q(a,a,g),s.events.emitRequestStart(C,e,{requestId:e,request:c}),a},K=l=>{a||(a=+new Date),E=b(E,l);let g=+new Date;return q(a,g,{total:E,loaded:l.loaded||0}),g},Y=()=>{a||(a=+new Date);let l=+new Date;return q(a,l,{total:E,loaded:E}),l},G=l=>{i=+new Date,f=b(f,l);let g={total:f,loaded:(l==null?void 0:l.loaded)||0};return Q(i,i,g),s.events.emitResponseStart(C,e,{requestId:e,request:c}),i},Le=l=>{i||(i=+new Date);let g=+new Date;return f=b(f,l),Q(i,g,{total:l.total||f,loaded:l.loaded||0}),g},Me=()=>{i||(i=+new Date);let l=+new Date;return s.removeAbortController(x,e),Q(i,l,{total:f,loaded:f}),l},Ke=(l,g,A)=>d(void 0,null,function*(){let y=[l,null,g];return y=yield c.client.__modifyResponse(y,c),y=yield c.client.__modifySuccessResponse(y,c),O.forEach(D=>D.onSuccess(y,c)),O.forEach(D=>D.onFinished(y,c)),A(y),y}),k=(l,g,A)=>d(void 0,null,function*(){let y=[null,l,g];return y=yield c.client.__modifyResponse(y,c),y=yield c.client.__modifyErrorResponse(y,c),O.forEach(D=>D.onError(y,c)),O.forEach(D=>D.onFinished(y,c)),A(y),y}),Z=l=>{let g=$("abort");return k(g,0,l)},Fe=l=>{let g=$("timeout");return k(g,0,l)},De=l=>{let g=$();return k(g,0,l)},ee=()=>s.getAbortController(x,e);return{fullUrl:w,headers:M,payload:v,config:P,getAbortController:ee,getRequestStartTimestamp:I,getResponseStartTimestamp:F,createAbortListener:(l,g)=>{let A=ee();if(!A)throw new Error("Controller is not found");let y=()=>{Z(g),l(),s.events.emitAbort(x,e,c)};return A.signal.addEventListener("abort",y),()=>A.signal.removeEventListener("abort",y)},onBeforeRequest:z,onRequestStart:B,onRequestProgress:K,onRequestEnd:Y,onResponseStart:G,onResponseProgress:Le,onResponseEnd:Me,onSuccess:Ke,onAbortError:Z,onTimeoutError:Fe,onUnexpectedError:De,onError:k}});var oe=1e3*5;var Kt=se(require("events"));var W=class{constructor(e,t){this.client=e;this.options=t;this.emitter=new Kt.default;this.garbageCollectors=new Map;this.set=(e,t,s)=>{var E,f,S;this.logger.debug("Processing cache response",{request:e,response:t,details:s});let{cacheKey:n,cache:o,cacheTime:u,garbageCollection:p}=e,a=this.storage.get(n),c={data:at(a==null?void 0:a.data,t),details:s,cacheTime:u,clearKey:this.clearKey,garbageCollection:p};if(this.events.emitCacheData(n,c),this.logger.debug("Emitting cache response",{request:e,response:t,details:s}),!o)return this.logger.debug("Prevented saving response to cache",{request:e,response:t,details:s});s.isFailed||(this.logger.debug("Saving response to cache storage",{request:e,response:t,details:s}),this.storage.set(n,c),(E=this.lazyStorage)==null||E.set(n,c),(S=(f=this.options)==null?void 0:f.onChange)==null||S.call(f,n,c),this.scheduleGarbageCollector(n))};this.get=e=>(this.getLazyResource(e),this.storage.get(e));this.keys=()=>{let e=this.storage.keys();return Array.from(e)};this.delete=e=>{var t,s,n;this.logger.debug("Deleting cache element",{cacheKey:e}),this.storage.delete(e),(s=(t=this.options)==null?void 0:t.onDelete)==null||s.call(t,e),(n=this.lazyStorage)==null||n.delete(e)};this.revalidate=e=>d(this,null,function*(){this.logger.debug("Revalidating cache element",{cacheKey:e});let t=yield this.getLazyKeys();if(typeof e=="string")this.events.emitRevalidation(e),this.delete(e);else for(let s of t)e.test(s)&&(this.events.emitRevalidation(s),this.delete(s))});this.getLazyResource=e=>d(this,null,function*(){var u;let t=yield(u=this.lazyStorage)==null?void 0:u.get(e),s=this.storage.get(e);if(this.lazyStorage&&t){let p=+new Date,a=s?s.details.timestamp<t.details.timestamp:!0,i=t.cacheTime<=p-t.details.timestamp,c=t.clearKey===this.clearKey;if(c||this.lazyStorage.delete(e),a&&!i&&c)return this.storage.set(e,t),this.events.emitCacheData(e,t),t}let o=(s==null?void 0:s.clearKey)===this.clearKey;return s&&!o&&this.delete(e),s});this.getLazyKeys=()=>d(this,null,function*(){var n;let e=yield(n=this.lazyStorage)==null?void 0:n.keys(),t=Array.from(e||[]),s=Array.from(this.storage.keys());return[...new Set([...t,...s])]});this.scheduleGarbageCollector=e=>d(this,null,function*(){let t=yield this.getLazyResource(e);if(clearTimeout(this.garbageCollectors.get(e)),t){let s=t.garbageCollection+t.details.timestamp-+new Date;s>=0?this.garbageCollectors.set(e,setTimeout(()=>{this.client.appManager.isOnline&&(this.logger.info("Garbage collecting cache element",{cacheKey:e}),this.delete(e))},s)):this.client.appManager.isOnline&&(this.logger.info("Garbage collecting cache element",{cacheKey:e}),this.delete(e))}});this.clear=()=>d(this,null,function*(){this.storage.clear()});var s,n,o,u,p;this.storage=((s=this.options)==null?void 0:s.storage)||new Map,this.events=it(this.emitter),(o=(n=this.options)==null?void 0:n.onInitialization)==null||o.call(n,this),this.clearKey=((u=this.options)==null?void 0:u.clearKey)||"",this.lazyStorage=(p=this.options)==null?void 0:p.lazyStorage,this.logger=this.client.loggerManager.init("Cache"),this.getLazyKeys().then(a=>{a.forEach(this.scheduleGarbageCollector)}),this.client.appManager.events.onOnline(()=>{this.getLazyKeys().then(a=>{a.forEach(this.scheduleGarbageCollector)})})}};var at=(r,e)=>{let s=U(e)&&r?r[0]:null,n=e[0]||s,o=e[1],u=e[2];return[n,o,u]},de=r=>`${r}_revalidate`,ge=r=>`${r}_cache`,Xt=r=>`${r}_cache_by_id`;var it=r=>({emitCacheData:(e,t)=>{r.emit(ge(e),t)},emitRevalidation:e=>{r.emit(de(e))},onData:(e,t)=>(r.on(ge(e),t),()=>r.removeListener(ge(e),t)),onRevalidate:(e,t)=>(r.on(de(e),t),()=>r.removeListener(de(e),t))});var Ft=se(require("events"));var J=class{constructor(e){this.options=e;this.emitter=new Ft.default;this.events=pt(this.emitter);this.setInitialFocus=e=>d(this,null,function*(){typeof e=="function"?(this.isFocused=!1,this.isFocused=yield e()):this.isFocused=e});this.setInitialOnline=e=>d(this,null,function*(){typeof e=="function"?(this.isOnline=!1,this.isOnline=yield e()):this.isOnline=e});this.setFocused=e=>{this.isFocused=e,e?this.events.emitFocus():this.events.emitBlur()};this.setOnline=e=>{this.isOnline=e,e?this.events.emitOnline():this.events.emitOffline()};let{focusEvent:t=N.focusEvent,onlineEvent:s=N.onlineEvent,initiallyFocused:n=N.initiallyFocused,initiallyOnline:o=N.initiallyOnline}=this.options||N;this.setInitialFocus(n),this.setInitialOnline(o),t(this.setFocused),s(this.setOnline),this.isBrowser=ke()}};var ut=()=>{try{return Boolean(window&&window.addEventListener)}catch(r){return!1}},ke=()=>{try{return Boolean(ut()&&window.document&&window.document.addEventListener)}catch(r){return!1}},X=(r,e,t)=>{ut()&&window.addEventListener(r,e,t)},ct=(r,e,t)=>{ke()&&window.document.addEventListener(r,e,t)};var pt=r=>({emitFocus:()=>{r.emit("focus")},emitBlur:()=>{r.emit("blur")},emitOnline:()=>{r.emit("online")},emitOffline:()=>{r.emit("offline")},onFocus:e=>(r.on("focus",e),()=>r.removeListener("focus",e)),onBlur:e=>(r.on("blur",e),()=>r.removeListener("blur",e)),onOnline:e=>(r.on("online",e),()=>r.removeListener("online",e)),onOffline:e=>(r.on("offline",e),()=>r.removeListener("offline",e))});var lt=(n=>(n.focus="focus",n.blur="blur",n.online="online",n.offline="offline",n))(lt||{}),N={initiallyFocused:!0,initiallyOnline:!0,focusEvent:r=>{ct("visibilitychange",()=>r(!0)),X("focus",()=>r(!0)),X("blur",()=>r(!1))},onlineEvent:r=>{X("online",()=>r(!0)),X("offline",()=>r(!1))}};var Dt=se(require("events"));var ye=class{constructor(){this.emitter=new Dt.default;this.events=dt(this.emitter);this.abortControllers=new Map;this.addAbortController=(e,t)=>{let s=this.abortControllers.get(e);if(!s){let o=new Map;s=o,this.abortControllers.set(e,o)}let n=s.get(t);(!n||n.signal.aborted)&&s.set(t,new AbortController)};this.getAbortController=(e,t)=>{var s;return(s=this.abortControllers.get(e))==null?void 0:s.get(t)};this.removeAbortController=(e,t)=>{var s;(s=this.abortControllers.get(e))==null||s.delete(t)};this.useAbortController=(e,t)=>{var n;let s=(n=this.abortControllers.get(e))==null?void 0:n.get(t);s==null||s.abort()};this.abortByKey=e=>{let t=this.abortControllers.get(e);t&&Array.from(t.entries()).forEach(([n])=>{this.useAbortController(e,n)})};this.abortByRequestId=(e,t)=>{this.useAbortController(e,t)};this.abortAll=()=>{Array.from(this.abortControllers.entries()).forEach(([t,s])=>{Array.from(s.entries()).forEach(([o])=>{this.useAbortController(t,o)})})}}};var he=r=>`${r}-loading-event`,fe=r=>`${r}-loading-event-by-id`,Re=r=>`${r}-remove-event`,me=r=>`${r}-remove-event-by-id`,Te=r=>`${r}-request-abort`,Ee=r=>`${r}-request-abort-by-id`,be=r=>`${r}-response`,ve=r=>`${r}-response-by-id`,qe=r=>`${r}-request-start`,xe=r=>`${r}-request-start-by-id`,Pe=r=>`${r}-response-start`,Ae=r=>`${r}-response-start-by-id`,Se=r=>`${r}-request-progress`,Ce=r=>`${r}-request-progress-by-id`,we=r=>`${r}-response-progress`,Oe=r=>`${r}-response-progress-by-id`;var dt=r=>({emitLoading:(e,t,s)=>{r.emit(fe(t),s),r.emit(he(e),s)},emitRequestStart:(e,t,s)=>{r.emit(xe(t),s),r.emit(qe(e),s)},emitResponseStart:(e,t,s)=>{r.emit(Ae(t),s),r.emit(Pe(e),s)},emitUploadProgress:(e,t,s,n)=>{r.emit(Ce(t),s,n),r.emit(Se(e),s,n)},emitDownloadProgress:(e,t,s,n)=>{r.emit(Oe(t),s,n),r.emit(we(e),s,n)},emitResponse:(e,t,s,n)=>{r.emit(ve(t),s,n),r.emit(be(e),s,n)},emitAbort:(e,t,s)=>{r.emit(Ee(t),s),r.emit(Te(e),s)},emitRemove:(e,t,s)=>{r.emit(Re(e),s),r.emit(me(t),s)},onLoading:(e,t)=>(r.on(he(e),t),()=>r.removeListener(he(e),t)),onLoadingById:(e,t)=>(r.on(fe(e),t),()=>r.removeListener(fe(e),t)),onRequestStart:(e,t)=>(r.on(qe(e),t),()=>r.removeListener(qe(e),t)),onRequestStartById:(e,t)=>(r.on(xe(e),t),()=>r.removeListener(xe(e),t)),onResponseStart:(e,t)=>(r.on(Pe(e),t),()=>r.removeListener(Pe(e),t)),onResponseStartById:(e,t)=>(r.on(Ae(e),t),()=>r.removeListener(Ae(e),t)),onUploadProgress:(e,t)=>(r.on(Se(e),t),()=>r.removeListener(Se(e),t)),onUploadProgressById:(e,t)=>(r.on(Ce(e),t),()=>r.removeListener(Ce(e),t)),onDownloadProgress:(e,t)=>(r.on(we(e),t),()=>r.removeListener(we(e),t)),onDownloadProgressById:(e,t)=>(r.on(Oe(e),t),()=>r.removeListener(Oe(e),t)),onResponse:(e,t)=>(r.on(be(e),t),()=>r.removeListener(be(e),t)),onResponseById:(e,t)=>(r.on(ve(e),t),()=>r.removeListener(ve(e),t)),onAbort:(e,t)=>(r.on(Te(e),t),()=>r.removeListener(Te(e),t)),onAbortById:(e,t)=>(r.on(Ee(e),t),()=>r.removeListener(Ee(e),t)),onRemove:(e,t)=>(r.on(Re(e),t),()=>r.removeListener(Re(e),t)),onRemoveById:(e,t)=>(r.on(me(e),t),()=>r.removeListener(me(e),t))});var $t=se(require("events"));var Ie=class{constructor(e,t){this.client=e;this.options=t;this.emitter=new $t.default;this.setSeverity=e=>{this.severity=e};this.init=e=>({error:(t,...s)=>{this.logger({level:"error",module:e,message:t,additionalData:s,severity:this.severity,enabled:this.client.debug})},warning:(t,...s)=>{this.logger({level:"warning",module:e,message:t,additionalData:s,severity:this.severity,enabled:this.client.debug})},info:(t,...s)=>{this.logger({level:"info",module:e,message:t,additionalData:s,severity:this.severity,enabled:this.client.debug})},debug:(t,...s)=>{this.logger({level:"debug",module:e,message:t,additionalData:s,severity:this.severity,enabled:this.client.debug})}});var s,n;this.logger=((s=this.options)==null?void 0:s.logger)||gt,this.severity=((n=this.options)==null?void 0:n.severity)||2}};var _t=()=>{let r=new Date;return`${r.toLocaleTimeString()}(:${r.getMilliseconds()})`},gt=r=>{var e;if(r.enabled&&r.severity>=ft[r.level]){let t=yt[r.level],s=ht[r.level],n=`%c[${r.module}]:[${_t()}]:`,o=`${s}${n} ${r.message}`;(e=r.additionalData)!=null&&e.length?(console.groupCollapsed(o,t),r.additionalData.forEach(u=>{console.log(u)}),console.groupEnd()):console.log(o,t)}};var Ue="background:rgba(0,0,0,0.2);padding:2px 5px;border-radius:5px;font-weight:bold;",yt={error:`${Ue}color:#db2525`,warning:`${Ue}color:#e1941e`,info:`${Ue}color:#1e74e1`,debug:`${Ue}color:#adadad`},ht={error:"\u{1F6A8}",warning:"\u{1F6A7}",info:"\u2139\uFE0F",debug:"\u{1F6E9}\uFE0F"},ft={error:0,warning:1,info:2,debug:3};var Vt=r=>{try{return JSON.stringify(r)}catch(e){return""}},Ne=(r,e)=>d(void 0,null,function*(){let t=e;if(!e.requestOptions.disableRequestInterceptors){for(let s of r)if(t=yield s(e),!t)throw new Error("Request modifier must return request")}return t}),Qe=(r,e,t)=>d(void 0,null,function*(){let s=e;if(!t.requestOptions.disableResponseInterceptors){for(let n of r)if(s=yield n(e,t),!s)throw new Error("Response modifier must return data")}return s}),Rt=r=>{let e=r.data instanceof FormData,t={};return e||(t["Content-Type"]="application/json"),Object.assign(t,r.headers),t},mt=r=>r instanceof FormData?r:Vt(r),Gt=r=>e=>{let{skipNull:t,skipEmptyString:s}=r;return!(s&&e===void 0||s&&e===""||t&&e===null)},L=(r,{encode:e,strict:t})=>e&&t?encodeURIComponent(r).replace(/[!'()*]/g,s=>`%${s.charCodeAt(0).toString(16).toUpperCase()}`):e?encodeURIComponent(r):r,Yt=(r,e,t)=>{let s=!Gt(t)(e);return!r||s?"":`${L(r,t)}=${L(String(e),t)}`},Zt=(r,e,t)=>{let{arrayFormat:s,arraySeparator:n}=t;return e.filter(Gt(t)).reduce((o,u,p)=>{switch(s){case"index":{let a=`${L(r,t)}[${L(String(p),t)}]=`;o.push(`${a}${L(String(u),t)}`);break}case"bracket":{let a=`${L(r,t)}[]=`;o.push(`${a}${L(String(u),t)}`);break}case"comma":{let a=!o.length&&`${L(r,t)}=`||"";return[[...o,`${a}${L(String(u),t)}`].join(",")]}case"separator":{let a=!o.length&&`${L(r,t)}=`||"";return[[...o,`${a}${L(String(u),t)}`].join(n||"|")]}case"bracket-separator":{let a=!o.length&&`${L(r,t)}[]=`||"";return[[...o,`${a}${L(String(u),t)}`].join(n||"|")]}default:{let a=`${L(r,t)}=`;o.push(`${a}${L(String(u),t)}`)}}return o},[]).join("&")},Tt=(r,e=Et)=>{if(!r||!Object.keys(r).length)return"";if(typeof r=="string")return r[0]==="?"?r:`?${r}`;let t=Object.entries(r).map(([s,n])=>Array.isArray(n)?Zt(s,n,e):Yt(s,n,e)).filter(Boolean).join("&");return t?`?${t}`:""};var bt=class{constructor(e){this.options=e;this.__onErrorCallbacks=[];this.__onSuccessCallbacks=[];this.__onResponseCallbacks=[];this.__onAuthCallbacks=[];this.__onRequestCallbacks=[];this.requestManager=new ye;this.loggerManager=new Ie(this);this.effects=[];this.stringifyQueryParams=e=>Tt(e,this.queryParamsConfig);this.headerMapper=Rt;this.payloadMapper=mt;this.logger=this.loggerManager.init("Client");this.setRequestDefaultOptions=e=>(this.requestDefaultOptions=e,this);this.setAdapterDefaultOptions=e=>(this.adapterDefaultOptions=e,this);this.setDebug=e=>(this.debug=e,this);this.setLoggerSeverity=e=>(this.loggerManager.setSeverity(e),this);this.setLogger=e=>(this.loggerManager=e(this),this);this.setQueryParamsConfig=e=>(this.queryParamsConfig=e,this);this.setStringifyQueryParams=e=>(this.stringifyQueryParams=e,this);this.setHeaderMapper=e=>(this.headerMapper=e,this);this.setPayloadMapper=e=>(this.payloadMapper=e,this);this.setAdapter=e=>(this.adapter=e(this),this);this.onAuth=e=>(this.__onAuthCallbacks.push(e),this);this.onError=e=>(this.__onErrorCallbacks.push(e),this);this.onSuccess=e=>(this.__onSuccessCallbacks.push(e),this);this.onRequest=e=>(this.__onRequestCallbacks.push(e),this);this.onResponse=e=>(this.__onResponseCallbacks.push(e),this);this.addEffect=e=>(this.effects=this.effects.concat(e),this);this.removeEffect=e=>{let t=typeof e=="string"?e:e.getEffectKey();return this.effects=this.effects.filter(s=>s.getEffectKey()!==t),this};this.__modifyAuth=e=>d(this,null,function*(){return Ne(this.__onAuthCallbacks,e)});this.__modifyRequest=e=>d(this,null,function*(){return Ne(this.__onRequestCallbacks,e)});this.__modifyErrorResponse=(e,t)=>d(this,null,function*(){return Qe(this.__onErrorCallbacks,e,t)});this.__modifySuccessResponse=(e,t)=>d(this,null,function*(){return Qe(this.__onSuccessCallbacks,e,t)});this.__modifyResponse=(e,t)=>d(this,null,function*(){return Qe(this.__onResponseCallbacks,e,t)});this.clear=()=>{let{appManager:e,cache:t,fetchDispatcher:s,submitDispatcher:n}=this.options;this.requestManager.abortControllers.clear(),this.fetchDispatcher.clear(),this.submitDispatcher.clear(),this.cache.clear(),this.requestManager.emitter.removeAllListeners(),this.fetchDispatcher.emitter.removeAllListeners(),this.submitDispatcher.emitter.removeAllListeners(),this.cache.emitter.removeAllListeners(),this.appManager=(e==null?void 0:e(this))||new J,this.cache=(t==null?void 0:t(this))||new W(this),this.fetchDispatcher=(s==null?void 0:s(this))||new H(this),this.submitDispatcher=(n==null?void 0:n(this))||new H(this)};this.createRequest=()=>e=>new _(this,e);let{url:t,adapter:s,appManager:n,cache:o,fetchDispatcher:u,submitDispatcher:p}=this.options;this.url=t,this.adapter=s||Je,this.appManager=(n==null?void 0:n(this))||new J,this.cache=(o==null?void 0:o(this))||new W(this),this.fetchDispatcher=(u==null?void 0:u(this))||new H(this),this.submitDispatcher=(p==null?void 0:p(this))||new H(this)}};var Et={strict:!0,encode:!0,arrayFormat:"bracket",arraySeparator:"",sort:!1,skipNull:!0,skipEmptyString:!0};
2
- //# sourceMappingURL=index.cjs.js.map