@npora/request 1.14.4 → 1.15.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.
Files changed (106) hide show
  1. package/README.md +253 -4
  2. package/dist/MockAdapter-ChWzzSnH.d.cts +71 -0
  3. package/dist/MockAdapter-H50LoFDu.d.ts +71 -0
  4. package/dist/Plugin-0Eh51_et.d.ts +124 -0
  5. package/dist/Plugin-YysllE6z.d.cts +124 -0
  6. package/dist/PluginError-CcuPSIRv.js +1 -0
  7. package/dist/PluginError-DT3VnlUB.cjs +1 -0
  8. package/dist/PluginError-DVP3pUt_.d.cts +18 -0
  9. package/dist/PluginError-DVP3pUt_.d.ts +18 -0
  10. package/dist/RequestError-BH6V64XR.js +1 -0
  11. package/dist/RequestError-DPSv-HVF.cjs +1 -0
  12. package/dist/SchemaValidationError-CjvWT8YA.d.ts +166 -0
  13. package/dist/SchemaValidationError-WMTfqSBV.d.cts +166 -0
  14. package/dist/adapter-BeVVCcNG.d.cts +21 -0
  15. package/dist/adapter-ODzpt_dM.d.ts +21 -0
  16. package/dist/authPlugin-6E6_0dAO.d.ts +53 -0
  17. package/dist/authPlugin-B_YpkyC8.d.cts +53 -0
  18. package/dist/buildRequest-BRZwRLoN.cjs +1 -0
  19. package/dist/buildRequest-Cwt8XEWO.js +1 -0
  20. package/dist/cachePlugin-B9Hvsprg.d.cts +297 -0
  21. package/dist/cachePlugin-CSHwJYwI.js +1 -0
  22. package/dist/cachePlugin-CvH26DBo.d.ts +297 -0
  23. package/dist/cachePlugin-ZPYdHbsM.cjs +1 -0
  24. package/dist/circuitBreakerPlugin-B45xghq9.d.cts +59 -0
  25. package/dist/circuitBreakerPlugin-DsH6YCNe.d.ts +59 -0
  26. package/dist/concurrencyPlugin-CuJMua41.d.cts +48 -0
  27. package/dist/concurrencyPlugin-dwGNFYrM.d.ts +48 -0
  28. package/dist/core.cjs +1 -0
  29. package/dist/core.d.cts +6 -0
  30. package/dist/core.d.ts +6 -0
  31. package/dist/core.js +1 -0
  32. package/dist/createAbortError-D4rRBq2B.js +1 -0
  33. package/dist/createAbortError-DJqbdYgk.cjs +1 -0
  34. package/dist/createClient-CibOTVAy.cjs +1 -0
  35. package/dist/createClient-I13D6XsD.js +1 -0
  36. package/dist/downloadPlugin-CEXXJiDo.d.cts +17 -0
  37. package/dist/downloadPlugin-s8VS8t9r.d.ts +17 -0
  38. package/dist/index.cjs +1 -4
  39. package/dist/index.d.cts +15 -1028
  40. package/dist/index.d.ts +15 -1028
  41. package/dist/index.js +1 -4
  42. package/dist/isPromiseLike-BuAv3bAe.js +1 -0
  43. package/dist/isPromiseLike-C8e95Or2.cjs +1 -0
  44. package/dist/isURLSearchParams-B93cMCGj.js +1 -0
  45. package/dist/isURLSearchParams-o-c8Q42t.cjs +1 -0
  46. package/dist/loggerPlugin-C15EW7Sc.d.ts +6 -0
  47. package/dist/loggerPlugin-uOFiUtBi.d.cts +6 -0
  48. package/dist/maxTimerDelay-Hn7X0Wuh.js +1 -0
  49. package/dist/maxTimerDelay-NH5XeTXb.cjs +1 -0
  50. package/dist/plugins/auth.cjs +1 -0
  51. package/dist/plugins/auth.d.cts +2 -0
  52. package/dist/plugins/auth.d.ts +2 -0
  53. package/dist/plugins/auth.js +1 -0
  54. package/dist/plugins/cache.cjs +1 -0
  55. package/dist/plugins/cache.d.cts +2 -0
  56. package/dist/plugins/cache.d.ts +2 -0
  57. package/dist/plugins/cache.js +1 -0
  58. package/dist/plugins/circuit-breaker.cjs +1 -0
  59. package/dist/plugins/circuit-breaker.d.cts +2 -0
  60. package/dist/plugins/circuit-breaker.d.ts +2 -0
  61. package/dist/plugins/circuit-breaker.js +1 -0
  62. package/dist/plugins/concurrency.cjs +1 -0
  63. package/dist/plugins/concurrency.d.cts +2 -0
  64. package/dist/plugins/concurrency.d.ts +2 -0
  65. package/dist/plugins/concurrency.js +1 -0
  66. package/dist/plugins/download.cjs +1 -0
  67. package/dist/plugins/download.d.cts +2 -0
  68. package/dist/plugins/download.d.ts +2 -0
  69. package/dist/plugins/download.js +1 -0
  70. package/dist/plugins/logger.cjs +1 -0
  71. package/dist/plugins/logger.d.cts +2 -0
  72. package/dist/plugins/logger.d.ts +2 -0
  73. package/dist/plugins/logger.js +1 -0
  74. package/dist/plugins/retry.cjs +1 -0
  75. package/dist/plugins/retry.d.cts +2 -0
  76. package/dist/plugins/retry.d.ts +2 -0
  77. package/dist/plugins/retry.js +1 -0
  78. package/dist/plugins/upload.cjs +1 -0
  79. package/dist/plugins/upload.d.cts +2 -0
  80. package/dist/plugins/upload.d.ts +2 -0
  81. package/dist/plugins/upload.js +1 -0
  82. package/dist/plugins.cjs +1 -0
  83. package/dist/plugins.d.cts +11 -0
  84. package/dist/plugins.d.ts +11 -0
  85. package/dist/plugins.js +1 -0
  86. package/dist/resolveExtensionConfig-BHHfQwjF.cjs +1 -0
  87. package/dist/resolveExtensionConfig-QAFHZVte.js +1 -0
  88. package/dist/resolveRequestOrigin-BndIJeZ7.js +1 -0
  89. package/dist/resolveRequestOrigin-CRATeWff.cjs +1 -0
  90. package/dist/response-BhyS3PAL.d.cts +441 -0
  91. package/dist/response-BhyS3PAL.d.ts +441 -0
  92. package/dist/retryPlugin-2mYKvWy3.d.ts +6 -0
  93. package/dist/retryPlugin-BqlUpmd0.d.cts +6 -0
  94. package/dist/testing.cjs +1 -0
  95. package/dist/testing.d.cts +2 -0
  96. package/dist/testing.d.ts +2 -0
  97. package/dist/testing.js +1 -0
  98. package/dist/uploadPlugin-AfhFIsO7.d.cts +5 -0
  99. package/dist/uploadPlugin-Bb7EawRX.d.ts +5 -0
  100. package/dist/validateResponseStatus-Dqzr342t.js +4 -0
  101. package/dist/validateResponseStatus-QAjcah2i.cjs +4 -0
  102. package/dist/waitForSignal-DyyPvJd5.js +1 -0
  103. package/dist/waitForSignal-yR1BeU8f.cjs +1 -0
  104. package/dist/xhrTransport-C0pg00i5.js +1 -0
  105. package/dist/xhrTransport-CeW2DDzo.cjs +1 -0
  106. package/package.json +65 -2
@@ -0,0 +1,297 @@
1
+ import { j as HttpMethod, o as RequestConfig } from "./response-BhyS3PAL.js";
2
+ import { t as Plugin } from "./Plugin-0Eh51_et.js";
3
+ //#region src/plugins/indexedDBCacheStore.d.ts
4
+ interface IndexedDBCacheStoreOptions {
5
+ /** Database shared by cache namespaces. @default @npora/request-cache */
6
+ databaseName?: string;
7
+ /** Isolates this cache from other applications in the database. */
8
+ namespace?: string;
9
+ /** Maximum entries retained with LRU eviction. @default 1000 */
10
+ maxEntries?: number;
11
+ /**
12
+ * Approximate structured-clone byte budget retained with LRU eviction.
13
+ * @default Infinity
14
+ */
15
+ maxBytes?: number;
16
+ /** Retry quota-exceeded writes after LRU recovery. @default true */
17
+ quotaRecovery?: boolean;
18
+ /** Decide whether an otherwise eligible entry should be persisted. */
19
+ shouldPersist?: (entry: Readonly<CacheEntry>, estimatedBytes: number) => boolean | Promise<boolean>;
20
+ /** Observe privacy-safe persistence and eviction decisions. */
21
+ onEvent?: (event: IndexedDBCacheStoreEvent) => void | Promise<void>;
22
+ /** Monotonic application cache schema version. @default 1 */
23
+ schemaVersion?: number;
24
+ }
25
+ interface IndexedDBCacheUsage {
26
+ entries: number;
27
+ estimatedBytes: number;
28
+ maxEntries: number;
29
+ maxBytes: number;
30
+ schemaVersion: number;
31
+ }
32
+ interface IndexedDBCacheCompactionOptions {
33
+ /** Remove entries expiring at or before this time. @default Date.now() */
34
+ expiredBefore?: number;
35
+ /** Bound removals performed by one maintenance transaction. @default Infinity */
36
+ maxRemovals?: number;
37
+ }
38
+ interface IndexedDBCacheCompactionResult {
39
+ scannedEntries: number;
40
+ removedEntries: number;
41
+ estimatedBytesFreed: number;
42
+ expiredBefore: number;
43
+ hasMore: boolean;
44
+ }
45
+ interface IndexedDBCacheStoreEvent {
46
+ type: 'eviction' | 'rejection';
47
+ reason: 'max-entries' | 'max-bytes' | 'quota-recovery' | 'schema-version' | 'malformed' | 'oversized' | 'admission-policy' | 'expired';
48
+ entries: number;
49
+ estimatedBytes: number;
50
+ timestamp: number;
51
+ }
52
+ /** A namespaced asynchronous cache backed by IndexedDB. */
53
+ declare class IndexedDBCacheStore implements CacheStore {
54
+ private readonly namespace;
55
+ private readonly maxEntries;
56
+ private readonly maxBytes;
57
+ private readonly quotaRecovery;
58
+ private readonly shouldPersist?;
59
+ private readonly onEvent?;
60
+ private readonly factory;
61
+ private readonly databaseName;
62
+ private readonly schemaVersion;
63
+ private database?;
64
+ constructor(factory: IDBFactory, options?: IndexedDBCacheStoreOptions);
65
+ get(key: string): Promise<CacheEntry | undefined>;
66
+ set(key: string, entry: CacheEntry): Promise<void>;
67
+ delete(key: string): Promise<void>;
68
+ invalidateTags(tags: readonly string[]): Promise<number>;
69
+ clear(): Promise<void>;
70
+ /** Inspect current-schema usage without exposing cache keys. */
71
+ getUsage(): Promise<IndexedDBCacheUsage>;
72
+ /** Remove current-schema entries older than an explicit stale boundary. */
73
+ compact(options?: IndexedDBCacheCompactionOptions): Promise<IndexedDBCacheCompactionResult>;
74
+ /** Close this store's database connection. */
75
+ close(): Promise<void>;
76
+ private createKey;
77
+ private writeRecord;
78
+ private recoverQuota;
79
+ private emitCleanupSummaries;
80
+ private emitEvent;
81
+ private visitNamespace;
82
+ private getDatabase;
83
+ }
84
+ //#endregion
85
+ //#region src/plugins/tieredCacheStore.d.ts
86
+ type MaybePromise$1<T> = T | Promise<T>;
87
+ interface TieredCacheStoreOptions {
88
+ /** Fast first-level store, usually MemoryCacheStore. */
89
+ primary: CacheStore;
90
+ /** Durable or shared second-level store. */
91
+ secondary: CacheStore;
92
+ /** Optional cross-context invalidation for the primary tier. */
93
+ broadcast?: TieredCacheBroadcastOptions;
94
+ /** Optional cross-context refresh coalescing through Web Locks. */
95
+ coordination?: TieredCacheCoordinationOptions;
96
+ }
97
+ interface TieredCacheBroadcastOptions {
98
+ /** Application-scoped channel supplied by the caller. */
99
+ channel: BroadcastChannel;
100
+ /** Maximum cache keys tracked for targeted invalidation. @default 1000 */
101
+ maxTrackedKeys?: number;
102
+ }
103
+ interface TieredCacheCoordinationOptions {
104
+ /** Web Locks manager, usually navigator.locks. */
105
+ locks: LockManager;
106
+ /** Application-scoped lock namespace. @default npora-cache */
107
+ namespace?: string;
108
+ }
109
+ /** A read-through, write-through cache composed from two stores. */
110
+ declare class TieredCacheStore implements CacheStore {
111
+ readonly acquireRefreshLease?: (key: string, signal?: AbortSignal) => Promise<CacheRefreshLease>;
112
+ private readonly primary;
113
+ private readonly secondary;
114
+ private readonly channel?;
115
+ private readonly locks?;
116
+ private readonly lockNamespace;
117
+ private readonly leaseReleases;
118
+ private readonly source;
119
+ private readonly trackedKeys;
120
+ private readonly maxTrackedKeys;
121
+ private trackedKeyCount;
122
+ constructor(options: TieredCacheStoreOptions);
123
+ get(key: string): MaybePromise$1<CacheEntry | undefined>;
124
+ set(key: string, entry: CacheEntry): MaybePromise$1<void>;
125
+ delete(key: string): MaybePromise$1<void>;
126
+ invalidateTags(tags: readonly string[]): MaybePromise$1<number>;
127
+ clear(): MaybePromise$1<void>;
128
+ private acquireCoordinatedLease;
129
+ /** Stop listening for cross-context invalidation messages. */
130
+ dispose(): void;
131
+ private requestLease;
132
+ private readSecondary;
133
+ private remember;
134
+ private trackKey;
135
+ private untrackKey;
136
+ private broadcastKey;
137
+ private broadcastClear;
138
+ private postMessage;
139
+ private readonly handleMessage;
140
+ private clearPrimary;
141
+ private recoverPrimaryWrite;
142
+ private afterSuccess;
143
+ private afterSettled;
144
+ }
145
+ //#endregion
146
+ //#region src/plugins/cachePlugin.d.ts
147
+ type MaybePromise<T> = T | Promise<T>;
148
+ interface CacheEntry {
149
+ data: unknown;
150
+ expiresAt: number;
151
+ status: number;
152
+ statusText: string;
153
+ headers: Array<[string, string]>;
154
+ tags?: readonly string[];
155
+ raw?: Response;
156
+ }
157
+ interface CacheStore {
158
+ get(key: string): MaybePromise<CacheEntry | undefined>;
159
+ set(key: string, entry: CacheEntry): MaybePromise<void>;
160
+ delete(key: string): MaybePromise<void>;
161
+ /** Optional capability required by cache.invalidateTags(). */
162
+ invalidateTags?(tags: readonly string[]): MaybePromise<number>;
163
+ /** Optional cross-context lease used to coalesce cache refreshes. */
164
+ acquireRefreshLease?(key: string, signal?: AbortSignal): Promise<CacheRefreshLease>;
165
+ clear(): MaybePromise<void>;
166
+ }
167
+ interface CacheRefreshLease {
168
+ /** Whether this lease waited for another context to release the key. */
169
+ readonly contended: boolean;
170
+ /** Release the lease. Calling this more than once has no effect. */
171
+ release(): void;
172
+ }
173
+ interface MemoryCacheStoreOptions {
174
+ /**
175
+ * Maximum entries retained by the in-memory LRU store.
176
+ * Use `Infinity` for no practical limit.
177
+ *
178
+ * @default 1000
179
+ */
180
+ maxEntries?: number;
181
+ }
182
+ declare class MemoryCacheStore implements CacheStore {
183
+ private readonly entries;
184
+ private readonly maxEntries;
185
+ private newestKey;
186
+ constructor(options?: MemoryCacheStoreOptions);
187
+ get(key: string): CacheEntry | undefined;
188
+ set(key: string, entry: CacheEntry): void;
189
+ delete(key: string): void;
190
+ invalidateTags(tags: readonly string[]): number;
191
+ clear(): void;
192
+ }
193
+ interface WebStorageCacheStoreOptions {
194
+ /** Isolates this cache from other applications using the same storage. */
195
+ namespace?: string;
196
+ /** Maximum persisted entries retained with LRU eviction. @default 1000 */
197
+ maxEntries?: number;
198
+ }
199
+ /** A namespaced persistent cache for localStorage or sessionStorage. */
200
+ declare class WebStorageCacheStore implements CacheStore {
201
+ private readonly storage;
202
+ private readonly prefix;
203
+ private readonly maxEntries;
204
+ constructor(storage: Storage, options?: WebStorageCacheStoreOptions);
205
+ get(key: string): CacheEntry | undefined;
206
+ set(key: string, entry: CacheEntry): void;
207
+ delete(key: string): void;
208
+ invalidateTags(tags: readonly string[]): number;
209
+ clear(): void;
210
+ private keys;
211
+ private read;
212
+ }
213
+ interface CachePluginOptions {
214
+ /**
215
+ * HTTP methods that may be cached.
216
+ *
217
+ * @default GET and HEAD
218
+ */
219
+ methods?: readonly HttpMethod[];
220
+ /**
221
+ * Additional request headers included in the default cache key.
222
+ * All explicitly configured request headers are included automatically.
223
+ *
224
+ * @default authorization, cookie, accept and accept-language
225
+ */
226
+ varyHeaders?: readonly string[];
227
+ /**
228
+ * Cache storage shared by this plugin instance.
229
+ *
230
+ * @default an isolated MemoryCacheStore
231
+ */
232
+ store?: CacheStore;
233
+ /**
234
+ * Maximum entries retained by the default MemoryCacheStore.
235
+ * Ignored when `store` is provided.
236
+ *
237
+ * @default 1000
238
+ */
239
+ maxEntries?: number;
240
+ /**
241
+ * Share one network operation between concurrent equivalent requests.
242
+ *
243
+ * @default true
244
+ */
245
+ dedupe?: boolean;
246
+ /**
247
+ * Observe cache decisions without receiving cache keys, URLs or headers.
248
+ * Callback failures are isolated from requests.
249
+ */
250
+ onEvent?: (event: CacheEvent) => void | Promise<void>;
251
+ }
252
+ interface CachePlugin extends Plugin {
253
+ clear(): MaybePromise<void>;
254
+ /** Delete the entry matching an effective request configuration. */
255
+ delete(config: RequestConfig): MaybePromise<void>;
256
+ /** Store parsed response data for an effective request configuration. */
257
+ set<T>(config: RequestConfig, data: T, options?: CacheSetOptions): MaybePromise<void>;
258
+ /** Update or delete an existing parsed cache value. */
259
+ update<T>(config: RequestConfig, updater: (data: T) => T | undefined): MaybePromise<boolean>;
260
+ /** Delete entries carrying any of the supplied tags. */
261
+ invalidateTags(tags: string | readonly string[]): MaybePromise<number>;
262
+ getStats(): Readonly<CacheStats>;
263
+ resetStats(): void;
264
+ }
265
+ interface CacheSetOptions {
266
+ /** Freshness lifetime in milliseconds. */
267
+ ttl?: number;
268
+ /** Cached HTTP status. @default 200 */
269
+ status?: number;
270
+ /** Cached HTTP status text. @default OK */
271
+ statusText?: string;
272
+ headers?: HeadersInit;
273
+ /** Tags assigned to the entry. */
274
+ tags?: readonly string[];
275
+ }
276
+ type CacheEventType = 'hit' | 'miss' | 'bypass' | 'invalidated' | 'invalidation-error' | 'deduplicated' | 'revalidated' | 'stale-if-error' | 'stale-while-revalidate' | 'background-refresh' | 'background-refresh-success' | 'background-refresh-error';
277
+ interface CacheEvent {
278
+ type: CacheEventType;
279
+ timestamp: number;
280
+ }
281
+ interface CacheStats {
282
+ hits: number;
283
+ misses: number;
284
+ bypasses: number;
285
+ invalidations: number;
286
+ invalidationErrors: number;
287
+ deduplicated: number;
288
+ revalidations: number;
289
+ staleIfError: number;
290
+ staleWhileRevalidate: number;
291
+ backgroundRefreshes: number;
292
+ backgroundRefreshSuccesses: number;
293
+ backgroundRefreshErrors: number;
294
+ }
295
+ declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
296
+ //#endregion
297
+ export { IndexedDBCacheStoreOptions as C, IndexedDBCacheStoreEvent as S, TieredCacheStore as _, CachePluginOptions as a, IndexedDBCacheCompactionResult as b, CacheStats as c, MemoryCacheStoreOptions as d, WebStorageCacheStore as f, TieredCacheCoordinationOptions as g, TieredCacheBroadcastOptions as h, CachePlugin as i, CacheStore as l, cachePlugin as m, CacheEvent as n, CacheRefreshLease as o, WebStorageCacheStoreOptions as p, CacheEventType as r, CacheSetOptions as s, CacheEntry as t, MemoryCacheStore as u, TieredCacheStoreOptions as v, IndexedDBCacheUsage as w, IndexedDBCacheStore as x, IndexedDBCacheCompactionOptions as y };
@@ -0,0 +1 @@
1
+ const e=require("./RequestError-DPSv-HVF.cjs"),t=require("./isURLSearchParams-o-c8Q42t.cjs"),n=require("./isPromiseLike-C8e95Or2.cjs"),r=require("./waitForSignal-yR1BeU8f.cjs"),i=require("./resolveExtensionConfig-BHHfQwjF.cjs"),a=`entries`,o=`namespace`;var IndexedDBCacheStore=class{constructor(e,t={}){this.namespace=normalizeIndexedDBName(t.namespace,`namespace`,`default`),this.maxEntries=normalizeIndexedDBMaxEntries(t.maxEntries),this.maxBytes=normalizeIndexedDBMaxBytes(t.maxBytes),this.quotaRecovery=normalizeQuotaRecovery(t.quotaRecovery),this.shouldPersist=normalizeIndexedDBAdmissionPolicy(t.shouldPersist),this.onEvent=normalizeIndexedDBEventObserver(t.onEvent),this.schemaVersion=normalizeIndexedDBSchemaVersion(t.schemaVersion),this.databaseName=normalizeIndexedDBName(t.databaseName,`database name`,`@npora/request-cache`),this.factory=e}async get(e){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let t=(await this.getDatabase()).transaction(a,`readwrite`),n=waitForTransaction(t),r=t.objectStore(a),i=this.createKey(e),o=await waitForRequest(r.get(i)),s=isFutureIndexedDBRecord(o,this.schemaVersion);if(!isValidIndexedDBRecord(o,this.namespace,i,this.schemaVersion)){o!==void 0&&!s&&r.delete(i),await n,o!==void 0&&!s&&this.emitEvent({type:`eviction`,reason:`malformed`,entries:1,estimatedBytes:readIndexedDBRecordSize(o)});return}return o.accessedAt=Date.now(),o.size=readIndexedDBRecordSize(o),r.put(o),await n,toPortableCacheEntry(o)}async set(t,n){if(this.maxEntries===0||this.maxBytes===0){await this.delete(t);return}let r=await this.getDatabase(),i={...toPortableCacheEntry(n),key:this.createKey(t),namespace:this.namespace,accessedAt:Date.now(),schemaVersion:this.schemaVersion};if(i.size=estimateStructuredCloneSize(i),i.size>this.maxBytes){await this.delete(t),this.emitEvent({type:`rejection`,reason:`oversized`,entries:1,estimatedBytes:i.size});return}let a=!this.shouldPersist||await this.shouldPersist(toPortableCacheEntry(i),i.size);if(typeof a!=`boolean`)throw new e.t(`IndexedDB cache shouldPersist must return a boolean`,{code:`CONFIG_ERROR`});if(!a){await this.delete(t),this.emitEvent({type:`rejection`,reason:`admission-policy`,entries:1,estimatedBytes:i.size});return}try{await this.writeRecord(r,i)}catch(e){if(!this.quotaRecovery||!isQuotaExceededError(e)||!await this.recoverQuota(r))throw e;await this.writeRecord(r,i)}}async delete(e){let t=(await this.getDatabase()).transaction(a,`readwrite`),n=waitForTransaction(t),r=t.objectStore(a),i=this.createKey(e);isFutureIndexedDBRecord(await waitForRequest(r.get(i)),this.schemaVersion)||r.delete(i),await n}async invalidateTags(e){let t=new Set(e),n=0;return await this.visitNamespace(e=>e.tags?.some(e=>t.has(e))?(n+=1,!0):!1),n}async clear(){await this.visitNamespace(()=>!0)}async getUsage(){let e=(await this.getDatabase()).transaction(a,`readonly`),t=waitForTransaction(e),n=e.objectStore(a).index(o).openCursor(this.namespace),r=0,i=0;return await visitCursor(n,e=>{let t=e.value;isValidIndexedDBRecord(t,this.namespace,void 0,this.schemaVersion)&&(r+=1,i=addSizes(i,readIndexedDBRecordSize(t)))}),await t,{entries:r,estimatedBytes:i,maxEntries:this.maxEntries,maxBytes:this.maxBytes,schemaVersion:this.schemaVersion}}async compact(e={}){let t=normalizeCompactionBoundary(e.expiredBefore),n=normalizeCompactionMaxRemovals(e.maxRemovals),r=(await this.getDatabase()).transaction(a,`readwrite`),i=waitForTransaction(r),s=r.objectStore(a).index(o).openCursor(this.namespace),c=new Map,l=0,u=0,d=0,f=!1;return await visitCursor(s,e=>{let r=e.value,i=classifyIndexedDBRecord(r,this.namespace,this.schemaVersion);if(l+=1,i===`malformed`||i===`schema-version`)e.delete(),addCleanupSummary(c,i,r),u+=1,d=addSizes(d,readIndexedDBRecordSize(r));else if(i===`current`&&r.expiresAt<=t){let t=readIndexedDBRecordSize(r);e.delete(),addCleanupSummary(c,`expired`,r),u+=1,d=addSizes(d,t)}if(u>=n)return f=!0,!1}),await i,this.emitCleanupSummaries(c.values()),{scannedEntries:l,removedEntries:u,estimatedBytesFreed:d,expiredBefore:t,hasMore:f}}async close(){let e=this.database;e&&(this.database=void 0,(await e).close())}createKey(e){return this.schemaVersion===1?`${this.namespace}\0${e}`:`${this.namespace}\0@npora-schema:${this.schemaVersion}\0${e}`}async writeRecord(e,t){let n=e.transaction(a,`readwrite`),r=waitForTransaction(n),i=n.objectStore(a),s=new Map;if(isFutureIndexedDBRecord(await waitForRequest(i.get(t.key)),this.schemaVersion)){await r;return}if(i.put(t),this.maxEntries!==1/0||this.maxBytes!==1/0){let e=await waitForRequest(i.index(o).getAll(this.namespace)),n=[];for(let t of e){let e=classifyIndexedDBRecord(t,this.namespace,this.schemaVersion);e===`malformed`||e===`schema-version`?(i.delete(t.key),addCleanupSummary(s,e,t)):e===`current`&&n.push(t)}n.sort((e,n)=>e.key===t.key?1:n.key===t.key?-1:e.accessedAt-n.accessedAt||e.key.localeCompare(n.key));let r=n.reduce((e,t)=>addSizes(e,readIndexedDBRecordSize(t)),0),a=n.length;for(let e of n){if(a<=this.maxEntries&&r<=this.maxBytes)break;i.delete(e.key),addCleanupSummary(s,r>this.maxBytes?`max-bytes`:`max-entries`,e),--a,r=Math.max(0,r-readIndexedDBRecordSize(e))}}await r,this.emitCleanupSummaries(s.values())}async recoverQuota(e){let t=e.transaction(a,`readwrite`),n=waitForTransaction(t),r=t.objectStore(a),i=await waitForRequest(r.index(o).getAll(this.namespace)),s=[],c=new Map,l=!1;for(let e of i){let t=classifyIndexedDBRecord(e,this.namespace,this.schemaVersion);t===`malformed`||t===`schema-version`?(r.delete(e.key),addCleanupSummary(c,t,e),l=!0):t===`current`&&s.push(e)}s.sort((e,t)=>e.accessedAt-t.accessedAt||e.key.localeCompare(t.key));for(let e of s.slice(0,Math.max(1,Math.ceil(s.length/2))))r.delete(e.key),addCleanupSummary(c,`quota-recovery`,e),l=!0;return await n,this.emitCleanupSummaries(c.values()),l}emitCleanupSummaries(e){for(let t of e)this.emitEvent({type:`eviction`,...t})}emitEvent(e){if(this.onEvent)try{Promise.resolve(this.onEvent({...e,timestamp:Date.now()})).catch(()=>{})}catch{}}async visitNamespace(e){let t=(await this.getDatabase()).transaction(a,`readwrite`),n=waitForTransaction(t),r=t.objectStore(a).index(o).openCursor(this.namespace),i=new Map;await visitCursor(r,t=>{let n=t.value,r=classifyIndexedDBRecord(n,this.namespace,this.schemaVersion);(r===`malformed`||r===`schema-version`||r===`current`&&e(n))&&(t.delete(),(r===`malformed`||r===`schema-version`)&&addCleanupSummary(i,r,n))}),await n,this.emitCleanupSummaries(i.values())}getDatabase(){return this.database??(this.database=openCacheDatabase(this.factory,this.databaseName).then(async e=>{try{let t=await pruneOlderSchemaRecords(e,this.namespace,this.schemaVersion);return this.emitCleanupSummaries(t),e}catch(t){throw e.close(),t}})),this.database}};function openCacheDatabase(e,t){return new Promise((n,r)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(a)||e.createObjectStore(a,{keyPath:`key`}).createIndex(o,o,{unique:!1})},i.onerror=()=>r(i.error),i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>e.close(),n(e)}})}function waitForRequest(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}function waitForTransaction(e){let t=new Promise((t,n)=>{let rejectWithTransactionError=t=>{n(e.error??readIDBRequestError(t.target)??Error(`IndexedDB transaction failed`))};e.onabort=rejectWithTransactionError,e.onerror=rejectWithTransactionError,e.oncomplete=()=>t()});return t.catch(()=>{}),t}function readIDBRequestError(e){if(!e||!(`error`in e))return null;let t=e.error;return t instanceof DOMException?t:null}function visitCursor(e,t){return new Promise((n,r)=>{e.onerror=()=>r(e.error),e.onsuccess=()=>{let i=e.result;if(!i){n();return}try{if(t(i)===!1){n();return}}catch(t){try{readCursorTransaction(e)?.abort()}catch{}r(t);return}i.continue()}})}function readCursorTransaction(e){let t=e.source;if(t)return`transaction`in t?t.transaction:`objectStore`in t?t.objectStore.transaction:`transaction`in t.source?t.source.transaction:t.source.objectStore.transaction}function toPortableCacheEntry(e){return{data:e.data,expiresAt:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags}}function isValidIndexedDBRecord(e,t,n,r=1){if(!e||typeof e!=`object`)return!1;let i=e;if(!(typeof i.key==`string`&&(n===void 0||i.key===n)&&i.namespace===t&&readIndexedDBSchemaVersion(i)===r&&(i.expiresAt===1/0||Number.isFinite(i.expiresAt))&&Number.isInteger(i.status)&&i.status>=200&&i.status<=599&&typeof i.statusText==`string`&&Array.isArray(i.headers)&&(i.tags===void 0||Array.isArray(i.tags)&&i.tags.length<=32&&i.tags.every(e=>typeof e==`string`&&e.length>0&&e.length<=128))&&Number.isFinite(i.accessedAt)))return!1;try{return new Headers(i.headers),!0}catch{return!1}}function readIndexedDBSchemaVersion(e){if(!e||typeof e!=`object`)return;let t=e.schemaVersion??1;return Number.isSafeInteger(t)&&t>=1&&t<=1e9?t:void 0}function classifyIndexedDBRecord(e,t,n){let r=readIndexedDBSchemaVersion(e);return r===void 0?`malformed`:r>n?`future`:r<n?`schema-version`:isValidIndexedDBRecord(e,t,void 0,n)?`current`:`malformed`}function isFutureIndexedDBRecord(e,t){let n=readIndexedDBSchemaVersion(e);return n!==void 0&&n>t}function readIndexedDBRecordSize(e){let t=e&&typeof e==`object`?e.size:void 0;return Number.isSafeInteger(t)&&t>=0?t:estimateStructuredCloneSize(e)}function estimateStructuredCloneSize(e,t=new WeakSet){if(e==null)return 0;if(typeof e==`string`)return Math.min(2**53-1,e.length*2);if(typeof e==`number`||typeof e==`bigint`)return 8;if(typeof e==`boolean`)return 4;if(typeof e!=`object`)return 0;if(t.has(e)||(t.add(e),e instanceof Date))return 8;if(typeof Blob<`u`&&e instanceof Blob)return e.size;if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Map){let n=16;for(let[r,i]of e)n=addSizes(n,estimateStructuredCloneSize(r,t),estimateStructuredCloneSize(i,t));return n}if(e instanceof Set){let n=16;for(let r of e)n=addSizes(n,estimateStructuredCloneSize(r,t));return n}let n=Array.isArray(e)?16:32;for(let[r,i]of Object.entries(e))n=addSizes(n,r.length*2,estimateStructuredCloneSize(i,t));return n}function addSizes(...e){let t=0;for(let n of e){if(n>=2**53-1-t)return 2**53-1;t+=n}return t}function addCleanupSummary(e,t,n){let r=e.get(t),i=readIndexedDBRecordSize(n);if(r){r.entries+=1,r.estimatedBytes=addSizes(r.estimatedBytes,i);return}e.set(t,{reason:t,entries:1,estimatedBytes:i})}function isQuotaExceededError(e){return!!(e&&typeof e==`object`&&e.name===`QuotaExceededError`)}async function pruneOlderSchemaRecords(e,t,n){let r=e.transaction(a,`readwrite`),i=waitForTransaction(r),s=r.objectStore(a).index(o).openCursor(t),c=new Map;return await visitCursor(s,e=>{let r=e.value,i=classifyIndexedDBRecord(r,t,n);(i===`malformed`||i===`schema-version`)&&(e.delete(),addCleanupSummary(c,i,r))}),await i,[...c.values()]}function normalizeIndexedDBName(t,n,r){let i=t??r;if(typeof i!=`string`||i.length===0||i.length>128)throw new e.t(`IndexedDB cache ${n} must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return i}function normalizeIndexedDBMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function normalizeIndexedDBMaxBytes(t){if(t===void 0)return 1/0;if(t===1/0)return t;if(!Number.isSafeInteger(t)||t<0)throw new e.t(`IndexedDB cache maxBytes must be a non-negative safe integer or Infinity`,{code:`CONFIG_ERROR`});return t}function normalizeQuotaRecovery(t){if(t===void 0)return!0;if(typeof t!=`boolean`)throw new e.t(`IndexedDB cache quotaRecovery must be a boolean`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBEventObserver(t){if(t!==void 0&&typeof t!=`function`)throw new e.t(`IndexedDB cache onEvent must be a function`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBAdmissionPolicy(t){if(t!==void 0&&typeof t!=`function`)throw new e.t(`IndexedDB cache shouldPersist must be a function`,{code:`CONFIG_ERROR`});return t}function normalizeCompactionBoundary(t){let n=t??Date.now();if(!Number.isFinite(n))throw new e.t(`IndexedDB cache compact expiredBefore must be finite`,{code:`CONFIG_ERROR`});return n}function normalizeCompactionMaxRemovals(t){if(t===void 0||t===1/0)return 1/0;if(!Number.isSafeInteger(t)||t<1)throw new e.t(`IndexedDB cache compact maxRemovals must be a positive safe integer or Infinity`,{code:`CONFIG_ERROR`});return t}function normalizeIndexedDBSchemaVersion(t){let n=t??1;if(!Number.isSafeInteger(n)||n<1||n>1e9)throw new e.t(`IndexedDB cache schemaVersion must be an integer from 1 to 1000000000`,{code:`CONFIG_ERROR`});return n}var TieredCacheStore=class{constructor(t){if(this.leaseReleases=new Set,this.source=`${Date.now()}:${Math.random()}`,this.trackedKeys=new Map,this.trackedKeyCount=0,this.handleMessage=e=>{let t=e.data;if(!isTieredCacheMessage(t)||t.source===this.source)return;if(t.action===`clear`){this.clearPrimary();return}let n=this.trackedKeys.get(t.fingerprint);if(!n){this.clearPrimary();return}this.trackedKeys.delete(t.fingerprint),this.trackedKeyCount-=n.size;for(let e of n)ignoreStoreResult(()=>this.primary.delete(e))},!t||!t.primary||!t.secondary||t.primary===t.secondary)throw new e.t(`Tiered cache requires distinct primary and secondary stores`,{code:`CONFIG_ERROR`});if(this.primary=t.primary,this.secondary=t.secondary,t.broadcast&&!t.broadcast.channel)throw new e.t(`Tiered cache broadcast requires a channel`,{code:`CONFIG_ERROR`});if(t.coordination&&!t.coordination.locks)throw new e.t(`Tiered cache coordination requires a lock manager`,{code:`CONFIG_ERROR`});this.channel=t.broadcast?.channel,this.locks=t.coordination?.locks,this.lockNamespace=normalizeLockNamespace(t.coordination?.namespace),this.maxTrackedKeys=normalizeTrackedKeys(t.broadcast?.maxTrackedKeys),this.locks&&(this.acquireRefreshLease=(e,t)=>this.acquireCoordinatedLease(e,t)),this.channel?.addEventListener(`message`,this.handleMessage)}get(e){let t;try{t=this.primary.get(e)}catch{return this.readSecondary(e)}return n.t(t)?Promise.resolve(t).then(t=>t?this.remember(e,t):this.readSecondary(e),()=>this.readSecondary(e)):t?this.remember(e,t):this.readSecondary(e)}set(e,t){let writePrimary=()=>{let r;try{r=this.primary.set(e,t)}catch(t){throw this.recoverPrimaryWrite(e),t}return n.t(r)?Promise.resolve(r).catch(t=>{throw this.recoverPrimaryWrite(e),t}):r},r=this.secondary.set(e,t),i=n.t(r)?Promise.resolve(r).then(writePrimary):writePrimary();return this.afterSuccess(i,()=>{this.trackKey(e),this.broadcastKey(e)})}delete(e){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.delete(e),()=>this.secondary.delete(e)],()=>void 0),()=>{this.untrackKey(e),this.broadcastKey(e)})}invalidateTags(t){let n=this.primary.invalidateTags,r=this.secondary.invalidateTags;if(!n||!r)throw new e.t(`Both tiered cache stores must support tag invalidation`,{code:`CONFIG_ERROR`});return this.afterSettled(()=>combineStoreOperations([()=>n.call(this.primary,t),()=>r.call(this.secondary,t)],e=>Math.max(...e)),()=>this.broadcastClear())}clear(){return this.afterSettled(()=>combineStoreOperations([()=>this.primary.clear(),()=>this.secondary.clear()],()=>void 0),()=>this.broadcastClear())}async acquireCoordinatedLease(t,n){let r=`${this.lockNamespace}:${fingerprintCacheKey(t)}`,i=await this.requestLease(r,!0,n);if(i)return i;let a=await this.requestLease(r,!1,n);if(!a)throw new e.t(`Cache refresh lock was unavailable`,{code:`NETWORK_ERROR`});return await ignoreStoreFailure(()=>this.primary.delete(t)),a}dispose(){this.channel?.removeEventListener(`message`,this.handleMessage);for(let e of this.leaseReleases)e();this.leaseReleases.clear(),this.trackedKeys.clear(),this.trackedKeyCount=0}requestLease(e,t,n){return new Promise((r,i)=>{let a=!1,o=createDeferred(),s={mode:`exclusive`,ifAvailable:t};n&&(s.signal=n),this.locks.request(e,s,async e=>{if(!e){a=!0,r(void 0);return}let n=!0,release=()=>{n&&(n=!1,this.leaseReleases.delete(release),o.resolve())};this.leaseReleases.add(release),a=!0,r({contended:!t,release}),await o.promise}).catch(e=>{a||i(e)})})}readSecondary(e){let promote=t=>{if(t){try{let r=this.primary.set(e,t);if(n.t(r))return Promise.resolve(r).then(()=>this.remember(e,t),()=>this.remember(e,t))}catch{}return this.remember(e,t)}},t=this.secondary.get(e);return n.t(t)?Promise.resolve(t).then(promote):promote(t)}remember(e,t){return this.trackKey(e),t}trackKey(e){if(!this.channel)return;let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);if(n?.has(e)){this.trackedKeys.delete(t),this.trackedKeys.set(t,n);return}for(;this.trackedKeyCount>=this.maxTrackedKeys;){let e=this.trackedKeys.entries().next().value;if(!e)break;this.trackedKeys.delete(e[0]),this.trackedKeyCount-=e[1].size}n??(n=new Set),n.add(e),this.trackedKeys.delete(t),this.trackedKeys.set(t,n),this.trackedKeyCount+=1}untrackKey(e){let t=fingerprintCacheKey(e),n=this.trackedKeys.get(t);n?.delete(e)&&(--this.trackedKeyCount,n.size===0&&this.trackedKeys.delete(t))}broadcastKey(e){this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`delete`,fingerprint:fingerprintCacheKey(e)})}broadcastClear(){this.trackedKeys.clear(),this.trackedKeyCount=0,this.postMessage({protocol:`npora-cache:1`,source:this.source,action:`clear`})}postMessage(e){try{this.channel?.postMessage(e)}catch{}}clearPrimary(){this.trackedKeys.clear(),this.trackedKeyCount=0,ignoreStoreResult(()=>this.primary.clear())}recoverPrimaryWrite(e){this.untrackKey(e),ignoreStoreResult(()=>this.primary.delete(e)),this.broadcastKey(e)}afterSuccess(e,t){return n.t(e)?Promise.resolve(e).then(e=>(t(),e)):(t(),e)}afterSettled(e,t){let r;try{r=e()}catch(e){throw t(),e}return n.t(r)?Promise.resolve(r).then(e=>(t(),e),e=>{throw t(),e}):(t(),r)}};function combineStoreOperations(e,t){let r=[],i=[],a,o=!1;for(let t of e)try{let e=t();n.t(e)?i.push(Promise.resolve(e).then(e=>{r.push(e)},e=>{o||(o=!0,a=e)})):r.push(e)}catch(e){o||(o=!0,a=e)}let finish=()=>{if(o)throw a;return t(r)};return i.length>0?Promise.all(i).then(finish):finish()}function fingerprintCacheKey(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function isTieredCacheMessage(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.protocol===`npora-cache:1`&&typeof t.source==`string`&&(t.action===`clear`||t.action===`delete`&&typeof t.fingerprint==`string`&&t.fingerprint.length<=16)}function normalizeTrackedKeys(t){let n=t??1e3;if(!Number.isInteger(n)||n<1||n>1e5)throw new e.t(`Tiered cache maxTrackedKeys must be an integer from 1 to 100000`,{code:`CONFIG_ERROR`});return n}function normalizeLockNamespace(t){let n=t??`npora-cache`;if(typeof n!=`string`||n.length<1||n.length>128)throw new e.t(`Tiered cache lock namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return n}function createDeferred(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}function ignoreStoreResult(e){try{let t=e();n.t(t)&&Promise.resolve(t).catch(()=>{})}catch{}}async function ignoreStoreFailure(e){try{await e()}catch{}}var MemoryCacheStore=class{constructor(e={}){this.entries=new Map,this.maxEntries=normalizeMaxEntries(e.maxEntries)}get(e){let t=this.entries.get(e);if(t)return this.newestKey!==e&&(this.entries.delete(e),this.entries.set(e,t),this.newestKey=e),t}set(e,t){if(this.maxEntries!==0){for(this.entries.delete(e);this.entries.size>=this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.entries.delete(e)}this.entries.set(e,t),this.newestKey=e}}delete(e){this.entries.delete(e),this.newestKey===e&&(this.newestKey=void 0)}invalidateTags(e){let t=new Set(e),n=0;for(let[e,r]of this.entries)r.tags?.some(e=>t.has(e))&&(this.entries.delete(e),n+=1,this.newestKey===e&&(this.newestKey=void 0));return n}clear(){this.entries.clear(),this.newestKey=void 0}},WebStorageCacheStore=class{constructor(e,t={}){this.storage=e,this.prefix=createWebStoragePrefix(t.namespace),this.maxEntries=normalizeMaxEntries(t.maxEntries)}get(e){if(this.maxEntries===0)return;let t=this.prefix+e,n=this.read(t);if(n){try{this.storage.setItem(t,serializeWebStorageEntry(n.entry,Date.now()))}catch{}return n.entry}}set(e,t){if(this.maxEntries===0)return;let n=this.prefix+e,r=this.keys(),i=r.includes(n),a=Math.max(0,r.length-this.maxEntries+ +!i);if(a>0){let e=r.map(e=>({key:e,accessedAt:this.read(e)?.accessedAt??0})).filter(e=>e.key!==n).sort((e,t)=>e.accessedAt-t.accessedAt);for(let t of e.slice(0,a))this.storage.removeItem(t.key)}this.storage.setItem(n,serializeWebStorageEntry(t,Date.now()))}delete(e){this.storage.removeItem(this.prefix+e)}invalidateTags(e){let t=new Set(e),n=0;for(let e of this.keys())this.read(e)?.entry.tags?.some(e=>t.has(e))&&(this.storage.removeItem(e),n+=1);return n}clear(){for(let e of this.keys())this.storage.removeItem(e)}keys(){let e=[];for(let t=0;t<this.storage.length;t+=1){let n=this.storage.key(t);n?.startsWith(this.prefix)&&e.push(n)}return e}read(e){let t=this.storage.getItem(e);if(t!==null)try{return parseWebStorageEntry(t)}catch{this.storage.removeItem(e);return}}};const s=[`GET`,`HEAD`],c=[`authorization`,`cookie`,`accept`,`accept-language`],l=[];function createCacheStats(){return{hits:0,misses:0,bypasses:0,invalidations:0,invalidationErrors:0,deduplicated:0,revalidations:0,staleIfError:0,staleWhileRevalidate:0,backgroundRefreshes:0,backgroundRefreshSuccesses:0,backgroundRefreshErrors:0}}function resetCacheStats(e){Object.assign(e,createCacheStats())}function createCacheEventRecorder(e,t){return r=>{if(incrementCacheStat(e,r),t)try{let e=t({type:r,timestamp:Date.now()});n.t(e)&&Promise.resolve(e).catch(ignoreCacheEventError)}catch{}}}function incrementCacheStat(e,t){let n=t===`hit`?`hits`:t===`miss`?`misses`:t===`bypass`?`bypasses`:t===`invalidated`?`invalidations`:t===`invalidation-error`?`invalidationErrors`:t===`deduplicated`?`deduplicated`:t===`revalidated`?`revalidations`:t===`stale-if-error`?`staleIfError`:t===`stale-while-revalidate`?`staleWhileRevalidate`:t===`background-refresh`?`backgroundRefreshes`:t===`background-refresh-success`?`backgroundRefreshSuccesses`:`backgroundRefreshErrors`;e[n]=Math.min(2**53-1,e[n]+1)}function ignoreCacheEventError(){}function cachePlugin(t={}){let a=t.store??new MemoryCacheStore({maxEntries:t.maxEntries}),o=new WeakSet,l=new WeakMap,u=new WeakMap,d=new WeakMap,f=new WeakMap,p=new WeakMap,m=new WeakMap,h=new WeakSet,g=new WeakSet,_=new WeakMap,v=new WeakMap,y=new WeakSet,b=new WeakSet,x=new Map,S=new Map,C=new WeakSet,w=new Map,T=new Map,E=new Map,D=new Map,O=createCacheStats(),k=createCacheEventRecorder(O,t.onEvent),A=0,j=new Set(t.methods??s),M=normalizeVaryHeaders(t.varyHeaders??c),N=normalizeCacheHeaders(void 0,M),P={};function trackKeyOperation(e,t,n,r){let i=Promise.resolve(t),a;return a=i.then(()=>n&&k(n),()=>r&&k(r)).finally(()=>{E.get(e)===a&&E.delete(e)}),E.set(e,a),i}function runKeyOperation(e,t,r=[],i,a){let o=new Set(r),s=E.get(e);if(s&&o.add(s),o.size>0)return trackKeyOperation(e,Promise.all(o).then(t),i,a);let c;try{c=t()}catch(e){throw a&&k(a),e}return n.t(c)?trackKeyOperation(e,c,i,a):(i&&k(i),c)}function invalidateKeyState(e,t){T.delete(e),x.delete(e),S.delete(e);let n=w.get(e);n&&(w.delete(e),n.abort(t))}function trackTagInvalidation(e,t){let n=Promise.resolve(t),r;r=n.then(()=>k(`invalidated`),()=>k(`invalidation-error`)).finally(()=>{for(let t of e)D.get(t)===r&&D.delete(t)});for(let t of e)D.set(t,r);return n}let F={name:`cache`,clear(){return A+=1,x.clear(),S.clear(),T.clear(),abortBackgroundRefreshes(w),a.clear()},delete(e){let t=createCacheKey(e,i.t(e,`cache`)??{},M,N,P);return invalidateKeyState(t,`Cache entry invalidated`),runKeyOperation(t,()=>a.delete(t),[],`invalidated`,`invalidation-error`)},set(e,t,n={}){let r=i.t(e,`cache`)??{},o=createCacheKey(e,r,M,N,P),s=normalizeCacheTtl(n.ttl??r.ttl,e),c=normalizeCacheStatus(n.status,e),l=normalizeCacheTags(n.tags??r.tags,e),u={data:cloneCacheValue(t),expiresAt:s===1/0?s:Date.now()+s,status:c,statusText:n.statusText??(c===200?`OK`:``),headers:[...new Headers(n.headers).entries()],tags:l.length>0?l:void 0},d=l.map(e=>D.get(e)).filter(e=>!!e);return invalidateKeyState(o,`Cache entry replaced`),runKeyOperation(o,()=>a.set(o,u),d)},update(e,t){let r=createCacheKey(e,i.t(e,`cache`)??{},M,N,P);return invalidateKeyState(r,`Cache entry updated`),runKeyOperation(r,()=>{let updateEntry=e=>{if(!e)return!1;let i=t(cloneCacheValue(e.data));if(i===void 0){let e=a.delete(r);return!n.t(e)||Promise.resolve(e).then(()=>!0)}let o=a.set(r,{...e,data:cloneCacheValue(i),raw:void 0});return!n.t(o)||Promise.resolve(o).then(()=>!0)},e=a.get(r);return n.t(e)?Promise.resolve(e).then(updateEntry):updateEntry(e)},D.values())},invalidateTags(t){let r=normalizeCacheTags(t);if(r.length===0)throw new e.t(`Cache tag invalidation requires at least one tag`,{code:`CONFIG_ERROR`});let i=a.invalidateTags;if(!i)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`});for(let[e,t]of T)r.some(e=>t.tags.has(e))&&invalidateKeyState(e,`Cache tags invalidated`);let o=new Set(r.map(e=>D.get(e)).filter(e=>!!e));for(let e of E.values())o.add(e);if(o.size>0)return trackTagInvalidation(r,Promise.all(o).then(()=>i.call(a,r)));let s;try{s=i.call(a,r)}catch(e){throw k(`invalidation-error`),e}return n.t(s)?trackTagInvalidation(r,s):(k(`invalidated`),s)},getStats(){return{...O}},resetStats(){resetCacheStats(O)},install(s){let c=new Set,O=new Set,I=!0;s.hooks.onRequest(t=>{let o=i.t(t.config,`cache`);if(!o)return;let s=normalizeCacheTags(o.invalidateTags,t.config);if(s.length>0){if(!a.invalidateTags)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`,config:t.config});d.set(t,s)}if(!o.enabled||!isCacheableRequest(t.config,j))return;normalizeCacheTtl(o.ttl,t.config),normalizeStaleIfError(o.staleIfError,t.config),normalizeStaleWhileRevalidate(o.staleWhileRevalidate,t.config);let c=normalizeCacheTags(o.tags,t.config),l=resolveRequestCachePolicy(t.config);if(l===`no-store`){k(`bypass`),g.add(t);return}(l===`revalidate`||t.background)&&h.add(t);let f=createCacheKey(t.config,o,M,N,P),p=acquireCacheGeneration(A,f,T,c);u.set(t,p);let read=()=>{let e=readStore(a,f);return t.config.signal&&n.t(e)?r.t(()=>e,t.config).then(e=>{if(isCurrentCacheGeneration(p,A,T))return handleCacheRecord(t,o,f,e,p)}):n.t(e)?Promise.resolve(e).then(e=>{if(isCurrentCacheGeneration(p,A,T))return handleCacheRecord(t,o,f,e,p)}):handleCacheRecord(t,o,f,e,p)},m=new Set,_=E.get(f);_&&m.add(_);for(let e of c){let t=D.get(e);t&&m.add(t)}if(m.size>0){let e=Promise.all(m).then(()=>{});return t.config.signal?r.t(()=>e,t.config).then(read):e.then(read)}return read()}),s.hooks.onResponse(e=>{if(y.has(e)&&e.fallbackResponse){k(`stale-if-error`),o.add(e),l.get(e)?.owner===e&&b.add(e);return}if(o.has(e))return;let t=i.t(e.config,`cache`);if(!t?.enabled||!e.response||!isCacheableRequest(e.config,j)||g.has(e))return;let s=m.get(e);s&&e.response.status===304&&(k(`revalidated`),e.response=createRevalidatedResponse(s,e.response,e.config));let c=l.get(e),d=c?.key??createCacheKey(e.config,t,M,N,P),h=isCurrentCacheGeneration(c?.generation??f.get(e)??u.get(e),A,T),_=(c?.generation??u.get(e))?.token.tags,v=_&&_.size>0?[..._]:s?.tags;if(isAsyncIterable(e.response.data)){if(b.add(e),!h)return;let t=deleteStore(a,d);return n.t(t)?e.config.signal?r.t(()=>t,e.config):t:void 0}let x=normalizeCacheTtl(t.ttl,e.config),S=normalizeStaleIfError(t.staleIfError,e.config),C=normalizeStaleWhileRevalidate(t.staleWhileRevalidate,e.config),w=resolveResponseCachePolicy(e.response,x,S,C),E=w.ttl;if(!w.persist){let t=h?deleteStore(a,d):void 0,i=n.t(t),o=c;return o?.owner===e&&(o.promise!==void 0||i)?p.set(e,createCacheEntry(e.response,Date.now()+Math.max(0,E),e.preserveRaw,v)):o?.owner===e&&b.add(e),i?e.config.signal?r.t(()=>t,e.config):t:void 0}let D=createCacheEntry(e.response,Date.now()+E,e.preserveRaw,v);if(p.set(e,D),!h||c?.rawDemanded)return;let O=writeStore(a,d,D);if(n.t(O))return e.config.signal?r.t(()=>O,e.config):O},{requiresRawResponse:!1});function handleCacheRecord(e,t,i,c,l){if(!(!I||!isCurrentCacheGeneration(l,A,T))){if(c){let u=!isExpired(c.expiresAt),d=h.has(e);if(u&&!d){if(e.preserveRaw&&!c.raw)return prepareCacheMiss(e,t,i,l);let n=restoreCacheEntry(c,e.config);if(n){k(`hit`),e.response=n,o.add(e);return}}if(!e.background&&!d&&canUseStaleWhileRevalidate(c,e.config,e.preserveRaw,normalizeStaleWhileRevalidate(t.staleWhileRevalidate,e.config))){let t=restoreCacheEntry(c,e.config);if(t){k(`stale-while-revalidate`),e.response=t,o.add(e),startBackgroundRefresh(s,w,i,e.initialConfig,e.preserveRaw,k);return}}if(!e.background&&canUseStaleIfError(c,e.config,e.preserveRaw,normalizeStaleIfError(t.staleIfError,e.config))&&_.set(e,c),canRevalidateCacheEntry(c,e.config,e.preserveRaw))return prepareCacheMiss(e,t,i,l,c);if(u&&d||e.background)return prepareCacheMiss(e,t,i,l);let f=deleteStore(a,i);if(n.t(f))return(e.config.signal?r.t(()=>f,e.config):Promise.resolve(f)).then(()=>prepareCacheMiss(e,t,i,l))}return prepareCacheMiss(e,t,i,l)}}function prepareCacheMiss(e,n,i,s,u){if(!I||!isCurrentCacheGeneration(s,A,T))return;if(!(n.dedupe??t.dedupe??!0)){e.background||k(`miss`),f.set(e,s);return}let d=e.preserveRaw?S.get(i):x.get(i)??S.get(i);if(d)return k(`deduplicated`),waitForSharedRecord(getInFlightPromise(d),e.config).then(t=>{t&&(e.response=createCachedResponse(t,e.config),o.add(e))});let p=a.acquireRefreshLease;if(p&&!v.has(e)){let t;try{let n=p.call(a,i,e.config.signal);t=e.config.signal?r.t(()=>n,e.config):n}catch{return v.set(e,{contended:!1,release(){}}),handleCacheRecord(e,n,i,u,s)}return t.then(t=>(v.set(e,t),O.add(t),t.contended&&(h.delete(e),k(`deduplicated`)),Promise.resolve(readStore(a,i)).then(t=>handleCacheRecord(e,n,i,t,s))),t=>{if(e.config.signal?.aborted)throw t;return v.set(e,{contended:!1,release(){}}),handleCacheRecord(e,n,i,u,s)})}if(e.preserveRaw){let e=x.get(i);e&&(e.rawDemanded=!0)}let g=createInFlightRequest(e,i,s);e.preserveRaw?(S.set(i,g),C.add(e)):x.set(i,g),l.set(e,g),c.add(e),e.background||k(`miss`),u&&prepareConditionalRevalidation(e.config,u)&&m.set(e,u)}return s.hooks.onError(e=>{let t=_.get(e);if(!t||!isEligibleStaleIfError(e.error))return;let n=restoreCacheEntry(t,e.config);n&&(y.add(e),e.fallbackResponse=n)}),s.hooks.onSettled(t=>{let r=v.get(t);r&&(r.release(),O.delete(r)),v.delete(t),h.delete(t),g.delete(t),_.delete(t),y.delete(t);let i=u.get(t),invalidateAfterSuccess=()=>{let e=d.get(t);if(d.delete(t),!(!e||t.background||t.error||!t.response))try{let t=F.invalidateTags(e);if(n.t(t))return Promise.resolve(t).then(()=>{}).catch(ignoreCacheEventError)}catch{}};i&&(u.delete(t),releaseCacheGeneration(i,T));let a=l.get(t);if(!a)return invalidateAfterSuccess();l.delete(t),c.delete(t),m.delete(t);let o=a.key,s=C.delete(t)?S:x;if(s.get(o)===a&&s.delete(o),b.delete(t))return a.resolve?.(void 0),invalidateAfterSuccess();let f=p.get(t);return p.delete(t),f&&t.response&&(!t.error||isSchemaValidationFailure(t.error))?(a.resolve?.(f),invalidateAfterSuccess()):(a.reject?.(t.error??new e.t(`Shared request failed`,{code:`NETWORK_ERROR`,config:t.config})),invalidateAfterSuccess())}),()=>{I=!1;for(let e of O)e.release();O.clear();for(let t of c){let n=l.get(t);if(l.delete(t),!n)continue;let r=n.key,i=C.delete(t)?S:x;i.get(r)===n&&i.delete(r),n.reject?.(new e.t(`Cache plugin removed during shared request`,{code:`ABORT_ERROR`}))}c.clear(),T.clear(),abortBackgroundRefreshes(w)}}};return F}function acquireCacheGeneration(e,t,n,r){let i=n.get(t);i||(i={activeRequests:0,tags:new Set},n.set(t,i)),i.activeRequests+=1;for(let e of r)i.tags.add(e);return{global:e,key:t,token:i}}function isCurrentCacheGeneration(e,t,n){return e!==void 0&&e.global===t&&n.get(e.key)===e.token}function releaseCacheGeneration(e,t){--e.token.activeRequests,e.token.activeRequests===0&&t.get(e.key)===e.token&&t.delete(e.key)}function createInFlightRequest(e,t,n){return{owner:e,key:t,generation:n}}function getInFlightPromise(e){if(e.promise)return e.promise;let t,n,r=new Promise((e,r)=>{t=e,n=r});return r.catch(()=>{}),e.promise=r,e.resolve=t,e.reject=n,r}function readStore(e,t){try{let r=e.get(t);return n.t(r)?Promise.resolve(r).catch(()=>void 0):r}catch{return}}function writeStore(e,t,r){try{let i=e.set(t,r);if(n.t(i))return Promise.resolve(i).catch(ignoreStoreError)}catch{}}function deleteStore(e,t){try{let r=e.delete(t);if(n.t(r))return Promise.resolve(r).catch(ignoreStoreError)}catch{}}function ignoreStoreError(){}function waitForSharedRecord(e,t){let n=t.signal;return n?n.aborted?Promise.reject(createSharedAbortError(n.reason,t)):new Promise((r,i)=>{let a=!1,cleanup=()=>{try{n.removeEventListener(`abort`,onAbort)}catch{}},resolveOnce=e=>{a||(a=!0,cleanup(),r(e))},rejectOnce=e=>{a||(a=!0,cleanup(),i(e))},onAbort=()=>{rejectOnce(createSharedAbortError(n.reason,t))};try{n.addEventListener(`abort`,onAbort,{once:!0})}catch(e){rejectOnce(e);return}n.aborted&&onAbort(),!a&&e.then(resolveOnce,e=>{rejectOnce(cloneSharedError(e,t))})}):e.catch(e=>{throw cloneSharedError(e,t)})}function createSharedAbortError(t,n){return new e.t(`Request aborted while waiting for shared response`,{code:`ABORT_ERROR`,config:n,cause:t})}function cloneSharedError(t,n){return t instanceof e.t?new e.t(t.message,{code:t.code,status:t.status,data:t.data,response:t.response,config:n,cause:t}):t}function createCacheEntry(e,t,n,r){return{data:cloneCacheValue(e.data),expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],tags:r?[...r]:void 0,raw:n?cloneResponse(e.raw):void 0}}function createCachedResponse(e,t){return{data:cloneCacheValue(e.data),status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:cloneRawResponse(e)}}function restoreCacheEntry(e,t){try{return createCachedResponse(e,t)}catch{return}}function isCacheableRequest(e,t){return t.has(e.method??`GET`)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`}function isAsyncIterable(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}function isSchemaValidationFailure(t){return t instanceof e.t&&t.code===`SCHEMA_ERROR`}function resolveRequestCachePolicy(e){let t=new Headers(e.headers),n=t.get(`cache-control`),r=!1;if(n)for(let e of n.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),i=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(i===`no-store`)return`no-store`;if(i===`no-cache`){r=!0;continue}if(i===`max-age`&&n!==-1){let e=t.slice(n+1).trim(),i=/^(?:"(\d+)"|(\d+))$/.exec(e);i&&Number(i[1]??i[2])===0&&(r=!0)}}else t.get(`pragma`)?.split(`,`).some(e=>e.trim().toLowerCase()===`no-cache`)&&(r=!0);return r?`revalidate`:`default`}function resolveResponseCachePolicy(e,t,n,r){let i=e.headers.get(`cache-control`),a,o=!1;if(i)for(let e of i.split(`,`)){let t=e.trim(),n=t.indexOf(`=`),r=(n===-1?t:t.slice(0,n)).trim().toLowerCase();if(r===`no-store`)return u;if(r===`no-cache`){o=!0;continue}if(r!==`max-age`)continue;if(a!==void 0)return u;let i=t.slice(n+1).trim(),s=/^(?:"(\d+)"|(\d+))$/.exec(i);if(!s)return u;a=Number(s[1]??s[2])}if(e.headers.get(`vary`)?.split(`,`).some(e=>{let t=e.trim().toLowerCase();return t===`*`||isRequestCacheControlHeader(t)})||t<=0||a!==void 0&&!Number.isSafeInteger(a))return u;let s=o?0:a===void 0?t:Math.min(t,Math.max(0,(a-parseAge(e.headers.get(`age`)))*1e3));return{ttl:s,persist:s>0||hasResponseValidator(e.headers)||resolveStaleIfErrorWindow(e.headers,n)>0||!o&&resolveStaleWhileRevalidateWindow(e.headers,r)>0}}const u={persist:!1,ttl:0};function parseAge(e){if(!e||!/^\d+$/.test(e.trim()))return 0;let t=Number(e);return Number.isSafeInteger(t)?t:0}function canUseStaleIfError(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(t.headers);if(i.has(`if-none-match`)||i.has(`if-modified-since`)||i.has(`range`))return!1;let a=resolveStaleIfErrorWindow(new Headers(e.headers),r);return a>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+a&&restoreCacheEntry(e,t)!==void 0}catch{return!1}}function canUseStaleWhileRevalidate(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(t.headers),a=new Headers(e.headers);if(i.has(`if-none-match`)||i.has(`if-modified-since`)||i.has(`range`)||hasCacheControlDirective(a,`no-cache`)||hasCacheControlDirective(a,`must-revalidate`))return!1;let o=resolveStaleWhileRevalidateWindow(a,r);return o>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+o&&restoreCacheEntry(e,t)!==void 0}catch{return!1}}function resolveStaleIfErrorWindow(e,t){let n=parseStaleIfError(e.get(`cache-control`));return t===void 0?n??0:n===void 0?t:Math.min(t,n)}function resolveStaleWhileRevalidateWindow(e,t){let n=parseCacheDeltaSeconds(e.get(`cache-control`),`stale-while-revalidate`);return t===void 0?n??0:n===void 0?t:Math.min(t,n)}function parseStaleIfError(e){return parseCacheDeltaSeconds(e,`stale-if-error`)}function parseCacheDeltaSeconds(e,t){let n;if(!e)return;for(let r of e.split(`,`)){let e=r.trim(),i=e.indexOf(`=`);if(i===-1||e.slice(0,i).trim().toLowerCase()!==t)continue;if(n!==void 0)return;let a=e.slice(i+1).trim(),o=/^(?:"(\d+)"|(\d+))$/.exec(a);if(!o)return;n=Number(o[1]??o[2])}if(n===void 0||!Number.isSafeInteger(n))return;let r=n*1e3;return Number.isSafeInteger(r)?r:void 0}function hasCacheControlDirective(e,t){return e.get(`cache-control`)?.split(`,`).some(e=>{let n=e.indexOf(`=`);return(n===-1?e:e.slice(0,n)).trim().toLowerCase()===t})??!1}function startBackgroundRefresh(e,t,n,r,i,a){if(t.has(n))return;let o=new AbortController,s={...r,signal:o.signal};t.set(n,o),a(`background-refresh`),Promise.resolve().then(()=>e.dispatch(s,{background:!0,preserveRaw:i})).then(()=>a(`background-refresh-success`),()=>a(`background-refresh-error`)).finally(()=>{t.get(n)===o&&t.delete(n)})}function abortBackgroundRefreshes(e){for(let t of e.values())t.abort(`Cache background refresh stopped`);e.clear()}function isEligibleStaleIfError(t){return t instanceof e.t&&(t.code===`NETWORK_ERROR`||t.code===`TIMEOUT_ERROR`||t.code===`HTTP_ERROR`&&t.status!==void 0&&t.status>=500&&t.status<600)}function canRevalidateCacheEntry(e,t,n){try{if(n&&!e.raw)return!1;let r=new Headers(t.headers);return r.has(`if-none-match`)||r.has(`if-modified-since`)||r.has(`range`)?!1:hasResponseValidator(new Headers(e.headers))&&restoreCacheEntry(e,t)!==void 0}catch{return!1}}function prepareConditionalRevalidation(e,t){let n=new Headers(t.headers),r=n.get(`etag`),i=n.get(`last-modified`);if(!r&&!i)return!1;let a=new Headers(e.headers);r&&a.set(`if-none-match`,r),i&&a.set(`if-modified-since`,i);let o=e.validateStatus;return e.headers=a,e.validateStatus=e=>e===304||(o?o(e):e>=200&&e<300),!0}function hasResponseValidator(e){return e.has(`etag`)||e.has(`last-modified`)}function createRevalidatedResponse(e,t,n){let r=new Headers(e.headers);return t.headers.forEach((e,t)=>{r.set(t,e)}),createCachedResponse({...e,headers:[...r.entries()]},n)}function createCacheKey(e,t,n,r,i){if(t.key)return t.key;let a=e.method??`GET`,o=e.responseType??`auto`,s=!e.headers&&!e.query&&!e.searchParams;if(s&&i.key!==void 0&&i.method===a&&i.baseURL===e.baseURL&&i.url===e.url&&i.responseType===o)return i.key;let c=JSON.stringify({method:a,baseURL:e.baseURL,url:e.url,query:s?l:normalizeQuery(e.searchParams??e.query),responseType:o,headers:e.headers?normalizeCacheHeaders(new Headers(e.headers),n):r});return s&&(i.method=a,i.baseURL=e.baseURL,i.url=e.url,i.responseType=o,i.key=c),c}function normalizeCacheHeaders(e,t){let n=[];e?.forEach((e,t)=>{isRequestCacheControlHeader(t)||n.push([t,e])});for(let r of t)!isRequestCacheControlHeader(r)&&!e?.has(r)&&n.push([r,null]);return n.sort(([e],[t])=>e.localeCompare(t))}function isRequestCacheControlHeader(e){return e===`cache-control`||e===`pragma`}function normalizeVaryHeaders(e){return[...new Set(e.map(e=>e.toLowerCase()))]}function normalizeQuery(e){if(!e)return l;if(t.t(e))return[...e.entries()];let n=[];for(let t of Object.keys(e).sort())appendQueryValue(n,t,e[t]);return n}function appendQueryValue(e,t,n){if(n!==void 0){if(n===null){e.push([t,``]);return}if(Array.isArray(n)){for(let r of n)appendQueryValue(e,t,r);return}e.push([t,String(n)])}}function cloneRawResponse(e){if(e.raw){let t=cloneResponse(e.raw);if(t)return new Response(t.body,{status:e.status,statusText:e.statusText,headers:e.headers})}return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})}function cloneResponse(e){try{return e.clone()}catch{return}}function cloneCacheValue(e){if(typeof e!=`object`||!e||typeof structuredClone!=`function`)return e;try{return structuredClone(e)}catch{return e}}function normalizeMaxEntries(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function normalizeCacheTtl(t,n){let r=t??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new e.t(`Cache ttl must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeCacheStatus(t,n){let r=t??200;if(!Number.isInteger(r)||r<200||r>599)throw new e.t(`Cache status must be an integer between 200 and 599`,{code:`CONFIG_ERROR`,config:n});return r}function normalizeStaleIfError(t,n){if(t!==void 0){if(t!==1/0&&(!Number.isFinite(t)||t<0))throw new e.t(`Cache staleIfError must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return t}}function normalizeStaleWhileRevalidate(t,n){if(t!==void 0){if(t!==1/0&&(!Number.isFinite(t)||t<0))throw new e.t(`Cache staleWhileRevalidate must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return t}}function normalizeCacheTags(t,n){if(t===void 0)return[];if(typeof t!=`string`&&!Array.isArray(t))throw new e.t(`Cache tags must be an array of strings`,{code:`CONFIG_ERROR`,config:n});let r=typeof t==`string`?[t]:t;if(r.length>32)throw new e.t(`Cache tags cannot contain more than 32 values`,{code:`CONFIG_ERROR`,config:n});let i=new Set;for(let t of r){if(typeof t!=`string`||t.length===0||t.length>128)throw new e.t(`Cache tags must contain 1 to 128 characters`,{code:`CONFIG_ERROR`,config:n});i.add(t)}return[...i]}function createWebStoragePrefix(t=`default`){if(typeof t!=`string`||t.length===0||t.length>128)throw new e.t(`Web storage cache namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return`@npora/request:${encodeURIComponent(t)}:`}function serializeWebStorageEntry(e,t){return JSON.stringify({version:1,data:e.data,expiresAt:e.expiresAt===1/0?null:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags,accessedAt:t})}function parseWebStorageEntry(e){let t=JSON.parse(e),n=t.expiresAt===null?1/0:t.expiresAt;if(t.version!==1||n!==1/0&&(typeof n!=`number`||!Number.isFinite(n))||typeof t.status!=`number`||!Number.isInteger(t.status)||t.status<200||t.status>599||typeof t.statusText!=`string`||!Array.isArray(t.headers)||typeof t.accessedAt!=`number`||!Number.isFinite(t.accessedAt))throw TypeError(`Invalid web storage cache entry`);let r=t.tags===void 0?void 0:normalizeCacheTags(t.tags);return{entry:{data:t.data,expiresAt:n,status:t.status,statusText:t.statusText,headers:[...new Headers(t.headers).entries()],tags:r&&r.length>0?r:void 0},accessedAt:t.accessedAt}}function isExpired(e){return e!==1/0&&(Number.isNaN(e)||Date.now()>=e)}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return IndexedDBCacheStore}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return TieredCacheStore}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return WebStorageCacheStore}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return cachePlugin}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return MemoryCacheStore}});
@@ -0,0 +1,59 @@
1
+ import { f as CircuitBreakerStateChange, o as RequestConfig, p as CircuitState } from "./response-BhyS3PAL.cjs";
2
+ import { t as Plugin } from "./Plugin-YysllE6z.cjs";
3
+ //#region src/plugins/circuitBreakerPlugin.d.ts
4
+ interface CircuitBreakerPluginOptions {
5
+ /**
6
+ * Consecutive counted failures required to open a closed circuit.
7
+ *
8
+ * @default 5
9
+ */
10
+ failureThreshold?: number;
11
+ /**
12
+ * Successful probes required to close a half-open circuit.
13
+ *
14
+ * @default 1
15
+ */
16
+ successThreshold?: number;
17
+ /**
18
+ * Time in milliseconds before an open circuit permits probes.
19
+ *
20
+ * @default 30000
21
+ */
22
+ resetTimeout?: number;
23
+ /**
24
+ * Maximum concurrent probes admitted while a circuit is half-open.
25
+ *
26
+ * @default 1
27
+ */
28
+ halfOpenMaxRequests?: number;
29
+ /**
30
+ * Maximum inactive isolation states retained by this plugin instance.
31
+ * Active requests are never evicted and may temporarily exceed the limit.
32
+ *
33
+ * @default 1000
34
+ */
35
+ maxCircuits?: number;
36
+ /**
37
+ * Create the default isolation key for a request.
38
+ *
39
+ * @default the resolved request origin or "default"
40
+ */
41
+ createKey?: (config: RequestConfig) => string;
42
+ /**
43
+ * Decide whether a final request failure affects the circuit.
44
+ *
45
+ * @default network errors, timeouts, HTTP 429, and HTTP 5xx
46
+ */
47
+ shouldCountFailure?: (error: unknown, config: RequestConfig) => boolean | Promise<boolean>;
48
+ /**
49
+ * Observe circuit state changes. Observer failures are isolated.
50
+ */
51
+ onStateChange?: (event: Readonly<CircuitBreakerStateChange>) => void | Promise<void>;
52
+ }
53
+ interface CircuitBreakerPlugin extends Plugin {
54
+ getState(key: string): CircuitState;
55
+ reset(key?: string): void;
56
+ }
57
+ declare function circuitBreakerPlugin(options?: CircuitBreakerPluginOptions): CircuitBreakerPlugin;
58
+ //#endregion
59
+ export { CircuitBreakerPluginOptions as n, circuitBreakerPlugin as r, CircuitBreakerPlugin as t };
@@ -0,0 +1,59 @@
1
+ import { f as CircuitBreakerStateChange, o as RequestConfig, p as CircuitState } from "./response-BhyS3PAL.js";
2
+ import { t as Plugin } from "./Plugin-0Eh51_et.js";
3
+ //#region src/plugins/circuitBreakerPlugin.d.ts
4
+ interface CircuitBreakerPluginOptions {
5
+ /**
6
+ * Consecutive counted failures required to open a closed circuit.
7
+ *
8
+ * @default 5
9
+ */
10
+ failureThreshold?: number;
11
+ /**
12
+ * Successful probes required to close a half-open circuit.
13
+ *
14
+ * @default 1
15
+ */
16
+ successThreshold?: number;
17
+ /**
18
+ * Time in milliseconds before an open circuit permits probes.
19
+ *
20
+ * @default 30000
21
+ */
22
+ resetTimeout?: number;
23
+ /**
24
+ * Maximum concurrent probes admitted while a circuit is half-open.
25
+ *
26
+ * @default 1
27
+ */
28
+ halfOpenMaxRequests?: number;
29
+ /**
30
+ * Maximum inactive isolation states retained by this plugin instance.
31
+ * Active requests are never evicted and may temporarily exceed the limit.
32
+ *
33
+ * @default 1000
34
+ */
35
+ maxCircuits?: number;
36
+ /**
37
+ * Create the default isolation key for a request.
38
+ *
39
+ * @default the resolved request origin or "default"
40
+ */
41
+ createKey?: (config: RequestConfig) => string;
42
+ /**
43
+ * Decide whether a final request failure affects the circuit.
44
+ *
45
+ * @default network errors, timeouts, HTTP 429, and HTTP 5xx
46
+ */
47
+ shouldCountFailure?: (error: unknown, config: RequestConfig) => boolean | Promise<boolean>;
48
+ /**
49
+ * Observe circuit state changes. Observer failures are isolated.
50
+ */
51
+ onStateChange?: (event: Readonly<CircuitBreakerStateChange>) => void | Promise<void>;
52
+ }
53
+ interface CircuitBreakerPlugin extends Plugin {
54
+ getState(key: string): CircuitState;
55
+ reset(key?: string): void;
56
+ }
57
+ declare function circuitBreakerPlugin(options?: CircuitBreakerPluginOptions): CircuitBreakerPlugin;
58
+ //#endregion
59
+ export { CircuitBreakerPluginOptions as n, circuitBreakerPlugin as r, CircuitBreakerPlugin as t };
@@ -0,0 +1,48 @@
1
+ import { o as RequestConfig } from "./response-BhyS3PAL.cjs";
2
+ import { t as Plugin } from "./Plugin-YysllE6z.cjs";
3
+ //#region src/plugins/concurrencyPlugin.d.ts
4
+ interface ConcurrencyPluginOptions {
5
+ /**
6
+ * Maximum active logical requests for each isolation key.
7
+ *
8
+ * @default 10
9
+ */
10
+ maxConcurrent?: number;
11
+ /**
12
+ * Maximum queued requests for each isolation key.
13
+ * Set to zero to reject instead of waiting.
14
+ *
15
+ * @default 1000
16
+ */
17
+ maxQueue?: number;
18
+ /**
19
+ * Maximum time in milliseconds a request may wait for a permit.
20
+ *
21
+ * @default 30000
22
+ */
23
+ queueTimeout?: number;
24
+ /**
25
+ * Maximum inactive isolation states retained by this plugin instance.
26
+ * Active and queued states are never evicted and may temporarily exceed
27
+ * the limit.
28
+ *
29
+ * @default 1000
30
+ */
31
+ maxKeys?: number;
32
+ /**
33
+ * Create the default isolation key for a request.
34
+ *
35
+ * @default the resolved request origin or "default"
36
+ */
37
+ createKey?: (config: RequestConfig) => string;
38
+ }
39
+ interface ConcurrencyState {
40
+ active: number;
41
+ queued: number;
42
+ }
43
+ interface ConcurrencyPlugin extends Plugin {
44
+ getState(key: string): Readonly<ConcurrencyState>;
45
+ }
46
+ declare function concurrencyPlugin(options?: ConcurrencyPluginOptions): ConcurrencyPlugin;
47
+ //#endregion
48
+ export { concurrencyPlugin as i, ConcurrencyPluginOptions as n, ConcurrencyState as r, ConcurrencyPlugin as t };
@@ -0,0 +1,48 @@
1
+ import { o as RequestConfig } from "./response-BhyS3PAL.js";
2
+ import { t as Plugin } from "./Plugin-0Eh51_et.js";
3
+ //#region src/plugins/concurrencyPlugin.d.ts
4
+ interface ConcurrencyPluginOptions {
5
+ /**
6
+ * Maximum active logical requests for each isolation key.
7
+ *
8
+ * @default 10
9
+ */
10
+ maxConcurrent?: number;
11
+ /**
12
+ * Maximum queued requests for each isolation key.
13
+ * Set to zero to reject instead of waiting.
14
+ *
15
+ * @default 1000
16
+ */
17
+ maxQueue?: number;
18
+ /**
19
+ * Maximum time in milliseconds a request may wait for a permit.
20
+ *
21
+ * @default 30000
22
+ */
23
+ queueTimeout?: number;
24
+ /**
25
+ * Maximum inactive isolation states retained by this plugin instance.
26
+ * Active and queued states are never evicted and may temporarily exceed
27
+ * the limit.
28
+ *
29
+ * @default 1000
30
+ */
31
+ maxKeys?: number;
32
+ /**
33
+ * Create the default isolation key for a request.
34
+ *
35
+ * @default the resolved request origin or "default"
36
+ */
37
+ createKey?: (config: RequestConfig) => string;
38
+ }
39
+ interface ConcurrencyState {
40
+ active: number;
41
+ queued: number;
42
+ }
43
+ interface ConcurrencyPlugin extends Plugin {
44
+ getState(key: string): Readonly<ConcurrencyState>;
45
+ }
46
+ declare function concurrencyPlugin(options?: ConcurrencyPluginOptions): ConcurrencyPlugin;
47
+ //#endregion
48
+ export { concurrencyPlugin as i, ConcurrencyPluginOptions as n, ConcurrencyState as r, ConcurrencyPlugin as t };
package/dist/core.cjs ADDED
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./RequestError-DPSv-HVF.cjs"),t=require("./createClient-CibOTVAy.cjs"),n=require("./PluginError-DT3VnlUB.cjs");exports.Client=t.n,exports.FetchAdapter=t.i,exports.InterceptorManager=t.r,exports.PluginError=n.t,exports.RequestError=e.t,exports.SchemaValidationError=t.a,exports.createClient=t.t;
@@ -0,0 +1,6 @@
1
+ import { A as StandardSchemaV1, C as ResponseLogEntry, D as UploadData, E as TransferProgress, O as UploadOptions, S as RequestLogger, T as RetryOptions, _ as DownloadProgress, a as QueryValue, b as LoggerOptions, c as ResponseType, d as CircuitBreakerOptions, f as CircuitBreakerStateChange, g as DownloadOutput, h as DownloadOptions, i as QueryParams, j as HttpMethod, k as UploadProgress, l as AuthOptions, m as ConcurrencyOptions, n as ServerSentEvent, o as RequestConfig, p as CircuitState, r as FetchOptions, s as RequestExtensions, t as NporaResponse, u as CacheOptions, v as ErrorLogEntry, w as RetryEvent, x as RequestLogEntry, y as LoggerEntry } from "./response-BhyS3PAL.cjs";
2
+ import { t as Adapter } from "./adapter-BeVVCcNG.cjs";
3
+ import { a as FetchAdapter, c as ClientOptions, i as RequestErrorOptions, n as RequestError, o as createClient, r as RequestErrorCode, s as Client, t as SchemaValidationError } from "./SchemaValidationError-WMTfqSBV.cjs";
4
+ import { a as PluginInterceptorManager, c as InterceptorOptions, i as PluginHookManager, n as PluginCleanup, o as Interceptor, r as PluginContext, s as InterceptorManager, t as Plugin } from "./Plugin-YysllE6z.cjs";
5
+ import { n as PluginErrorCode, r as PluginErrorOptions, t as PluginError } from "./PluginError-DVP3pUt_.cjs";
6
+ export { Adapter, AuthOptions, CacheOptions, CircuitBreakerOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, DownloadOptions, DownloadOutput, DownloadProgress, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, TransferProgress, UploadData, UploadOptions, UploadProgress, createClient };
package/dist/core.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { A as StandardSchemaV1, C as ResponseLogEntry, D as UploadData, E as TransferProgress, O as UploadOptions, S as RequestLogger, T as RetryOptions, _ as DownloadProgress, a as QueryValue, b as LoggerOptions, c as ResponseType, d as CircuitBreakerOptions, f as CircuitBreakerStateChange, g as DownloadOutput, h as DownloadOptions, i as QueryParams, j as HttpMethod, k as UploadProgress, l as AuthOptions, m as ConcurrencyOptions, n as ServerSentEvent, o as RequestConfig, p as CircuitState, r as FetchOptions, s as RequestExtensions, t as NporaResponse, u as CacheOptions, v as ErrorLogEntry, w as RetryEvent, x as RequestLogEntry, y as LoggerEntry } from "./response-BhyS3PAL.js";
2
+ import { t as Adapter } from "./adapter-ODzpt_dM.js";
3
+ import { a as FetchAdapter, c as ClientOptions, i as RequestErrorOptions, n as RequestError, o as createClient, r as RequestErrorCode, s as Client, t as SchemaValidationError } from "./SchemaValidationError-CjvWT8YA.js";
4
+ import { a as PluginInterceptorManager, c as InterceptorOptions, i as PluginHookManager, n as PluginCleanup, o as Interceptor, r as PluginContext, s as InterceptorManager, t as Plugin } from "./Plugin-0Eh51_et.js";
5
+ import { n as PluginErrorCode, r as PluginErrorOptions, t as PluginError } from "./PluginError-DVP3pUt_.js";
6
+ export { Adapter, AuthOptions, CacheOptions, CircuitBreakerOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, DownloadOptions, DownloadOutput, DownloadProgress, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, TransferProgress, UploadData, UploadOptions, UploadProgress, createClient };
package/dist/core.js ADDED
@@ -0,0 +1 @@
1
+ import{t as e}from"./RequestError-BH6V64XR.js";import{a as t,i as n,n as r,r as i,t as a}from"./createClient-I13D6XsD.js";import{t as o}from"./PluginError-CcuPSIRv.js";export{r as Client,n as FetchAdapter,i as InterceptorManager,o as PluginError,e as RequestError,t as SchemaValidationError,a as createClient};
@@ -0,0 +1 @@
1
+ import{t as e}from"./RequestError-BH6V64XR.js";function throwIfAborted(e){let t=e.signal;if(t?.aborted)throw createAbortError(t.reason,e)}function createAbortError(t,n,r=t){return t instanceof e?new e(t.message,{code:t.code,status:t.status,data:t.data,response:t.response,config:t.config??n,cause:t}):new e(`Request aborted`,{code:`ABORT_ERROR`,config:n,cause:r})}export{throwIfAborted as n,createAbortError as t};
@@ -0,0 +1 @@
1
+ const e=require("./RequestError-DPSv-HVF.cjs");function throwIfAborted(e){let t=e.signal;if(t?.aborted)throw createAbortError(t.reason,e)}function createAbortError(t,n,r=t){return t instanceof e.t?new e.t(t.message,{code:t.code,status:t.status,data:t.data,response:t.response,config:t.config??n,cause:t}):new e.t(`Request aborted`,{code:`ABORT_ERROR`,config:n,cause:r})}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return throwIfAborted}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return createAbortError}});