@npora/request 1.20.0 → 1.20.2
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.
- package/README.md +9 -217
- package/dist/{MockAdapter-BICgVzM5.d.ts → MockAdapter-6MdaHStI.d.ts} +2 -2
- package/dist/{MockAdapter-DUAEKGEf.d.cts → MockAdapter-DS80lrWx.d.cts} +2 -2
- package/dist/{Plugin-Bvp9LRU2.d.ts → Plugin-BvvTFwQj.d.ts} +1 -1
- package/dist/{Plugin-CiarxusT.d.cts → Plugin-LFR-Mb-u.d.cts} +1 -1
- package/dist/{SchemaValidationError-GNbIGIO4.d.cts → SchemaValidationError-D5T7agcb.d.cts} +3 -3
- package/dist/{SchemaValidationError-BzEstkRr.d.ts → SchemaValidationError-erxAaNjo.d.ts} +3 -3
- package/dist/{adapter-DpGCHZY_.d.cts → adapter-C6IM9_f3.d.cts} +1 -1
- package/dist/{adapter-BrKR5FEe.d.ts → adapter-DkVzG4v_.d.ts} +1 -1
- package/dist/{authPlugin-C0D4tQTd.d.cts → authPlugin-C-JOJhQ9.d.cts} +1 -1
- package/dist/{authPlugin-C8ASQ-4Z.d.ts → authPlugin-JZQ0ISdH.d.ts} +1 -1
- package/dist/cachePlugin-C5ge5iH6.cjs +1 -0
- package/dist/{cachePlugin-BLzm2q_M.d.ts → cachePlugin-DI1tXJPk.d.ts} +2 -2
- package/dist/cachePlugin-LkXinWXp.js +1 -0
- package/dist/{cachePlugin-7KDU5wRA.d.cts → cachePlugin-wCADcVdJ.d.cts} +2 -2
- package/dist/{circuitBreakerPlugin-aVehvbcF.d.ts → circuitBreakerPlugin-BA-Fb4e0.d.ts} +2 -2
- package/dist/{circuitBreakerPlugin-WwvV4SrI.d.cts → circuitBreakerPlugin-Ch8uc67V.d.cts} +2 -2
- package/dist/{concurrencyPlugin-Bh3zutAz.d.ts → concurrencyPlugin-DgiZSKYy.d.ts} +2 -2
- package/dist/{concurrencyPlugin-BRTeAkoQ.d.cts → concurrencyPlugin-IDGEoShG.d.cts} +2 -2
- package/dist/core.d.cts +4 -4
- package/dist/core.d.ts +4 -4
- package/dist/{downloadPlugin--XvJLAbm.d.cts → downloadPlugin-CDBxyGy8.d.cts} +1 -1
- package/dist/{downloadPlugin-Ctmd46kx.d.ts → downloadPlugin-TkaOEp9I.d.ts} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +16 -16
- package/dist/index.d.ts +16 -16
- package/dist/index.js +1 -1
- package/dist/loggerPlugin-06w_0Hbs.d.cts +6 -0
- package/dist/loggerPlugin-DllEKlkQ.d.ts +6 -0
- package/dist/{openTelemetryMetricsPlugin-W-C_coOR.d.ts → openTelemetryMetricsPlugin-BSlh7PDU.d.ts} +2 -2
- package/dist/{openTelemetryMetricsPlugin-9MCT4mGr.d.cts → openTelemetryMetricsPlugin-CAAyfWw-.d.cts} +2 -2
- package/dist/{openTelemetryPlugin-DLI9MeuF.d.cts → openTelemetryPlugin-CWgLyQQV.d.cts} +2 -2
- package/dist/{openTelemetryPlugin-CObjBe6B.d.ts → openTelemetryPlugin-hAAiIVka.d.ts} +2 -2
- package/dist/plugins/auth.d.cts +1 -1
- package/dist/plugins/auth.d.ts +1 -1
- package/dist/plugins/cache.cjs +1 -1
- package/dist/plugins/cache.d.cts +1 -1
- package/dist/plugins/cache.d.ts +1 -1
- package/dist/plugins/cache.js +1 -1
- package/dist/plugins/circuit-breaker.d.cts +1 -1
- package/dist/plugins/circuit-breaker.d.ts +1 -1
- package/dist/plugins/concurrency.d.cts +1 -1
- package/dist/plugins/concurrency.d.ts +1 -1
- package/dist/plugins/download.d.cts +1 -1
- package/dist/plugins/download.d.ts +1 -1
- package/dist/plugins/logger.d.cts +1 -1
- package/dist/plugins/logger.d.ts +1 -1
- package/dist/plugins/memory-cache.d.cts +1 -1
- package/dist/plugins/memory-cache.d.ts +1 -1
- package/dist/plugins/opentelemetry-metrics.d.cts +1 -1
- package/dist/plugins/opentelemetry-metrics.d.ts +1 -1
- package/dist/plugins/opentelemetry.d.cts +1 -1
- package/dist/plugins/opentelemetry.d.ts +1 -1
- package/dist/plugins/rate-limit.d.cts +1 -1
- package/dist/plugins/rate-limit.d.ts +1 -1
- package/dist/plugins/retry.cjs +1 -1
- package/dist/plugins/retry.d.cts +1 -1
- package/dist/plugins/retry.d.ts +1 -1
- package/dist/plugins/retry.js +1 -1
- package/dist/plugins/upload.d.cts +1 -1
- package/dist/plugins/upload.d.ts +1 -1
- package/dist/plugins.cjs +1 -1
- package/dist/plugins.d.cts +12 -12
- package/dist/plugins.d.ts +12 -12
- package/dist/plugins.js +1 -1
- package/dist/{rateLimitPlugin-DxdRA__e.d.ts → rateLimitPlugin-B5a7LKCy.d.ts} +2 -2
- package/dist/{rateLimitPlugin-DA0PD-2F.d.cts → rateLimitPlugin-BUkgrdXu.d.cts} +2 -2
- package/dist/{response-ZnYtht6Z.d.cts → response-LhB9NRBw.d.cts} +1 -0
- package/dist/{response-ZnYtht6Z.d.ts → response-LhB9NRBw.d.ts} +1 -0
- package/dist/retryPlugin-CvTlR5xZ.d.ts +6 -0
- package/dist/retryPlugin-DkqM2IjS.d.cts +6 -0
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/{uploadPlugin-Bocwzcvn.d.ts → uploadPlugin-BUH9XZoy.d.ts} +1 -1
- package/dist/{uploadPlugin-CJI5yQHd.d.cts → uploadPlugin-ZP-i_dac.d.cts} +1 -1
- package/package.json +4 -3
- package/dist/cachePlugin-BzOK0Z8f.js +0 -1
- package/dist/cachePlugin-NsWv-5B3.cjs +0 -1
- package/dist/loggerPlugin-C2GQgtWM.d.cts +0 -6
- package/dist/loggerPlugin-D7kLW8RW.d.ts +0 -6
- package/dist/retryPlugin-DdCO93vb.d.ts +0 -6
- package/dist/retryPlugin-DtakMSeN.d.cts +0 -6
package/README.md
CHANGED
|
@@ -406,223 +406,15 @@ const user = await request.get<User>('/users/1', {
|
|
|
406
406
|
cache.clear()
|
|
407
407
|
```
|
|
408
408
|
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
```ts
|
|
414
|
-
const cache = cachePlugin({
|
|
415
|
-
store: sharedStore,
|
|
416
|
-
dedupe: true,
|
|
417
|
-
onEvent(event) {
|
|
418
|
-
metrics.increment(`cache.${event.type}`)
|
|
419
|
-
}
|
|
420
|
-
})
|
|
421
|
-
```
|
|
422
|
-
|
|
423
|
-
Use `cache.getStats()` for a snapshot of hits, misses, bypasses,
|
|
424
|
-
invalidations, deduplication, revalidation, stale recovery, and background
|
|
425
|
-
refresh outcomes.
|
|
426
|
-
`cache.resetStats()` resets only these counters; it does not clear entries.
|
|
427
|
-
Events contain only a decision type and timestamp, never URLs, cache keys, or
|
|
428
|
-
headers. Observer failures do not affect requests.
|
|
429
|
-
Failed manual or automatic invalidations are counted in
|
|
430
|
-
`invalidationErrors` and emit `invalidation-error` without exposing the error.
|
|
431
|
-
|
|
432
|
-
Seed or optimistically update parsed cache data without a network request:
|
|
433
|
-
|
|
434
|
-
```ts
|
|
435
|
-
await cache.set({ url: '/users/1' }, user, {
|
|
436
|
-
ttl: 30000,
|
|
437
|
-
tags: ['user:1']
|
|
438
|
-
})
|
|
439
|
-
|
|
440
|
-
await cache.update<User>({ url: '/users/1' }, current => ({
|
|
441
|
-
...current,
|
|
442
|
-
name: 'Updated locally'
|
|
443
|
-
}))
|
|
444
|
-
```
|
|
445
|
-
|
|
446
|
-
Return `undefined` from `update` to delete the entry. It returns `false` when
|
|
447
|
-
no entry exists. These operations use the same effective cache key as requests,
|
|
448
|
-
wait for overlapping asynchronous store operations, and prevent older
|
|
449
|
-
same-key responses from overwriting the new value.
|
|
450
|
-
|
|
451
|
-
Delete one entry without flushing unrelated cached responses:
|
|
452
|
-
|
|
453
|
-
```ts
|
|
454
|
-
await cache.delete({
|
|
455
|
-
url: '/users/1',
|
|
456
|
-
baseURL: '/api',
|
|
457
|
-
extensions: {
|
|
458
|
-
cache: { enabled: true }
|
|
459
|
-
}
|
|
460
|
-
})
|
|
461
|
-
```
|
|
462
|
-
|
|
463
|
-
Pass the effective request configuration used to create the entry, including
|
|
464
|
-
merged `baseURL`, query, response type, and representation headers. A custom
|
|
465
|
-
`extensions.cache.key` can be deleted without reproducing those dimensions.
|
|
466
|
-
|
|
467
|
-
Group related entries with bounded cache tags and invalidate them together:
|
|
468
|
-
|
|
469
|
-
```ts
|
|
470
|
-
await request.get('/users/1', {
|
|
471
|
-
extensions: {
|
|
472
|
-
cache: {
|
|
473
|
-
enabled: true,
|
|
474
|
-
tags: ['user:1', 'users']
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
})
|
|
478
|
-
|
|
479
|
-
await cache.invalidateTags('user:1')
|
|
480
|
-
```
|
|
481
|
-
|
|
482
|
-
The default memory store supports tags directly. Custom stores must implement
|
|
483
|
-
the optional `CacheStore.invalidateTags()` capability.
|
|
484
|
-
|
|
485
|
-
Persist JSON-compatible cached data across client instances with isolated
|
|
486
|
-
browser storage:
|
|
487
|
-
|
|
488
|
-
```ts
|
|
489
|
-
import { WebStorageCacheStore } from '@npora/request/plugins/cache'
|
|
490
|
-
|
|
491
|
-
const cache = cachePlugin({
|
|
492
|
-
store: new WebStorageCacheStore(sessionStorage, {
|
|
493
|
-
namespace: 'dashboard-v1',
|
|
494
|
-
maxEntries: 250
|
|
495
|
-
})
|
|
496
|
-
})
|
|
497
|
-
```
|
|
498
|
-
|
|
499
|
-
Use `localStorage` only when responses may safely survive browser restarts and
|
|
500
|
-
sign-out boundaries. The adapter never persists native `Response` objects;
|
|
501
|
-
`getResponse()` refetches when raw bytes are required.
|
|
502
|
-
|
|
503
|
-
For larger values and non-blocking storage, use IndexedDB instead:
|
|
504
|
-
|
|
505
|
-
```ts
|
|
506
|
-
import { IndexedDBCacheStore } from '@npora/request/plugins/cache'
|
|
507
|
-
|
|
508
|
-
const store = new IndexedDBCacheStore(indexedDB, {
|
|
509
|
-
databaseName: 'dashboard-cache',
|
|
510
|
-
namespace: 'account:1',
|
|
511
|
-
schemaVersion: 2,
|
|
512
|
-
maxEntries: 500,
|
|
513
|
-
maxBytes: 20 * 1024 * 1024,
|
|
514
|
-
shouldPersist: (entry, bytes) => (
|
|
515
|
-
entry.status === 200 && bytes < 2 * 1024 * 1024
|
|
516
|
-
),
|
|
517
|
-
onEvent: event => metrics.record('persistent-cache', event)
|
|
518
|
-
})
|
|
519
|
-
const cache = cachePlugin({ store })
|
|
520
|
-
```
|
|
521
|
-
|
|
522
|
-
IndexedDB uses structured cloning, preserving values such as `Blob`, `Date`,
|
|
523
|
-
`Map`, typed arrays, and `BigInt` while still omitting native `Response` bodies.
|
|
524
|
-
Increment the positive integer `schemaVersion` whenever the cached data shape
|
|
525
|
-
becomes incompatible. Older records are isolated and pruned automatically;
|
|
526
|
-
the default version `1` continues to read records created before this option
|
|
527
|
-
existed. Older clients preserve every higher-version record without validating
|
|
528
|
-
its envelope, including during writes, clearing, compaction, and quota
|
|
529
|
-
recovery, so rolling deployments remain safe when the persisted structure
|
|
530
|
-
changes completely.
|
|
531
|
-
`maxBytes` adds an approximate structured-clone byte budget alongside
|
|
532
|
-
`maxEntries`. Oversized entries are skipped and older entries are evicted by
|
|
533
|
-
LRU. Quota-exceeded writes remove the oldest half of the current schema cache
|
|
534
|
-
and retry once by default; set `quotaRecovery: false` to report the first quota
|
|
535
|
-
failure without recovery.
|
|
536
|
-
Use `await store.getUsage()` to inspect the current schema's aggregate entry
|
|
537
|
-
count and estimated bytes. The optional `onEvent` observer reports aggregated
|
|
538
|
-
eviction, recovery, cleanup, and oversized-entry rejection events without
|
|
539
|
-
exposing keys, namespaces, URLs, or response data. Observer failures never
|
|
540
|
-
affect cache operations.
|
|
541
|
-
Use `shouldPersist(entry, estimatedBytes)` for application-specific admission,
|
|
542
|
-
such as excluding sensitive payloads, one-hit responses, or large low-value
|
|
543
|
-
objects. It may return a boolean or promise. Returning `false` removes an older
|
|
544
|
-
same-key value and emits an aggregate `admission-policy` rejection; thrown
|
|
545
|
-
errors are reported to the caller and leave the old value unchanged.
|
|
546
|
-
Run bounded maintenance without loading the namespace into memory:
|
|
547
|
-
|
|
548
|
-
```ts
|
|
549
|
-
const result = await store.compact({
|
|
550
|
-
// Preserve seven days for stale-if-error recovery.
|
|
551
|
-
expiredBefore: Date.now() - 7 * 24 * 60 * 60 * 1000,
|
|
552
|
-
maxRemovals: 500
|
|
553
|
-
})
|
|
554
|
-
```
|
|
555
|
-
|
|
556
|
-
`compact()` removes current-schema entries beyond the chosen stale boundary,
|
|
557
|
-
reports aggregate scan/removal/byte counts, and emits privacy-safe `expired`
|
|
558
|
-
events. Repeat while `hasMore` is true when using `maxRemovals`. Usage
|
|
559
|
-
inspection now streams records through an IndexedDB cursor, avoiding a
|
|
560
|
-
namespace-sized result array.
|
|
561
|
-
|
|
562
|
-
Combine memory speed with persistence through a read-through, write-through
|
|
563
|
-
store:
|
|
564
|
-
|
|
565
|
-
```ts
|
|
566
|
-
const persistent = new IndexedDBCacheStore(indexedDB, {
|
|
567
|
-
namespace: 'account:1',
|
|
568
|
-
schemaVersion: 2
|
|
569
|
-
})
|
|
570
|
-
const channel = new BroadcastChannel('dashboard-cache:account:1:v1')
|
|
571
|
-
const store = new TieredCacheStore({
|
|
572
|
-
primary: new MemoryCacheStore({ maxEntries: 100 }),
|
|
573
|
-
secondary: persistent,
|
|
574
|
-
broadcast: { channel },
|
|
575
|
-
coordination: {
|
|
576
|
-
locks: navigator.locks,
|
|
577
|
-
namespace: 'dashboard-cache:account:1:v1'
|
|
578
|
-
}
|
|
579
|
-
})
|
|
580
|
-
const cache = cachePlugin({
|
|
581
|
-
store
|
|
582
|
-
})
|
|
583
|
-
```
|
|
584
|
-
|
|
585
|
-
Hot reads remain synchronous. Cold secondary hits are promoted to memory, and
|
|
586
|
-
writes reach the persistent tier before becoming visible in memory. The
|
|
587
|
-
optional channel evicts stale primary entries in other tabs without sending
|
|
588
|
-
URLs, headers, response data, or complete cache keys. Call `store.dispose()`
|
|
589
|
-
and `channel.close()` when the context is torn down. Optional Web Locks
|
|
590
|
-
coordination serializes same-key refreshes across tabs; waiters reread the
|
|
591
|
-
shared secondary cache instead of issuing a duplicate request. Omit
|
|
592
|
-
`coordination` where `navigator.locks` is unavailable.
|
|
593
|
-
Mutation requests can invalidate tags automatically after their final success:
|
|
594
|
-
|
|
595
|
-
```ts
|
|
596
|
-
await request.patch('/users/1', {
|
|
597
|
-
json: update,
|
|
598
|
-
extensions: {
|
|
599
|
-
cache: {
|
|
600
|
-
invalidateTags: ['user:1', 'users']
|
|
601
|
-
}
|
|
602
|
-
}
|
|
603
|
-
})
|
|
604
|
-
```
|
|
605
|
-
|
|
606
|
-
Final HTTP, Schema, interceptor, cancellation, and exhausted-retry failures do
|
|
607
|
-
not invalidate entries.
|
|
608
|
-
|
|
609
|
-
The default memory store keeps up to 1,000 entries using LRU eviction. Expired
|
|
610
|
-
entries with `ETag` or `Last-Modified` validators are conditionally revalidated;
|
|
611
|
-
set `maxEntries` to tune the bound, use `0` to disable storage, or use `Infinity`
|
|
612
|
-
for an explicitly unbounded store.
|
|
613
|
-
|
|
614
|
-
Request `Cache-Control: no-cache` or `max-age=0` to force validation, and use
|
|
615
|
-
`Cache-Control: no-store` to bypass cache reads, writes, and request sharing.
|
|
616
|
-
Response `stale-if-error` can serve an expired entry after network, timeout, or
|
|
617
|
-
5xx failure; `extensions.cache.staleIfError` sets an application limit in
|
|
618
|
-
milliseconds.
|
|
619
|
-
Response `stale-while-revalidate` can return stale data immediately while one
|
|
620
|
-
deduplicated refresh runs through the same client pipeline in the background.
|
|
409
|
+
See [cache workflows](docs/cache.md) for request sharing, cache updates, tag
|
|
410
|
+
invalidation, HTTP revalidation, stale recovery, persistent stores, and
|
|
411
|
+
coordination across browser tabs.
|
|
621
412
|
|
|
622
413
|
Built-in plugins:
|
|
623
414
|
|
|
624
415
|
- `retryPlugin()`
|
|
625
416
|
- `cachePlugin()`
|
|
417
|
+
- `memoryCachePlugin()`
|
|
626
418
|
- `circuitBreakerPlugin()`
|
|
627
419
|
- `concurrencyPlugin()`
|
|
628
420
|
- `rateLimitPlugin()`
|
|
@@ -863,12 +655,12 @@ for the complete matrix.
|
|
|
863
655
|
|
|
864
656
|
## Versioning
|
|
865
657
|
|
|
866
|
-
`@npora/request` follows Semantic Versioning.
|
|
867
|
-
|
|
868
|
-
|
|
658
|
+
`@npora/request` follows Semantic Versioning. Exports from every public
|
|
659
|
+
entrypoint listed in `package.json.exports`, their TypeScript declarations,
|
|
660
|
+
documented behavior, stable error codes, and plugin lifecycle are public API.
|
|
661
|
+
Breaking changes require a new major version.
|
|
869
662
|
|
|
870
|
-
Internal modules
|
|
871
|
-
API.
|
|
663
|
+
Internal modules outside those public entrypoints are not public API.
|
|
872
664
|
|
|
873
665
|
## License
|
|
874
666
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as HttpMethod, p as RequestConfig, t as NporaResponse, u as QueryParams } from "./response-
|
|
2
|
-
import { t as Adapter } from "./adapter-
|
|
1
|
+
import { G as HttpMethod, p as RequestConfig, t as NporaResponse, u as QueryParams } from "./response-LhB9NRBw.js";
|
|
2
|
+
import { t as Adapter } from "./adapter-DkVzG4v_.js";
|
|
3
3
|
//#region src/adapters/MockAdapter.d.ts
|
|
4
4
|
type MockHandler<T = unknown> = (config: RequestConfig) => T | Promise<T>;
|
|
5
5
|
type MockURLMatcher = string | RegExp;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as HttpMethod, p as RequestConfig, t as NporaResponse, u as QueryParams } from "./response-
|
|
2
|
-
import { t as Adapter } from "./adapter-
|
|
1
|
+
import { G as HttpMethod, p as RequestConfig, t as NporaResponse, u as QueryParams } from "./response-LhB9NRBw.cjs";
|
|
2
|
+
import { t as Adapter } from "./adapter-C6IM9_f3.cjs";
|
|
3
3
|
//#region src/adapters/MockAdapter.d.ts
|
|
4
4
|
type MockHandler<T = unknown> = (config: RequestConfig) => T | Promise<T>;
|
|
5
5
|
type MockURLMatcher = string | RegExp;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { p as RequestConfig, t as NporaResponse } from "./response-
|
|
1
|
+
import { p as RequestConfig, t as NporaResponse } from "./response-LhB9NRBw.js";
|
|
2
2
|
//#region src/interceptors/InterceptorManager.d.ts
|
|
3
3
|
type Interceptor<T> = (value: T) => T | Promise<T>;
|
|
4
4
|
interface InterceptorOptions {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { p as RequestConfig, t as NporaResponse } from "./response-
|
|
1
|
+
import { p as RequestConfig, t as NporaResponse } from "./response-LhB9NRBw.cjs";
|
|
2
2
|
//#region src/interceptors/InterceptorManager.d.ts
|
|
3
3
|
type Interceptor<T> = (value: T) => T | Promise<T>;
|
|
4
4
|
interface InterceptorOptions {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { W as StandardSchemaV1, g as RequestURL, h as RequestInputConfig, i as StreamingSchemaLocation, n as ServerSentEvent, p as RequestConfig, r as SseReconnectOptions, t as NporaResponse } from "./response-
|
|
2
|
-
import { t as Adapter } from "./adapter-
|
|
3
|
-
import { s as InterceptorManager, t as Plugin } from "./Plugin-
|
|
1
|
+
import { W as StandardSchemaV1, g as RequestURL, h as RequestInputConfig, i as StreamingSchemaLocation, n as ServerSentEvent, p as RequestConfig, r as SseReconnectOptions, t as NporaResponse } from "./response-LhB9NRBw.cjs";
|
|
2
|
+
import { t as Adapter } from "./adapter-C6IM9_f3.cjs";
|
|
3
|
+
import { s as InterceptorManager, t as Plugin } from "./Plugin-LFR-Mb-u.cjs";
|
|
4
4
|
//#region src/types/client.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Client creation options.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { W as StandardSchemaV1, g as RequestURL, h as RequestInputConfig, i as StreamingSchemaLocation, n as ServerSentEvent, p as RequestConfig, r as SseReconnectOptions, t as NporaResponse } from "./response-
|
|
2
|
-
import { t as Adapter } from "./adapter-
|
|
3
|
-
import { s as InterceptorManager, t as Plugin } from "./Plugin-
|
|
1
|
+
import { W as StandardSchemaV1, g as RequestURL, h as RequestInputConfig, i as StreamingSchemaLocation, n as ServerSentEvent, p as RequestConfig, r as SseReconnectOptions, t as NporaResponse } from "./response-LhB9NRBw.js";
|
|
2
|
+
import { t as Adapter } from "./adapter-DkVzG4v_.js";
|
|
3
|
+
import { s as InterceptorManager, t as Plugin } from "./Plugin-BvvTFwQj.js";
|
|
4
4
|
//#region src/types/client.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Client creation options.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./RequestError-DrCr_lwO.cjs"),t=require("./isBinaryBody-DNjjEzFS.cjs"),n=require("./waitForSignal-9c9DAqqS.cjs"),r=require("./isPromiseLike-B4LL7DlV.cjs"),i=require("./resolveExtensionConfig-D_eh4DjS.cjs");function a(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 o(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 s(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 c(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 l(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 u(e){return e!==1/0&&(Number.isNaN(e)||Date.now()>=e)}var MemoryCacheStore=class{constructor(e={}){this.entries=new Map,this.maxEntries=d(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=f(t.namespace),this.maxEntries=d(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,p(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,p(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 m(t)}catch{this.storage.removeItem(e);return}}};function d(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function f(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 p(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 m(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:l(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}}const h=[];function g(e,t,n,r,i){if(t.key)return t.key;let a=e.method??`GET`,o=String(e.url),s=e.responseType??`auto`,c=e.fetchOptions?.credentials??`same-origin`,l=!e.headers&&!e.query&&!e.searchParams;if(l&&i.key!==void 0&&i.method===a&&i.baseURL===e.baseURL&&i.url===o&&i.responseType===s&&i.credentials===c)return i.key;let u=JSON.stringify({method:a,baseURL:e.baseURL,url:o,query:l?h:b(e.searchParams??e.query),responseType:s,credentials:c,headers:e.headers?_(new Headers(e.headers),n):r});return l&&(i.method=a,i.baseURL=e.baseURL,i.url=o,i.responseType=s,i.credentials=c,i.key=u),u}function _(e,t){let n=[];e?.forEach((e,t)=>{v(t)||n.push([t,e])});for(let r of t)!v(r)&&!e?.has(r)&&n.push([r,null]);return n.sort(([e],[t])=>e.localeCompare(t))}function v(e){return e===`cache-control`||e===`pragma`}function y(e){return[...new Set(e.map(e=>e.toLowerCase()))]}function b(e){if(!e)return h;if(t.r(e))return[...e.entries()];let n=[];for(let t of Object.keys(e).sort())x(n,t,e[t]);return n}function x(e,t,n){if(n!==void 0){if(n===null){e.push([t,``]);return}if(Array.isArray(n)){for(let r of n)x(e,t,r);return}e.push([t,String(n)])}}const S={hit:`hits`,miss:`misses`,bypass:`bypasses`,invalidated:`invalidations`,"invalidation-error":`invalidationErrors`,deduplicated:`deduplicated`,revalidated:`revalidations`,"stale-if-error":`staleIfError`,"stale-while-revalidate":`staleWhileRevalidate`,"background-refresh":`backgroundRefreshes`,"background-refresh-success":`backgroundRefreshSuccesses`,"background-refresh-error":`backgroundRefreshErrors`};function C(){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 w(e){Object.assign(e,C())}function T(e,t){return n=>{if(E(e,n),t)try{let e=t({type:n,timestamp:Date.now()});r.t(e)&&Promise.resolve(e).catch(D)}catch{}}}function E(e,t){let n=S[t];e[n]=Math.min(2**53-1,e[n]+1)}function D(){}const O=[`GET`,`HEAD`],k=[`authorization`,`cookie`,`accept`,`accept-language`];function A(e){let t=e.store??new MemoryCacheStore({maxEntries:e.maxEntries}),n=new WeakSet,r=new WeakMap,i=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakMap,c=new WeakSet,l=new WeakSet,u=new WeakMap,d=new WeakMap,f=new WeakSet,p=new WeakSet,m=new Map,h=new Map,g=new WeakSet,v=new Map,b=new Map,x=new Map,S=new Map,w=C(),E=T(w,e.onEvent),D=new Set(e.methods??O),A=y(e.varyHeaders??k);return{store:t,cacheHits:n,leaders:r,requestGenerations:i,automaticInvalidations:a,completedRecords:o,revalidations:s,forcedRevalidations:c,noStoreRequests:l,staleFallbacks:u,refreshLeases:d,cacheFallbacks:f,uncacheableLeaders:p,inFlight:m,rawInFlight:h,rawLeaders:g,backgroundRefreshes:v,keyGenerations:b,keyOperations:x,tagInvalidations:S,stats:w,recordEvent:E,generation:0,methods:D,varyHeaders:A,emptyHeaderValues:_(void 0,A),keyMemo:{}}}const j={persist:!1,ttl:0};function ee(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=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());e&&Number(e[1]??e[2])===0&&(r=!0)}}else t.get(`pragma`)?.split(`,`).some(e=>e.trim().toLowerCase()===`no-cache`)&&(r=!0);return r?`revalidate`:`default`}function M(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 j;if(r===`no-cache`){o=!0;continue}if(r!==`max-age`)continue;if(a!==void 0)return j;let i=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());if(!i)return j;a=Number(i[1]??i[2])}if(e.headers.get(`vary`)?.split(`,`).some(e=>{let t=e.trim().toLowerCase();return t===`*`||oe(t)})||t<=0||a!==void 0&&!Number.isSafeInteger(a))return j;let s=o?0:a===void 0?t:Math.min(t,Math.max(0,(a-ie(e.headers.get(`age`)))*1e3));return{ttl:s,persist:s>0||ae(e.headers)||N(e.headers,n)>0||!o&&P(e.headers,r)>0}}function N(e,t){return ne(e,t,`stale-if-error`)}function P(e,t){return ne(e,t,`stale-while-revalidate`)}function te(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 ne(e,t,n){let r=re(e.get(`cache-control`),n);return t===void 0?r??0:r===void 0?t:Math.min(t,r)}function re(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=/^(?:"(\d+)"|(\d+))$/.exec(e.slice(i+1).trim());if(!a)return;n=Number(a[1]??a[2])}if(n===void 0||!Number.isSafeInteger(n))return;let r=n*1e3;return Number.isSafeInteger(r)?r:void 0}function ie(e){if(!e||!/^\d+$/.test(e.trim()))return 0;let t=Number(e);return Number.isSafeInteger(t)?t:0}function ae(e){return e.has(`etag`)||e.has(`last-modified`)}function oe(e){return e===`cache-control`||e===`pragma`}function se(e,t,n){return t.has(e.method??`GET`)&&(!ce(e)||!!n.key)&&(!e.parseJson||!!n.key)&&(!e.querySerializer||!!n.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.integrity===void 0&&(e.fetchOptions?.redirect===void 0||e.fetchOptions.redirect===`follow`)}function ce(e){return e.body!=null||e.json!==void 0||e.form!=null||e.formData!=null}function le(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}function ue(t){return e.n(t)&&t.code===`SCHEMA_ERROR`}function de(e,t,n,r){try{if(n&&!e.raw||F(t))return!1;let i=N(new Headers(e.headers),r);return i>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+i}catch{return!1}}function fe(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(e.headers);if(F(t)||te(i,`no-cache`)||te(i,`must-revalidate`))return!1;let a=P(i,r);return a>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+a}catch{return!1}}function pe(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 me(e){for(let t of e.values())t.abort(`Cache background refresh stopped`);e.clear()}function he(t){return e.n(t)&&(t.code===`NETWORK_ERROR`||t.code===`TIMEOUT_ERROR`||t.code===`HTTP_ERROR`&&t.status!==void 0&&t.status>=500&&t.status<600)}function ge(e,t,n){try{return n&&!e.raw||F(t)?!1:ve(new Headers(e.headers))}catch{return!1}}function _e(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,s=e.throwHttpErrors;return e.headers=a,e.throwHttpErrors=void 0,e.validateStatus=e=>e===304||(o?o(e):s===!1||e>=200&&e<300),!0}function ve(e){return e.has(`etag`)||e.has(`last-modified`)}function F(e){let t=new Headers(e.headers);return t.has(`if-none-match`)||t.has(`if-modified-since`)||t.has(`range`)}function ye(e,t,n,r){return{data:R(e.data),expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],tags:r?[...r]:void 0,raw:n?Se(e.raw):void 0}}function I(e,t){return{data:R(e.data),status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:xe(e)}}function L(e,t){try{return I(e,t)}catch{return}}function be(e,t,n){let r=new Headers(e.headers);return t.headers.forEach((e,t)=>{r.set(t,e)}),I({...e,headers:[...r.entries()]},n)}function xe(e){if(e.raw){let t=Se(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 Se(e){try{return e.clone()}catch{return}}function R(e){if(typeof e!=`object`||!e||typeof structuredClone!=`function`)return e;try{return structuredClone(e)}catch{return e}}function Ce(e){let{keyOperations:t,tagInvalidations:n,recordEvent:i,keyGenerations:a,inFlight:o,rawInFlight:s,backgroundRefreshes:c}=e;function l(e,n,r,a){let o=Promise.resolve(n),s;return s=o.then(()=>r&&i(r),()=>a&&i(a)).finally(()=>{t.get(e)===s&&t.delete(e)}),t.set(e,s),o}function u(e,n,a=[],o,s){let c=new Set(a),u=t.get(e);if(u&&c.add(u),c.size>0)return l(e,Promise.all(c).then(n),o,s);let d;try{d=n()}catch(e){throw s&&i(s),e}return r.t(d)?l(e,d,o,s):(o&&i(o),d)}function d(e,t){a.delete(e),o.delete(e),s.delete(e);let n=c.get(e);n&&(c.delete(e),n.abort(t))}function f(e,t){let r=Promise.resolve(t),a;a=r.then(()=>i(`invalidated`),()=>i(`invalidation-error`)).finally(()=>{for(let t of e)n.get(t)===a&&n.delete(t)});for(let t of e)n.set(t,a);return r}return{runKeyOperation:u,invalidateKeyState:d,trackTagInvalidation:f}}function we(t){let{store:n,keyGenerations:s,inFlight:c,rawInFlight:u,backgroundRefreshes:d,keyOperations:f,tagInvalidations:p,recordEvent:m,varyHeaders:h,emptyHeaderValues:_,keyMemo:v,stats:y}=t,{runKeyOperation:b,invalidateKeyState:x,trackTagInvalidation:S}=Ce(t);return{clear(){return t.generation+=1,c.clear(),u.clear(),s.clear(),me(d),n.clear()},delete(e){let t=g(e,i.t(e,`cache`)??{},h,_,v);return x(t,`Cache entry invalidated`),b(t,()=>n.delete(t),[],`invalidated`,`invalidation-error`)},set(e,t,r={}){let s=i.t(e,`cache`)??{},c=g(e,s,h,_,v),u=a(r.ttl??s.ttl,e),d=o(r.status,e),f=l(r.tags??s.tags,e),m={data:R(t),expiresAt:u===1/0?u:Date.now()+u,status:d,statusText:r.statusText??(d===200?`OK`:``),headers:[...new Headers(r.headers).entries()],tags:f.length>0?f:void 0},y=f.map(e=>p.get(e)).filter(e=>!!e);return x(c,`Cache entry replaced`),b(c,()=>n.set(c,m),y)},update(e,t){let a=g(e,i.t(e,`cache`)??{},h,_,v);return x(a,`Cache entry updated`),b(a,()=>{let e=e=>{if(!e)return!1;let i=t(R(e.data));if(i===void 0){let e=n.delete(a);return!r.t(e)||Promise.resolve(e).then(()=>!0)}let o=n.set(a,{...e,data:R(i),raw:void 0});return!r.t(o)||Promise.resolve(o).then(()=>!0)},i=n.get(a);return r.t(i)?Promise.resolve(i).then(e):e(i)},p.values())},invalidateTags(t){let i=l(t);if(i.length===0)throw new e.t(`Cache tag invalidation requires at least one tag`,{code:`CONFIG_ERROR`});let a=n.invalidateTags;if(!a)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`});for(let[e,t]of s)i.some(e=>t.tags.has(e))&&x(e,`Cache tags invalidated`);let o=new Set(i.map(e=>p.get(e)).filter(e=>!!e));for(let e of f.values())o.add(e);if(o.size>0)return S(i,Promise.all(o).then(()=>a.call(n,i)));let c;try{c=a.call(n,i)}catch(e){throw m(`invalidation-error`),e}return r.t(c)?S(i,c):(m(`invalidated`),c)},getStats(){return{...y}},resetStats(){w(y)}}}function Te(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 z(e,t,n){return e!==void 0&&e.global===t&&n.get(e.key)===e.token}function Ee(e,t){--e.token.activeRequests,e.token.activeRequests===0&&t.get(e.key)===e.token&&t.delete(e.key)}function De(e,t,n){return{owner:e,key:t,generation:n}}function Oe(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 ke(e,t){try{let n=e.get(t);return r.t(n)?Promise.resolve(n).catch(()=>void 0):n}catch{return}}function Ae(e,t,n){try{let i=e.set(t,n);if(r.t(i))return Promise.resolve(i).catch(Me)}catch{}}function je(e,t){try{let n=e.delete(t);if(r.t(n))return Promise.resolve(n).catch(Me)}catch{}}function Me(){}function Ne(e,t){let n=t.signal;return n?n.aborted?Promise.reject(Pe(n.reason,t)):new Promise((r,i)=>{let a=!1,o=()=>{try{n.removeEventListener(`abort`,l)}catch{}},s=e=>{a||(a=!0,o(),r(e))},c=e=>{a||(a=!0,o(),i(e))},l=()=>{c(Pe(n.reason,t))};try{n.addEventListener(`abort`,l,{once:!0})}catch(e){c(e);return}n.aborted&&l(),!a&&e.then(s,e=>{c(Fe(e,t))})}):e.catch(e=>{throw Fe(e,t)})}function Pe(t,n){return new e.t(`Request aborted while waiting for shared response`,{code:`ABORT_ERROR`,config:n,cause:t})}function Fe(t,n){return e.n(t)?new e.t(t.message,{code:t.code,status:t.status,data:t.data,response:t.response,config:n,cause:t}):t}function Ie(e){let{cacheFallbacks:t,recordEvent:o,cacheHits:l,leaders:u,uncacheableLeaders:d,methods:f,noStoreRequests:p,revalidations:m,requestGenerations:h,keyGenerations:g,completedRecords:_,store:v}=e;return y=>{if(t.has(y)&&y.fallbackResponse){o(`stale-if-error`),l.add(y),y.cacheHit=!0,u.get(y)?.owner===y&&d.add(y);return}if(l.has(y))return;let b=i.t(y.config,`cache`);if(!b?.enabled||!y.response||!se(y.config,f,b)||p.has(y))return;let x=m.get(y);if(y.response.raw.type===`opaque`||y.response.raw.type===`opaqueredirect`){u.get(y)?.owner===y&&d.add(y);return}x&&y.response.status===304&&(o(`revalidated`),y.response=be(x,y.response,y.config));let S=u.get(y),C=S?.generation??h.get(y);if(!C)return;let w=C.key,T=z(C,e.generation,g),E=C.token.tags,D=E&&E.size>0?[...E]:x?.tags;if(le(y.response.data)){if(d.add(y),!T)return;let e=je(v,w);return r.t(e)?y.config.signal?n.n(()=>e,y.config):e:void 0}let O=a(b.ttl,y.config),k=s(b.staleIfError,y.config),A=c(b.staleWhileRevalidate,y.config),j=M(y.response,O,k,A),ee=j.ttl;if(!j.persist){let e=T?je(v,w):void 0,t=r.t(e),i=S;return i?.owner===y&&(i.promise!==void 0||t)?_.set(y,ye(y.response,Date.now()+Math.max(0,ee),y.preserveRaw,D)):i?.owner===y&&d.add(y),t?y.config.signal?n.n(()=>e,y.config):e:void 0}let N=ye(y.response,Date.now()+ee,y.preserveRaw,D);if(_.set(y,N),!T||S?.rawDemanded)return;let P=Ae(v,w,N);if(r.t(P))return y.config.signal?n.n(()=>P,y.config):P}}function Le(e,t,r,i){let{keyGenerations:a,recordEvent:o,rawInFlight:s,inFlight:c,cacheHits:l,store:u,refreshLeases:d,forcedRevalidations:f,rawLeaders:p,leaders:m,revalidations:h}=e,{ownedLeaders:g,ownedRefreshLeases:_}=t;function v(v,y,b,x,S){if(!(!t.active||!z(x,e.generation,a))){if(y.dedupe??r.dedupe??!0){let e=v.preserveRaw?s.get(b):c.get(b)??s.get(b);if(e)return o(`deduplicated`),Ne(Oe(e),v.config).then(e=>{e&&(v.response=I(e,v.config),l.add(v),v.cacheHit=!0)});let r=u.acquireRefreshLease;if(r&&!d.has(v)){let e,a=()=>(d.set(v,{contended:!1,release(){}}),i(v,y,b,S,x));try{let i=r.call(u,b,v.config.signal).then(e=>(!t.active||v.config.signal?.aborted?e.release():(d.set(v,e),_.add(e)),e));e=n.t(i,v.config)}catch{return a()}return e.then(e=>{if(t.active)return e.contended&&(f.delete(v),o(`deduplicated`)),n.n(()=>ke(u,b),v.config).then(e=>i(v,y,b,e,x))},e=>{if(v.config.signal?.aborted)throw e;return a()})}if(v.preserveRaw){let e=c.get(b);e&&(e.rawDemanded=!0)}let a=De(v,b,x);v.preserveRaw?(s.set(b,a),p.add(v)):c.set(b,a),m.set(v,a),g.add(v)}v.background||o(`miss`),S&&_e(v.config,S)&&h.set(v,S)}}return v}function Re(e,t,i,a){let{keyGenerations:o,forcedRevalidations:l,recordEvent:d,cacheHits:f,backgroundRefreshes:p,staleFallbacks:m,store:h}=e;function g(g,_,v,y,b){if(!(!t.active||!z(b,e.generation,o))){if(y){let e=!u(y.expiresAt),t=l.has(g);if(e&&!t){if(g.preserveRaw&&!y.raw)return a(g,_,v,b);let e=L(y,g.config);if(e){d(`hit`),g.response=e,f.add(g),g.cacheHit=!0;return}}if(!g.background&&!t&&fe(y,g.config,g.preserveRaw,c(_.staleWhileRevalidate,g.config))){let e=L(y,g.config);if(e){d(`stale-while-revalidate`),g.response=e,f.add(g),g.cacheHit=!0,pe(i,p,v,g.initialConfig,g.preserveRaw,d);return}}if(!g.background&&de(y,g.config,g.preserveRaw,s(_.staleIfError,g.config))&&m.set(g,y),ge(y,g.config,g.preserveRaw)&&L(y,g.config))return a(g,_,v,b,y);if(e&&t||g.background)return a(g,_,v,b);let o=je(h,v);if(r.t(o))return(g.config.signal?n.n(()=>o,g.config):Promise.resolve(o)).then(()=>a(g,_,v,b))}return a(g,_,v,b)}}return g}function ze(t,o,u,d){let{store:f,automaticInvalidations:p,methods:m,recordEvent:h,noStoreRequests:_,forcedRevalidations:v,varyHeaders:y,emptyHeaderValues:b,keyMemo:x,keyGenerations:S,requestGenerations:C,keyOperations:w,tagInvalidations:T}=t,E=Re(t,o,u,Le(t,o,d,(...e)=>E(...e)));return o=>{let u=i.t(o.config,`cache`);if(!u)return;let d=l(u.invalidateTags,o.config);if(d.length>0){if(!f.invalidateTags)throw new e.t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`,config:o.config});p.set(o,d)}if(!u.enabled||!se(o.config,m,u))return;a(u.ttl,o.config),s(u.staleIfError,o.config),c(u.staleWhileRevalidate,o.config);let D=l(u.tags,o.config),O=ee(o.config);if(O===`no-store`){h(`bypass`),_.add(o);return}(O===`revalidate`||o.background)&&v.add(o);let k=g(o.config,u,y,b,x),A=Te(t.generation,k,S,D);C.set(o,A);let j=()=>{let e=ke(f,k);return r.t(e)?(o.config.signal?n.n(()=>e,o.config):Promise.resolve(e)).then(e=>{if(z(A,t.generation,S))return E(o,u,k,e,A)}):E(o,u,k,e,A)},M=new Set,N=w.get(k);N&&M.add(N);for(let e of D){let t=T.get(e);t&&M.add(t)}if(M.size>0){let e=Promise.all(M).then(()=>{});return o.config.signal?n.n(()=>e,o.config).then(j):e.then(j)}return j()}}function Be(){return{active:!0,ownedLeaders:new Set,ownedRefreshLeases:new Set}}function Ve(e){let{staleFallbacks:t,cacheFallbacks:n}=e;return e=>{let r=t.get(e);if(!r||!he(e.error))return;let i=L(r,e.config);i&&(n.add(e),e.fallbackResponse=i)}}function He(t,n,i){let{refreshLeases:a,forcedRevalidations:o,noStoreRequests:s,staleFallbacks:c,cacheFallbacks:l,requestGenerations:u,automaticInvalidations:d,keyGenerations:f,leaders:p,revalidations:m,rawLeaders:h,rawInFlight:g,inFlight:_,uncacheableLeaders:v,completedRecords:y}=t,{ownedLeaders:b,ownedRefreshLeases:x}=n;return t=>{let n=a.get(t);n&&(n.release(),x.delete(n)),a.delete(t),o.delete(t),s.delete(t),c.delete(t),l.delete(t);let S=u.get(t),C=()=>{let e=d.get(t);if(d.delete(t),!(!e||t.background||t.error||!t.response))try{let t=i.invalidateTags(e);if(r.t(t))return Promise.resolve(t).then(()=>{}).catch(D)}catch{}};S&&(u.delete(t),Ee(S,f));let w=p.get(t);if(!w)return C();p.delete(t),b.delete(t),m.delete(t);let T=w.key,E=h.delete(t)?g:_;if(E.get(T)===w&&E.delete(T),v.delete(t))return w.resolve?.(void 0),C();let O=y.get(t);return y.delete(t),O&&t.response&&(!t.error||ue(t.error))?(w.resolve?.(O),C()):(w.reject?.(t.error??new e.t(`Shared request failed`,{code:`NETWORK_ERROR`,config:t.config})),C())}}function Ue(t,n){let{leaders:r,rawLeaders:i,rawInFlight:a,inFlight:o,keyGenerations:s,backgroundRefreshes:c}=t,{ownedLeaders:l,ownedRefreshLeases:u}=n;return()=>{n.active=!1;for(let e of u)e.release();u.clear();for(let t of l){let n=r.get(t);if(r.delete(t),!n)continue;let s=n.key,c=i.delete(t)?a:o;c.get(s)===n&&c.delete(s),n.reject?.(new e.t(`Cache plugin removed during shared request`,{code:`ABORT_ERROR`}))}l.clear(),s.clear(),me(c)}}const B=`entries`,V=`namespace`;function We(e,t){return new Promise((n,r)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(`entries`)||e.createObjectStore(B,{keyPath:`key`}).createIndex(V,V,{unique:!1})},i.onerror=()=>r(i.error),i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>e.close(),n(e)}})}function H(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}function U(e){let t=new Promise((t,n)=>{let r=t=>{n(e.error??Ge(t.target)??Error(`IndexedDB transaction failed`))};e.onabort=r,e.onerror=r,e.oncomplete=()=>t()});return t.catch(()=>{}),t}function Ge(e){if(!e||!(`error`in e))return null;let t=e.error;return t instanceof DOMException?t:null}function W(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{Ke(e)?.abort()}catch{}r(t);return}i.continue()}})}function Ke(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 G(e){return{data:e.data,expiresAt:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags}}function K(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&&qe(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 qe(e){if(!e||typeof e!=`object`)return;let t=e.schemaVersion??1;return Number.isSafeInteger(t)&&t>=1&&t<=1e9?t:void 0}function q(e,t,n){let r=qe(e);return r===void 0?`malformed`:r>n?`future`:r<n?`schema-version`:K(e,t,void 0,n)?`current`:`malformed`}function J(e,t){let n=qe(e);return n!==void 0&&n>t}function Y(e){let t=e&&typeof e==`object`?e.size:void 0;return Number.isSafeInteger(t)&&t>=0?t:X(e)}function X(e,n=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(n.has(e)||(n.add(e),e instanceof Date))return 8;if(t.n(e))return e.size;if(t.t(e)||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Map){let t=16;for(let[r,i]of e)t=Z(t,X(r,n),X(i,n));return t}if(e instanceof Set){let t=16;for(let r of e)t=Z(t,X(r,n));return t}let r=Array.isArray(e)?16:32;for(let[t,i]of Object.entries(e))r=Z(r,t.length*2,X(i,n));return r}function Z(...e){let t=0;for(let n of e){if(n>=2**53-1-t)return 2**53-1;t+=n}return t}function Q(e,t,n){let r=e.get(t),i=Y(n);if(r){r.entries+=1,r.estimatedBytes=Z(r.estimatedBytes,i);return}e.set(t,{reason:t,entries:1,estimatedBytes:i})}function Je(e){return!!(e&&typeof e==`object`&&e.name===`QuotaExceededError`)}function Ye(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 Xe(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function Ze(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 Qe(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 $e(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 et(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 tt(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 nt(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 rt(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}async function it(e,t,n){let r=e.transaction(B,`readwrite`),i=U(r),a=r.objectStore(B).index(V).openCursor(t),o=new Map;return await W(a,e=>{let r=e.value,i=q(r,t,n);(i===`malformed`||i===`schema-version`)&&(e.delete(),Q(o,i,r))}),await i,[...o.values()]}var IndexedDBCacheStore=class{constructor(e,t={}){this.namespace=Ye(t.namespace,`namespace`,`default`),this.maxEntries=Xe(t.maxEntries),this.maxBytes=Ze(t.maxBytes),this.quotaRecovery=Qe(t.quotaRecovery),this.shouldPersist=et(t.shouldPersist),this.onEvent=$e(t.onEvent),this.schemaVersion=rt(t.schemaVersion),this.databaseName=Ye(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(B,`readwrite`),n=U(t),r=t.objectStore(B),i=this.createKey(e),a=await H(r.get(i)),o=J(a,this.schemaVersion);if(!K(a,this.namespace,i,this.schemaVersion)){a!==void 0&&!o&&r.delete(i),await n,a!==void 0&&!o&&this.emitEvent({type:`eviction`,reason:`malformed`,entries:1,estimatedBytes:Y(a)});return}return a.accessedAt=Date.now(),a.size=Y(a),r.put(a),await n,G(a)}async set(t,n){if(this.maxEntries===0||this.maxBytes===0){await this.delete(t);return}let r=await this.getDatabase(),i={...G(n),key:this.createKey(t),namespace:this.namespace,accessedAt:Date.now(),schemaVersion:this.schemaVersion};if(i.size=X(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(G(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||!Je(e)||!await this.recoverQuota(r))throw e;await this.writeRecord(r,i)}}async delete(e){let t=(await this.getDatabase()).transaction(B,`readwrite`),n=U(t),r=t.objectStore(B),i=this.createKey(e);J(await H(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(B,`readonly`),t=U(e),n=e.objectStore(B).index(V).openCursor(this.namespace),r=0,i=0;return await W(n,e=>{let t=e.value;K(t,this.namespace,void 0,this.schemaVersion)&&(r+=1,i=Z(i,Y(t)))}),await t,{entries:r,estimatedBytes:i,maxEntries:this.maxEntries,maxBytes:this.maxBytes,schemaVersion:this.schemaVersion}}async compact(e={}){let t=tt(e.expiredBefore),n=nt(e.maxRemovals),r=(await this.getDatabase()).transaction(B,`readwrite`),i=U(r),a=r.objectStore(B).index(V).openCursor(this.namespace),o=new Map,s=0,c=0,l=0,u=!1;return await W(a,e=>{let r=e.value,i=q(r,this.namespace,this.schemaVersion);if(s+=1,i===`malformed`||i===`schema-version`)e.delete(),Q(o,i,r),c+=1,l=Z(l,Y(r));else if(i===`current`&&r.expiresAt<=t){let t=Y(r);e.delete(),Q(o,`expired`,r),c+=1,l=Z(l,t)}if(c>=n)return u=!0,!1}),await i,this.emitCleanupSummaries(o.values()),{scannedEntries:s,removedEntries:c,estimatedBytesFreed:l,expiredBefore:t,hasMore:u}}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(B,`readwrite`),r=U(n),i=n.objectStore(B),a=new Map;if(J(await H(i.get(t.key)),this.schemaVersion)){await r;return}if(i.put(t),this.maxEntries!==1/0||this.maxBytes!==1/0){let e=await H(i.index(V).getAll(this.namespace)),n=[];for(let t of e){let e=q(t,this.namespace,this.schemaVersion);e===`malformed`||e===`schema-version`?(i.delete(t.key),Q(a,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)=>Z(e,Y(t)),0),o=n.length;for(let e of n){if(o<=this.maxEntries&&r<=this.maxBytes)break;i.delete(e.key),Q(a,r>this.maxBytes?`max-bytes`:`max-entries`,e),--o,r=Math.max(0,r-Y(e))}}await r,this.emitCleanupSummaries(a.values())}async recoverQuota(e){let t=e.transaction(B,`readwrite`),n=U(t),r=t.objectStore(B),i=await H(r.index(V).getAll(this.namespace)),a=[],o=new Map,s=!1;for(let e of i){let t=q(e,this.namespace,this.schemaVersion);t===`malformed`||t===`schema-version`?(r.delete(e.key),Q(o,t,e),s=!0):t===`current`&&a.push(e)}a.sort((e,t)=>e.accessedAt-t.accessedAt||e.key.localeCompare(t.key));for(let e of a.slice(0,Math.max(1,Math.ceil(a.length/2))))r.delete(e.key),Q(o,`quota-recovery`,e),s=!0;return await n,this.emitCleanupSummaries(o.values()),s}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(B,`readwrite`),n=U(t),r=t.objectStore(B).index(V).openCursor(this.namespace),i=new Map;await W(r,t=>{let n=t.value,r=q(n,this.namespace,this.schemaVersion);(r===`malformed`||r===`schema-version`||r===`current`&&e(n))&&(t.delete(),(r===`malformed`||r===`schema-version`)&&Q(i,r,n))}),await n,this.emitCleanupSummaries(i.values())}getDatabase(){return this.database??(this.database=We(this.factory,this.databaseName).then(async e=>{try{let t=await it(e,this.namespace,this.schemaVersion);return this.emitCleanupSummaries(t),e}catch(t){throw e.close(),t}})),this.database}},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(!ot(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)ut(()=>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=ct(t.coordination?.namespace),this.maxTrackedKeys=st(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 r.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 n=()=>{let n;try{n=this.primary.set(e,t)}catch(t){throw this.recoverPrimaryWrite(e),t}return r.t(n)?Promise.resolve(n).catch(t=>{throw this.recoverPrimaryWrite(e),t}):n},i=this.secondary.set(e,t),a=r.t(i)?Promise.resolve(i).then(n):n();return this.afterSuccess(a,()=>{this.trackKey(e),this.broadcastKey(e)})}delete(e){return this.afterSettled(()=>at([()=>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(()=>at([()=>n.call(this.primary,t),()=>r.call(this.secondary,t)],e=>Math.max(...e)),()=>this.broadcastClear())}clear(){return this.afterSettled(()=>at([()=>this.primary.clear(),()=>this.secondary.clear()],()=>void 0),()=>this.broadcastClear())}async acquireCoordinatedLease(t,n){let r=`${this.lockNamespace}:${$(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 dt(()=>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=lt(),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,i=()=>{n&&(n=!1,this.leaseReleases.delete(i),o.resolve())};this.leaseReleases.add(i),a=!0,r({contended:!t,release:i}),await o.promise}).catch(e=>{a||i(e)})})}readSecondary(e){let t=t=>{if(t){try{let n=this.primary.set(e,t);if(r.t(n))return Promise.resolve(n).then(()=>this.remember(e,t),()=>this.remember(e,t))}catch{}return this.remember(e,t)}},n=this.secondary.get(e);return r.t(n)?Promise.resolve(n).then(t):t(n)}remember(e,t){return this.trackKey(e),t}trackKey(e){if(!this.channel)return;let t=$(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=$(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:$(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,ut(()=>this.primary.clear())}recoverPrimaryWrite(e){this.untrackKey(e),ut(()=>this.primary.delete(e)),this.broadcastKey(e)}afterSuccess(e,t){return r.t(e)?Promise.resolve(e).then(e=>(t(),e)):(t(),e)}afterSettled(e,t){let n;try{n=e()}catch(e){throw t(),e}return r.t(n)?Promise.resolve(n).then(e=>(t(),e),e=>{throw t(),e}):(t(),n)}};function at(e,t){let n=[],i=[],a,o=!1;for(let t of e)try{let e=t();r.t(e)?i.push(Promise.resolve(e).then(e=>{n.push(e)},e=>{o||(o=!0,a=e)})):n.push(e)}catch(e){o||(o=!0,a=e)}let s=()=>{if(o)throw a;return t(n)};return i.length>0?Promise.all(i).then(s):s()}function $(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 ot(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 st(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 ct(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 lt(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}function ut(e){try{let t=e();r.t(t)&&Promise.resolve(t).catch(()=>{})}catch{}}async function dt(e){try{await e()}catch{}}function cachePlugin(e={}){let t=A(e),n={name:`cache`,...we(t),install(r){let i=Be();return r.hooks.onRequest(ze(t,i,r,e)),r.hooks.onResponse(Ie(t),{requiresRawResponse:!1}),r.hooks.onError(Ve(t)),r.hooks.onSettled(He(t,i,n)),Ue(t,i)}};return n}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return WebStorageCacheStore}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return MemoryCacheStore}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return TieredCacheStore}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return IndexedDBCacheStore}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return cachePlugin}});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as HttpMethod, p as RequestConfig } from "./response-
|
|
2
|
-
import { t as Plugin } from "./Plugin-
|
|
1
|
+
import { G as HttpMethod, p as RequestConfig } from "./response-LhB9NRBw.js";
|
|
2
|
+
import { t as Plugin } from "./Plugin-BvvTFwQj.js";
|
|
3
3
|
//#region src/plugins/cacheStores.d.ts
|
|
4
4
|
type MaybePromise$1<T> = T | Promise<T>;
|
|
5
5
|
interface CacheEntry {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as isRequestError,t}from"./RequestError-B0HIY1zK.js";import{n,r,t as i}from"./isBinaryBody-D-Wp2IPk.js";import{n as a,t as o}from"./waitForSignal-BcVEtAgx.js";import{t as s}from"./isPromiseLike-B6ok3Q-C.js";import{t as c}from"./resolveExtensionConfig-C_MshvkE.js";function l(e,n){let r=e??3e4;if(r!==1/0&&(!Number.isFinite(r)||r<0))throw new t(`Cache ttl must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return r}function u(e,n){let r=e??200;if(!Number.isInteger(r)||r<200||r>599)throw new t(`Cache status must be an integer between 200 and 599`,{code:`CONFIG_ERROR`,config:n});return r}function d(e,n){if(e!==void 0){if(e!==1/0&&(!Number.isFinite(e)||e<0))throw new t(`Cache staleIfError must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return e}}function f(e,n){if(e!==void 0){if(e!==1/0&&(!Number.isFinite(e)||e<0))throw new t(`Cache staleWhileRevalidate must be a non-negative finite number or Infinity`,{code:`CONFIG_ERROR`,config:n});return e}}function p(e,n){if(e===void 0)return[];if(typeof e!=`string`&&!Array.isArray(e))throw new t(`Cache tags must be an array of strings`,{code:`CONFIG_ERROR`,config:n});let r=typeof e==`string`?[e]:e;if(r.length>32)throw new t(`Cache tags cannot contain more than 32 values`,{code:`CONFIG_ERROR`,config:n});let i=new Set;for(let e of r){if(typeof e!=`string`||e.length===0||e.length>128)throw new t(`Cache tags must contain 1 to 128 characters`,{code:`CONFIG_ERROR`,config:n});i.add(e)}return[...i]}function m(e){return e!==1/0&&(Number.isNaN(e)||Date.now()>=e)}var MemoryCacheStore=class{constructor(e={}){this.entries=new Map,this.maxEntries=h(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=g(t.namespace),this.maxEntries=h(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,_(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,_(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 v(t)}catch{this.storage.removeItem(e);return}}};function h(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function g(e=`default`){if(typeof e!=`string`||e.length===0||e.length>128)throw new t(`Web storage cache namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return`@npora/request:${encodeURIComponent(e)}:`}function _(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 v(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:p(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}}const y=[];function b(e,t,n,r,i){if(t.key)return t.key;let a=e.method??`GET`,o=String(e.url),s=e.responseType??`auto`,c=e.fetchOptions?.credentials??`same-origin`,l=!e.headers&&!e.query&&!e.searchParams;if(l&&i.key!==void 0&&i.method===a&&i.baseURL===e.baseURL&&i.url===o&&i.responseType===s&&i.credentials===c)return i.key;let u=JSON.stringify({method:a,baseURL:e.baseURL,url:o,query:l?y:w(e.searchParams??e.query),responseType:s,credentials:c,headers:e.headers?x(new Headers(e.headers),n):r});return l&&(i.method=a,i.baseURL=e.baseURL,i.url=o,i.responseType=s,i.credentials=c,i.key=u),u}function x(e,t){let n=[];e?.forEach((e,t)=>{S(t)||n.push([t,e])});for(let r of t)!S(r)&&!e?.has(r)&&n.push([r,null]);return n.sort(([e],[t])=>e.localeCompare(t))}function S(e){return e===`cache-control`||e===`pragma`}function C(e){return[...new Set(e.map(e=>e.toLowerCase()))]}function w(e){if(!e)return y;if(r(e))return[...e.entries()];let t=[];for(let n of Object.keys(e).sort())T(t,n,e[n]);return t}function T(e,t,n){if(n!==void 0){if(n===null){e.push([t,``]);return}if(Array.isArray(n)){for(let r of n)T(e,t,r);return}e.push([t,String(n)])}}const E={hit:`hits`,miss:`misses`,bypass:`bypasses`,invalidated:`invalidations`,"invalidation-error":`invalidationErrors`,deduplicated:`deduplicated`,revalidated:`revalidations`,"stale-if-error":`staleIfError`,"stale-while-revalidate":`staleWhileRevalidate`,"background-refresh":`backgroundRefreshes`,"background-refresh-success":`backgroundRefreshSuccesses`,"background-refresh-error":`backgroundRefreshErrors`};function D(){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 O(e){Object.assign(e,D())}function k(e,t){return n=>{if(A(e,n),t)try{let e=t({type:n,timestamp:Date.now()});s(e)&&Promise.resolve(e).catch(j)}catch{}}}function A(e,t){let n=E[t];e[n]=Math.min(2**53-1,e[n]+1)}function j(){}const M=[`GET`,`HEAD`],N=[`authorization`,`cookie`,`accept`,`accept-language`];function P(e){let t=e.store??new MemoryCacheStore({maxEntries:e.maxEntries}),n=new WeakSet,r=new WeakMap,i=new WeakMap,a=new WeakMap,o=new WeakMap,s=new WeakMap,c=new WeakSet,l=new WeakSet,u=new WeakMap,d=new WeakMap,f=new WeakSet,p=new WeakSet,m=new Map,h=new Map,g=new WeakSet,_=new Map,v=new Map,y=new Map,b=new Map,S=D(),w=k(S,e.onEvent),T=new Set(e.methods??M),E=C(e.varyHeaders??N);return{store:t,cacheHits:n,leaders:r,requestGenerations:i,automaticInvalidations:a,completedRecords:o,revalidations:s,forcedRevalidations:c,noStoreRequests:l,staleFallbacks:u,refreshLeases:d,cacheFallbacks:f,uncacheableLeaders:p,inFlight:m,rawInFlight:h,rawLeaders:g,backgroundRefreshes:_,keyGenerations:v,keyOperations:y,tagInvalidations:b,stats:S,recordEvent:w,generation:0,methods:T,varyHeaders:E,emptyHeaderValues:x(void 0,E),keyMemo:{}}}const F={persist:!1,ttl:0};function ee(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=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());e&&Number(e[1]??e[2])===0&&(r=!0)}}else t.get(`pragma`)?.split(`,`).some(e=>e.trim().toLowerCase()===`no-cache`)&&(r=!0);return r?`revalidate`:`default`}function te(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 F;if(r===`no-cache`){o=!0;continue}if(r!==`max-age`)continue;if(a!==void 0)return F;let i=/^(?:"(\d+)"|(\d+))$/.exec(t.slice(n+1).trim());if(!i)return F;a=Number(i[1]??i[2])}if(e.headers.get(`vary`)?.split(`,`).some(e=>{let t=e.trim().toLowerCase();return t===`*`||le(t)})||t<=0||a!==void 0&&!Number.isSafeInteger(a))return F;let s=o?0:a===void 0?t:Math.min(t,Math.max(0,(a-se(e.headers.get(`age`)))*1e3));return{ttl:s,persist:s>0||ce(e.headers)||ne(e.headers,n)>0||!o&&re(e.headers,r)>0}}function ne(e,t){return ae(e,t,`stale-if-error`)}function re(e,t){return ae(e,t,`stale-while-revalidate`)}function ie(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 ae(e,t,n){let r=oe(e.get(`cache-control`),n);return t===void 0?r??0:r===void 0?t:Math.min(t,r)}function oe(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=/^(?:"(\d+)"|(\d+))$/.exec(e.slice(i+1).trim());if(!a)return;n=Number(a[1]??a[2])}if(n===void 0||!Number.isSafeInteger(n))return;let r=n*1e3;return Number.isSafeInteger(r)?r:void 0}function se(e){if(!e||!/^\d+$/.test(e.trim()))return 0;let t=Number(e);return Number.isSafeInteger(t)?t:0}function ce(e){return e.has(`etag`)||e.has(`last-modified`)}function le(e){return e===`cache-control`||e===`pragma`}function ue(e,t,n){return t.has(e.method??`GET`)&&(!de(e)||!!n.key)&&(!e.parseJson||!!n.key)&&(!e.querySerializer||!!n.key)&&e.responseType!==`stream`&&e.responseType!==`sse`&&e.responseType!==`ndjson`&&e.responseType!==`bytes`&&e.responseType!==`formData`&&e.fetchOptions?.mode!==`no-cors`&&e.fetchOptions?.integrity===void 0&&(e.fetchOptions?.redirect===void 0||e.fetchOptions.redirect===`follow`)}function de(e){return e.body!=null||e.json!==void 0||e.form!=null||e.formData!=null}function fe(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}function pe(t){return isRequestError(t)&&t.code===`SCHEMA_ERROR`}function me(e,t,n,r){try{if(n&&!e.raw||I(t))return!1;let i=ne(new Headers(e.headers),r);return i>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+i}catch{return!1}}function he(e,t,n,r){try{if(n&&!e.raw)return!1;let i=new Headers(e.headers);if(I(t)||ie(i,`no-cache`)||ie(i,`must-revalidate`))return!1;let a=re(i,r);return a>0&&Number.isFinite(e.expiresAt)&&Date.now()<e.expiresAt+a}catch{return!1}}function ge(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 _e(e){for(let t of e.values())t.abort(`Cache background refresh stopped`);e.clear()}function ve(t){return isRequestError(t)&&(t.code===`NETWORK_ERROR`||t.code===`TIMEOUT_ERROR`||t.code===`HTTP_ERROR`&&t.status!==void 0&&t.status>=500&&t.status<600)}function ye(e,t,n){try{return n&&!e.raw||I(t)?!1:xe(new Headers(e.headers))}catch{return!1}}function be(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,s=e.throwHttpErrors;return e.headers=a,e.throwHttpErrors=void 0,e.validateStatus=e=>e===304||(o?o(e):s===!1||e>=200&&e<300),!0}function xe(e){return e.has(`etag`)||e.has(`last-modified`)}function I(e){let t=new Headers(e.headers);return t.has(`if-none-match`)||t.has(`if-modified-since`)||t.has(`range`)}function Se(e,t,n,r){return{data:z(e.data),expiresAt:t,status:e.status,statusText:e.statusText,headers:[...e.headers.entries()],tags:r?[...r]:void 0,raw:n?Te(e.raw):void 0}}function L(e,t){return{data:z(e.data),status:e.status,statusText:e.statusText,headers:new Headers(e.headers),config:t,raw:we(e)}}function R(e,t){try{return L(e,t)}catch{return}}function Ce(e,t,n){let r=new Headers(e.headers);return t.headers.forEach((e,t)=>{r.set(t,e)}),L({...e,headers:[...r.entries()]},n)}function we(e){if(e.raw){let t=Te(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 Te(e){try{return e.clone()}catch{return}}function z(e){if(typeof e!=`object`||!e||typeof structuredClone!=`function`)return e;try{return structuredClone(e)}catch{return e}}function Ee(e){let{keyOperations:t,tagInvalidations:n,recordEvent:r,keyGenerations:i,inFlight:a,rawInFlight:o,backgroundRefreshes:c}=e;function l(e,n,i,a){let o=Promise.resolve(n),s;return s=o.then(()=>i&&r(i),()=>a&&r(a)).finally(()=>{t.get(e)===s&&t.delete(e)}),t.set(e,s),o}function u(e,n,i=[],a,o){let c=new Set(i),u=t.get(e);if(u&&c.add(u),c.size>0)return l(e,Promise.all(c).then(n),a,o);let d;try{d=n()}catch(e){throw o&&r(o),e}return s(d)?l(e,d,a,o):(a&&r(a),d)}function d(e,t){i.delete(e),a.delete(e),o.delete(e);let n=c.get(e);n&&(c.delete(e),n.abort(t))}function f(e,t){let i=Promise.resolve(t),a;a=i.then(()=>r(`invalidated`),()=>r(`invalidation-error`)).finally(()=>{for(let t of e)n.get(t)===a&&n.delete(t)});for(let t of e)n.set(t,a);return i}return{runKeyOperation:u,invalidateKeyState:d,trackTagInvalidation:f}}function De(e){let{store:n,keyGenerations:r,inFlight:i,rawInFlight:a,backgroundRefreshes:o,keyOperations:d,tagInvalidations:f,recordEvent:m,varyHeaders:h,emptyHeaderValues:g,keyMemo:_,stats:v}=e,{runKeyOperation:y,invalidateKeyState:x,trackTagInvalidation:S}=Ee(e);return{clear(){return e.generation+=1,i.clear(),a.clear(),r.clear(),_e(o),n.clear()},delete(e){let t=b(e,c(e,`cache`)??{},h,g,_);return x(t,`Cache entry invalidated`),y(t,()=>n.delete(t),[],`invalidated`,`invalidation-error`)},set(e,t,r={}){let i=c(e,`cache`)??{},a=b(e,i,h,g,_),o=l(r.ttl??i.ttl,e),s=u(r.status,e),d=p(r.tags??i.tags,e),m={data:z(t),expiresAt:o===1/0?o:Date.now()+o,status:s,statusText:r.statusText??(s===200?`OK`:``),headers:[...new Headers(r.headers).entries()],tags:d.length>0?d:void 0},v=d.map(e=>f.get(e)).filter(e=>!!e);return x(a,`Cache entry replaced`),y(a,()=>n.set(a,m),v)},update(e,t){let r=b(e,c(e,`cache`)??{},h,g,_);return x(r,`Cache entry updated`),y(r,()=>{let e=e=>{if(!e)return!1;let i=t(z(e.data));if(i===void 0){let e=n.delete(r);return!s(e)||Promise.resolve(e).then(()=>!0)}let a=n.set(r,{...e,data:z(i),raw:void 0});return!s(a)||Promise.resolve(a).then(()=>!0)},i=n.get(r);return s(i)?Promise.resolve(i).then(e):e(i)},f.values())},invalidateTags(e){let i=p(e);if(i.length===0)throw new t(`Cache tag invalidation requires at least one tag`,{code:`CONFIG_ERROR`});let a=n.invalidateTags;if(!a)throw new t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`});for(let[e,t]of r)i.some(e=>t.tags.has(e))&&x(e,`Cache tags invalidated`);let o=new Set(i.map(e=>f.get(e)).filter(e=>!!e));for(let e of d.values())o.add(e);if(o.size>0)return S(i,Promise.all(o).then(()=>a.call(n,i)));let c;try{c=a.call(n,i)}catch(e){throw m(`invalidation-error`),e}return s(c)?S(i,c):(m(`invalidated`),c)},getStats(){return{...v}},resetStats(){O(v)}}}function Oe(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 B(e,t,n){return e!==void 0&&e.global===t&&n.get(e.key)===e.token}function ke(e,t){--e.token.activeRequests,e.token.activeRequests===0&&t.get(e.key)===e.token&&t.delete(e.key)}function Ae(e,t,n){return{owner:e,key:t,generation:n}}function je(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 Me(e,t){try{let n=e.get(t);return s(n)?Promise.resolve(n).catch(()=>void 0):n}catch{return}}function Ne(e,t,n){try{let r=e.set(t,n);if(s(r))return Promise.resolve(r).catch(Pe)}catch{}}function V(e,t){try{let n=e.delete(t);if(s(n))return Promise.resolve(n).catch(Pe)}catch{}}function Pe(){}function Fe(e,t){let n=t.signal;return n?n.aborted?Promise.reject(Ie(n.reason,t)):new Promise((r,i)=>{let a=!1,o=()=>{try{n.removeEventListener(`abort`,l)}catch{}},s=e=>{a||(a=!0,o(),r(e))},c=e=>{a||(a=!0,o(),i(e))},l=()=>{c(Ie(n.reason,t))};try{n.addEventListener(`abort`,l,{once:!0})}catch(e){c(e);return}n.aborted&&l(),!a&&e.then(s,e=>{c(Le(e,t))})}):e.catch(e=>{throw Le(e,t)})}function Ie(e,n){return new t(`Request aborted while waiting for shared response`,{code:`ABORT_ERROR`,config:n,cause:e})}function Le(n,r){return isRequestError(n)?new t(n.message,{code:n.code,status:n.status,data:n.data,response:n.response,config:r,cause:n}):n}function Re(e){let{cacheFallbacks:t,recordEvent:n,cacheHits:r,leaders:i,uncacheableLeaders:o,methods:u,noStoreRequests:p,revalidations:m,requestGenerations:h,keyGenerations:g,completedRecords:_,store:v}=e;return y=>{if(t.has(y)&&y.fallbackResponse){n(`stale-if-error`),r.add(y),y.cacheHit=!0,i.get(y)?.owner===y&&o.add(y);return}if(r.has(y))return;let b=c(y.config,`cache`);if(!b?.enabled||!y.response||!ue(y.config,u,b)||p.has(y))return;let x=m.get(y);if(y.response.raw.type===`opaque`||y.response.raw.type===`opaqueredirect`){i.get(y)?.owner===y&&o.add(y);return}x&&y.response.status===304&&(n(`revalidated`),y.response=Ce(x,y.response,y.config));let S=i.get(y),C=S?.generation??h.get(y);if(!C)return;let w=C.key,T=B(C,e.generation,g),E=C.token.tags,D=E&&E.size>0?[...E]:x?.tags;if(fe(y.response.data)){if(o.add(y),!T)return;let e=V(v,w);return s(e)?y.config.signal?a(()=>e,y.config):e:void 0}let O=l(b.ttl,y.config),k=d(b.staleIfError,y.config),A=f(b.staleWhileRevalidate,y.config),j=te(y.response,O,k,A),M=j.ttl;if(!j.persist){let e=T?V(v,w):void 0,t=s(e),n=S;return n?.owner===y&&(n.promise!==void 0||t)?_.set(y,Se(y.response,Date.now()+Math.max(0,M),y.preserveRaw,D)):n?.owner===y&&o.add(y),t?y.config.signal?a(()=>e,y.config):e:void 0}let N=Se(y.response,Date.now()+M,y.preserveRaw,D);if(_.set(y,N),!T||S?.rawDemanded)return;let P=Ne(v,w,N);if(s(P))return y.config.signal?a(()=>P,y.config):P}}function ze(e,t,n,r){let{keyGenerations:i,recordEvent:s,rawInFlight:c,inFlight:l,cacheHits:u,store:d,refreshLeases:f,forcedRevalidations:p,rawLeaders:m,leaders:h,revalidations:g}=e,{ownedLeaders:_,ownedRefreshLeases:v}=t;function y(y,b,x,S,C){if(!(!t.active||!B(S,e.generation,i))){if(b.dedupe??n.dedupe??!0){let e=y.preserveRaw?c.get(x):l.get(x)??c.get(x);if(e)return s(`deduplicated`),Fe(je(e),y.config).then(e=>{e&&(y.response=L(e,y.config),u.add(y),y.cacheHit=!0)});let n=d.acquireRefreshLease;if(n&&!f.has(y)){let e,i=()=>(f.set(y,{contended:!1,release(){}}),r(y,b,x,C,S));try{let r=n.call(d,x,y.config.signal).then(e=>(!t.active||y.config.signal?.aborted?e.release():(f.set(y,e),v.add(e)),e));e=o(r,y.config)}catch{return i()}return e.then(e=>{if(t.active)return e.contended&&(p.delete(y),s(`deduplicated`)),a(()=>Me(d,x),y.config).then(e=>r(y,b,x,e,S))},e=>{if(y.config.signal?.aborted)throw e;return i()})}if(y.preserveRaw){let e=l.get(x);e&&(e.rawDemanded=!0)}let i=Ae(y,x,S);y.preserveRaw?(c.set(x,i),m.add(y)):l.set(x,i),h.set(y,i),_.add(y)}y.background||s(`miss`),C&&be(y.config,C)&&g.set(y,C)}}return y}function Be(e,t,n,r){let{keyGenerations:i,forcedRevalidations:o,recordEvent:c,cacheHits:l,backgroundRefreshes:u,staleFallbacks:p,store:h}=e;function g(g,_,v,y,b){if(!(!t.active||!B(b,e.generation,i))){if(y){let e=!m(y.expiresAt),t=o.has(g);if(e&&!t){if(g.preserveRaw&&!y.raw)return r(g,_,v,b);let e=R(y,g.config);if(e){c(`hit`),g.response=e,l.add(g),g.cacheHit=!0;return}}if(!g.background&&!t&&he(y,g.config,g.preserveRaw,f(_.staleWhileRevalidate,g.config))){let e=R(y,g.config);if(e){c(`stale-while-revalidate`),g.response=e,l.add(g),g.cacheHit=!0,ge(n,u,v,g.initialConfig,g.preserveRaw,c);return}}if(!g.background&&me(y,g.config,g.preserveRaw,d(_.staleIfError,g.config))&&p.set(g,y),ye(y,g.config,g.preserveRaw)&&R(y,g.config))return r(g,_,v,b,y);if(e&&t||g.background)return r(g,_,v,b);let i=V(h,v);if(s(i))return(g.config.signal?a(()=>i,g.config):Promise.resolve(i)).then(()=>r(g,_,v,b))}return r(g,_,v,b)}}return g}function Ve(e,n,r,i){let{store:o,automaticInvalidations:u,methods:m,recordEvent:h,noStoreRequests:g,forcedRevalidations:_,varyHeaders:v,emptyHeaderValues:y,keyMemo:x,keyGenerations:S,requestGenerations:C,keyOperations:w,tagInvalidations:T}=e,E=Be(e,n,r,ze(e,n,i,(...e)=>E(...e)));return n=>{let r=c(n.config,`cache`);if(!r)return;let i=p(r.invalidateTags,n.config);if(i.length>0){if(!o.invalidateTags)throw new t(`Cache store does not support tag invalidation`,{code:`CONFIG_ERROR`,config:n.config});u.set(n,i)}if(!r.enabled||!ue(n.config,m,r))return;l(r.ttl,n.config),d(r.staleIfError,n.config),f(r.staleWhileRevalidate,n.config);let D=p(r.tags,n.config),O=ee(n.config);if(O===`no-store`){h(`bypass`),g.add(n);return}(O===`revalidate`||n.background)&&_.add(n);let k=b(n.config,r,v,y,x),A=Oe(e.generation,k,S,D);C.set(n,A);let j=()=>{let t=Me(o,k);return s(t)?(n.config.signal?a(()=>t,n.config):Promise.resolve(t)).then(t=>{if(B(A,e.generation,S))return E(n,r,k,t,A)}):E(n,r,k,t,A)},M=new Set,N=w.get(k);N&&M.add(N);for(let e of D){let t=T.get(e);t&&M.add(t)}if(M.size>0){let e=Promise.all(M).then(()=>{});return n.config.signal?a(()=>e,n.config).then(j):e.then(j)}return j()}}function He(){return{active:!0,ownedLeaders:new Set,ownedRefreshLeases:new Set}}function Ue(e){let{staleFallbacks:t,cacheFallbacks:n}=e;return e=>{let r=t.get(e);if(!r||!ve(e.error))return;let i=R(r,e.config);i&&(n.add(e),e.fallbackResponse=i)}}function We(e,n,r){let{refreshLeases:i,forcedRevalidations:a,noStoreRequests:o,staleFallbacks:c,cacheFallbacks:l,requestGenerations:u,automaticInvalidations:d,keyGenerations:f,leaders:p,revalidations:m,rawLeaders:h,rawInFlight:g,inFlight:_,uncacheableLeaders:v,completedRecords:y}=e,{ownedLeaders:b,ownedRefreshLeases:x}=n;return e=>{let n=i.get(e);n&&(n.release(),x.delete(n)),i.delete(e),a.delete(e),o.delete(e),c.delete(e),l.delete(e);let S=u.get(e),C=()=>{let t=d.get(e);if(d.delete(e),!(!t||e.background||e.error||!e.response))try{let e=r.invalidateTags(t);if(s(e))return Promise.resolve(e).then(()=>{}).catch(j)}catch{}};S&&(u.delete(e),ke(S,f));let w=p.get(e);if(!w)return C();p.delete(e),b.delete(e),m.delete(e);let T=w.key,E=h.delete(e)?g:_;if(E.get(T)===w&&E.delete(T),v.delete(e))return w.resolve?.(void 0),C();let D=y.get(e);return y.delete(e),D&&e.response&&(!e.error||pe(e.error))?(w.resolve?.(D),C()):(w.reject?.(e.error??new t(`Shared request failed`,{code:`NETWORK_ERROR`,config:e.config})),C())}}function Ge(e,n){let{leaders:r,rawLeaders:i,rawInFlight:a,inFlight:o,keyGenerations:s,backgroundRefreshes:c}=e,{ownedLeaders:l,ownedRefreshLeases:u}=n;return()=>{n.active=!1;for(let e of u)e.release();u.clear();for(let e of l){let n=r.get(e);if(r.delete(e),!n)continue;let s=n.key,c=i.delete(e)?a:o;c.get(s)===n&&c.delete(s),n.reject?.(new t(`Cache plugin removed during shared request`,{code:`ABORT_ERROR`}))}l.clear(),s.clear(),_e(c)}}const H=`entries`,U=`namespace`;function Ke(e,t){return new Promise((n,r)=>{let i=e.open(t,1);i.onupgradeneeded=()=>{let e=i.result;e.objectStoreNames.contains(`entries`)||e.createObjectStore(H,{keyPath:`key`}).createIndex(U,U,{unique:!1})},i.onerror=()=>r(i.error),i.onsuccess=()=>{let e=i.result;e.onversionchange=()=>e.close(),n(e)}})}function W(e){return new Promise((t,n)=>{e.onerror=()=>n(e.error),e.onsuccess=()=>t(e.result)})}function G(e){let t=new Promise((t,n)=>{let r=t=>{n(e.error??qe(t.target)??Error(`IndexedDB transaction failed`))};e.onabort=r,e.onerror=r,e.oncomplete=()=>t()});return t.catch(()=>{}),t}function qe(e){if(!e||!(`error`in e))return null;let t=e.error;return t instanceof DOMException?t:null}function K(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{Je(e)?.abort()}catch{}r(t);return}i.continue()}})}function Je(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 q(e){return{data:e.data,expiresAt:e.expiresAt,status:e.status,statusText:e.statusText,headers:e.headers,tags:e.tags}}function Ye(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&&Xe(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 Xe(e){if(!e||typeof e!=`object`)return;let t=e.schemaVersion??1;return Number.isSafeInteger(t)&&t>=1&&t<=1e9?t:void 0}function J(e,t,n){let r=Xe(e);return r===void 0?`malformed`:r>n?`future`:r<n?`schema-version`:Ye(e,t,void 0,n)?`current`:`malformed`}function Ze(e,t){let n=Xe(e);return n!==void 0&&n>t}function Y(e){let t=e&&typeof e==`object`?e.size:void 0;return Number.isSafeInteger(t)&&t>=0?t:X(e)}function X(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(n(e))return e.size;if(i(e)||ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Map){let n=16;for(let[r,i]of e)n=Z(n,X(r,t),X(i,t));return n}if(e instanceof Set){let n=16;for(let r of e)n=Z(n,X(r,t));return n}let r=Array.isArray(e)?16:32;for(let[n,i]of Object.entries(e))r=Z(r,n.length*2,X(i,t));return r}function Z(...e){let t=0;for(let n of e){if(n>=2**53-1-t)return 2**53-1;t+=n}return t}function Q(e,t,n){let r=e.get(t),i=Y(n);if(r){r.entries+=1,r.estimatedBytes=Z(r.estimatedBytes,i);return}e.set(t,{reason:t,entries:1,estimatedBytes:i})}function Qe(e){return!!(e&&typeof e==`object`&&e.name===`QuotaExceededError`)}function $e(e,n,r){let i=e??r;if(typeof i!=`string`||i.length===0||i.length>128)throw new t(`IndexedDB cache ${n} must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return i}function et(e){return e===void 0?1e3:Number.isFinite(e)?Math.max(0,Math.floor(e)):e>0?1/0:0}function tt(e){if(e===void 0)return 1/0;if(e===1/0)return e;if(!Number.isSafeInteger(e)||e<0)throw new t(`IndexedDB cache maxBytes must be a non-negative safe integer or Infinity`,{code:`CONFIG_ERROR`});return e}function nt(e){if(e===void 0)return!0;if(typeof e!=`boolean`)throw new t(`IndexedDB cache quotaRecovery must be a boolean`,{code:`CONFIG_ERROR`});return e}function rt(e){if(e!==void 0&&typeof e!=`function`)throw new t(`IndexedDB cache onEvent must be a function`,{code:`CONFIG_ERROR`});return e}function it(e){if(e!==void 0&&typeof e!=`function`)throw new t(`IndexedDB cache shouldPersist must be a function`,{code:`CONFIG_ERROR`});return e}function at(e){let n=e??Date.now();if(!Number.isFinite(n))throw new t(`IndexedDB cache compact expiredBefore must be finite`,{code:`CONFIG_ERROR`});return n}function ot(e){if(e===void 0||e===1/0)return 1/0;if(!Number.isSafeInteger(e)||e<1)throw new t(`IndexedDB cache compact maxRemovals must be a positive safe integer or Infinity`,{code:`CONFIG_ERROR`});return e}function st(e){let n=e??1;if(!Number.isSafeInteger(n)||n<1||n>1e9)throw new t(`IndexedDB cache schemaVersion must be an integer from 1 to 1000000000`,{code:`CONFIG_ERROR`});return n}async function ct(e,t,n){let r=e.transaction(H,`readwrite`),i=G(r),a=r.objectStore(H).index(U).openCursor(t),o=new Map;return await K(a,e=>{let r=e.value,i=J(r,t,n);(i===`malformed`||i===`schema-version`)&&(e.delete(),Q(o,i,r))}),await i,[...o.values()]}var IndexedDBCacheStore=class{constructor(e,t={}){this.namespace=$e(t.namespace,`namespace`,`default`),this.maxEntries=et(t.maxEntries),this.maxBytes=tt(t.maxBytes),this.quotaRecovery=nt(t.quotaRecovery),this.shouldPersist=it(t.shouldPersist),this.onEvent=rt(t.onEvent),this.schemaVersion=st(t.schemaVersion),this.databaseName=$e(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(H,`readwrite`),n=G(t),r=t.objectStore(H),i=this.createKey(e),a=await W(r.get(i)),o=Ze(a,this.schemaVersion);if(!Ye(a,this.namespace,i,this.schemaVersion)){a!==void 0&&!o&&r.delete(i),await n,a!==void 0&&!o&&this.emitEvent({type:`eviction`,reason:`malformed`,entries:1,estimatedBytes:Y(a)});return}return a.accessedAt=Date.now(),a.size=Y(a),r.put(a),await n,q(a)}async set(e,n){if(this.maxEntries===0||this.maxBytes===0){await this.delete(e);return}let r=await this.getDatabase(),i={...q(n),key:this.createKey(e),namespace:this.namespace,accessedAt:Date.now(),schemaVersion:this.schemaVersion};if(i.size=X(i),i.size>this.maxBytes){await this.delete(e),this.emitEvent({type:`rejection`,reason:`oversized`,entries:1,estimatedBytes:i.size});return}let a=!this.shouldPersist||await this.shouldPersist(q(i),i.size);if(typeof a!=`boolean`)throw new t(`IndexedDB cache shouldPersist must return a boolean`,{code:`CONFIG_ERROR`});if(!a){await this.delete(e),this.emitEvent({type:`rejection`,reason:`admission-policy`,entries:1,estimatedBytes:i.size});return}try{await this.writeRecord(r,i)}catch(e){if(!this.quotaRecovery||!Qe(e)||!await this.recoverQuota(r))throw e;await this.writeRecord(r,i)}}async delete(e){let t=(await this.getDatabase()).transaction(H,`readwrite`),n=G(t),r=t.objectStore(H),i=this.createKey(e);Ze(await W(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(H,`readonly`),t=G(e),n=e.objectStore(H).index(U).openCursor(this.namespace),r=0,i=0;return await K(n,e=>{let t=e.value;Ye(t,this.namespace,void 0,this.schemaVersion)&&(r+=1,i=Z(i,Y(t)))}),await t,{entries:r,estimatedBytes:i,maxEntries:this.maxEntries,maxBytes:this.maxBytes,schemaVersion:this.schemaVersion}}async compact(e={}){let t=at(e.expiredBefore),n=ot(e.maxRemovals),r=(await this.getDatabase()).transaction(H,`readwrite`),i=G(r),a=r.objectStore(H).index(U).openCursor(this.namespace),o=new Map,s=0,c=0,l=0,u=!1;return await K(a,e=>{let r=e.value,i=J(r,this.namespace,this.schemaVersion);if(s+=1,i===`malformed`||i===`schema-version`)e.delete(),Q(o,i,r),c+=1,l=Z(l,Y(r));else if(i===`current`&&r.expiresAt<=t){let t=Y(r);e.delete(),Q(o,`expired`,r),c+=1,l=Z(l,t)}if(c>=n)return u=!0,!1}),await i,this.emitCleanupSummaries(o.values()),{scannedEntries:s,removedEntries:c,estimatedBytesFreed:l,expiredBefore:t,hasMore:u}}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(H,`readwrite`),r=G(n),i=n.objectStore(H),a=new Map;if(Ze(await W(i.get(t.key)),this.schemaVersion)){await r;return}if(i.put(t),this.maxEntries!==1/0||this.maxBytes!==1/0){let e=await W(i.index(U).getAll(this.namespace)),n=[];for(let t of e){let e=J(t,this.namespace,this.schemaVersion);e===`malformed`||e===`schema-version`?(i.delete(t.key),Q(a,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)=>Z(e,Y(t)),0),o=n.length;for(let e of n){if(o<=this.maxEntries&&r<=this.maxBytes)break;i.delete(e.key),Q(a,r>this.maxBytes?`max-bytes`:`max-entries`,e),--o,r=Math.max(0,r-Y(e))}}await r,this.emitCleanupSummaries(a.values())}async recoverQuota(e){let t=e.transaction(H,`readwrite`),n=G(t),r=t.objectStore(H),i=await W(r.index(U).getAll(this.namespace)),a=[],o=new Map,s=!1;for(let e of i){let t=J(e,this.namespace,this.schemaVersion);t===`malformed`||t===`schema-version`?(r.delete(e.key),Q(o,t,e),s=!0):t===`current`&&a.push(e)}a.sort((e,t)=>e.accessedAt-t.accessedAt||e.key.localeCompare(t.key));for(let e of a.slice(0,Math.max(1,Math.ceil(a.length/2))))r.delete(e.key),Q(o,`quota-recovery`,e),s=!0;return await n,this.emitCleanupSummaries(o.values()),s}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(H,`readwrite`),n=G(t),r=t.objectStore(H).index(U).openCursor(this.namespace),i=new Map;await K(r,t=>{let n=t.value,r=J(n,this.namespace,this.schemaVersion);(r===`malformed`||r===`schema-version`||r===`current`&&e(n))&&(t.delete(),(r===`malformed`||r===`schema-version`)&&Q(i,r,n))}),await n,this.emitCleanupSummaries(i.values())}getDatabase(){return this.database??(this.database=Ke(this.factory,this.databaseName).then(async e=>{try{let t=await ct(e,this.namespace,this.schemaVersion);return this.emitCleanupSummaries(t),e}catch(t){throw e.close(),t}})),this.database}},TieredCacheStore=class{constructor(e){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(!ut(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)mt(()=>this.primary.delete(e))},!e||!e.primary||!e.secondary||e.primary===e.secondary)throw new t(`Tiered cache requires distinct primary and secondary stores`,{code:`CONFIG_ERROR`});if(this.primary=e.primary,this.secondary=e.secondary,e.broadcast&&!e.broadcast.channel)throw new t(`Tiered cache broadcast requires a channel`,{code:`CONFIG_ERROR`});if(e.coordination&&!e.coordination.locks)throw new t(`Tiered cache coordination requires a lock manager`,{code:`CONFIG_ERROR`});this.channel=e.broadcast?.channel,this.locks=e.coordination?.locks,this.lockNamespace=ft(e.coordination?.namespace),this.maxTrackedKeys=dt(e.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 s(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 n=()=>{let n;try{n=this.primary.set(e,t)}catch(t){throw this.recoverPrimaryWrite(e),t}return s(n)?Promise.resolve(n).catch(t=>{throw this.recoverPrimaryWrite(e),t}):n},r=this.secondary.set(e,t),i=s(r)?Promise.resolve(r).then(n):n();return this.afterSuccess(i,()=>{this.trackKey(e),this.broadcastKey(e)})}delete(e){return this.afterSettled(()=>lt([()=>this.primary.delete(e),()=>this.secondary.delete(e)],()=>void 0),()=>{this.untrackKey(e),this.broadcastKey(e)})}invalidateTags(e){let n=this.primary.invalidateTags,r=this.secondary.invalidateTags;if(!n||!r)throw new t(`Both tiered cache stores must support tag invalidation`,{code:`CONFIG_ERROR`});return this.afterSettled(()=>lt([()=>n.call(this.primary,e),()=>r.call(this.secondary,e)],e=>Math.max(...e)),()=>this.broadcastClear())}clear(){return this.afterSettled(()=>lt([()=>this.primary.clear(),()=>this.secondary.clear()],()=>void 0),()=>this.broadcastClear())}async acquireCoordinatedLease(e,n){let r=`${this.lockNamespace}:${$(e)}`,i=await this.requestLease(r,!0,n);if(i)return i;let a=await this.requestLease(r,!1,n);if(!a)throw new t(`Cache refresh lock was unavailable`,{code:`NETWORK_ERROR`});return await ht(()=>this.primary.delete(e)),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=pt(),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,i=()=>{n&&(n=!1,this.leaseReleases.delete(i),o.resolve())};this.leaseReleases.add(i),a=!0,r({contended:!t,release:i}),await o.promise}).catch(e=>{a||i(e)})})}readSecondary(e){let t=t=>{if(t){try{let n=this.primary.set(e,t);if(s(n))return Promise.resolve(n).then(()=>this.remember(e,t),()=>this.remember(e,t))}catch{}return this.remember(e,t)}},n=this.secondary.get(e);return s(n)?Promise.resolve(n).then(t):t(n)}remember(e,t){return this.trackKey(e),t}trackKey(e){if(!this.channel)return;let t=$(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=$(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:$(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,mt(()=>this.primary.clear())}recoverPrimaryWrite(e){this.untrackKey(e),mt(()=>this.primary.delete(e)),this.broadcastKey(e)}afterSuccess(e,t){return s(e)?Promise.resolve(e).then(e=>(t(),e)):(t(),e)}afterSettled(e,t){let n;try{n=e()}catch(e){throw t(),e}return s(n)?Promise.resolve(n).then(e=>(t(),e),e=>{throw t(),e}):(t(),n)}};function lt(e,t){let n=[],r=[],i,a=!1;for(let t of e)try{let e=t();s(e)?r.push(Promise.resolve(e).then(e=>{n.push(e)},e=>{a||(a=!0,i=e)})):n.push(e)}catch(e){a||(a=!0,i=e)}let o=()=>{if(a)throw i;return t(n)};return r.length>0?Promise.all(r).then(o):o()}function $(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 ut(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 dt(e){let n=e??1e3;if(!Number.isInteger(n)||n<1||n>1e5)throw new t(`Tiered cache maxTrackedKeys must be an integer from 1 to 100000`,{code:`CONFIG_ERROR`});return n}function ft(e){let n=e??`npora-cache`;if(typeof n!=`string`||n.length<1||n.length>128)throw new t(`Tiered cache lock namespace must contain 1 to 128 characters`,{code:`CONFIG_ERROR`});return n}function pt(){let e;return{promise:new Promise(t=>{e=t}),resolve:e}}function mt(e){try{let t=e();s(t)&&Promise.resolve(t).catch(()=>{})}catch{}}async function ht(e){try{await e()}catch{}}function cachePlugin(e={}){let t=P(e),n={name:`cache`,...De(t),install(r){let i=He();return r.hooks.onRequest(Ve(t,i,r,e)),r.hooks.onResponse(Re(t),{requiresRawResponse:!1}),r.hooks.onError(Ue(t)),r.hooks.onSettled(We(t,i,n)),Ge(t,i)}};return n}export{WebStorageCacheStore as a,MemoryCacheStore as i,TieredCacheStore as n,IndexedDBCacheStore as r,cachePlugin as t};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { G as HttpMethod, p as RequestConfig } from "./response-
|
|
2
|
-
import { t as Plugin } from "./Plugin-
|
|
1
|
+
import { G as HttpMethod, p as RequestConfig } from "./response-LhB9NRBw.cjs";
|
|
2
|
+
import { t as Plugin } from "./Plugin-LFR-Mb-u.cjs";
|
|
3
3
|
//#region src/plugins/cacheStores.d.ts
|
|
4
4
|
type MaybePromise$1<T> = T | Promise<T>;
|
|
5
5
|
interface CacheEntry {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as CircuitState, p as RequestConfig, x as CircuitBreakerStateChange } from "./response-
|
|
2
|
-
import { t as Plugin } from "./Plugin-
|
|
1
|
+
import { S as CircuitState, p as RequestConfig, x as CircuitBreakerStateChange } from "./response-LhB9NRBw.js";
|
|
2
|
+
import { t as Plugin } from "./Plugin-BvvTFwQj.js";
|
|
3
3
|
//#region src/plugins/circuitBreakerPlugin.d.ts
|
|
4
4
|
interface CircuitBreakerPluginOptions {
|
|
5
5
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { S as CircuitState, p as RequestConfig, x as CircuitBreakerStateChange } from "./response-
|
|
2
|
-
import { t as Plugin } from "./Plugin-
|
|
1
|
+
import { S as CircuitState, p as RequestConfig, x as CircuitBreakerStateChange } from "./response-LhB9NRBw.cjs";
|
|
2
|
+
import { t as Plugin } from "./Plugin-LFR-Mb-u.cjs";
|
|
3
3
|
//#region src/plugins/circuitBreakerPlugin.d.ts
|
|
4
4
|
interface CircuitBreakerPluginOptions {
|
|
5
5
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { p as RequestConfig } from "./response-
|
|
2
|
-
import { t as Plugin } from "./Plugin-
|
|
1
|
+
import { p as RequestConfig } from "./response-LhB9NRBw.js";
|
|
2
|
+
import { t as Plugin } from "./Plugin-BvvTFwQj.js";
|
|
3
3
|
//#region src/plugins/concurrencyPlugin.d.ts
|
|
4
4
|
interface ConcurrencyPluginOptions {
|
|
5
5
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { p as RequestConfig } from "./response-
|
|
2
|
-
import { t as Plugin } from "./Plugin-
|
|
1
|
+
import { p as RequestConfig } from "./response-LhB9NRBw.cjs";
|
|
2
|
+
import { t as Plugin } from "./Plugin-LFR-Mb-u.cjs";
|
|
3
3
|
//#region src/plugins/concurrencyPlugin.d.ts
|
|
4
4
|
interface ConcurrencyPluginOptions {
|
|
5
5
|
/**
|
package/dist/core.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { A as MemoryCacheOptions, B as TransferProgress, C as ConcurrencyOptions, D as ErrorLogEntry, E as DownloadProgress, F as RequestLogEntry, G as HttpMethod, H as UploadOptions, I as RequestLogger, L as ResponseLogEntry, M as OpenTelemetryMetricsOptions, N as OpenTelemetryOptions, O as LoggerEntry, P as RateLimitOptions, R as RetryEvent, S as CircuitState, T as DownloadOutput, U as UploadProgress, V as UploadData, W as StandardSchemaV1, _ as ResponseType, a as FetchFunction, b as CircuitBreakerOptions, c as JsonParserContext, d as QuerySerializer, f as QueryValue, g as RequestURL, h as RequestInputConfig, i as StreamingSchemaLocation, j as OpenTelemetryAttributeValue, k as LoggerOptions, l as JsonStringifier, m as RequestExtensions, n as ServerSentEvent, o as FetchOptions, p as RequestConfig, r as SseReconnectOptions, s as JsonParser, t as NporaResponse, u as QueryParams, v as AuthOptions, w as DownloadOptions, x as CircuitBreakerStateChange, y as CacheOptions, z as RetryOptions } from "./response-
|
|
2
|
-
import { t as Adapter } from "./adapter-
|
|
3
|
-
import { a as RequestErrorOptions, c as createClient, i as RequestErrorCode, l as Client, n as isSchemaValidationError, o as isRequestError, r as RequestError, s as FetchAdapter, t as SchemaValidationError, u as ClientOptions } from "./SchemaValidationError-
|
|
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-
|
|
1
|
+
import { A as MemoryCacheOptions, B as TransferProgress, C as ConcurrencyOptions, D as ErrorLogEntry, E as DownloadProgress, F as RequestLogEntry, G as HttpMethod, H as UploadOptions, I as RequestLogger, L as ResponseLogEntry, M as OpenTelemetryMetricsOptions, N as OpenTelemetryOptions, O as LoggerEntry, P as RateLimitOptions, R as RetryEvent, S as CircuitState, T as DownloadOutput, U as UploadProgress, V as UploadData, W as StandardSchemaV1, _ as ResponseType, a as FetchFunction, b as CircuitBreakerOptions, c as JsonParserContext, d as QuerySerializer, f as QueryValue, g as RequestURL, h as RequestInputConfig, i as StreamingSchemaLocation, j as OpenTelemetryAttributeValue, k as LoggerOptions, l as JsonStringifier, m as RequestExtensions, n as ServerSentEvent, o as FetchOptions, p as RequestConfig, r as SseReconnectOptions, s as JsonParser, t as NporaResponse, u as QueryParams, v as AuthOptions, w as DownloadOptions, x as CircuitBreakerStateChange, y as CacheOptions, z as RetryOptions } from "./response-LhB9NRBw.cjs";
|
|
2
|
+
import { t as Adapter } from "./adapter-C6IM9_f3.cjs";
|
|
3
|
+
import { a as RequestErrorOptions, c as createClient, i as RequestErrorCode, l as Client, n as isSchemaValidationError, o as isRequestError, r as RequestError, s as FetchAdapter, t as SchemaValidationError, u as ClientOptions } from "./SchemaValidationError-D5T7agcb.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-LFR-Mb-u.cjs";
|
|
5
5
|
import { n as PluginErrorCode, r as PluginErrorOptions, t as PluginError } from "./PluginError-DVP3pUt_.cjs";
|
|
6
6
|
export { Adapter, AuthOptions, CacheOptions, CircuitBreakerOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, DownloadOptions, DownloadOutput, DownloadProgress, ErrorLogEntry, FetchAdapter, FetchFunction, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, JsonParser, JsonParserContext, JsonStringifier, LoggerEntry, LoggerOptions, MemoryCacheOptions, NporaResponse, OpenTelemetryAttributeValue, OpenTelemetryMetricsOptions, OpenTelemetryOptions, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QuerySerializer, QueryValue, RateLimitOptions, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestInputConfig, RequestLogEntry, RequestLogger, RequestURL, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, SseReconnectOptions, StandardSchemaV1, StreamingSchemaLocation, TransferProgress, UploadData, UploadOptions, UploadProgress, createClient, isRequestError, isSchemaValidationError };
|
package/dist/core.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { A as MemoryCacheOptions, B as TransferProgress, C as ConcurrencyOptions, D as ErrorLogEntry, E as DownloadProgress, F as RequestLogEntry, G as HttpMethod, H as UploadOptions, I as RequestLogger, L as ResponseLogEntry, M as OpenTelemetryMetricsOptions, N as OpenTelemetryOptions, O as LoggerEntry, P as RateLimitOptions, R as RetryEvent, S as CircuitState, T as DownloadOutput, U as UploadProgress, V as UploadData, W as StandardSchemaV1, _ as ResponseType, a as FetchFunction, b as CircuitBreakerOptions, c as JsonParserContext, d as QuerySerializer, f as QueryValue, g as RequestURL, h as RequestInputConfig, i as StreamingSchemaLocation, j as OpenTelemetryAttributeValue, k as LoggerOptions, l as JsonStringifier, m as RequestExtensions, n as ServerSentEvent, o as FetchOptions, p as RequestConfig, r as SseReconnectOptions, s as JsonParser, t as NporaResponse, u as QueryParams, v as AuthOptions, w as DownloadOptions, x as CircuitBreakerStateChange, y as CacheOptions, z as RetryOptions } from "./response-
|
|
2
|
-
import { t as Adapter } from "./adapter-
|
|
3
|
-
import { a as RequestErrorOptions, c as createClient, i as RequestErrorCode, l as Client, n as isSchemaValidationError, o as isRequestError, r as RequestError, s as FetchAdapter, t as SchemaValidationError, u as ClientOptions } from "./SchemaValidationError-
|
|
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-
|
|
1
|
+
import { A as MemoryCacheOptions, B as TransferProgress, C as ConcurrencyOptions, D as ErrorLogEntry, E as DownloadProgress, F as RequestLogEntry, G as HttpMethod, H as UploadOptions, I as RequestLogger, L as ResponseLogEntry, M as OpenTelemetryMetricsOptions, N as OpenTelemetryOptions, O as LoggerEntry, P as RateLimitOptions, R as RetryEvent, S as CircuitState, T as DownloadOutput, U as UploadProgress, V as UploadData, W as StandardSchemaV1, _ as ResponseType, a as FetchFunction, b as CircuitBreakerOptions, c as JsonParserContext, d as QuerySerializer, f as QueryValue, g as RequestURL, h as RequestInputConfig, i as StreamingSchemaLocation, j as OpenTelemetryAttributeValue, k as LoggerOptions, l as JsonStringifier, m as RequestExtensions, n as ServerSentEvent, o as FetchOptions, p as RequestConfig, r as SseReconnectOptions, s as JsonParser, t as NporaResponse, u as QueryParams, v as AuthOptions, w as DownloadOptions, x as CircuitBreakerStateChange, y as CacheOptions, z as RetryOptions } from "./response-LhB9NRBw.js";
|
|
2
|
+
import { t as Adapter } from "./adapter-DkVzG4v_.js";
|
|
3
|
+
import { a as RequestErrorOptions, c as createClient, i as RequestErrorCode, l as Client, n as isSchemaValidationError, o as isRequestError, r as RequestError, s as FetchAdapter, t as SchemaValidationError, u as ClientOptions } from "./SchemaValidationError-erxAaNjo.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-BvvTFwQj.js";
|
|
5
5
|
import { n as PluginErrorCode, r as PluginErrorOptions, t as PluginError } from "./PluginError-DVP3pUt_.js";
|
|
6
6
|
export { Adapter, AuthOptions, CacheOptions, CircuitBreakerOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, DownloadOptions, DownloadOutput, DownloadProgress, ErrorLogEntry, FetchAdapter, FetchFunction, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, JsonParser, JsonParserContext, JsonStringifier, LoggerEntry, LoggerOptions, MemoryCacheOptions, NporaResponse, OpenTelemetryAttributeValue, OpenTelemetryMetricsOptions, OpenTelemetryOptions, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QuerySerializer, QueryValue, RateLimitOptions, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestInputConfig, RequestLogEntry, RequestLogger, RequestURL, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, SseReconnectOptions, StandardSchemaV1, StreamingSchemaLocation, TransferProgress, UploadData, UploadOptions, UploadProgress, createClient, isRequestError, isSchemaValidationError };
|