@d1g1tal/transportr 3.3.3 → 3.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -790,18 +790,35 @@ type RequestEvent = (typeof RequestEvent)[keyof typeof RequestEvent];
790
790
  */
791
791
  declare class Transportr {
792
792
  private readonly _baseUrl;
793
+ private readonly _origin;
794
+ /** Pre-normalized base pathname with any trailing slash stripped — reused per request to avoid repeated regex/replace work. */
795
+ private readonly _basePath;
793
796
  private readonly _options;
797
+ /** Pre-built Headers template for methods that strip Content-Type (GET/HEAD/OPTIONS/etc.). Cloned per request. Rebuilt by `configure()` when defaults change. */
798
+ private _noBodyHeadersTemplate;
794
799
  private readonly subscribr;
795
800
  private readonly hooks;
801
+ /** Aggregate count of hooks registered on this instance — zero phases are skipped without array allocation. */
802
+ private readonly hookCount;
803
+ /** Per-event subscription counts on this instance — used to skip publish() entirely when no listeners exist. */
804
+ private readonly subCounts;
796
805
  private static globalSubscribr;
797
806
  private static globalHooks;
807
+ /** Aggregate count of registered global hooks — zero means we skip the entire global-hook loop. */
808
+ private static globalHookCount;
809
+ /** Per-event subscription counts on the global subscribr — mirrors `subCounts` per instance. */
810
+ private static globalSubCounts;
798
811
  private static signalControllers;
799
812
  /** Map of in-flight deduplicated requests keyed by URL + method */
800
813
  private static inflightRequests;
801
814
  /** Cached config for the common "no retry" case (retry === undefined) */
802
815
  private static readonly noRetryConfig;
816
+ /** Memoized normalized retry options keyed by the user-provided RetryOptions object (reference identity). */
817
+ private static readonly retryConfigCache;
803
818
  /** Cache for parsed MediaType instances to avoid re-parsing the same content-type strings */
804
819
  private static mediaTypeCache;
820
+ /** Cache mapping raw response Content-Type header strings to their resolved ResponseHandler (or null when no handler matches). */
821
+ private static readonly handlerResolutionCache;
805
822
  private static contentTypeHandlers;
806
823
  /**
807
824
  * Create a new Transportr instance with the provided location or origin and context path.
@@ -1145,11 +1162,51 @@ declare class Transportr {
1145
1162
  private _get;
1146
1163
  /**
1147
1164
  * It processes the request options and returns a new object with the processed options.
1165
+ * Hot path: when no retry, no dedupe, and no upload/download progress tracking, this is essentially
1166
+ * `fetch(url, options)` with two `Set` operations and one event publish bracket — all inner closures have been hoisted
1167
+ * to private static helpers to avoid per-request allocations.
1148
1168
  * @param path The path to the resource.
1149
- * @param processedRequestOptions The user options for the request.
1150
- * @returns A new object with the processed options.
1169
+ * @param config The processed request configuration produced by `processRequestOptions`.
1170
+ * @returns A promise resolving to the typed response.
1151
1171
  */
1152
1172
  private _request;
1173
+ /**
1174
+ * Performs the underlying fetch with retry logic. Hoisted out of `_request` so the function body
1175
+ * does not allocate a closure per request.
1176
+ * @param url The fully-resolved request URL.
1177
+ * @param requestOptions The processed request options.
1178
+ * @param path The original request path (used in error/retry events).
1179
+ * @param method The HTTP method.
1180
+ * @param canRetry Whether the request is eligible for retry.
1181
+ * @param retryConfig Normalized retry configuration.
1182
+ * @param originalBody The original (pre-upload-wrap) body, needed to rebuild the upload stream on retry.
1183
+ * @param onUploadProgress Optional upload progress callback.
1184
+ * @param startTime The performance.now() timestamp captured at request start (for timing reporting).
1185
+ * @param global Whether this request publishes to global event subscribers.
1186
+ * @returns The typed response.
1187
+ */
1188
+ private _doFetch;
1189
+ /**
1190
+ * Wraps the request body with a progress-tracking TransformStream.
1191
+ * Re-creates the stream from the original body on each call so retries get a fresh stream.
1192
+ * @param requestOptions Mutable request options whose `body` will be replaced with the wrapped stream.
1193
+ * @param originalBody The original body before any wrapping.
1194
+ * @param onUploadProgress The progress callback (already validated as defined by the caller).
1195
+ */
1196
+ private static _wrapUploadBody;
1197
+ /**
1198
+ * Wraps the response body with a progress-tracking TransformStream when onDownloadProgress is set.
1199
+ * @param response The response to potentially wrap.
1200
+ * @param requestOptions The request options carrying the optional onDownloadProgress callback.
1201
+ * @returns The original response or a new response with progress tracking.
1202
+ */
1203
+ private static _wrapDownloadProgress;
1204
+ /**
1205
+ * Captures a RequestTiming snapshot from a start timestamp to now.
1206
+ * @param startTime The start timestamp from `performance.now()`.
1207
+ * @returns Timing information for the request.
1208
+ */
1209
+ private static _snapshotTiming;
1153
1210
  /**
1154
1211
  * Normalizes a retry option into a full RetryOptions object.
1155
1212
  * @param retry The retry option from request options.
@@ -1173,6 +1230,33 @@ declare class Transportr {
1173
1230
  * @returns A promise that resolves to the response body.
1174
1231
  */
1175
1232
  private executeBodyMethod;
1233
+ /**
1234
+ * Runs the beforeRequest hook chain (global → instance → per-request).
1235
+ * Returns immediately if no hooks of any kind are registered, allocating nothing.
1236
+ * @param requestOptions Mutable request options (hooks may patch via Object.assign).
1237
+ * @param url The current request URL.
1238
+ * @param path The original path argument (used to rebuild the URL when hooks update searchParams).
1239
+ * @param perRequest Per-request beforeRequest hooks, if any.
1240
+ * @returns The (possibly rebuilt) request URL.
1241
+ */
1242
+ private runBeforeRequestHooks;
1243
+ /**
1244
+ * Runs the afterResponse hook chain (global → instance → per-request).
1245
+ * Returns the input response untouched when no hooks are registered.
1246
+ * @param response The current response.
1247
+ * @param requestOptions The original request options passed to each hook.
1248
+ * @param perRequest Per-request afterResponse hooks, if any.
1249
+ * @returns The (possibly replaced) response.
1250
+ */
1251
+ private runAfterResponseHooks;
1252
+ /**
1253
+ * Runs the beforeError hook chain (global → instance → per-request).
1254
+ * Returns the input error untouched when no hooks are registered.
1255
+ * @param error The current HttpError.
1256
+ * @param perRequest Per-request beforeError hooks, if any.
1257
+ * @returns The (possibly transformed) error.
1258
+ */
1259
+ private runBeforeErrorHooks;
1176
1260
  /**
1177
1261
  * It returns a response handler based on the content type of the response.
1178
1262
  * @param path The path to the resource.
@@ -1205,8 +1289,12 @@ declare class Transportr {
1205
1289
  private static mergeSearchParams;
1206
1290
  /**
1207
1291
  * Processes request options by merging user, instance, and method-specific options.
1208
- * This method optimizes performance by using cached instance options and performing
1209
- * shallow merges where possible instead of deep object cloning.
1292
+ *
1293
+ * Hot path optimizations:
1294
+ * - No parameter destructuring (avoids two transient rest objects per call).
1295
+ * - Skips Headers/URLSearchParams construction entirely when neither user nor method overrides supply them.
1296
+ * - Reuses the pre-stripped `_noBodyHeadersTemplate` for non-body methods so we never have to delete `content-type` per request.
1297
+ * - Builds `requestOptions` via `Object.assign` with a stable property order to keep V8 hidden classes monomorphic.
1210
1298
  * @param userOptions The user-provided options for the request.
1211
1299
  * @param options Additional method-specific options.
1212
1300
  * @returns Processed request options with signal controller and global flag.
@@ -1228,7 +1316,9 @@ declare class Transportr {
1228
1316
  private static getOrParseMediaType;
1229
1317
  /**
1230
1318
  * Creates a new URL with the given path and search parameters.
1231
- * @param url The base URL.
1319
+ * Uses the pre-normalized base pathname/origin to avoid per-request regex work.
1320
+ * Polymorphic on the first arg to preserve the legacy direct-URL test API.
1321
+ * @param source A Transportr instance (preferred) or a base URL.
1232
1322
  * @param path The path to append to the base URL.
1233
1323
  * @param searchParams The search parameters to append to the URL.
1234
1324
  * @returns A new URL with the given path and search parameters.
@@ -1252,6 +1342,8 @@ declare class Transportr {
1252
1342
  private handleError;
1253
1343
  /**
1254
1344
  * Publishes an event to the global and instance event handlers.
1345
+ * Skips entirely when no subscribers are registered for the event — the common case in production —
1346
+ * which avoids both the CustomEvent allocation and the validateEventName/forEach overhead inside Subscribr.
1255
1347
  * @param eventObject The event object to publish.
1256
1348
  */
1257
1349
  private publish;
@@ -1,8 +1,9 @@
1
- var M=/^[-!#$%&'*+.^_`|~A-Za-z0-9]*$/u,Me=/(["\\])/ug,Ie=/^[\t\u0020-\u007E\u0080-\u00FF]*$/u,ae=class ue extends Map{constructor(e=[]){super(e)}static isValid(e,t){return M.test(e)&&Ie.test(t)}get(e){return super.get(e.toLowerCase())}has(e){return super.has(e.toLowerCase())}set(e,t){if(!ue.isValid(e,t))throw new Error(`Invalid media type parameter name/value: ${e}/${t}`);return super.set(e.toLowerCase(),t),this}delete(e){return super.delete(e.toLowerCase())}toString(){return Array.from(this).map(([e,t])=>`;${e}=${!t||!M.test(t)?`"${t.replace(Me,"\\$1")}"`:t}`).join("")}get[Symbol.toStringTag](){return"MediaTypeParameters"}},Le=new Set([" "," ",`
2
- `,"\r"]),Ne=/[ \t\n\r]+$/u,De=/^[ \t\n\r]+|[ \t\n\r]+$/ug,_e=class O{static parse(e){e=e.replace(De,"");let t=0,[n,r]=O.collect(e,t,["/"]);if(t=r,!n.length||t>=e.length||!M.test(n))throw new TypeError(O.generateErrorMessage("type",n));++t;let[o,i]=O.collect(e,t,[";"],!0,!0);if(t=i,!o.length||!M.test(o))throw new TypeError(O.generateErrorMessage("subtype",o));let a=new ae;for(;t<e.length;){for(++t;Le.has(e[t]);)++t;let u;if([u,t]=O.collect(e,t,[";","="],!1),t>=e.length||e[t]===";")continue;++t;let p;if(e[t]==='"')for([p,t]=O.collectHttpQuotedString(e,t);t<e.length&&e[t]!==";";)++t;else if([p,t]=O.collect(e,t,[";"],!1,!0),!p)continue;u&&ae.isValid(u,p)&&!a.has(u)&&a.set(u,p)}return{type:n,subtype:o,parameters:a}}get[Symbol.toStringTag](){return"MediaTypeParser"}static collect(e,t,n,r=!0,o=!1){let i="";for(let{length:a}=e;t<a&&!n.includes(e[t]);t++)i+=e[t];return r&&(i=i.toLowerCase()),o&&(i=i.replace(Ne,"")),[i,t]}static collectHttpQuotedString(e,t){let n="";for(let r=e.length,o;++t<r&&(o=e[t])!=='"';)n+=o=="\\"&&++t<r?e[t]:o;return[n,t]}static generateErrorMessage(e,t){return`Invalid ${e} "${t}": only HTTP token code points are valid.`}},T=class le{_type;_subtype;_parameters;constructor(e,t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("The parameters argument must be an object");({type:this._type,subtype:this._subtype,parameters:this._parameters}=_e.parse(e));for(let[n,r]of Object.entries(t))this._parameters.set(n,r)}static parse(e){try{return new le(e)}catch{}return null}get type(){return this._type}get subtype(){return this._subtype}get essence(){return`${this._type}/${this._subtype}`}get parameters(){return this._parameters}matches(e){return typeof e=="string"?this.essence.includes(e):this._type===e._type&&this._subtype===e._subtype}toString(){return`${this.essence}${this._parameters.toString()}`}get[Symbol.toStringTag](){return"MediaType"}};var je=class extends Map{set(s,e){return super.set(s,e instanceof Set?e:(super.get(s)??new Set).add(e)),this}getOrInsert(s,e){return this.has(s)?super.get(s):(super.set(s,e instanceof Set?e:(super.get(s)??new Set).add(e)),e)}getOrInsertComputed(s,e){if(this.has(s))return super.get(s);let t=e(s);return super.set(s,t instanceof Set?t:(super.get(s)??new Set).add(t)),t}find(s,e){let t=this.get(s);if(t!==void 0)return Array.from(t).find(e)}hasValue(s,e){let t=super.get(s);return t?t.has(e):!1}deleteValue(s,e){if(e===void 0)return this.delete(s);let t=super.get(s);if(t){let n=t.delete(e);return t.size===0&&super.delete(s),n}return!1}get[Symbol.toStringTag](){return"SetMultiMap"}},Fe=class{context;eventHandler;constructor(s,e){this.context=s,this.eventHandler=e}handle(s,e){this.eventHandler.call(this.context,s,e)}get[Symbol.toStringTag](){return"ContextEventHandler"}},Je=class{_eventName;_contextEventHandler;constructor(s,e){this._eventName=s,this._contextEventHandler=e}get eventName(){return this._eventName}get contextEventHandler(){return this._contextEventHandler}get[Symbol.toStringTag](){return"Subscription"}},I=class{subscribers=new je;errorHandler;setErrorHandler(s){this.errorHandler=s}subscribe(s,e,t=e,n){if(this.validateEventName(s),n?.once){let i=e;e=(a,u)=>{i.call(t,a,u),this.unsubscribe(o)}}let r=new Fe(t,e);this.subscribers.set(s,r);let o=new Je(s,r);return o}unsubscribe({eventName:s,contextEventHandler:e}){let t=this.subscribers.get(s)??new Set,n=t.delete(e);return n&&t.size===0&&this.subscribers.delete(s),n}publish(s,e=new CustomEvent(s),t){this.validateEventName(s),this.subscribers.get(s)?.forEach(n=>{try{n.handle(e,t)}catch(r){this.errorHandler?this.errorHandler(r,s,e,t):console.error(`Error in event handler for '${s}':`,r)}})}isSubscribed({eventName:s,contextEventHandler:e}){return this.subscribers.get(s)?.has(e)??!1}validateEventName(s){if(!s||typeof s!="string")throw new TypeError("Event name must be a non-empty string");if(s.trim()!==s)throw new Error("Event name cannot have leading or trailing whitespace")}destroy(){this.subscribers.clear()}get[Symbol.toStringTag](){return"Subscribr"}};var B=class extends Error{_entity;responseStatus;_url;_method;_timing;constructor(e,{message:t,cause:n,entity:r,url:o,method:i,timing:a}={}){super(t,{cause:n}),this._entity=r,this.responseStatus=e,this._url=o,this._method=i,this._timing=a}get entity(){return this._entity}get statusCode(){return this.responseStatus.code}get statusText(){return this.responseStatus?.text}get url(){return this._url}get method(){return this._method}get timing(){return this._timing}get name(){return"HttpError"}get[Symbol.toStringTag](){return this.name}};var w=class{_code;_text;constructor(e,t){this._code=e,this._text=t}get code(){return this._code}get text(){return this._text}get[Symbol.toStringTag](){return"ResponseStatus"}toString(){return`${this._code} ${this._text}`}};var v={charset:"utf-8"},de=/\/$/,ce="XSRF-TOKEN",pe="X-XSRF-TOKEN",m={PNG:new T("image/png"),TEXT:new T("text/plain",v),JSON:new T("application/json",v),HTML:new T("text/html",v),JAVA_SCRIPT:new T("text/javascript",v),CSS:new T("text/css",v),XML:new T("application/xml",v),BIN:new T("application/octet-stream"),EVENT_STREAM:new T("text/event-stream",v),NDJSON:new T("application/x-ndjson",v)},G=m.JSON.toString(),X=globalThis.location?.origin??"http://localhost",fe={DEFAULT:"default",FORCE_CACHE:"force-cache",NO_CACHE:"no-cache",NO_STORE:"no-store",ONLY_IF_CACHED:"only-if-cached",RELOAD:"reload"},b={CONFIGURED:"configured",SUCCESS:"success",ERROR:"error",ABORTED:"aborted",TIMEOUT:"timeout",RETRY:"retry",COMPLETE:"complete",ALL_COMPLETE:"all-complete"},P={ABORT:"abort",TIMEOUT:"timeout"},H={ABORT:"AbortError",TIMEOUT:"TimeoutError"},k={once:!0,passive:!0},L=()=>new CustomEvent(P.ABORT,{detail:{cause:H.ABORT}}),Re=()=>new CustomEvent(P.TIMEOUT,{detail:{cause:H.TIMEOUT}}),he=["POST","PUT","PATCH","DELETE"],ge=new w(500,"Internal Server Error"),me=new w(499,"Aborted"),ye=new w(504,"Request Timeout"),V=[408,413,429,500,502,503,504],z=["GET","PUT","HEAD","DELETE","OPTIONS"],N=300,D=2;var _=class{abortSignal;abortController=new AbortController;events=new Map;constructor({signal:e,timeout:t=1/0}={}){if(t<0)throw new RangeError("The timeout cannot be negative");let n=[this.abortController.signal];e!=null&&n.push(e),t!==1/0&&n.push(AbortSignal.timeout(t)),(this.abortSignal=AbortSignal.any(n)).addEventListener(P.ABORT,this,k)}handleEvent({target:{reason:e}}){this.abortController.signal.aborted||e instanceof DOMException&&e.name===H.TIMEOUT&&this.abortSignal.dispatchEvent(Re())}get signal(){return this.abortSignal}onAbort(e){return this.addEventListener(P.ABORT,e)}onTimeout(e){return this.addEventListener(P.TIMEOUT,e)}abort(e=L()){this.abortController.abort(e.detail?.cause)}destroy(){this.abortSignal.removeEventListener(P.ABORT,this,k);for(let[e,t]of this.events)this.abortSignal.removeEventListener(t,e,k);return this.events.clear(),this}addEventListener(e,t){return this.abortSignal.addEventListener(e,t,k),this.events.set(t,e),this}get[Symbol.toStringTag](){return"SignalController"}};var j,W,F=()=>j||(j=(typeof document>"u"||typeof DOMParser>"u"||typeof DocumentFragment>"u"?import("jsdom").then(({JSDOM:e})=>{let{window:t}=new e("<!DOCTYPE html><html><head></head><body></body></html>",{url:"http://localhost"});globalThis.window=t,Object.assign(globalThis,{document:t.document,DOMParser:t.DOMParser,DocumentFragment:t.DocumentFragment})}).catch(()=>{throw j=void 0,new Error("jsdom is required for HTML/XML/DOM features in Node.js environments. Install it with: npm install jsdom")}):Promise.resolve()).then(()=>import("./OP3JQ447.js")).then(({default:e})=>{W=e})),be=async(s,e)=>(await F(),new DOMParser().parseFromString(W.sanitize(await s.text()),e)),K=async(s,e)=>{await F();let t=URL.createObjectURL(await s.blob());try{return new Promise((n,r)=>e(t,n,r))}finally{URL.revokeObjectURL(t)}},Te=async s=>await s.text(),Y=s=>K(s,(e,t,n)=>{let r=document.createElement("script");Object.assign(r,{src:e,type:"text/javascript",async:!0}),r.onload=()=>{document.head.removeChild(r),t()},r.onerror=()=>{document.head.removeChild(r),n(new Error("Script failed to load"))},document.head.appendChild(r)}),Q=s=>K(s,(e,t,n)=>{let r=document.createElement("link");Object.assign(r,{href:e,type:"text/css",rel:"stylesheet"}),r.onload=()=>t(),r.onerror=()=>{document.head.removeChild(r),n(new Error("Stylesheet load failed"))},document.head.appendChild(r)}),Z=async s=>await s.json(),Ee=async s=>await s.blob(),ee=s=>K(s,(e,t,n)=>{let r=new Image;r.onload=()=>t(r),r.onerror=()=>n(new Error("Image failed to load")),r.src=e}),Se=async s=>await s.arrayBuffer(),te=async s=>Promise.resolve(s.body),se=async s=>be(s,"application/xml"),ne=async s=>be(s,"text/html"),Oe=async s=>(await F(),document.createRange().createContextualFragment(W.sanitize(await s.text()))),we=async s=>(await F(),document.createRange().createContextualFragment(await s.text()));async function*ve(s,e,t){let n=s.getReader(),r=new TextDecoder,o="";try{for(;;){let i;for(;(i=o.indexOf(e))!==-1;)yield o.slice(0,i),o=o.slice(i+e.length);let{done:a,value:u}=await n.read();if(a)break;o+=r.decode(u,{stream:!0})}if(t){let i=(o+r.decode()).trim();i&&(yield i)}}finally{await n.cancel()}}var $e=s=>{let e="message",t="",n,r=[],o=s.split(`
3
- `);for(let i=0,a=o.length;i<a;i++){let u=o[i];if(u.charCodeAt(0)===58)continue;let p=u.indexOf(":"),R,d;switch(p===-1?(R=u,d=""):(R=u.slice(0,p),d=u.charCodeAt(p+1)===32?u.slice(p+2):u.slice(p+1)),R){case"event":e=d;break;case"data":r.push(d);break;case"id":t=d;break;case"retry":{let h=parseInt(d,10);isNaN(h)||(n=h);break}}}return r.length>0||e!=="message"?{event:e,data:r.join(`
4
- `),id:t,retry:n}:void 0},qe=s=>({async*[Symbol.asyncIterator](){for await(let e of ve(s.body,`
1
+ var k=/^[-!#$%&'*+.^_`|~A-Za-z0-9]*$/u,Be=/(["\\])/ug,ke=/^[\t\u0020-\u007E\u0080-\u00FF]*$/u,re=class oe extends Map{constructor(e=[]){super(e)}static isValid(e,t){return k.test(e)&&ke.test(t)}get(e){return super.get(e.toLowerCase())}has(e){return super.has(e.toLowerCase())}set(e,t){if(!oe.isValid(e,t))throw new Error(`Invalid media type parameter name/value: ${e}/${t}`);return super.set(e.toLowerCase(),t),this}delete(e){return super.delete(e.toLowerCase())}toString(){return Array.from(this).map(([e,t])=>`;${e}=${!t||!k.test(t)?`"${t.replace(Be,"\\$1")}"`:t}`).join("")}get[Symbol.toStringTag](){return"MediaTypeParameters"}},xe=new Set([" "," ",`
2
+ `,"\r"]),Le=/[ \t\n\r]+$/u,Ue=/^[ \t\n\r]+|[ \t\n\r]+$/ug,Me=class E{static parse(e){e=e.replace(Ue,"");let t=0,[r,s]=E.collect(e,t,["/"]);if(t=s,!r.length||t>=e.length||!k.test(r))throw new TypeError(E.generateErrorMessage("type",r));++t;let[o,i]=E.collect(e,t,[";"],!0,!0);if(t=i,!o.length||!k.test(o))throw new TypeError(E.generateErrorMessage("subtype",o));let a=new re;for(;t<e.length;){for(++t;xe.has(e[t]);)++t;let u;if([u,t]=E.collect(e,t,[";","="],!1),t>=e.length||e[t]===";")continue;++t;let l;if(e[t]==='"')for([l,t]=E.collectHttpQuotedString(e,t);t<e.length&&e[t]!==";";)++t;else if([l,t]=E.collect(e,t,[";"],!1,!0),!l)continue;u&&re.isValid(u,l)&&!a.has(u)&&a.set(u,l)}return{type:r,subtype:o,parameters:a}}get[Symbol.toStringTag](){return"MediaTypeParser"}static collect(e,t,r,s=!0,o=!1){let i="";for(let{length:a}=e;t<a&&!r.includes(e[t]);t++)i+=e[t];return s&&(i=i.toLowerCase()),o&&(i=i.replace(Le,"")),[i,t]}static collectHttpQuotedString(e,t){let r="";for(let s=e.length,o;++t<s&&(o=e[t])!=='"';)r+=o=="\\"&&++t<s?e[t]:o;return[r,t]}static generateErrorMessage(e,t){return`Invalid ${e} "${t}": only HTTP token code points are valid.`}},y=class ie{_type;_subtype;_parameters;constructor(e,t={}){if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError("The parameters argument must be an object");({type:this._type,subtype:this._subtype,parameters:this._parameters}=Me.parse(e));for(let[r,s]of Object.entries(t))this._parameters.set(r,s)}static parse(e){try{return new ie(e)}catch{}return null}get type(){return this._type}get subtype(){return this._subtype}get essence(){return`${this._type}/${this._subtype}`}get parameters(){return this._parameters}matches(e){return typeof e=="string"?this.essence.includes(e):this._type===e._type&&this._subtype===e._subtype}toString(){return`${this.essence}${this._parameters.toString()}`}get[Symbol.toStringTag](){return"MediaType"}};var Ie=class extends Map{set(n,e){return super.set(n,e instanceof Set?e:(super.get(n)??new Set).add(e)),this}getOrInsert(n,e){return this.has(n)?super.get(n):(super.set(n,e instanceof Set?e:(super.get(n)??new Set).add(e)),e)}getOrInsertComputed(n,e){if(this.has(n))return super.get(n);let t=e(n);return super.set(n,t instanceof Set?t:(super.get(n)??new Set).add(t)),t}find(n,e){let t=this.get(n);if(t!==void 0)return Array.from(t).find(e)}hasValue(n,e){let t=super.get(n);return t?t.has(e):!1}deleteValue(n,e){if(e===void 0)return this.delete(n);let t=super.get(n);if(t){let r=t.delete(e);return t.size===0&&super.delete(n),r}return!1}get[Symbol.toStringTag](){return"SetMultiMap"}},Ne=class{context;eventHandler;constructor(n,e){this.context=n,this.eventHandler=e}handle(n,e){this.eventHandler.call(this.context,n,e)}get[Symbol.toStringTag](){return"ContextEventHandler"}},De=class{_eventName;_contextEventHandler;constructor(n,e){this._eventName=n,this._contextEventHandler=e}get eventName(){return this._eventName}get contextEventHandler(){return this._contextEventHandler}get[Symbol.toStringTag](){return"Subscription"}},x=class{subscribers=new Ie;errorHandler;setErrorHandler(n){this.errorHandler=n}subscribe(n,e,t=e,r){if(this.validateEventName(n),r?.once){let i=e;e=(a,u)=>{i.call(t,a,u),this.unsubscribe(o)}}let s=new Ne(t,e);this.subscribers.set(n,s);let o=new De(n,s);return o}unsubscribe({eventName:n,contextEventHandler:e}){let t=this.subscribers.get(n)??new Set,r=t.delete(e);return r&&t.size===0&&this.subscribers.delete(n),r}publish(n,e=new CustomEvent(n),t){this.validateEventName(n),this.subscribers.get(n)?.forEach(r=>{try{r.handle(e,t)}catch(s){this.errorHandler?this.errorHandler(s,n,e,t):console.error(`Error in event handler for '${n}':`,s)}})}isSubscribed({eventName:n,contextEventHandler:e}){return this.subscribers.get(n)?.has(e)??!1}validateEventName(n){if(!n||typeof n!="string")throw new TypeError("Event name must be a non-empty string");if(n.trim()!==n)throw new Error("Event name cannot have leading or trailing whitespace")}destroy(){this.subscribers.clear()}get[Symbol.toStringTag](){return"Subscribr"}};var S=class extends Error{_entity;responseStatus;_url;_method;_timing;constructor(e,{message:t,cause:r,entity:s,url:o,method:i,timing:a}={}){super(t,{cause:r}),this._entity=s,this.responseStatus=e,this._url=o,this._method=i,this._timing=a}get entity(){return this._entity}get statusCode(){return this.responseStatus.code}get statusText(){return this.responseStatus?.text}get url(){return this._url}get method(){return this._method}get timing(){return this._timing}get name(){return"HttpError"}get[Symbol.toStringTag](){return this.name}};var w=class{_code;_text;constructor(e,t){this._code=e,this._text=t}get code(){return this._code}get text(){return this._text}get[Symbol.toStringTag](){return"ResponseStatus"}toString(){return`${this._code} ${this._text}`}};var O={charset:"utf-8"};var ae="XSRF-TOKEN",ue="X-XSRF-TOKEN",R={PNG:new y("image/png"),TEXT:new y("text/plain",O),JSON:new y("application/json",O),HTML:new y("text/html",O),JAVA_SCRIPT:new y("text/javascript",O),CSS:new y("text/css",O),XML:new y("application/xml",O),BIN:new y("application/octet-stream"),EVENT_STREAM:new y("text/event-stream",O),NDJSON:new y("application/x-ndjson",O)},$=R.JSON.toString(),J=globalThis.location?.origin??"http://localhost",le={DEFAULT:"default",FORCE_CACHE:"force-cache",NO_CACHE:"no-cache",NO_STORE:"no-store",ONLY_IF_CACHED:"only-if-cached",RELOAD:"reload"},m={CONFIGURED:"configured",SUCCESS:"success",ERROR:"error",ABORTED:"aborted",TIMEOUT:"timeout",RETRY:"retry",COMPLETE:"complete",ALL_COMPLETE:"all-complete"},v={ABORT:"abort",TIMEOUT:"timeout"},q={ABORT:"AbortError",TIMEOUT:"TimeoutError"},C={once:!0,passive:!0},L=()=>new CustomEvent(v.ABORT,{detail:{cause:q.ABORT}}),de=()=>new CustomEvent(v.TIMEOUT,{detail:{cause:q.TIMEOUT}}),ce=["POST","PUT","PATCH","DELETE"],pe=new w(500,"Internal Server Error"),fe=new w(499,"Aborted"),he=new w(504,"Request Timeout"),G=[408,413,429,500,502,503,504],z=["GET","PUT","HEAD","DELETE","OPTIONS"],U=300,M=2;var I=class{abortSignal;abortController=new AbortController;events;hasComposite;constructor({signal:e,timeout:t=1/0}={}){if(t<0)throw new RangeError("The timeout cannot be negative");let r=e!=null,s=t!==1/0;if(!r&&!s){this.abortSignal=this.abortController.signal,this.hasComposite=!1;return}let o=[this.abortController.signal];r&&o.push(e),s&&o.push(AbortSignal.timeout(t)),this.abortSignal=AbortSignal.any(o),this.hasComposite=!0,s&&this.abortSignal.addEventListener(v.ABORT,this,C)}handleEvent({target:{reason:e}}){this.abortController.signal.aborted||e instanceof DOMException&&e.name===q.TIMEOUT&&this.abortSignal.dispatchEvent(de())}get signal(){return this.abortSignal}onAbort(e){return this.addEventListener(v.ABORT,e)}onTimeout(e){return this.addEventListener(v.TIMEOUT,e)}abort(e=L()){this.abortController.abort(e.detail?.cause)}destroy(){this.hasComposite&&this.abortSignal.removeEventListener(v.ABORT,this,C);let e=this.events;if(e!==void 0){for(let[t,r]of e)this.abortSignal.removeEventListener(r,t,C);e.clear()}return this}addEventListener(e,t){return this.abortSignal.addEventListener(e,t,C),(this.events??=new Map).set(t,e),this}get[Symbol.toStringTag](){return"SignalController"}};var N,X,D=()=>N||(N=(typeof document>"u"||typeof DOMParser>"u"||typeof DocumentFragment>"u"?import("jsdom").then(({JSDOM:e})=>{let{window:t}=new e("<!DOCTYPE html><html><head></head><body></body></html>",{url:"http://localhost"});globalThis.window=t,Object.assign(globalThis,{document:t.document,DOMParser:t.DOMParser,DocumentFragment:t.DocumentFragment})}).catch(()=>{throw N=void 0,new Error("jsdom is required for HTML/XML/DOM features in Node.js environments. Install it with: npm install jsdom")}):Promise.resolve()).then(()=>import("./BDFNHL2U.js")).then(({default:e})=>{X=e})),Re=async(n,e)=>(await D(),new DOMParser().parseFromString(X.sanitize(await n.text()),e)),V=async(n,e)=>{await D();let t=URL.createObjectURL(await n.blob());try{return new Promise((r,s)=>e(t,r,s))}finally{URL.revokeObjectURL(t)}},ge=n=>n.text(),W=n=>V(n,(e,t,r)=>{let s=document.createElement("script");Object.assign(s,{src:e,type:"text/javascript",async:!0}),s.onload=()=>{document.head.removeChild(s),t()},s.onerror=()=>{document.head.removeChild(s),r(new Error("Script failed to load"))},document.head.appendChild(s)}),K=n=>V(n,(e,t,r)=>{let s=document.createElement("link");Object.assign(s,{href:e,type:"text/css",rel:"stylesheet"}),s.onload=()=>t(),s.onerror=()=>{document.head.removeChild(s),r(new Error("Stylesheet load failed"))},document.head.appendChild(s)}),Y=n=>n.json(),me=n=>n.blob(),Q=n=>V(n,(e,t,r)=>{let s=new Image;s.onload=()=>t(s),s.onerror=()=>r(new Error("Image failed to load")),s.src=e}),ye=n=>n.arrayBuffer(),Z=n=>Promise.resolve(n.body),ee=async n=>Re(n,"application/xml"),te=async n=>Re(n,"text/html"),be=async n=>(await D(),document.createRange().createContextualFragment(X.sanitize(await n.text()))),Te=async n=>(await D(),document.createRange().createContextualFragment(await n.text()));async function*Ee(n,e,t){let r=n.getReader(),s=new TextDecoder,o=e.length,i="",a=0;try{for(;;){let u;for(;(u=i.indexOf(e,a))!==-1;)yield i.slice(a,u),a=u+o;a>0&&a>=i.length-a&&(i=a<i.length?i.slice(a):"",a=0);let{done:l,value:d}=await r.read();if(l)break;i+=s.decode(d,{stream:!0})}if(t){let l=((a<i.length?i.slice(a):"")+s.decode()).trim();l&&(yield l)}}finally{await r.cancel()}}var _e=n=>{let e="message",t="",r,s,o,i=n.split(`
3
+ `);for(let u=0,l=i.length;u<l;u++){let d=i[u];if(d.charCodeAt(0)===58)continue;let c=d.indexOf(":"),p,f;switch(c===-1?(p=d,f=""):(p=d.slice(0,c),f=d.charCodeAt(c+1)===32?d.slice(c+2):d.slice(c+1)),p){case"event":e=f;break;case"data":s===void 0?s=f:(o??=[]).push(f);break;case"id":t=f;break;case"retry":{let h=parseInt(f,10);isNaN(h)||(r=h);break}}}if(s===void 0&&e==="message")return;let a=o===void 0?s??"":`${s}
4
+ ${o.join(`
5
+ `)}`;return{event:e,data:a,id:t,retry:r}},Se=n=>({async*[Symbol.asyncIterator](){for await(let e of Ee(n.body,`
5
6
 
6
- `,!1)){if(!e)continue;let t=$e(e);t&&(yield t)}}}),Pe=s=>({async*[Symbol.asyncIterator](){for await(let e of ve(s.body,`
7
- `,!0)){let t=e.trim();t&&(yield JSON.parse(t))}}});var He=s=>s!==void 0&&he.includes(s),Ae=s=>s instanceof FormData||s instanceof Blob||s instanceof ArrayBuffer||s instanceof ReadableStream||s instanceof URLSearchParams||ArrayBuffer.isView(s),Be=s=>{if(typeof document>"u"||!document.cookie)return;let e=`${s}=`,t=document.cookie.split(";");for(let n=0,r=t.length;n<r;n++){let o=t[n].trim();if(o.startsWith(e))return decodeURIComponent(o.slice(e.length))}},Ce=s=>JSON.stringify(s),J=s=>s!==null&&typeof s=="string",ke=s=>s instanceof ArrayBuffer||Object.prototype.toString.call(s)==="[object ArrayBuffer]",y=s=>s!==null&&typeof s=="object"&&!Array.isArray(s)&&Object.getPrototypeOf(s)===Object.prototype,$=(...s)=>{let e=s.length;if(e===0)return;if(e===1){let[n]=s;return y(n)?re(n):n}let t={};for(let n of s){if(!y(n))return;for(let[r,o]of Object.entries(n)){let i=t[r];Array.isArray(o)?t[r]=[...o,...Array.isArray(i)?i.filter(a=>!o.includes(a)):[]]:y(o)?t[r]=y(i)?$(i,o):re(o):t[r]=o}}return t};function re(s){if(y(s)){let e={},t=Object.keys(s);for(let n=0,r=t.length,o;n<r;n++)o=t[n],e[o]=re(s[o]);return e}return s}var xe=class s{_baseUrl;_options;subscribr;hooks={beforeRequest:[],afterResponse:[],beforeError:[]};static globalSubscribr=new I;static globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]};static signalControllers=new Set;static inflightRequests=new Map;static noRetryConfig={limit:0,statusCodes:[],methods:[],delay:N,backoffFactor:D};static mediaTypeCache=new Map(Object.values(m).map(e=>[e.toString(),e]));static contentTypeHandlers=[[m.TEXT.type,Te],[m.JSON.subtype,Z],[m.BIN.subtype,te],[m.HTML.subtype,ne],[m.XML.subtype,se],[m.PNG.type,ee],[m.JAVA_SCRIPT.subtype,Y],[m.CSS.subtype,Q]];constructor(e=X,t={}){y(e)&&([e,t]=[X,e]),this._baseUrl=s.getBaseUrl(e),this._options=s.createOptions(t,s.defaultRequestOptions),this.subscribr=new I}static CredentialsPolicy={INCLUDE:"include",OMIT:"omit",SAME_ORIGIN:"same-origin"};static RequestMode={CORS:"cors",NAVIGATE:"navigate",NO_CORS:"no-cors",SAME_ORIGIN:"same-origin"};static RequestPriority={HIGH:"high",LOW:"low",AUTO:"auto"};static RedirectPolicy={ERROR:"error",FOLLOW:"follow",MANUAL:"manual"};static ReferrerPolicy={NO_REFERRER:"no-referrer",NO_REFERRER_WHEN_DOWNGRADE:"no-referrer-when-downgrade",ORIGIN:"origin",ORIGIN_WHEN_CROSS_ORIGIN:"origin-when-cross-origin",SAME_ORIGIN:"same-origin",STRICT_ORIGIN:"strict-origin",STRICT_ORIGIN_WHEN_CROSS_ORIGIN:"strict-origin-when-cross-origin",UNSAFE_URL:"unsafe-url"};static RequestEvent=b;static defaultRequestOptions={body:void 0,cache:fe.NO_STORE,credentials:s.CredentialsPolicy.SAME_ORIGIN,headers:new Headers({"content-type":G,accept:G}),searchParams:void 0,integrity:void 0,keepalive:void 0,method:"GET",mode:s.RequestMode.CORS,priority:s.RequestPriority.AUTO,redirect:s.RedirectPolicy.FOLLOW,referrer:"about:client",referrerPolicy:s.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,signal:void 0,timeout:3e4,global:!0};static register(e,t,n){return s.globalSubscribr.subscribe(e,t,n)}static unregister(e){return s.globalSubscribr.unsubscribe(e)}static abortAll(){for(let e of this.signalControllers)e.abort(L());this.signalControllers.clear()}static all(e){return Promise.all(e)}static async race(e){let t=[],n=new Array(e.length);for(let r=0;r<e.length;r++){let o=new AbortController;t.push(o),n[r]=e[r](o.signal)}try{return await Promise.race(n)}finally{for(let r of t)r.abort()}}static registerContentTypeHandler(e,t){s.contentTypeHandlers.unshift([e,t])}static unregisterContentTypeHandler(e){let t=s.contentTypeHandlers.findIndex(([n])=>n===e);return t===-1?!1:(s.contentTypeHandlers.splice(t,1),!0)}static addHooks(e){e.beforeRequest&&s.globalHooks.beforeRequest.push(...e.beforeRequest),e.afterResponse&&s.globalHooks.afterResponse.push(...e.afterResponse),e.beforeError&&s.globalHooks.beforeError.push(...e.beforeError)}static clearHooks(){s.globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]}}static unregisterAll(){s.abortAll(),s.globalSubscribr=new I,s.clearHooks(),s.inflightRequests.clear()}get baseUrl(){return this._baseUrl}register(e,t,n){return this.subscribr.subscribe(e,t,n)}unregister(e){return this.subscribr.unsubscribe(e)}addHooks(e){return e.beforeRequest&&this.hooks.beforeRequest.push(...e.beforeRequest),e.afterResponse&&this.hooks.afterResponse.push(...e.afterResponse),e.beforeError&&this.hooks.beforeError.push(...e.beforeError),this}clearHooks(){return this.hooks.beforeRequest.length=0,this.hooks.afterResponse.length=0,this.hooks.beforeError.length=0,this}configure({headers:e,searchParams:t,hooks:n,...r}){return e&&s.mergeHeaders(this._options.headers,e),t&&s.mergeSearchParams(this._options.searchParams,t),Object.keys(r).length>0&&Object.assign(this._options,r),n&&this.addHooks(n),this}destroy(){this.clearHooks(),this.subscribr.destroy()}async get(e,t){return this._get(e,t)}async post(e,t,n){return this.executeBodyMethod("POST",e,t,n)}async put(e,t,n){return this.executeBodyMethod("PUT",e,t,n)}async patch(e,t,n){return this.executeBodyMethod("PATCH",e,t,n)}async delete(e,t,n){return this.executeBodyMethod("DELETE",e,t,n)}async head(e,t){return this.execute(e,t,{method:"HEAD"})}async options(e,t={}){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t,{method:"OPTIONS"}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),u=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let c of u)if(c)for(let l of c){let g=await l(r,a);g&&(Object.assign(r,g),g.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let p=await this._request(e,n),R=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let c of R)if(c)for(let l of c){let g=await l(p,r);g&&(p=g)}let d=p.headers.get("allow"),h;if(d){let c=d.split(",");h=new Array(c.length);for(let l=0,g=c.length;l<g;l++)h[l]=c[l].trim()}return this.publish({name:b.SUCCESS,data:h,global:t.global}),o?h:[!0,h]}catch(a){if(!o)return[!1,a];throw a}}async request(e,t={}){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t,{}),r=n.requestOptions.unwrap!==!1;try{let o=await this._request(e,n);return this.publish({name:b.SUCCESS,data:o,global:t.global}),r?o:[!0,o]}catch(o){if(!r)return[!1,o];throw o}}async getJson(e,t){return this._get(e,t,{headers:{accept:`${m.JSON}`}},Z)}async getXml(e,t){return this._get(e,t,{headers:{accept:`${m.XML}`}},se)}async getHtml(e,t,n){let r=await this._get(e,t,{headers:{accept:`${m.HTML}`}},ne);return Array.isArray(r)?r:n&&r?r.querySelector(n):r}async getHtmlFragment(e,t,n){let r=(y(e)?e:t)?.allowScripts===!0,o=await this._get(e,t,{headers:{accept:`${m.HTML}`}},r?we:Oe);return Array.isArray(o)?o:n&&o?o.querySelector(n):o}async getScript(e,t){return this._get(e,t,{headers:{accept:`${m.JAVA_SCRIPT}`}},Y)}async getStylesheet(e,t){return this._get(e,t,{headers:{accept:`${m.CSS}`}},Q)}async getBlob(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},Ee)}async getImage(e,t){return this._get(e,t,{headers:{accept:"image/*"}},ee)}async getBuffer(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},Se)}async getStream(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},te)}async getEventStream(e,t){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t??{},{method:t?.body?"POST":"GET",headers:{accept:`${m.EVENT_STREAM}`}}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),u=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let c of u)if(c)for(let l of c){let g=await l(r,a);g&&(Object.assign(r,g),g.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let R=await this._request(e,n),d=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let c of d)if(c)for(let l of c){let g=await l(R,r);g&&(R=g)}this.publish({name:b.SUCCESS,data:R,global:n.global});let h=qe(R);return o?h:[!0,h]}catch(a){if(!o)return[!1,a];throw a}}async getJsonStream(e,t){y(e)&&([e,t]=[void 0,e]);let n=this.processRequestOptions(t??{},{method:"GET",headers:{accept:`${m.NDJSON}`}}),{requestOptions:r}=n,o=r.unwrap!==!1,i=r.hooks;try{let a=s.createUrl(this._baseUrl,e,r.searchParams),u=[s.globalHooks.beforeRequest,this.hooks.beforeRequest,i?.beforeRequest];for(let c of u)if(c)for(let l of c){let g=await l(r,a);g&&(Object.assign(r,g),g.searchParams!==void 0&&(a=s.createUrl(this._baseUrl,e,r.searchParams)))}let R=await this._request(e,n),d=[s.globalHooks.afterResponse,this.hooks.afterResponse,i?.afterResponse];for(let c of d)if(c)for(let l of c){let g=await l(R,r);g&&(R=g)}this.publish({name:b.SUCCESS,data:R,global:n.global});let h=Pe(R);return o?h:[!0,h]}catch(a){if(!o)return[!1,a];throw a}}async _get(e,t,n={},r){return n.method="GET",n.body=void 0,this.execute(e,t,n,r)}async _request(e,{signalController:t,requestOptions:n,global:r}){s.signalControllers.add(t);let o=s.normalizeRetryOptions(n.retry),i=n.method??"GET",a=o.limit>0&&o.methods.includes(i),u=n.dedupe===!0&&(i==="GET"||i==="HEAD"),p=0,R=performance.now(),d=()=>{let h=performance.now();return{start:R,end:h,duration:h-R}};try{let h=s.createUrl(this._baseUrl,e,n.searchParams),c;if(u){c=`${i}:${h.href}`;let f=s.inflightRequests.get(c);if(f)return(await f).clone()}let l=n.body,g=n.onUploadProgress,A=async()=>{if(!g||l==null)return;let f=null;if(typeof l=="string")f=new TextEncoder().encode(l);else if(l instanceof Blob)f=new Uint8Array(await l.arrayBuffer());else if(ke(l))f=new Uint8Array(l);else if(ArrayBuffer.isView(l))f=new Uint8Array(l.buffer,l.byteOffset,l.byteLength);else if(!(l instanceof ReadableStream))return;let E=f?f.byteLength:null,x=f?new ReadableStream({start(q){q.enqueue(f),q.close()}}):l,S=0,C=new TransformStream({transform(q,U){S+=q.byteLength,g({loaded:S,total:E,percentage:E!==null&&E>0?Math.round(S/E*100):null}),U.enqueue(q)}});n.body=x.pipeThrough(C),Object.assign(n,{duplex:"half"})},oe=async()=>{for(;;)try{await A();let f=await fetch(h,n);if(!f.ok){if(a&&p<o.limit&&o.statusCodes.includes(f.status)){p++,this.publish({name:b.RETRY,data:{attempt:p,status:f.status,method:i,path:e,timing:d()},global:r}),await s.retryDelay(o,p);continue}let E;try{E=await f.text()}catch{}throw await this.handleError(e,f,{entity:E,url:h,method:i,timing:d()},n)}return f}catch(f){if(f instanceof B)throw f;if(a&&p<o.limit){p++,this.publish({name:b.RETRY,data:{attempt:p,error:f.message,method:i,path:e,timing:d()},global:r}),await s.retryDelay(o,p);continue}throw await this.handleError(e,void 0,{cause:f,url:h,method:i,timing:d()},n)}},ie=f=>{let E=n.onDownloadProgress;if(!E||!f.body)return f;let x=f.headers.get("content-length"),S=x?parseInt(x,10):null,C=0,q=new TransformStream({transform(U,Ue){C+=U.byteLength,E({loaded:C,total:S,percentage:S!==null&&S>0?Math.round(C/S*100):null}),Ue.enqueue(U)}});return new Response(f.body.pipeThrough(q),{status:f.status,statusText:f.statusText,headers:f.headers})};if(u){let f=oe();s.inflightRequests.set(c,f);try{return ie(await f)}finally{s.inflightRequests.delete(c)}}return ie(await oe())}finally{s.signalControllers.delete(t.destroy()),n.signal?.aborted||(this.publish({name:b.COMPLETE,data:{timing:d()},global:r}),s.signalControllers.size===0&&this.publish({name:b.ALL_COMPLETE,global:r}))}}static normalizeRetryOptions(e){return e===void 0?s.noRetryConfig:typeof e=="number"?{limit:e,statusCodes:V,methods:z,delay:N,backoffFactor:D}:{limit:e.limit??0,statusCodes:e.statusCodes??V,methods:e.methods??z,delay:e.delay??N,backoffFactor:e.backoffFactor??D}}static retryDelay(e,t){let n=typeof e.delay=="function"?e.delay(t):e.delay*e.backoffFactor**(t-1);return new Promise(r=>setTimeout(r,n))}executeBodyMethod(e,t,n,r,o){let[i,a,u]=J(t)?[t,n,r]:[void 0,t,n];return this.execute(i,Object.assign(u??{},{body:a,method:e}),{},o)}async execute(e,t={},n={},r){y(e)&&([e,t]=[void 0,e]);let o=this.processRequestOptions(t,n),{requestOptions:i}=o,a=i.unwrap!==!1,u=i.hooks;try{let p=s.createUrl(this._baseUrl,e,i.searchParams);for(let d of[s.globalHooks.beforeRequest,this.hooks.beforeRequest,u?.beforeRequest])if(d)for(let h of d){let c=await h(i,p);c&&(Object.assign(i,c),c.searchParams!==void 0&&(p=s.createUrl(this._baseUrl,e,i.searchParams)))}let R=await this._request(e,o);for(let d of[s.globalHooks.afterResponse,this.hooks.afterResponse,u?.afterResponse])if(d)for(let h of d){let c=await h(R,i);c&&(R=c)}try{!r&&R.status!==204&&(r=this.getResponseHandler(R.headers.get("content-type")));let d=await r?.(R);return this.publish({name:b.SUCCESS,data:d,global:o.global}),a?d:[!0,d]}catch(d){throw await this.handleError(e,R,{cause:d},i)}}catch(p){if(!a)return[!1,p];throw p}}static createOptions({headers:e,searchParams:t,...n},{headers:r,searchParams:o,...i}){return r=s.mergeHeaders(new Headers,e,r),o=s.mergeSearchParams(new URLSearchParams,t,o),{...$(i,n),headers:r,searchParams:o}}static mergeHeaders(e,...t){for(let n of t)if(n!==void 0)if(n instanceof Headers)n.forEach((r,o)=>e.set(o,r));else if(Array.isArray(n))for(let[r,o]of n)e.set(r,o);else{let r=Object.keys(n);for(let o=0,i=r.length;o<i;o++){let a=r[o],u=n[a];u!==void 0&&e.set(a,u)}}return e}static mergeSearchParams(e,...t){for(let n of t)if(n!==void 0)if(n instanceof URLSearchParams)n.forEach((r,o)=>e.set(o,r));else if(J(n)||Array.isArray(n))for(let[r,o]of new URLSearchParams(n))e.set(r,o);else{let r=Object.keys(n);for(let o=0;o<r.length;o++){let i=r[o],a=n[i];a!==void 0&&e.set(i,typeof a=="string"?a:String(a))}}return e}processRequestOptions({body:e,headers:t,searchParams:n,...r},{headers:o,searchParams:i,...a}){let u={...this._options,...r,...a,headers:s.mergeHeaders(new Headers(this._options.headers),t,o),searchParams:s.mergeSearchParams(new URLSearchParams(this._options.searchParams),n,i)};if(He(u.method))if(Ae(e))Object.assign(u,{body:e}),u.headers.delete("content-type");else{let l=this._options.body,g=y(l)&&y(e)?$(l,e):e!==void 0?e:l,A=u.headers.get("content-type")?.includes("json")??!1;Object.assign(u,{body:A&&y(g)?Ce(g):g})}else u.headers.delete("content-type"),u.body instanceof URLSearchParams&&s.mergeSearchParams(u.searchParams,u.body),u.body=void 0;let{signal:p,timeout:R,global:d=!1,xsrf:h}=u;if(h){let{cookieName:l,headerName:g}=typeof h=="object"?h:{},A=Be(l??ce);A&&u.headers.set(g??pe,A)}let c=new _({signal:p,timeout:R}).onAbort(l=>this.publish({name:b.ABORTED,event:l,global:d})).onTimeout(l=>this.publish({name:b.TIMEOUT,event:l,global:d}));return u.signal=c.signal,this.publish({name:b.CONFIGURED,data:u,global:d}),{signalController:c,requestOptions:u,global:d}}static getBaseUrl(e){if(e instanceof URL)return e;if(!J(e))throw new TypeError("Invalid URL");return new URL(e,e.startsWith("/")?globalThis.location.origin:void 0)}static getOrParseMediaType(e){if(e===null)return;let t=s.mediaTypeCache.get(e);return t!==void 0||(t=T.parse(e)??void 0,t!==void 0&&(s.mediaTypeCache.size>=100&&s.mediaTypeCache.delete(s.mediaTypeCache.keys().next().value),s.mediaTypeCache.set(e,t))),t}static createUrl(e,t,n){let r=t?new URL(`${e.pathname.replace(de,"")}${t}`,e.origin):new URL(e);return n&&s.mergeSearchParams(r.searchParams,n),r}static generateResponseStatusFromError(e,{status:t,statusText:n}=new Response){switch(e){case H.ABORT:return me;case H.TIMEOUT:return ye;default:return t>=400?new w(t,n):ge}}async handleError(e,t,{cause:n,entity:r,url:o,method:i,timing:a}={},u){let p=i&&o?`${i} ${o.href} failed${t?` with status ${t.status}`:""}`:`An error has occurred with your request to: '${e}'`,R=new B(s.generateResponseStatusFromError(n?.name,t),{message:p,cause:n,entity:r,url:o,method:i,timing:a});for(let d of[s.globalHooks.beforeError,this.hooks.beforeError,u?.hooks?.beforeError])if(d)for(let h of d){let c=await h(R);c instanceof B&&(R=c)}return this.publish({name:b.ERROR,data:R}),R}publish({name:e,event:t=new CustomEvent(e),data:n,global:r=!0}){r&&s.globalSubscribr.publish(e,t,n),this.subscribr.publish(e,t,n)}getResponseHandler(e){if(!e)return;let t=s.getOrParseMediaType(e);if(t){for(let[n,r]of s.contentTypeHandlers)if(t.matches(n))return r}}get[Symbol.toStringTag](){return"Transportr"}};export{xe as Transportr};
7
+ `,!1)){if(!e)continue;let t=_e(e);t&&(yield t)}}}),we=n=>({async*[Symbol.asyncIterator](){for await(let e of Ee(n.body,`
8
+ `,!0)){let t=e.trim();t&&(yield JSON.parse(t))}}});var Oe=n=>n!==void 0&&ce.includes(n),ve=n=>n instanceof FormData||n instanceof Blob||n instanceof ArrayBuffer||n instanceof ReadableStream||n instanceof URLSearchParams||ArrayBuffer.isView(n),qe=n=>{if(typeof document>"u")return;let e=document.cookie;if(!e)return;let t=`${n}=`,r=t.length,s=e.length,o=0;for(;o<s;){for(;o<s&&e.charCodeAt(o)===32;)o++;let i=e.indexOf(";",o);if(i===-1&&(i=s),i-o>=r&&e.startsWith(t,o))return decodeURIComponent(e.slice(o+r,i));o=i+1}},Pe=n=>JSON.stringify(n),_=n=>n!==null&&typeof n=="string",He=n=>n instanceof ArrayBuffer||Object.prototype.toString.call(n)==="[object ArrayBuffer]",g=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype,F=(...n)=>{let e=n.length;if(e===0)return;if(e===1){let[r]=n;return g(r)?ne(r):r}let t={};for(let r=0,s=n.length;r<s;r++){let o=n[r];if(!g(o))return;let i=Object.keys(o);for(let a=0,u=i.length;a<u;a++){let l=i[a],d=o[l],c=t[l];if(Array.isArray(d))if(Array.isArray(c)){let p=d.slice();for(let f=0,h=c.length;f<h;f++){let T=c[f];d.includes(T)||p.push(T)}t[l]=p}else t[l]=d.slice();else g(d)?t[l]=g(c)?F(c,d):ne(d):t[l]=d}}return t};function ne(n){if(g(n)){let e={},t=Object.keys(n);for(let r=0,s=t.length,o;r<s;r++)o=t[r],e[o]=ne(n[o]);return e}return n}var Ce=class n{_baseUrl;_origin;_basePath;_options;_noBodyHeadersTemplate;subscribr;hooks={beforeRequest:[],afterResponse:[],beforeError:[]};hookCount={beforeRequest:0,afterResponse:0,beforeError:0};subCounts=Object.create(null);static globalSubscribr=new x;static globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]};static globalHookCount={beforeRequest:0,afterResponse:0,beforeError:0};static globalSubCounts=Object.create(null);static signalControllers=new Set;static inflightRequests=new Map;static noRetryConfig={limit:0,statusCodes:[],methods:[],delay:U,backoffFactor:M};static retryConfigCache=new WeakMap;static mediaTypeCache=new Map(Object.values(R).map(e=>[e.toString(),e]));static handlerResolutionCache=new Map;static contentTypeHandlers=[[R.TEXT.type,ge],[R.JSON.subtype,Y],[R.BIN.subtype,Z],[R.HTML.subtype,te],[R.XML.subtype,ee],[R.PNG.type,Q],[R.JAVA_SCRIPT.subtype,W],[R.CSS.subtype,K]];constructor(e=J,t={}){g(e)&&([e,t]=[J,e]),this._baseUrl=n.getBaseUrl(e),this._origin=this._baseUrl.origin;let r=this._baseUrl.pathname;this._basePath=r.length>0&&r.charCodeAt(r.length-1)===47?r.slice(0,-1):r,this._options=n.createOptions(t,n.defaultRequestOptions),this._noBodyHeadersTemplate=new Headers(this._options.headers),this._noBodyHeadersTemplate.delete("content-type"),this.subscribr=new x}static CredentialsPolicy={INCLUDE:"include",OMIT:"omit",SAME_ORIGIN:"same-origin"};static RequestMode={CORS:"cors",NAVIGATE:"navigate",NO_CORS:"no-cors",SAME_ORIGIN:"same-origin"};static RequestPriority={HIGH:"high",LOW:"low",AUTO:"auto"};static RedirectPolicy={ERROR:"error",FOLLOW:"follow",MANUAL:"manual"};static ReferrerPolicy={NO_REFERRER:"no-referrer",NO_REFERRER_WHEN_DOWNGRADE:"no-referrer-when-downgrade",ORIGIN:"origin",ORIGIN_WHEN_CROSS_ORIGIN:"origin-when-cross-origin",SAME_ORIGIN:"same-origin",STRICT_ORIGIN:"strict-origin",STRICT_ORIGIN_WHEN_CROSS_ORIGIN:"strict-origin-when-cross-origin",UNSAFE_URL:"unsafe-url"};static RequestEvent=m;static defaultRequestOptions={body:void 0,cache:le.NO_STORE,credentials:n.CredentialsPolicy.SAME_ORIGIN,headers:new Headers({"content-type":$,accept:$}),searchParams:void 0,integrity:void 0,keepalive:void 0,method:"GET",mode:n.RequestMode.CORS,priority:n.RequestPriority.AUTO,redirect:n.RedirectPolicy.FOLLOW,referrer:"about:client",referrerPolicy:n.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN,signal:void 0,timeout:3e4,global:!0};static register(e,t,r){let s=n.globalSubscribr.subscribe(e,t,r);return n.globalSubCounts[e]=(n.globalSubCounts[e]??0)+1,s}static unregister(e){let t=n.globalSubscribr.unsubscribe(e);if(t){let r=e.eventName,s=(n.globalSubCounts[r]??1)-1;s<=0?delete n.globalSubCounts[r]:n.globalSubCounts[r]=s}return t}static abortAll(){for(let e of this.signalControllers)e.abort(L());this.signalControllers.clear()}static all(e){return Promise.all(e)}static async race(e){let t=[],r=new Array(e.length);for(let s=0;s<e.length;s++){let o=new AbortController;t.push(o),r[s]=e[s](o.signal)}try{return await Promise.race(r)}finally{for(let s of t)s.abort()}}static registerContentTypeHandler(e,t){n.contentTypeHandlers.unshift([e,t]),n.handlerResolutionCache.clear()}static unregisterContentTypeHandler(e){let t=n.contentTypeHandlers.findIndex(([r])=>r===e);return t===-1?!1:(n.contentTypeHandlers.splice(t,1),n.handlerResolutionCache.clear(),!0)}static addHooks(e){let{beforeRequest:t,afterResponse:r,beforeError:s}=e;t&&(n.globalHooks.beforeRequest.push(...t),n.globalHookCount.beforeRequest+=t.length),r&&(n.globalHooks.afterResponse.push(...r),n.globalHookCount.afterResponse+=r.length),s&&(n.globalHooks.beforeError.push(...s),n.globalHookCount.beforeError+=s.length)}static clearHooks(){n.globalHooks={beforeRequest:[],afterResponse:[],beforeError:[]},n.globalHookCount.beforeRequest=0,n.globalHookCount.afterResponse=0,n.globalHookCount.beforeError=0}static unregisterAll(){n.abortAll(),n.globalSubscribr=new x,n.globalSubCounts=Object.create(null),n.clearHooks(),n.inflightRequests.clear()}get baseUrl(){return this._baseUrl}register(e,t,r){let s=this.subscribr.subscribe(e,t,r);return this.subCounts[e]=(this.subCounts[e]??0)+1,s}unregister(e){let t=this.subscribr.unsubscribe(e);if(t){let r=e.eventName,s=(this.subCounts[r]??1)-1;s<=0?delete this.subCounts[r]:this.subCounts[r]=s}return t}addHooks(e){let{beforeRequest:t,afterResponse:r,beforeError:s}=e;return t&&(this.hooks.beforeRequest.push(...t),this.hookCount.beforeRequest+=t.length),r&&(this.hooks.afterResponse.push(...r),this.hookCount.afterResponse+=r.length),s&&(this.hooks.beforeError.push(...s),this.hookCount.beforeError+=s.length),this}clearHooks(){return this.hooks.beforeRequest.length=0,this.hooks.afterResponse.length=0,this.hooks.beforeError.length=0,this.hookCount.beforeRequest=0,this.hookCount.afterResponse=0,this.hookCount.beforeError=0,this}configure({headers:e,searchParams:t,hooks:r,...s}){return e&&(n.mergeHeaders(this._options.headers,e),this._noBodyHeadersTemplate=new Headers(this._options.headers),this._noBodyHeadersTemplate.delete("content-type")),t&&n.mergeSearchParams(this._options.searchParams,t),Object.assign(this._options,s),r&&this.addHooks(r),this}destroy(){this.clearHooks(),this.subscribr.destroy();for(let e in this.subCounts)delete this.subCounts[e]}async get(e,t){return this._get(e,t)}async post(e,t,r){return this.executeBodyMethod("POST",e,t,r)}async put(e,t,r){return this.executeBodyMethod("PUT",e,t,r)}async patch(e,t,r){return this.executeBodyMethod("PATCH",e,t,r)}async delete(e,t,r){return this.executeBodyMethod("DELETE",e,t,r)}async head(e,t){return this.execute(e,t,{method:"HEAD"})}async options(e,t={}){g(e)&&([e,t]=[void 0,e]);let r=this.processRequestOptions(t,{method:"OPTIONS"}),{requestOptions:s}=r,o=s.unwrap!==!1,i=s.hooks;try{let a=n.createUrl(this,e,s.searchParams);await this.runBeforeRequestHooks(s,a,e,i?.beforeRequest);let u=await this._request(e,r);u=await this.runAfterResponseHooks(u,s,i?.afterResponse);let l=u.headers.get("allow"),d;if(l){let c=l.split(",");d=new Array(c.length);for(let p=0,f=c.length;p<f;p++)d[p]=c[p].trim()}return this.publish({name:m.SUCCESS,data:d,global:t.global}),o?d:[!0,d]}catch(a){if(!o)return[!1,a];throw a}}async request(e,t={}){g(e)&&([e,t]=[void 0,e]);let r=this.processRequestOptions(t,{}),s=r.requestOptions.unwrap!==!1;try{let o=await this._request(e,r);return this.publish({name:m.SUCCESS,data:o,global:t.global}),s?o:[!0,o]}catch(o){if(!s)return[!1,o];throw o}}async getJson(e,t){return this._get(e,t,{headers:{accept:`${R.JSON}`}},Y)}async getXml(e,t){return this._get(e,t,{headers:{accept:`${R.XML}`}},ee)}async getHtml(e,t,r){let s=await this._get(e,t,{headers:{accept:`${R.HTML}`}},te);return Array.isArray(s)?s:r&&s?s.querySelector(r):s}async getHtmlFragment(e,t,r){let s=(g(e)?e:t)?.allowScripts===!0,o=await this._get(e,t,{headers:{accept:`${R.HTML}`}},s?Te:be);return Array.isArray(o)?o:r&&o?o.querySelector(r):o}async getScript(e,t){return this._get(e,t,{headers:{accept:`${R.JAVA_SCRIPT}`}},W)}async getStylesheet(e,t){return this._get(e,t,{headers:{accept:`${R.CSS}`}},K)}async getBlob(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},me)}async getImage(e,t){return this._get(e,t,{headers:{accept:"image/*"}},Q)}async getBuffer(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},ye)}async getStream(e,t){return this._get(e,t,{headers:{accept:"application/octet-stream"}},Z)}async getEventStream(e,t){g(e)&&([e,t]=[void 0,e]);let r=this.processRequestOptions(t??{},{method:t?.body?"POST":"GET",headers:{accept:`${R.EVENT_STREAM}`}}),{requestOptions:s}=r,o=s.unwrap!==!1,i=s.hooks;try{let a=n.createUrl(this,e,s.searchParams);await this.runBeforeRequestHooks(s,a,e,i?.beforeRequest);let u=await this._request(e,r),l=await this.runAfterResponseHooks(u,s,i?.afterResponse);this.publish({name:m.SUCCESS,data:l,global:r.global});let d=Se(l);return o?d:[!0,d]}catch(a){if(!o)return[!1,a];throw a}}async getJsonStream(e,t){g(e)&&([e,t]=[void 0,e]);let r=this.processRequestOptions(t??{},{method:"GET",headers:{accept:`${R.NDJSON}`}}),{requestOptions:s}=r,o=s.unwrap!==!1,i=s.hooks;try{let a=n.createUrl(this,e,s.searchParams);await this.runBeforeRequestHooks(s,a,e,i?.beforeRequest);let u=await this._request(e,r),l=await this.runAfterResponseHooks(u,s,i?.afterResponse);this.publish({name:m.SUCCESS,data:l,global:r.global});let d=we(l);return o?d:[!0,d]}catch(a){if(!o)return[!1,a];throw a}}async _get(e,t,r={},s){return r.method="GET",r.body=void 0,this.execute(e,t,r,s)}async _request(e,t){let{signalController:r,requestOptions:s,global:o}=t;n.signalControllers.add(r);let i=n.normalizeRetryOptions(s.retry),a=s.method??"GET",u=i.limit>0&&i.methods.includes(a),l=s.dedupe===!0&&(a==="GET"||a==="HEAD"),d=performance.now();try{let c=n.createUrl(this,e,s.searchParams),p;if(l){p=`${a}:${c.href}`;let A=n.inflightRequests.get(p);if(A)return(await A).clone()}let f=s.onUploadProgress,h=s.body;f&&h!=null&&(s.duplex="half");let T=this._doFetch(c,s,e,a,u,i,h,f,d,o);if(l){n.inflightRequests.set(p,T);try{return n._wrapDownloadProgress(await T,s)}finally{n.inflightRequests.delete(p)}}return n._wrapDownloadProgress(await T,s)}finally{if(n.signalControllers.delete(r.destroy()),!s.signal?.aborted){let c=performance.now();this.publish({name:m.COMPLETE,data:{timing:{start:d,end:c,duration:c-d}},global:o}),n.signalControllers.size===0&&this.publish({name:m.ALL_COMPLETE,global:o})}}}async _doFetch(e,t,r,s,o,i,a,u,l,d){let c=0;for(;;)try{u&&await n._wrapUploadBody(t,a,u);let p=await fetch(e,t);if(!p.ok){if(o&&c<i.limit&&i.statusCodes.includes(p.status)){c++,this.publish({name:m.RETRY,data:{attempt:c,status:p.status,method:s,path:r,timing:n._snapshotTiming(l)},global:d}),await n.retryDelay(i,c);continue}let f;if(t.captureErrorBody!==!1)try{f=await p.text()}catch{}throw await this.handleError(r,p,{entity:f,url:e,method:s,timing:n._snapshotTiming(l)},t)}return p}catch(p){if(p instanceof S)throw p;if(o&&c<i.limit){c++,this.publish({name:m.RETRY,data:{attempt:c,error:p.message,method:s,path:r,timing:n._snapshotTiming(l)},global:d}),await n.retryDelay(i,c);continue}throw await this.handleError(r,void 0,{cause:p,url:e,method:s,timing:n._snapshotTiming(l)},t)}}static async _wrapUploadBody(e,t,r){if(t==null)return;let s=null;if(typeof t=="string")s=new TextEncoder().encode(t);else if(t instanceof Blob)s=new Uint8Array(await t.arrayBuffer());else if(He(t))s=new Uint8Array(t);else if(ArrayBuffer.isView(t))s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else if(!(t instanceof ReadableStream))return;let o=s?s.byteLength:null,i=s?new ReadableStream({start(l){l.enqueue(s),l.close()}}):t,a=0,u=new TransformStream({transform(l,d){a+=l.byteLength,r({loaded:a,total:o,percentage:o!==null&&o>0?Math.round(a/o*100):null}),d.enqueue(l)}});e.body=i.pipeThrough(u)}static _wrapDownloadProgress(e,t){let r=t.onDownloadProgress;if(!r||!e.body)return e;let s=e.headers.get("content-length"),o=s?parseInt(s,10):null,i=0,a=new TransformStream({transform(u,l){i+=u.byteLength,r({loaded:i,total:o,percentage:o!==null&&o>0?Math.round(i/o*100):null}),l.enqueue(u)}});return new Response(e.body.pipeThrough(a),{status:e.status,statusText:e.statusText,headers:e.headers})}static _snapshotTiming(e){let t=performance.now();return{start:e,end:t,duration:t-e}}static normalizeRetryOptions(e){if(e===void 0)return n.noRetryConfig;if(typeof e=="number")return{limit:e,statusCodes:G,methods:z,delay:U,backoffFactor:M};let t=n.retryConfigCache.get(e);if(t!==void 0)return t;let r={limit:e.limit??0,statusCodes:e.statusCodes??G,methods:e.methods??z,delay:e.delay??U,backoffFactor:e.backoffFactor??M};return n.retryConfigCache.set(e,r),r}static retryDelay(e,t){let r=typeof e.delay=="function"?e.delay(t):e.delay*e.backoffFactor**(t-1);return new Promise(s=>setTimeout(s,r))}executeBodyMethod(e,t,r,s,o){let[i,a,u]=_(t)?[t,r,s]:[void 0,t,r],l=u!==void 0?Object.assign({},u,{body:a,method:e}):{body:a,method:e};return this.execute(i,l,{},o)}async runBeforeRequestHooks(e,t,r,s){let o=n.globalHooks.beforeRequest,i=this.hooks.beforeRequest,a=s===void 0?0:s.length;if(o.length===0&&i.length===0&&a===0)return t;for(let u=0,l=o.length;u<l;u++){let d=await o[u](e,t);d&&(Object.assign(e,d),d.searchParams!==void 0&&(t=n.createUrl(this,r,e.searchParams)))}for(let u=0,l=i.length;u<l;u++){let d=await i[u](e,t);d&&(Object.assign(e,d),d.searchParams!==void 0&&(t=n.createUrl(this,r,e.searchParams)))}for(let u=0;u<a;u++){let l=await s[u](e,t);l&&(Object.assign(e,l),l.searchParams!==void 0&&(t=n.createUrl(this,r,e.searchParams)))}return t}async runAfterResponseHooks(e,t,r){let s=n.globalHooks.afterResponse,o=this.hooks.afterResponse,i=r===void 0?0:r.length;if(s.length===0&&o.length===0&&i===0)return e;for(let a=0,u=s.length;a<u;a++){let l=await s[a](e,t);l&&(e=l)}for(let a=0,u=o.length;a<u;a++){let l=await o[a](e,t);l&&(e=l)}for(let a=0;a<i;a++){let u=await r[a](e,t);u&&(e=u)}return e}async runBeforeErrorHooks(e,t){let r=n.globalHooks.beforeError,s=this.hooks.beforeError,o=t===void 0?0:t.length;if(r.length===0&&s.length===0&&o===0)return e;for(let i=0,a=r.length;i<a;i++){let u=await r[i](e);u instanceof S&&(e=u)}for(let i=0,a=s.length;i<a;i++){let u=await s[i](e);u instanceof S&&(e=u)}for(let i=0;i<o;i++){let a=await t[i](e);a instanceof S&&(e=a)}return e}async execute(e,t={},r={},s){g(e)&&([e,t]=[void 0,e]);let o=this.processRequestOptions(t,r),{requestOptions:i}=o,a=i.unwrap!==!1,u=i.hooks;try{let l=n.createUrl(this,e,i.searchParams);await this.runBeforeRequestHooks(i,l,e,u?.beforeRequest);let d=await this._request(e,o);d=await this.runAfterResponseHooks(d,i,u?.afterResponse);try{!s&&d.status!==204&&(s=this.getResponseHandler(d.headers.get("content-type")));let c=await s?.(d);return this.publish({name:m.SUCCESS,data:c,global:o.global}),a?c:[!0,c]}catch(c){throw await this.handleError(e,d,{cause:c},i)}}catch(l){if(!a)return[!1,l];throw l}}static createOptions({headers:e,searchParams:t,...r},{headers:s,searchParams:o,...i}){return s=n.mergeHeaders(new Headers,e,s),o=n.mergeSearchParams(new URLSearchParams,t,o),{...F(i,r),headers:s,searchParams:o}}static mergeHeaders(e,...t){for(let r of t)if(r!==void 0)if(r instanceof Headers)r.forEach((s,o)=>e.set(o,s));else if(Array.isArray(r))for(let[s,o]of r)e.set(s,o);else{let s=Object.keys(r);for(let o=0,i=s.length;o<i;o++){let a=s[o],u=r[a];u!==void 0&&e.set(a,u)}}return e}static mergeSearchParams(e,...t){for(let r of t)if(r!==void 0)if(r instanceof URLSearchParams)r.forEach((s,o)=>e.set(o,s));else if(_(r)||Array.isArray(r))for(let[s,o]of new URLSearchParams(r))e.set(s,o);else{let s=Object.keys(r);for(let o=0;o<s.length;o++){let i=s[o],a=r[i];a!==void 0&&e.set(i,typeof a=="string"?a:String(a))}}return e}processRequestOptions(e,t){let r=e.headers,s=e.searchParams,o=e.body,i=t.headers,a=t.searchParams,u=t.method??e.method??this._options.method??"GET",l=Oe(u),d;!l&&r===void 0&&i===void 0?d=new Headers(this._noBodyHeadersTemplate):(d=new Headers(this._options.headers),(r!==void 0||i!==void 0)&&n.mergeHeaders(d,r,i));let c=this._options.searchParams,p=c!==void 0&&c.size>0,f;!p&&s===void 0&&a===void 0?f=new URLSearchParams:(f=new URLSearchParams(c),(s!==void 0||a!==void 0)&&n.mergeSearchParams(f,s,a));let h=Object.assign({},this._options,e,t);if(h.headers=d,h.searchParams=f,l)if(ve(o))h.body=o,d.delete("content-type");else{let b=this._options.body,P=g(b)&&g(o)?F(b,o):o!==void 0?o:b,H=d.get("content-type"),Ae=H!==null&&H.includes("json");h.body=Ae&&g(P)?Pe(P):P}else h.body instanceof URLSearchParams&&n.mergeSearchParams(f,h.body),h.body=void 0,(r!==void 0||i!==void 0)&&d.delete("content-type");let T=h.signal,A=h.timeout,B=h.global??!1,j=h.xsrf;if(j){let{cookieName:b,headerName:P}=typeof j=="object"?j:{},H=qe(b??ae);H&&d.set(P??ue,H)}let se=new I({signal:T,timeout:A}).onAbort(b=>this.publish({name:m.ABORTED,event:b,global:B})).onTimeout(b=>this.publish({name:m.TIMEOUT,event:b,global:B}));return h.signal=se.signal,this.publish({name:m.CONFIGURED,data:h,global:B}),{signalController:se,requestOptions:h,global:B}}static getBaseUrl(e){if(e instanceof URL)return e;if(!_(e))throw new TypeError("Invalid URL");return new URL(e,e.startsWith("/")?globalThis.location.origin:void 0)}static getOrParseMediaType(e){if(e===null)return;let t=n.mediaTypeCache.get(e);return t!==void 0||(t=y.parse(e)??void 0,t!==void 0&&(n.mediaTypeCache.size>=100&&n.mediaTypeCache.delete(n.mediaTypeCache.keys().next().value),n.mediaTypeCache.set(e,t))),t}static createUrl(e,t,r){let s;if(e instanceof URL){let o=e.pathname,i=o.charCodeAt(o.length-1)===47?o.slice(0,-1):o;s=t?new URL(`${i}${t}`,e.origin):new URL(e)}else s=t?new URL(`${e._basePath}${t}`,e._origin):new URL(e._baseUrl);return r&&n.mergeSearchParams(s.searchParams,r),s}static generateResponseStatusFromError(e,{status:t,statusText:r}=new Response){switch(e){case q.ABORT:return fe;case q.TIMEOUT:return he;default:return t>=400?new w(t,r):pe}}async handleError(e,t,{cause:r,entity:s,url:o,method:i,timing:a}={},u){let l=i&&o?`${i} ${o.href} failed${t?` with status ${t.status}`:""}`:`An error has occurred with your request to: '${e}'`,d=new S(n.generateResponseStatusFromError(r?.name,t),{message:l,cause:r,entity:s,url:o,method:i,timing:a});return d=await this.runBeforeErrorHooks(d,u?.hooks?.beforeError),this.publish({name:m.ERROR,data:d}),d}publish({name:e,event:t,data:r,global:s=!0}){let o=s&&(n.globalSubCounts[e]??0)>0,i=(this.subCounts[e]??0)>0;if(!o&&!i)return;let a=t??new CustomEvent(e);o&&n.globalSubscribr.publish(e,a,r),i&&this.subscribr.publish(e,a,r)}getResponseHandler(e){if(!e)return;let t=n.handlerResolutionCache.get(e);if(t!==void 0)return t===null?void 0:t;let r=n.getOrParseMediaType(e);if(!r){n.handlerResolutionCache.set(e,null);return}let s=n.contentTypeHandlers;for(let o=0,i=s.length;o<i;o++){let a=s[o];if(r.matches(a[0])){let u=a[1];return n.handlerResolutionCache.set(e,u),u}}n.handlerResolutionCache.set(e,null)}get[Symbol.toStringTag](){return"Transportr"}};export{Ce as Transportr};
8
9
  //# sourceMappingURL=transportr.js.map