fetch-layers 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +57 -6
  3. package/README.ru.md +57 -6
  4. package/dist/classify-body-DOG6Vbf_.mjs +2 -1
  5. package/dist/classify-body-DOG6Vbf_.mjs.map +1 -0
  6. package/dist/{errors-CSZuncD0.d.mts → errors-BITxtr5V.d.mts} +2 -5
  7. package/dist/index.d.mts +4 -8
  8. package/dist/index.mjs +2 -1
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{layer-Db25lSAX.d.mts → layer-3tx7wJdK.d.mts} +5 -4
  11. package/dist/{layer-DRRyGTne.d.mts → layer-BvZMV3L4.d.mts} +8 -3
  12. package/dist/{layer-D1S2Wlu1.d.mts → layer-C5h5TXG6.d.mts} +10 -1
  13. package/dist/{layer-C9nwqcxP.d.mts → layer-CH2X3ibX.d.mts} +50 -2
  14. package/dist/{layer-Dhb1y_u6.mjs → layer-DQ0xiRMN.mjs} +2 -1
  15. package/dist/layer-DQ0xiRMN.mjs.map +1 -0
  16. package/dist/layers/auth/index.d.mts +4 -3
  17. package/dist/layers/idempotency/index.d.mts +3 -42
  18. package/dist/layers/idempotency/index.mjs +1 -1
  19. package/dist/layers/index.d.mts +38 -14
  20. package/dist/layers/index.mjs +2 -1
  21. package/dist/layers/index.mjs.map +1 -0
  22. package/dist/layers/retry/index.d.mts +1 -1
  23. package/dist/layers/retry/index.mjs +1 -1
  24. package/dist/reset-registry-CQPiZVBB.mjs +2 -1
  25. package/dist/reset-registry-CQPiZVBB.mjs.map +1 -0
  26. package/dist/session-CcBNIxp4.mjs +2 -0
  27. package/dist/session-CcBNIxp4.mjs.map +1 -0
  28. package/dist/shared/storage.mjs +2 -1
  29. package/dist/shared/storage.mjs.map +1 -0
  30. package/dist/signals-DQjF6ojU.mjs +2 -1
  31. package/dist/signals-DQjF6ojU.mjs.map +1 -0
  32. package/dist/storage-C0XsVkz-.d.mts +2 -1
  33. package/package.json +2 -3
  34. package/dist/session-Dm-H-5hJ.mjs +0 -1
@@ -146,6 +146,14 @@ interface ResolvedRequestConfig extends Omit<InternalRequestConfig, 'headers'> {
146
146
  headerName: string;
147
147
  key: string;
148
148
  };
149
+ /**
150
+ * Client baseUrl, set by client.ts. Layers run before transport
151
+ * joins baseUrl with path, so withIdempotency needs it to tell two
152
+ * APIs on the same storage apart.
153
+ *
154
+ * @internal
155
+ */
156
+ origin?: string;
149
157
  }
150
158
  /**
151
159
  * RequestConfig without path, method and body. Used in shorthand
@@ -235,4 +243,5 @@ interface Layer {
235
243
  attach?(client: Client, state: unknown): void;
236
244
  }
237
245
  //#endregion
238
- export { ResponseWithMeta as _, QueryArrayFormat as a, QueryParamPrimitive as c, RequestConfig as d, RequestFn as f, ResponseType as g, ResponseMeta as h, HttpMethod as i, QueryParamValue as l, ResolvedRequestConfig as m, LayerContext as n, QueryObjectFormat as o, RequestOptions as p, Client as r, QueryParamObject as s, Layer as t, QueryParams as u };
246
+ export { ResponseWithMeta as _, QueryArrayFormat as a, QueryParamPrimitive as c, RequestConfig as d, RequestFn as f, ResponseType as g, ResponseMeta as h, HttpMethod as i, QueryParamValue as l, ResolvedRequestConfig as m, LayerContext as n, QueryObjectFormat as o, RequestOptions as p, Client as r, QueryParamObject as s, Layer as t, QueryParams as u };
247
+ //# sourceMappingURL=layer-C5h5TXG6.d.mts.map
@@ -1,4 +1,5 @@
1
- import { i as HttpMethod, t as Layer, u as QueryParams } from "./layer-D1S2Wlu1.mjs";
1
+ import { i as HttpMethod, t as Layer, u as QueryParams } from "./layer-C5h5TXG6.mjs";
2
+ import { t as StorageLike } from "./storage-C0XsVkz-.mjs";
2
3
  //#region src/layers/idempotency/types.d.ts
3
4
  /** Input for the source: decide between a new key and the old one. */
4
5
  interface IdempotencyContext {
@@ -13,6 +14,11 @@ interface IdempotencyContext {
13
14
  query?: QueryParams;
14
15
  /** Explicit scope. Defaults to "${method} ${path}". */
15
16
  scope?: string;
17
+ /**
18
+ * Client baseUrl. Feeds the fingerprint, so two APIs sharing one
19
+ * storage never share a key for the same path and body.
20
+ */
21
+ origin?: string;
16
22
  }
17
23
  /**
18
24
  * - success: server confirmed, the key is no longer needed;
@@ -44,6 +50,47 @@ interface IdempotencySource {
44
50
  resolve?(context: IdempotencyContext, outcome: IdempotencyOutcome): void;
45
51
  }
46
52
  //#endregion
53
+ //#region src/layers/idempotency/session.d.ts
54
+ interface SessionSourceOptions {
55
+ /**
56
+ * Storage. Wrap localStorage and sessionStorage in fromWebStorage,
57
+ * use createMemoryStorage for Node.
58
+ */
59
+ storage: StorageLike;
60
+ /** Key of the record object. Defaults to idempotency:session. */
61
+ storageKey?: string;
62
+ /**
63
+ * Key generator. Defaults to crypto.randomUUID. Can be replaced
64
+ * for tests or non-standard schemes.
65
+ */
66
+ generateKey?: () => string;
67
+ /**
68
+ * Max entries, defaults to 100. When exceeded, the least recently
69
+ * used record is dropped.
70
+ *
71
+ * A record is a triple (scope, query, fingerprint): one scope with
72
+ * different bodies takes several.
73
+ */
74
+ maxEntries?: number;
75
+ }
76
+ /** createSessionSource options without storage. */
77
+ type StorageSourceOptions = Omit<SessionSourceOptions, 'storage'>;
78
+ /**
79
+ * Key source on top of a synchronous StorageLike.
80
+ *
81
+ * If a key exists for the tuple (origin, scope, query, body), it is
82
+ * returned and its last-used time is updated. If the body or query
83
+ * changed, or the tuple is new, a new key is generated. On success
84
+ * and definite-failure the record is deleted, on indefinite-failure
85
+ * it is kept for the retry.
86
+ *
87
+ * Ready factories for sessionStorage, localStorage and memory live
88
+ * in fetch-layers/layers.
89
+ *
90
+ * @throws Error if maxEntries is below 1.
91
+ */
92
+ declare function createSessionSource(options: SessionSourceOptions): IdempotencySource;
93
+ //#endregion
47
94
  //#region src/layers/idempotency/layer.d.ts
48
95
  interface IdempotencyOptions {
49
96
  /**
@@ -66,4 +113,5 @@ interface IdempotencyOptions {
66
113
  */
67
114
  declare function withIdempotency(source: IdempotencySource, options?: IdempotencyOptions): Layer;
68
115
  //#endregion
69
- export { IdempotencySource as a, IdempotencyOutcome as i, withIdempotency as n, IdempotencyContext as r, IdempotencyOptions as t };
116
+ export { createSessionSource as a, IdempotencySource as c, StorageSourceOptions as i, withIdempotency as n, IdempotencyContext as o, SessionSourceOptions as r, IdempotencyOutcome as s, IdempotencyOptions as t };
117
+ //# sourceMappingURL=layer-CH2X3ibX.d.mts.map
@@ -1 +1,2 @@
1
- import{a as e,d as t,h as n,l as r,s as i}from"./classify-body-DOG6Vbf_.mjs";import{a,n as o,r as s}from"./signals-DQjF6ojU.mjs";function c(e){return e===`POST`||e===`PUT`||e===`PATCH`||e===`DELETE`}function l(e){try{return e()}catch{return}}const u=`Idempotency-Key`;function d(e){let t=e.replace(/^\/+/,``),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)}function f(f={}){let{maxAttempts:p=3,baseDelayMs:m=300,maxDelayMs:h=1e4,jitterRatio:g=.15,warnOnUnsafeRetry:_=!0,retryOnNetwork:v=!0,retryOnTimeout:y=!0,shouldRetry:b,computeDelay:x,onBeforeRetry:S,sleep:C=o}=f;if(i(p,`withRetry: maxAttempts`,1),r(m,`withRetry: baseDelayMs`),r(h,`withRetry: maxDelayMs`),!Number.isFinite(g)||g<0||g>1)throw Error(`withRetry: jitterRatio must be a number in [0, 1], got ${String(g)}`);let w=t(m,100);if(h<w)throw Error(`withRetry: maxDelayMs (${h}) must be >= baseDelayMs (${w})`);let T=h,E=e=>!(!e.isRetryable||e.kind===`network`&&!v||e.kind===`timeout`&&!y),D=e=>{let t=1-g+Math.random()*g*2;return w*2**(e-1)*t},O=b??E,k=x??D;return{name:`withRetry`,stage:2,wrap(r,i){let o=new Set,f=i.warn,m=(e,t)=>{o.has(e)||(o.add(e),l(()=>f?.(t)))},h=!1;return{fn:async function(i){if(i.skipRetry)return r(i);if(e(i.body))return h||(h=!0,l(()=>f?.(`[fetch-layers] withRetry is enabled, but the request body is a stream. Streams are single-use; retries are disabled for this request. Use skipRetry: true to silence this warning, or pre-buffer the stream.`))),r(i);let o=i.method??`GET`,g=i.idempotency!==void 0||a(i.headers,u)!==void 0;_&&c(o)&&!g&&!i.skipIdempotency&&m(`retry-unsafe:${o}:${d(i.path)}`,`[fetch-layers] Retry is enabled for ${o} ${i.path} without the ${u} header. On a network failure the retry may create a duplicate. Add the header or disable retry with skipRetry.`);let v=i;for(let e=0;e<p;e++){s(v.signal);try{return await r(v)}catch(r){let i=n(r);if(i.isCancelled||i.isAuthError||e===p-1)throw i;let a=e+1,o;try{o=O(i,a)}catch(e){l(()=>f?.(`[fetch-layers] withRetry: shouldRetry threw, falling back to default. ${e instanceof Error?e.message:String(e)}`)),o=E(i)}if(!o)throw i;let s;if(i.retryAfterMs!==void 0){if(i.retryAfterMs>T)throw i;s=t(i.retryAfterMs,100)}else{let e;try{e=k(a,i)}catch(t){l(()=>f?.(`[fetch-layers] withRetry: computeDelay threw, falling back to default. ${t instanceof Error?t.message:String(t)}`)),e=D(a)}s=Math.min(t(e,100),T)}if(v=l(()=>S?.(v,a,i))??v,v.skipRetry)throw i;await C(s,v.signal)}}throw Error(`withRetry: unexpected exit from retry loop`)}}}}}export{l as n,c as r,f as t};
1
+ import{a as e,d as t,h as n,l as r,s as i}from"./classify-body-DOG6Vbf_.mjs";import{a,n as o,r as s}from"./signals-DQjF6ojU.mjs";function c(e){return e===`POST`||e===`PUT`||e===`PATCH`||e===`DELETE`}function l(e){try{return e()}catch{return}}const u=`Idempotency-Key`;function d(e){let t=e.replace(/^\/+/,``),n=t.indexOf(`/`);return n===-1?t:t.slice(0,n)}function f(f={}){let{maxAttempts:p=3,baseDelayMs:m=300,maxDelayMs:h=1e4,jitterRatio:g=.15,warnOnUnsafeRetry:_=!0,retryOnNetwork:v=!0,retryOnTimeout:y=!0,shouldRetry:b,computeDelay:x,onBeforeRetry:S,sleep:C=o}=f;if(i(p,`withRetry: maxAttempts`,1),r(m,`withRetry: baseDelayMs`),r(h,`withRetry: maxDelayMs`),!Number.isFinite(g)||g<0||g>1)throw Error(`withRetry: jitterRatio must be a number in [0, 1], got ${String(g)}`);let w=t(m,100);if(h<w)throw Error(`withRetry: maxDelayMs (${h}) must be >= baseDelayMs (${w})`);let T=h,E=e=>!(!e.isRetryable||e.kind===`network`&&!v||e.kind===`timeout`&&!y),D=e=>{let t=1-g+Math.random()*g*2;return w*2**(e-1)*t},O=b??E,k=x??D;return{name:`withRetry`,stage:2,wrap(r,i){let o=new Set,f=i.warn,m=(e,t)=>{o.has(e)||(o.add(e),l(()=>f?.(t)))},h=!1;return{fn:async function(i){if(i.skipRetry)return r(i);if(e(i.body))return h||(h=!0,l(()=>f?.(`[fetch-layers] withRetry is enabled, but the request body is a stream. Streams are single-use; retries are disabled for this request. Use skipRetry: true to silence this warning, or pre-buffer the stream.`))),r(i);let o=i.method??`GET`,g=i.idempotency!==void 0||a(i.headers,u)!==void 0;p>1&&_&&c(o)&&!g&&!i.skipIdempotency&&m(`retry-unsafe:${o}:${d(i.path)}`,`[fetch-layers] Retry is enabled for ${o} ${i.path} without the ${u} header. On a network failure the retry may create a duplicate. Add the header or disable retry with skipRetry.`);let v=i;for(let e=0;e<p;e++){s(v.signal);try{return await r(v)}catch(r){let i=n(r);if(i.isCancelled||i.isAuthError||e===p-1)throw i;let a=e+1,o;try{o=O(i,a)}catch(e){l(()=>f?.(`[fetch-layers] withRetry: shouldRetry threw, falling back to default. ${e instanceof Error?e.message:String(e)}`)),o=E(i)}if(!o)throw i;let s;if(i.retryAfterMs!==void 0){if(i.retryAfterMs>T)throw i;s=t(i.retryAfterMs,100)}else{let e;try{e=k(a,i)}catch(t){l(()=>f?.(`[fetch-layers] withRetry: computeDelay threw, falling back to default. ${t instanceof Error?t.message:String(t)}`)),e=D(a)}s=Math.min(t(e,100),T)}if(v=l(()=>S?.(v,a,i))??v,v.skipRetry)throw i;await C(s,v.signal)}}throw Error(`withRetry: unexpected exit from retry loop`)}}}}}export{l as n,c as r,f as t};
2
+ //# sourceMappingURL=layer-DQ0xiRMN.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"layer-DQ0xiRMN.mjs","names":["defaultSleep","sleep"],"sources":["../src/shared/method.ts","../src/shared/safe-call.ts","../src/layers/retry/layer.ts"],"sourcesContent":["import type { HttpMethod } from '../core/types';\n\n/**\n * Mutating methods. Idempotency and unsafe retry warning apply to\n * them.\n */\nexport function isMutatingMethod(method: HttpMethod): boolean {\n return method === 'POST' || method === 'PUT' || method === 'PATCH' || method === 'DELETE';\n}\n","/**\n * For app callbacks (logger, hooks): a failure does not break the\n * request. Returns undefined on error.\n */\nexport function safeCall<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n return undefined;\n }\n}\n","import { type ApiError, toApiError } from '../../core/errors';\nimport { isStreamingBody } from '../../shared/classify-body';\nimport { isMutatingMethod } from '../../shared/method';\nimport { safeCall } from '../../shared/safe-call';\nimport { sleep as defaultSleep, throwIfAborted } from '../../shared/signals';\nimport {\n assertInteger,\n assertNonNegativeNumber,\n clampDelay,\n MIN_RETRY_MS,\n} from '../../shared/validators';\nimport { getHeader } from '../../transport/headers';\n\nimport type { Layer, LayerContext, LayerWrapResult } from '../../core/layer';\nimport type { RequestFn, ResolvedRequestConfig } from '../../core/types';\n\n/**\n * Default idempotency header name. Used by the unsafe retry warning\n * when withIdempotency is not wired up but the app set the key\n * manually. An idempotency marker in the config skips the header\n * check.\n */\nconst DEFAULT_IDEMPOTENCY_HEADER = 'Idempotency-Key';\n\nexport interface RetryOptions {\n /**\n * Max attempts, including the first one. Defaults to 3, minimum 1.\n */\n maxAttempts?: number;\n\n /**\n * Initial delay in milliseconds. Defaults to 300. Values below\n * MIN_RETRY_MS are raised to the minimum.\n */\n baseDelayMs?: number;\n\n /**\n * Upper bound of the delay. Defaults to 10000. Caps the computed\n * delay and acts as threshold for Retry-After: if the server asked\n * for more, the retry is skipped.\n *\n * Must be >= baseDelayMs after it was raised to MIN_RETRY_MS,\n * otherwise withRetry throws.\n */\n maxDelayMs?: number;\n\n /**\n * Spread around the computed delay, defaults to 0.15 (+-15%).\n * 0 disables the spread, 1 gives +-100%. Not applied to\n * Retry-After. Value in [0, 1].\n */\n jitterRatio?: number;\n\n /**\n * Warn about a mutating retry without idempotency header. Defaults\n * to true.\n *\n * No warning when withIdempotency applied a key, the app set\n * Idempotency-Key itself, or passed skipIdempotency: true. Once per\n * method and root path segment: for DELETE /sessions/123 the root\n * segment is sessions.\n */\n warnOnUnsafeRetry?: boolean;\n\n /** Retry network errors (kind network). Defaults to true. */\n retryOnNetwork?: boolean;\n\n /**\n * Retry timeouts (kind timeout). Defaults to true. For unsafe\n * methods a retry without Idempotency-Key may create a duplicate.\n */\n retryOnTimeout?: boolean;\n\n /**\n * Retry policy. Defaults to isRetryable, adjusted by retryOnNetwork\n * and retryOnTimeout. Cancel and auth errors are not retried even\n * if the function returns true.\n *\n * On callback failure the default policy is used, the error goes\n * to warn.\n *\n * @param attempt - failed attempt number, 1-based.\n */\n shouldRetry?: (error: ApiError, attempt: number) => boolean;\n\n /**\n * Delay before retry. Not applied when the server sent Retry-After.\n * Result is clamped to [MIN_RETRY_MS, maxDelayMs].\n *\n * On callback failure the default delay is used, the error goes\n * to warn.\n *\n * @param attempt - failed attempt number, 1-based.\n */\n computeDelay?: (attempt: number, error: ApiError) => number;\n\n /**\n * Before each retry. May return a new config (e.g. replace\n * Idempotency-Key on 409) or stop retries by returning\n * skipRetry: true - the error is rethrown at once.\n *\n * Runs only when shouldRetry allowed the retry, so a status the\n * default policy does not retry (409, 404, 400) never reaches it.\n * To handle 409 here, add it to shouldRetry.\n *\n * @param attempt - attempt number from 1. First retry: attempt === 1.\n */\n onBeforeRetry?: (\n config: ResolvedRequestConfig,\n attempt: number,\n error: ApiError,\n ) => ResolvedRequestConfig | void;\n\n /** Pause between attempts. Defaults to setTimeout with abort. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n}\n\n/**\n * First path segment: for \"/orders/123\" it is \"orders\". Dedup key\n * for the warning: dynamic ids inside one resource collapse,\n * different resources give different keys.\n */\nfunction rootSegment(path: string): string {\n const trimmed = path.replace(/^\\/+/, '');\n const slash = trimmed.indexOf('/');\n return slash === -1 ? trimmed : trimmed.slice(0, slash);\n}\n\n/**\n * Automatic retry layer.\n *\n * Retries network errors, timeouts, 5xx, 408 and 429. Does not retry\n * cancel, auth errors and other 4xx.\n *\n * Delays are exponential with +-15% spread (300, 600, 1200 ms), upper\n * bound is maxDelayMs.\n *\n * Retry-After from the response replaces the computed delay. If the\n * value is above maxDelayMs, the retry is skipped: the server asks to\n * wait longer than the app is ready to.\n *\n * Retries are disabled for streaming bodies: a stream is single-use,\n * a second fetch throws TypeError, which transport takes for a\n * network error.\n *\n * @throws Error on invalid options.\n */\nexport function withRetry(options: RetryOptions = {}): Layer {\n const {\n maxAttempts = 3,\n baseDelayMs: rawBaseDelayMs = 300,\n maxDelayMs: rawMaxDelayMs = 10_000,\n jitterRatio = 0.15,\n warnOnUnsafeRetry = true,\n retryOnNetwork = true,\n retryOnTimeout = true,\n shouldRetry,\n computeDelay,\n onBeforeRetry,\n sleep = defaultSleep,\n } = options;\n\n assertInteger(maxAttempts, 'withRetry: maxAttempts', 1);\n assertNonNegativeNumber(rawBaseDelayMs, 'withRetry: baseDelayMs');\n assertNonNegativeNumber(rawMaxDelayMs, 'withRetry: maxDelayMs');\n\n if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) {\n throw new Error(\n `withRetry: jitterRatio must be a number in [0, 1], got ${String(jitterRatio)}`,\n );\n }\n\n const baseDelayMs = clampDelay(rawBaseDelayMs, MIN_RETRY_MS);\n\n if (rawMaxDelayMs < baseDelayMs) {\n throw new Error(\n `withRetry: maxDelayMs (${rawMaxDelayMs}) must be >= baseDelayMs (${baseDelayMs})`,\n );\n }\n\n const maxDelayMs = rawMaxDelayMs;\n\n /**\n * Default retries everything isRetryable allows, but network and\n * timeout are filtered by separate options: timeouts can be turned\n * off while network retries stay on.\n */\n const defaultShouldRetry = (err: ApiError): boolean => {\n if (!err.isRetryable) return false;\n if (err.kind === 'network' && !retryOnNetwork) return false;\n if (err.kind === 'timeout' && !retryOnTimeout) return false;\n return true;\n };\n\n /** 1-based: first retry gets base delay, second - doubled. */\n const defaultCompute = (attempt: number): number => {\n const jitter = 1 - jitterRatio + Math.random() * jitterRatio * 2;\n return baseDelayMs * 2 ** (attempt - 1) * jitter;\n };\n\n const retryPolicy = shouldRetry ?? defaultShouldRetry;\n const delayPolicy = computeDelay ?? defaultCompute;\n\n return {\n name: 'withRetry',\n stage: 2,\n\n wrap(next: RequestFn, context: LayerContext): LayerWrapResult {\n // Set inside wrap: each createClient gets its own instance, even\n // if the same Layer is passed to several clients.\n const warnedUnsafeRetry = new Set<string>();\n const warn = context.warn;\n\n const warnUnsafeRetryOnce = (key: string, message: string): void => {\n if (warnedUnsafeRetry.has(key)) return;\n warnedUnsafeRetry.add(key);\n safeCall(() => warn?.(message));\n };\n\n let warnedStreamNoRetry = false;\n\n const fn: RequestFn = async function retryRequest<T>(\n initialConfig: ResolvedRequestConfig,\n ): Promise<T> {\n if (initialConfig.skipRetry) {\n return next<T>(initialConfig);\n }\n\n // A stream is single-use: fetch takes it on the first send,\n // a retry throws TypeError, transport takes it for a network\n // error.\n if (isStreamingBody(initialConfig.body)) {\n if (!warnedStreamNoRetry) {\n warnedStreamNoRetry = true;\n safeCall(() =>\n warn?.(\n '[fetch-layers] withRetry is enabled, but the request body is a stream. ' +\n 'Streams are single-use; retries are disabled for this request. ' +\n 'Use skipRetry: true to silence this warning, or pre-buffer the stream.',\n ),\n );\n }\n return next<T>(initialConfig);\n }\n\n const method = initialConfig.method ?? 'GET';\n\n // Marker is set by withIdempotency. If missing, check the\n // header: the app could set the key manually.\n const hasIdempotencyKey =\n initialConfig.idempotency !== undefined ||\n getHeader(initialConfig.headers, DEFAULT_IDEMPOTENCY_HEADER) !== undefined;\n\n // Before the first attempt: the warning is about config, not\n // about an actual retry.\n if (\n maxAttempts > 1 &&\n warnOnUnsafeRetry &&\n isMutatingMethod(method) &&\n !hasIdempotencyKey &&\n !initialConfig.skipIdempotency\n ) {\n warnUnsafeRetryOnce(\n `retry-unsafe:${method}:${rootSegment(initialConfig.path)}`,\n `[fetch-layers] Retry is enabled for ${method} ${initialConfig.path} ` +\n `without the ${DEFAULT_IDEMPOTENCY_HEADER} header. On a network failure ` +\n `the retry may create a duplicate. Add the header or disable retry ` +\n `with skipRetry.`,\n );\n }\n\n let config = initialConfig;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n throwIfAborted(config.signal);\n\n try {\n return await next<T>(config);\n } catch (e) {\n const err = toApiError(e);\n\n if (err.isCancelled) throw err;\n if (err.isAuthError) throw err;\n if (attempt === maxAttempts - 1) throw err;\n\n const failedAttempt = attempt + 1;\n\n let retryDecision: boolean;\n try {\n retryDecision = retryPolicy(err, failedAttempt);\n } catch (policyError) {\n safeCall(() =>\n warn?.(\n `[fetch-layers] withRetry: shouldRetry threw, falling back to default. ` +\n `${policyError instanceof Error ? policyError.message : String(policyError)}`,\n ),\n );\n retryDecision = defaultShouldRetry(err);\n }\n\n if (!retryDecision) throw err;\n\n // Retry-After takes priority: if the server asked for more\n // than maxDelayMs, skip the retry.\n let delay: number;\n if (err.retryAfterMs !== undefined) {\n if (err.retryAfterMs > maxDelayMs) throw err;\n delay = clampDelay(err.retryAfterMs, MIN_RETRY_MS);\n } else {\n let computed: number;\n try {\n computed = delayPolicy(failedAttempt, err);\n } catch (policyError) {\n safeCall(() =>\n warn?.(\n `[fetch-layers] withRetry: computeDelay threw, falling back to default. ` +\n `${policyError instanceof Error ? policyError.message : String(policyError)}`,\n ),\n );\n computed = defaultCompute(failedAttempt);\n }\n\n delay = Math.min(clampDelay(computed, MIN_RETRY_MS), maxDelayMs);\n }\n\n // onBeforeRetry may replace the config or stop retries via\n // skipRetry: true.\n config = safeCall(() => onBeforeRetry?.(config, failedAttempt, err)) ?? config;\n if (config.skipRetry) throw err;\n\n await sleep(delay, config.signal);\n }\n }\n\n throw new Error('withRetry: unexpected exit from retry loop');\n };\n\n return { fn };\n },\n };\n}\n"],"mappings":"iIAMA,SAAgB,EAAiB,EAA6B,CAC5D,OAAO,IAAW,QAAU,IAAW,OAAS,IAAW,SAAW,IAAW,QACnF,CCJA,SAAgB,EAAY,EAA4B,CACtD,GAAI,CACF,OAAO,EAAG,CACZ,MAAQ,CACN,MACF,CACF,CCYA,MAAM,EAA6B,kBAoGnC,SAAS,EAAY,EAAsB,CACzC,IAAM,EAAU,EAAK,QAAQ,OAAQ,EAAE,EACjC,EAAQ,EAAQ,QAAQ,GAAG,EACjC,OAAO,IAAU,GAAK,EAAU,EAAQ,MAAM,EAAG,CAAK,CACxD,CAqBA,SAAgB,EAAU,EAAwB,CAAC,EAAU,CAC3D,GAAM,CACJ,cAAc,EACd,YAAa,EAAiB,IAC9B,WAAY,EAAgB,IAC5B,cAAc,IACd,oBAAoB,GACpB,iBAAiB,GACjB,iBAAiB,GACjB,cACA,eACA,gBACA,MAAA,EAAQA,GACN,EAMJ,GAJA,EAAc,EAAa,yBAA0B,CAAC,EACtD,EAAwB,EAAgB,wBAAwB,EAChE,EAAwB,EAAe,uBAAuB,EAE1D,CAAC,OAAO,SAAS,CAAW,GAAK,EAAc,GAAK,EAAc,EACpE,MAAU,MACR,0DAA0D,OAAO,CAAW,GAC9E,EAGF,IAAM,EAAc,EAAW,EAAA,GAA4B,EAE3D,GAAI,EAAgB,EAClB,MAAU,MACR,0BAA0B,EAAc,4BAA4B,EAAY,EAClF,EAGF,IAAM,EAAa,EAOb,EAAsB,GAG1B,EAFI,CAAC,EAAI,aACL,EAAI,OAAS,WAAa,CAAC,GAC3B,EAAI,OAAS,WAAa,CAAC,GAK3B,EAAkB,GAA4B,CAClD,IAAM,EAAS,EAAI,EAAc,KAAK,OAAO,EAAI,EAAc,EAC/D,OAAO,EAAc,IAAM,EAAU,GAAK,CAC5C,EAEM,EAAc,GAAe,EAC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IAAA,GAAW,CAClC,GAAI,EAAI,aAAe,EAAY,MAAM,EACzC,EAAQ,EAAW,EAAI,aAAA,GAA0B,CACnD,KAAO,CACL,IAAI,EACJ,GAAI,CACF,EAAW,EAAY,EAAe,CAAG,CAC3C,OAAS,EAAa,CACpB,MACE,IACE,0EACK,aAAuB,MAAQ,EAAY,QAAU,OAAO,CAAW,GAC9E,CACF,EACA,EAAW,EAAe,CAAa,CACzC,CAEA,EAAQ,KAAK,IAAI,EAAW,EAAA,GAAsB,EAAG,CAAU,CACjE,CAKA,GADA,EAAS,MAAe,IAAgB,EAAQ,EAAe,CAAG,CAAC,GAAK,EACpE,EAAO,UAAW,MAAM,EAE5B,MAAMC,EAAM,EAAO,EAAO,MAAM,CAClC,CACF,CAEA,MAAU,MAAM,4CAA4C,CAC9D,CAEY,CACd,CACF,CACF"}
@@ -1,5 +1,5 @@
1
- import { r as Client } from "../../layer-D1S2Wlu1.mjs";
2
- import { a as SessionProvider, i as SessionExpiredReason, r as RefreshResult, t as AuthOptions } from "../../layer-Db25lSAX.mjs";
1
+ import { r as Client } from "../../layer-C5h5TXG6.mjs";
2
+ import { a as SessionProvider, i as SessionExpiredReason, r as RefreshResult, t as AuthOptions } from "../../layer-3tx7wJdK.mjs";
3
3
  //#region src/layers/auth/reset-registry.d.ts
4
4
  /**
5
5
  * Resets the token refresh breaker on the given client.
@@ -9,4 +9,5 @@ import { a as SessionProvider, i as SessionExpiredReason, r as RefreshResult, t
9
9
  */
10
10
  declare function resetRefreshCircuit(client: Client): boolean;
11
11
  //#endregion
12
- export { type AuthOptions, type RefreshResult, type SessionExpiredReason, type SessionProvider, resetRefreshCircuit };
12
+ export { type AuthOptions, type RefreshResult, type SessionExpiredReason, type SessionProvider, resetRefreshCircuit };
13
+ //# sourceMappingURL=index.d.mts.map
@@ -1,44 +1,4 @@
1
- import { t as StorageLike } from "../../storage-C0XsVkz-.mjs";
2
- import { a as IdempotencySource, i as IdempotencyOutcome, r as IdempotencyContext, t as IdempotencyOptions } from "../../layer-C9nwqcxP.mjs";
3
- //#region src/layers/idempotency/session.d.ts
4
- interface SessionSourceOptions {
5
- /**
6
- * Storage. Wrap localStorage and sessionStorage in fromWebStorage,
7
- * use createMemoryStorage for Node.
8
- */
9
- storage: StorageLike;
10
- /** Key of the record object. Defaults to idempotency:session. */
11
- storageKey?: string;
12
- /**
13
- * Key generator. Defaults to crypto.randomUUID. Can be replaced
14
- * for tests or non-standard schemes.
15
- */
16
- generateKey?: () => string;
17
- /**
18
- * Max entries, defaults to 100. When exceeded, the least recently
19
- * used record is dropped.
20
- *
21
- * A record is a triple (scope, query, fingerprint): one scope with
22
- * different bodies takes several.
23
- */
24
- maxEntries?: number;
25
- }
26
- /**
27
- * Key source on top of a synchronous StorageLike.
28
- *
29
- * If a key exists for the triple (scope, query, fingerprint), it is
30
- * returned and its last-used time is updated. If the body or query
31
- * changed, or the pair is new, a new key is generated. On success
32
- * and definite-failure the record is deleted, on indefinite-failure
33
- * it is kept for the retry.
34
- *
35
- * Ready factories for sessionStorage, localStorage and memory live
36
- * in fetch-layers/layers.
37
- *
38
- * @throws Error if maxEntries is below 1.
39
- */
40
- declare function createSessionSource(options: SessionSourceOptions): IdempotencySource;
41
- //#endregion
1
+ import { a as createSessionSource, c as IdempotencySource, i as StorageSourceOptions, o as IdempotencyContext, r as SessionSourceOptions, s as IdempotencyOutcome, t as IdempotencyOptions } from "../../layer-CH2X3ibX.mjs";
42
2
  //#region src/layers/idempotency/serialize.d.ts
43
3
  /**
44
4
  * Stable value serialization. Object keys are sorted alphabetically:
@@ -52,4 +12,5 @@ declare function createSessionSource(options: SessionSourceOptions): Idempotency
52
12
  */
53
13
  declare function stableSerialize(value: unknown): string;
54
14
  //#endregion
55
- export { type IdempotencyContext, type IdempotencyOptions, type IdempotencyOutcome, type IdempotencySource, type SessionSourceOptions, createSessionSource, stableSerialize };
15
+ export { type IdempotencyContext, type IdempotencyOptions, type IdempotencyOutcome, type IdempotencySource, type SessionSourceOptions, type StorageSourceOptions, createSessionSource, stableSerialize };
16
+ //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- import{n as e,t}from"../../session-Dm-H-5hJ.mjs";export{t as createSessionSource,e as stableSerialize};
1
+ import{n as e,t}from"../../session-CcBNIxp4.mjs";export{t as createSessionSource,e as stableSerialize};
@@ -1,38 +1,62 @@
1
- import { n as LayerContext, t as Layer } from "../layer-D1S2Wlu1.mjs";
2
- import { n as withAuth, t as AuthOptions } from "../layer-Db25lSAX.mjs";
3
- import { a as IdempotencySource, n as withIdempotency, t as IdempotencyOptions } from "../layer-C9nwqcxP.mjs";
4
- import { n as withRetry, t as RetryOptions } from "../layer-DRRyGTne.mjs";
1
+ import { n as LayerContext, t as Layer } from "../layer-C5h5TXG6.mjs";
2
+ import { n as withAuth, t as AuthOptions } from "../layer-3tx7wJdK.mjs";
3
+ import { c as IdempotencySource, i as StorageSourceOptions, n as withIdempotency, t as IdempotencyOptions } from "../layer-CH2X3ibX.mjs";
4
+ import { n as withRetry, t as RetryOptions } from "../layer-BvZMV3L4.mjs";
5
5
  //#region src/layers/idempotency/sources.d.ts
6
6
  /**
7
7
  * Key source on top of sessionStorage. Storage is isolated between
8
- * tabs: two orders from two tabs get different keys. For
9
- * deduplication across tabs use localStorageSource.
8
+ * tabs: two orders from two tabs get different keys. The guarantee
9
+ * holds within one tab, which is also true for localStorageSource:
10
+ * nextKey is synchronous, so its read-modify-write is not atomic
11
+ * across tabs.
12
+ *
13
+ * Records hold the serialized body, query and baseUrl as plain text
14
+ * with no TTL, readable by any script on the origin. Do not use for
15
+ * card data, credentials or personal data.
10
16
  *
11
17
  * Outside a browser use memoryStorageSource or your own source on
12
18
  * top of Redis, KV, IndexedDB.
13
19
  *
20
+ * @param options - storageKey, maxEntries and generateKey. Pass a
21
+ * distinct storageKey when one origin talks to several APIs:
22
+ * by default all clients share the `idempotency:session` record.
14
23
  * @throws Error if sessionStorage is not available: SSR, Workers,
15
24
  * disabled cookies. The error is thrown when the factory is
16
25
  * called, not on the first request.
17
26
  */
18
- declare function sessionStorageSource(): IdempotencySource;
27
+ declare function sessionStorageSource(options?: StorageSourceOptions): IdempotencySource;
19
28
  /**
20
- * Key source on top of localStorage. Storage is shared between all
21
- * tabs: one operation with one body from different tabs gets one key
22
- * and is recognized as a duplicate on the server.
29
+ * Key source on top of localStorage. Shared between tabs, but the
30
+ * read-modify-write in nextKey is not atomic across them: two tabs
31
+ * can generate two keys for one operation. The guarantee holds
32
+ * within one tab. For cross-tab deduplication use a source on top of
33
+ * a storage with atomic writes.
34
+ *
35
+ * Records hold the serialized body, query and baseUrl as plain text
36
+ * with no TTL. Do not use for card data, credentials or personal
37
+ * data: any script on the origin can read it.
23
38
  *
24
39
  * Outside a browser use memoryStorageSource or your own source on
25
40
  * top of Redis, KV, IndexedDB.
26
41
  *
42
+ * @param options - storageKey, maxEntries and generateKey. Pass a
43
+ * distinct storageKey when one origin talks to several APIs:
44
+ * by default all clients share the `idempotency:session` record.
27
45
  * @throws Error if localStorage is not available: SSR, Workers,
28
46
  * disabled cookies. The error is thrown when the factory is
29
47
  * called, not on the first request.
30
48
  */
31
- declare function localStorageSource(): IdempotencySource;
49
+ declare function localStorageSource(options?: StorageSourceOptions): IdempotencySource;
32
50
  /**
33
51
  * In-memory key source. Lives as long as the process; data is lost
34
- * on page reload. For tests, SSR, Workers and one-off operations.
52
+ * on page reload. Nothing leaves the process heap: the safe choice
53
+ * for card data, credentials and personal data.
54
+ *
55
+ * With several SSR instances each process has its own store, so a
56
+ * retry routed to another instance gets a new key. Use a shared
57
+ * source for that case.
35
58
  */
36
- declare function memoryStorageSource(): IdempotencySource;
59
+ declare function memoryStorageSource(options?: StorageSourceOptions): IdempotencySource;
37
60
  //#endregion
38
- export { type AuthOptions, type IdempotencyOptions, type Layer, type LayerContext, type RetryOptions, localStorageSource, memoryStorageSource, sessionStorageSource, withAuth, withIdempotency, withRetry };
61
+ export { type AuthOptions, type IdempotencyOptions, type Layer, type LayerContext, type RetryOptions, type StorageSourceOptions, localStorageSource, memoryStorageSource, sessionStorageSource, withAuth, withIdempotency, withRetry };
62
+ //# sourceMappingURL=index.d.mts.map
@@ -1 +1,2 @@
1
- import{f as e,h as t,m as n,p as r,u as i}from"../classify-body-DOG6Vbf_.mjs";import{a,i as o,o as s,r as c,s as l}from"../signals-DQjF6ojU.mjs";import{createMemoryStorage as u,fromWebStorage as d}from"../shared/storage.mjs";import{n as f,r as p,t as m}from"../layer-Dhb1y_u6.mjs";import{t as h}from"../reset-registry-CQPiZVBB.mjs";import{t as g}from"../session-Dm-H-5hJ.mjs";var _=class{openUntil=0;isOpen=!1;timer=null;callbacks;constructor(e={}){this.callbacks=e}isBlocking(){return this.isOpen?Date.now()>=this.openUntil?(this.close(),!1):!0:!1}open(e){if(!Number.isFinite(e)||e<=0)throw Error(`CircuitBreaker.open: durationMs must be a positive number, got ${String(e)}`);let t=this.isOpen&&Date.now()<this.openUntil;this.openUntil=Date.now()+e,this.isOpen=!0,this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.close(),e),o(this.timer),t||f(()=>this.callbacks.onOpen?.())}close(){this.isOpen&&(this.timer&&=(clearTimeout(this.timer),null),this.isOpen=!1,this.openUntil=0,f(()=>this.callbacks.onClose?.()))}},v=class{inFlight=null;run(e){if(this.inFlight)return this.inFlight;let t=e().finally(()=>{this.inFlight===t&&(this.inFlight=null)});return this.inFlight=t,t}forget(){this.inFlight=null}},y=class{circuit;singleFlight=new v;refreshTimeoutMs;lastSuccessfulRefreshAt=0;resetCount=0;refreshSignals=new WeakSet;constructor(e={},t=3e4){this.circuit=new _({onOpen:e.onCircuitOpen,onClose:e.onCircuitClose}),this.refreshTimeoutMs=t}reset(){this.resetCount++,this.lastSuccessfulRefreshAt=0,this.singleFlight.forget(),this.circuit.close()}isRefreshSignal(e){return e!==void 0&&this.refreshSignals.has(e)}refresh(t,n){if(this.circuit.isBlocking())return Promise.resolve({status:`temporarily-failed`,error:new e({kind:`unknown`,code:`REFRESH_CIRCUIT_OPEN`,message:`Token refresh is temporarily unavailable`,isUncertain:!1})});let r=Date.now();return this.lastSuccessfulRefreshAt>0&&r-this.lastSuccessfulRefreshAt<n?Promise.resolve({status:`cooldown`}):this.singleFlight.run(()=>this.doRefresh(t,n))}async doRefresh(t,n){let i=this.resetCount,a=new AbortController,s,c=new Promise((e,t)=>{s=setTimeout(()=>{let e=new DOMException(`Refresh timeout`,`TimeoutError`);a.abort(e),t(e)},this.refreshTimeoutMs),o(s)});c.catch(()=>{});let l;try{this.refreshSignals.add(a.signal);let e=t.refresh(a.signal);e.catch(()=>{}),l=await Promise.race([e,c])}catch(t){let i=r(t);return i.kind===`timeout`?(this.circuit.open(n),{status:`temporarily-failed`,error:new e({kind:`timeout`,code:`REFRESH_TIMEOUT`,message:`Token refresh timed out`,isUncertain:!0})}):i.isCancelled?{status:`temporarily-failed`,error:i}:i.status===401||i.status===403?{status:`definitely-failed`,reason:i.status===403?`refresh-forbidden`:`refresh-rejected`}:((i.kind===`network`||i.isServerError)&&this.circuit.open(n),{status:`temporarily-failed`,error:i})}finally{clearTimeout(s)}if(l.status===`temporarily-failed`){let e=r(l.error);return e.isCancelled||this.circuit.open(n),{status:`temporarily-failed`,error:e}}return l.status===`success`&&this.resetCount===i&&(this.lastSuccessfulRefreshAt=Date.now()),l}};function b(e){let{provider:n,onSessionExpired:r,circuitBreakerMs:a=5e3,refreshTimeoutMs:o=3e4}=e;return i(a,`withAuth: circuitBreakerMs`),i(o,`withAuth: refreshTimeoutMs`),{name:`withAuth`,stage:1,wrap(i,l){let u=new y({onCircuitOpen:()=>{f(()=>e.onCircuitOpen?.())},onCircuitClose:()=>{f(()=>e.onCircuitClose?.())}},o);return{fn:async function(e){if(e.skipAuth)return i(e);c(e.signal);let o=await x(n),d={...e,headers:s(e.headers,o)};try{return await i(d)}catch(o){let d=t(o);if(d.status!==401)throw d;if(c(e.signal),u.isRefreshSignal(e.signal))throw f(()=>l.warn?.(`[fetch-layers] withAuth: 401 inside provider.refresh. Use a separate client without withAuth for the refresh endpoint.`)),d;let p=await u.refresh(n,a);if(p.status===`temporarily-failed`)throw t(p.error);if(p.status===`definitely-failed`)throw S(n),f(()=>r?.(p.reason)),d;if(p.status===`cooldown`){c(e.signal);let a=await x(n);try{return await i({...e,headers:s(e.headers,a)})}catch(e){let i=t(e);throw i.status===401&&(S(n),f(()=>r?.(`token-rejected`))),i}}c(e.signal);let m=p.headers??await x(n);try{return await i({...e,headers:s(e.headers,m)})}catch(e){let i=t(e);throw i.status===401&&(S(n),f(()=>r?.(`token-rejected`))),i}}},state:u}},attach(e,t){t instanceof y&&h(e,()=>t.reset())}}}async function x(t){try{let e=await t.getAuthHeaders();return!e||typeof e!=`object`?{}:e}catch(t){throw n(t,`AbortError`)?new e({kind:`abort`,code:`ABORTED`,message:`Request aborted`,cause:t}):new e({kind:`unknown`,code:`AUTH_PROVIDER_ERROR`,message:`Auth provider failed to return headers`,cause:t})}}function S(e){try{e.clear?.()}catch{}}function C(e,n={}){let{headerName:r=`Idempotency-Key`}=n;return{name:`withIdempotency`,stage:3,wrap(n){return{fn:async function(i){let o=i.method??`GET`;if(!p(o)||i.skipIdempotency)return n(i);let c=a(i.headers,r);if(c!==void 0&&c.trim()!==``)return n({...i,idempotency:{headerName:r,key:c}});let u={path:i.path,method:o,body:i.body,query:i.query,scope:i.idempotencyScope},d;try{d=e.nextKey(u)}catch(e){throw t(e)}let f=s(i.headers);l(f,r,d);let m={...i,headers:f,idempotency:{headerName:r,key:d}};try{let t=await n(m);return T(e,u,`success`),t}catch(n){let r=t(n);throw T(e,u,w(r)),r}}}}}}function w(e){return e.status>=400&&e.status<500&&e.status!==408&&e.status!==429?`definite-failure`:`indefinite-failure`}function T(e,t,n){if(e.resolve)try{e.resolve(t,n)}catch{}}function E(){return g({storage:d(k())})}function D(){return g({storage:d(A())})}function O(){return g({storage:u()})}function k(){if(typeof sessionStorage>`u`)throw Error(`sessionStorageSource is not available outside a browser. For SSR and tests use memoryStorageSource.`);return sessionStorage}function A(){if(typeof localStorage>`u`)throw Error(`localStorageSource is not available outside a browser. For SSR and tests use memoryStorageSource.`);return localStorage}export{D as localStorageSource,O as memoryStorageSource,E as sessionStorageSource,b as withAuth,C as withIdempotency,m as withRetry};
1
+ import{a as e,f as t,h as n,m as r,p as i,u as a}from"../classify-body-DOG6Vbf_.mjs";import{a as o,i as s,o as c,r as l,s as u}from"../signals-DQjF6ojU.mjs";import{createMemoryStorage as d,fromWebStorage as f}from"../shared/storage.mjs";import{n as p,r as m,t as h}from"../layer-DQ0xiRMN.mjs";import{t as g}from"../reset-registry-CQPiZVBB.mjs";import{t as _}from"../session-CcBNIxp4.mjs";var v=class{openUntil=0;isOpen=!1;timer=null;callbacks;constructor(e={}){this.callbacks=e}isBlocking(){return this.isOpen?Date.now()>=this.openUntil?(this.close(),!1):!0:!1}open(e){if(!Number.isFinite(e)||e<=0)throw Error(`CircuitBreaker.open: durationMs must be a positive number, got ${String(e)}`);let t=this.isOpen&&Date.now()<this.openUntil;this.openUntil=Date.now()+e,this.isOpen=!0,this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.close(),e),s(this.timer),t||p(()=>this.callbacks.onOpen?.())}close(){this.isOpen&&(this.timer&&=(clearTimeout(this.timer),null),this.isOpen=!1,this.openUntil=0,p(()=>this.callbacks.onClose?.()))}},y=class{inFlight=null;run(e){if(this.inFlight)return this.inFlight;let t=e().finally(()=>{this.inFlight===t&&(this.inFlight=null)});return this.inFlight=t,t}forget(){this.inFlight=null}};function b(e){if(!e||typeof e!=`object`)return!1;let t=e;switch(t.status){case`success`:return t.headers===void 0||typeof t.headers==`object`&&t.headers!==null;case`definitely-failed`:return t.reason===`refresh-rejected`||t.reason===`refresh-forbidden`||t.reason===`token-rejected`;case`temporarily-failed`:return`error`in t;default:return!1}}var x=class{circuit;singleFlight=new y;refreshTimeoutMs;lastSuccessfulRefreshAt=0;resetCount=0;refreshSignals=new WeakSet;constructor(e={},t=3e4){this.circuit=new v({onOpen:e.onCircuitOpen,onClose:e.onCircuitClose}),this.refreshTimeoutMs=t}reset(){this.resetCount++,this.lastSuccessfulRefreshAt=0,this.singleFlight.forget(),this.circuit.close()}isRefreshSignal(e){return e!==void 0&&this.refreshSignals.has(e)}refresh(e,n){if(this.circuit.isBlocking())return Promise.resolve({status:`temporarily-failed`,error:new t({kind:`unknown`,code:`REFRESH_CIRCUIT_OPEN`,message:`Token refresh is temporarily unavailable`,isUncertain:!1})});let r=Date.now();return this.lastSuccessfulRefreshAt>0&&r-this.lastSuccessfulRefreshAt<n?Promise.resolve({status:`cooldown`}):this.singleFlight.run(()=>this.doRefresh(e,n))}openCircuitUnlessReset(e,t){this.resetCount===t&&this.circuit.open(e)}async doRefresh(e,n){let r=this.resetCount,a=new AbortController,o,c=new Promise((e,t)=>{o=setTimeout(()=>{let e=new DOMException(`Refresh timeout`,`TimeoutError`);a.abort(e),t(e)},this.refreshTimeoutMs),s(o)});c.catch(()=>{});let l;try{this.refreshSignals.add(a.signal);let n=e.refresh(a.signal);n.catch(()=>{});let r=await Promise.race([n,c]);if(!b(r))throw new t({kind:`unknown`,code:`AUTH_PROVIDER_ERROR`,message:`provider.refresh returned an invalid result`,cause:r});l=r}catch(e){let a=i(e);return a.kind===`timeout`?(this.openCircuitUnlessReset(n,r),{status:`temporarily-failed`,error:new t({kind:`timeout`,code:`REFRESH_TIMEOUT`,message:`Token refresh timed out`,isUncertain:!0})}):a.isCancelled?{status:`temporarily-failed`,error:a}:a.status===401||a.status===403?{status:`definitely-failed`,reason:a.status===403?`refresh-forbidden`:`refresh-rejected`}:((a.kind===`network`||a.isServerError)&&this.openCircuitUnlessReset(n,r),{status:`temporarily-failed`,error:a})}finally{clearTimeout(o)}if(l.status===`temporarily-failed`){let e=i(l.error);return e.isCancelled||this.openCircuitUnlessReset(n,r),{status:`temporarily-failed`,error:e}}return l.status===`success`&&this.resetCount===r&&(this.lastSuccessfulRefreshAt=Date.now()),l}};function S(t){let{provider:r,onSessionExpired:i,circuitBreakerMs:o=5e3,refreshTimeoutMs:s=3e4}=t;return a(o,`withAuth: circuitBreakerMs`),a(s,`withAuth: refreshTimeoutMs`),{name:`withAuth`,stage:1,wrap(a,u){let d=new x({onCircuitOpen:()=>{p(()=>t.onCircuitOpen?.())},onCircuitClose:()=>{p(()=>t.onCircuitClose?.())}},s);return{fn:async function(t){if(t.skipAuth)return a(t);l(t.signal);let s=await w(r),f={...t,headers:c(t.headers,s)};try{return await a(f)}catch(s){let f=n(s);if(f.status!==401)throw f;if(l(t.signal),d.isRefreshSignal(t.signal))throw p(()=>u.warn?.(`[fetch-layers] withAuth: 401 inside provider.refresh. Use a separate client without withAuth for the refresh endpoint.`)),f;let m=await d.refresh(r,o);if(m.status===`temporarily-failed`)throw n(m.error);if(m.status===`definitely-failed`)throw T(r),p(()=>i?.(m.reason)),f;if(e(t.body))throw p(()=>u.warn?.(`[fetch-layers] withAuth: the request body is a stream and cannot be replayed after token refresh. The token was refreshed; resend the request with a new body or use skipAuth for this call.`)),f;if(m.status===`cooldown`){l(t.signal);let e=await w(r);try{return await a({...t,headers:c(t.headers,e)})}catch(e){let t=n(e);throw t.status===401&&(T(r),p(()=>i?.(`token-rejected`))),t}}l(t.signal);let h=C(m.headers)?m.headers:await w(r);try{return await a({...t,headers:c(t.headers,h)})}catch(e){let t=n(e);throw t.status===401&&(T(r),p(()=>i?.(`token-rejected`))),t}}},state:d}},attach(e,t){t instanceof x&&g(e,()=>t.reset())}}}function C(e){return e!==void 0&&Object.keys(e).length>0}async function w(e){try{let t=await e.getAuthHeaders();return!t||typeof t!=`object`?{}:t}catch(e){throw r(e,`AbortError`)?new t({kind:`abort`,code:`ABORTED`,message:`Request aborted`,cause:e}):new t({kind:`unknown`,code:`AUTH_PROVIDER_ERROR`,message:`Auth provider failed to return headers`,cause:e})}}function T(e){try{e.clear?.()}catch{}}function E(e,r={}){let{headerName:i=`Idempotency-Key`}=r;return{name:`withIdempotency`,stage:3,wrap(r){return{fn:async function(a){let s=a.method??`GET`;if(!m(s)||a.skipIdempotency)return r(a);let l=o(a.headers,i);if(l!==void 0&&l.trim()!==``)return r({...a,idempotency:{headerName:i,key:l}});let d={path:a.path,method:s,body:a.body,query:a.query,scope:a.idempotencyScope,origin:a.origin},f;try{f=e.nextKey(d)}catch(e){throw n(e)}if(typeof f!=`string`||f.trim()===``)throw new t({kind:`serialize`,code:`IDEMPOTENCY_KEY_INVALID`,message:`Idempotency source returned an empty or non-string key`});let p=c(a.headers);u(p,i,f);let h={...a,headers:p,idempotency:{headerName:i,key:f}};try{let t=await r(h);return O(e,d,`success`),t}catch(t){let r=n(t);throw O(e,d,D(r)),r}}}}}}function D(e){return e.status>=400&&e.status<500&&e.status!==408&&e.status!==429?`definite-failure`:`indefinite-failure`}function O(e,t,n){if(e.resolve)try{e.resolve(t,n)}catch{}}function k(e={}){return _({...e,storage:f(M())})}function A(e={}){return _({...e,storage:f(N())})}function j(e={}){return _({...e,storage:d()})}function M(){if(typeof sessionStorage>`u`)throw Error(`sessionStorageSource is not available outside a browser. For SSR and tests use memoryStorageSource.`);return sessionStorage}function N(){if(typeof localStorage>`u`)throw Error(`localStorageSource is not available outside a browser. For SSR and tests use memoryStorageSource.`);return localStorage}export{A as localStorageSource,j as memoryStorageSource,k as sessionStorageSource,S as withAuth,E as withIdempotency,h as withRetry};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["DEFAULT_REFRESH_TIMEOUT_MS"],"sources":["../../src/layers/auth/circuit-breaker.ts","../../src/layers/auth/single-flight.ts","../../src/layers/auth/refresh-manager.ts","../../src/layers/auth/layer.ts","../../src/layers/idempotency/layer.ts","../../src/layers/idempotency/sources.ts"],"sourcesContent":["import { safeCall } from '../../shared/safe-call';\nimport { unrefTimer } from '../../shared/timers';\n\nexport interface CircuitBreakerCallbacks {\n onOpen?: () => void;\n onClose?: () => void;\n}\n\n/**\n * After a temporary failure blocks new refresh attempts for a given\n * time: without the breaker, every new 401 would start a new attempt\n * and the auth server would get a stream of requests.\n *\n * onOpen and onClose are called exactly once per state transition.\n */\nexport class CircuitBreaker {\n private openUntil = 0;\n private isOpen = false;\n private timer: ReturnType<typeof setTimeout> | null = null;\n private readonly callbacks: CircuitBreakerCallbacks;\n\n constructor(callbacks: CircuitBreakerCallbacks = {}) {\n this.callbacks = callbacks;\n }\n\n /**\n * true if the breaker blocks refresh. If the blocking time has\n * passed, closes and returns false.\n */\n isBlocking(): boolean {\n if (!this.isOpen) return false;\n\n if (Date.now() >= this.openUntil) {\n this.close();\n return false;\n }\n\n return true;\n }\n\n /**\n * Opens the breaker for durationMs. A repeated call extends the\n * blocking, onOpen is not called again.\n *\n * In Node the timer does not hold the event loop (unref), so the\n * process can exit.\n *\n * @throws Error if durationMs is not a positive number: a zero or\n * negative duration would open the breaker already in closed\n * state.\n */\n open(durationMs: number): void {\n if (!Number.isFinite(durationMs) || durationMs <= 0) {\n throw new Error(\n `CircuitBreaker.open: durationMs must be a positive number, got ${String(durationMs)}`,\n );\n }\n\n const wasOpen = this.isOpen && Date.now() < this.openUntil;\n\n this.openUntil = Date.now() + durationMs;\n this.isOpen = true;\n\n if (this.timer) {\n clearTimeout(this.timer);\n }\n this.timer = setTimeout(() => this.close(), durationMs);\n unrefTimer(this.timer);\n\n if (!wasOpen) {\n safeCall(() => this.callbacks.onOpen?.());\n }\n }\n\n /**\n * Closes the breaker and clears the timer. Idempotent: a repeated\n * call on a closed breaker does nothing and does not call onClose.\n */\n close(): void {\n if (!this.isOpen) return;\n\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n\n this.isOpen = false;\n this.openUntil = 0;\n\n safeCall(() => this.callbacks.onClose?.());\n }\n}\n","/**\n * When several run calls arrive before the first one finishes, they\n * all get the result of one promise. After it finishes, the next run\n * starts a new operation.\n *\n * Used by RefreshManager: concurrent 401s must not start several\n * refreshes.\n */\nexport class SingleFlight<T> {\n private inFlight: Promise<T> | null = null;\n\n /**\n * Starts an operation or joins the current one.\n *\n * @returns the same promise as the first call for concurrent callers.\n */\n run(fn: () => Promise<T>): Promise<T> {\n if (this.inFlight) {\n return this.inFlight;\n }\n\n const promise = fn().finally(() => {\n // The reference may have been nulled by forget and replaced by\n // a new promise from run. Then it must not be touched.\n if (this.inFlight === promise) {\n this.inFlight = null;\n }\n });\n\n this.inFlight = promise;\n return promise;\n }\n\n /**\n * Forgets the current promise. Callers waiting on it keep waiting:\n * a promise cannot be cancelled in JS. The next run starts a new\n * operation.\n */\n forget(): void {\n this.inFlight = null;\n }\n}\n","import { ApiError, classifyFetchError } from '../../core/errors';\nimport { unrefTimer } from '../../shared/timers';\n\nimport { CircuitBreaker } from './circuit-breaker';\nimport { SingleFlight } from './single-flight';\n\nimport type { RefreshResult, SessionProvider } from './types';\n\nconst DEFAULT_REFRESH_TIMEOUT_MS = 30_000;\n\n/**\n * Internal refresh result. Differs from public RefreshResult by\n * cooldown status: a successful refresh happened less than\n * circuitBreakerMs ago. Handled inside withAuth, never leaves the\n * library.\n */\nexport type RefreshManagerResult = RefreshResult | { status: 'cooldown' };\n\n/** Breaker state callbacks. Source is AuthOptions. */\nexport interface RefreshManagerCallbacks {\n onCircuitOpen?: () => void;\n onCircuitClose?: () => void;\n}\n\n/**\n * Shape check for provider.refresh. A missing return or a typo in\n * status must not be taken for success: the request would be retried\n * with the old token and the session would look alive.\n */\nfunction isRefreshResult(value: unknown): value is RefreshResult {\n if (!value || typeof value !== 'object') return false;\n\n const result = value as {\n status?: unknown;\n headers?: unknown;\n reason?: unknown;\n error?: unknown;\n };\n\n switch (result.status) {\n case 'success':\n return (\n result.headers === undefined ||\n (typeof result.headers === 'object' && result.headers !== null)\n );\n case 'definitely-failed':\n return (\n result.reason === 'refresh-rejected' ||\n result.reason === 'refresh-forbidden' ||\n result.reason === 'token-rejected'\n );\n case 'temporarily-failed':\n return 'error' in result;\n default:\n return false;\n }\n}\n\n/**\n * Token refresh manager. One per client.\n *\n * Three mechanisms: single-flight (one refresh for concurrent 401s),\n * breaker (blocking after a failure) and cooldown (no second refresh\n * right after a successful one).\n */\nexport class RefreshManager {\n private readonly circuit: CircuitBreaker;\n private readonly singleFlight = new SingleFlight<RefreshManagerResult>();\n private readonly refreshTimeoutMs: number;\n\n /** Last successful refresh time. Used for cooldown. */\n private lastSuccessfulRefreshAt = 0;\n\n /**\n * Grows on every reset(). doRefresh remembers the value before\n * await and compares after. If reset() ran during refresh, the\n * result is not written to lastSuccessfulRefreshAt.\n */\n private resetCount = 0;\n\n /**\n * Signals passed to provider.refresh. Needed to tell a 401 inside\n * refresh from a regular 401: such request must not start refresh\n * again.\n */\n private readonly refreshSignals = new WeakSet<AbortSignal>();\n\n constructor(\n callbacks: RefreshManagerCallbacks = {},\n refreshTimeoutMs = DEFAULT_REFRESH_TIMEOUT_MS,\n ) {\n this.circuit = new CircuitBreaker({\n onOpen: callbacks.onCircuitOpen,\n onClose: callbacks.onCircuitClose,\n });\n this.refreshTimeoutMs = refreshTimeoutMs;\n }\n\n /**\n * Resets the breaker, cooldown and forgets the current refresh.\n * Called via resetRefreshCircuit when the app knows the problem is\n * gone.\n *\n * Forgetting must happen before closing the breaker: otherwise the\n * next 401 joins the previous promise and reset has no effect.\n */\n reset(): void {\n this.resetCount++;\n this.lastSuccessfulRefreshAt = 0;\n this.singleFlight.forget();\n this.circuit.close();\n }\n\n /**\n * true if signal was created inside the current doRefresh: the\n * request was initiated by the provider, not by the app.\n */\n isRefreshSignal(signal: AbortSignal | undefined): boolean {\n return signal !== undefined && this.refreshSignals.has(signal);\n }\n\n /**\n * Refreshes the session or joins the current refresh.\n *\n * @param circuitBreakerMs - breaker duration and cooldown window.\n */\n refresh(provider: SessionProvider, circuitBreakerMs: number): Promise<RefreshManagerResult> {\n if (this.circuit.isBlocking()) {\n return Promise.resolve({\n status: 'temporarily-failed',\n error: new ApiError({\n kind: 'unknown',\n code: 'REFRESH_CIRCUIT_OPEN',\n message: 'Token refresh is temporarily unavailable',\n isUncertain: false,\n }),\n });\n }\n\n const now = Date.now();\n if (this.lastSuccessfulRefreshAt > 0 && now - this.lastSuccessfulRefreshAt < circuitBreakerMs) {\n return Promise.resolve({ status: 'cooldown' });\n }\n\n return this.singleFlight.run(() => this.doRefresh(provider, circuitBreakerMs));\n }\n\n /**\n * Opens the breaker unless reset() ran while the refresh was in\n * flight. The app already declared the problem gone; a failure of\n * the abandoned attempt must not block the next one. The result\n * itself is still returned to the callers waiting on that attempt:\n * a promise cannot be cancelled in JS.\n */\n private openCircuitUnlessReset(circuitBreakerMs: number, resetCountAtStart: number): void {\n if (this.resetCount === resetCountAtStart) {\n this.circuit.open(circuitBreakerMs);\n }\n }\n\n /**\n * Calls provider.refresh with a timeout and classifies the result.\n * TypeError around provider.refresh is a network error: the\n * implementation usually calls fetch inside.\n *\n * Returns a normalized error in temporarily-failed: withAuth must\n * not call toApiError again.\n */\n private async doRefresh(\n provider: SessionProvider,\n circuitBreakerMs: number,\n ): Promise<RefreshManagerResult> {\n const resetCountAtStart = this.resetCount;\n\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n // The timeout rejects the promise on its own, regardless of\n // whether the implementation listens to signal. controller.abort\n // is a hint to it.\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n const reason = new DOMException('Refresh timeout', 'TimeoutError');\n controller.abort(reason);\n reject(reason);\n }, this.refreshTimeoutMs);\n\n unrefTimer(timer);\n });\n\n timeoutPromise.catch(() => {});\n\n let result: RefreshResult;\n\n try {\n this.refreshSignals.add(controller.signal);\n const providerPromise = provider.refresh(controller.signal);\n\n // After the timeout the race is already settled, but the\n // provider may reject later. Without catch this is an\n // unhandledRejection.\n providerPromise.catch(() => {});\n\n const raw: unknown = await Promise.race([providerPromise, timeoutPromise]);\n\n if (!isRefreshResult(raw)) {\n // Caught below and returned as temporarily-failed: the session\n // may still be alive, so no logout and no breaker.\n throw new ApiError({\n kind: 'unknown',\n code: 'AUTH_PROVIDER_ERROR',\n message: 'provider.refresh returned an invalid result',\n cause: raw,\n });\n }\n\n result = raw;\n } catch (e) {\n const err = classifyFetchError(e);\n\n // Refresh timeout is a failure, open the breaker.\n if (err.kind === 'timeout') {\n this.openCircuitUnlessReset(circuitBreakerMs, resetCountAtStart);\n return {\n status: 'temporarily-failed',\n error: new ApiError({\n kind: 'timeout',\n code: 'REFRESH_TIMEOUT',\n message: 'Token refresh timed out',\n isUncertain: true,\n }),\n };\n }\n\n // Cancel is not a network failure, do not open the breaker.\n if (err.isCancelled) {\n return { status: 'temporarily-failed', error: err };\n }\n\n // 401 or 403 from refresh means the session is dead.\n if (err.status === 401 || err.status === 403) {\n return {\n status: 'definitely-failed',\n reason: err.status === 403 ? 'refresh-forbidden' : 'refresh-rejected',\n };\n }\n\n // Network or 5xx from the auth server - open the breaker.\n // unknown and parse are more likely a bug in refresh: a false\n // open would hide the cause under REFRESH_CIRCUIT_OPEN.\n if (err.kind === 'network' || err.isServerError) {\n this.openCircuitUnlessReset(circuitBreakerMs, resetCountAtStart);\n }\n\n return { status: 'temporarily-failed', error: err };\n } finally {\n clearTimeout(timer);\n }\n\n if (result.status === 'temporarily-failed') {\n const err = classifyFetchError(result.error);\n if (!err.isCancelled) {\n this.openCircuitUnlessReset(circuitBreakerMs, resetCountAtStart);\n }\n return { status: 'temporarily-failed', error: err };\n }\n\n if (result.status === 'success') {\n // reset() during refresh: do not write lastSuccessfulRefreshAt,\n // cooldown must not apply to the next 401.\n if (this.resetCount === resetCountAtStart) {\n this.lastSuccessfulRefreshAt = Date.now();\n }\n }\n\n return result;\n }\n}\n","import { ApiError, isNamedError, toApiError } from '../../core/errors';\nimport { isStreamingBody } from '../../shared/classify-body';\nimport { safeCall } from '../../shared/safe-call';\nimport { throwIfAborted } from '../../shared/signals';\nimport { assertPositiveNumber } from '../../shared/validators';\nimport { mergeHeaders } from '../../transport/headers';\n\nimport { RefreshManager } from './refresh-manager';\nimport { attachReset } from './reset-registry';\n\nimport type { SessionExpiredReason, SessionProvider } from './types';\nimport type { Layer, LayerContext, LayerWrapResult } from '../../core/layer';\nimport type { RequestFn, ResolvedRequestConfig } from '../../core/types';\n\nconst DEFAULT_CIRCUIT_BREAKER_MS = 5000;\nconst DEFAULT_REFRESH_TIMEOUT_MS = 30_000;\n\nexport interface AuthOptions {\n /** Required. */\n provider: SessionProvider;\n\n /**\n * Called on final session expiry. The app decides what to do:\n * show a modal, redirect, nothing. Exceptions are ignored: a\n * callback failure does not replace the original 401.\n */\n onSessionExpired?: (reason: SessionExpiredReason) => void;\n\n /**\n * Blocking duration after a temporary refresh failure, in\n * milliseconds. Defaults to 5000. Must be positive.\n *\n * Used by the breaker (blocks new refreshes after a failure) and\n * by cooldown (blocks a second refresh right after a successful\n * one).\n */\n circuitBreakerMs?: number;\n\n /**\n * Timeout of a single refresh attempt, in milliseconds. Defaults\n * to 30000.\n *\n * The provider gets an AbortSignal and may pass it to its fetch.\n * If the signal is ignored, the library-side timeout does not\n * fire: bound refresh in SessionProvider.refresh instead.\n */\n refreshTimeoutMs?: number;\n\n /**\n * Called when the token refresh breaker opens. The breaker opens\n * after a temporary refresh failure and blocks new attempts for\n * circuitBreakerMs.\n */\n onCircuitOpen?: () => void;\n\n /**\n * Called when the breaker closes. Closes either after\n * circuitBreakerMs or manually via resetRefreshCircuit(client).\n */\n onCircuitClose?: () => void;\n}\n\n/**\n * Auth layer.\n *\n * Adds headers from provider before each request. On 401 starts a\n * token refresh and retries the original request once. On a temporary\n * refresh failure rethrows the error without logging the user out. On\n * a final failure calls onSessionExpired.\n *\n * Refresh starts only on 401: 403 does not trigger it.\n *\n * If a successful refresh happened less than circuitBreakerMs ago and\n * the request got 401 again, the layer retries with the current\n * headers without a new refresh.\n *\n * Layer is a template: if the same object is passed to two\n * createClient calls, each gets its own RefreshManager.\n */\nexport function withAuth(options: AuthOptions): Layer {\n const {\n provider,\n onSessionExpired,\n circuitBreakerMs = DEFAULT_CIRCUIT_BREAKER_MS,\n refreshTimeoutMs = DEFAULT_REFRESH_TIMEOUT_MS,\n } = options;\n\n assertPositiveNumber(circuitBreakerMs, 'withAuth: circuitBreakerMs');\n assertPositiveNumber(refreshTimeoutMs, 'withAuth: refreshTimeoutMs');\n\n return {\n name: 'withAuth',\n stage: 1,\n\n wrap(next: RequestFn, context: LayerContext): LayerWrapResult {\n const manager = new RefreshManager(\n {\n onCircuitOpen: () => {\n safeCall(() => options.onCircuitOpen?.());\n },\n onCircuitClose: () => {\n safeCall(() => options.onCircuitClose?.());\n },\n },\n refreshTimeoutMs,\n );\n\n const fn: RequestFn = async function authRequest<T>(\n config: ResolvedRequestConfig,\n ): Promise<T> {\n if (config.skipAuth) {\n return next<T>(config);\n }\n\n throwIfAborted(config.signal);\n\n const authHeaders = await safeGetAuthHeaders(provider);\n const withAuthConfig: ResolvedRequestConfig = {\n ...config,\n headers: mergeHeaders(config.headers, authHeaders),\n };\n\n try {\n return await next<T>(withAuthConfig);\n } catch (e) {\n const err = toApiError(e);\n\n if (err.status !== 401) throw err;\n\n throwIfAborted(config.signal);\n\n // 401 inside provider.refresh: a second refresh through\n // SingleFlight would return the same promise and loop the\n // call. Rethrow 401 without onSessionExpired.\n if (manager.isRefreshSignal(config.signal)) {\n safeCall(() =>\n context.warn?.(\n '[fetch-layers] withAuth: 401 inside provider.refresh. ' +\n 'Use a separate client without withAuth for the refresh endpoint.',\n ),\n );\n throw err;\n }\n\n const outcome = await manager.refresh(provider, circuitBreakerMs);\n\n if (outcome.status === 'temporarily-failed') {\n throw toApiError(outcome.error);\n }\n\n if (outcome.status === 'definitely-failed') {\n safeClear(provider);\n safeCall(() => onSessionExpired?.(outcome.reason));\n throw err;\n }\n\n // A stream is consumed by the first send: a second one throws\n // TypeError, which transport reports as a network error. The\n // refreshed token is kept, the 401 goes out unchanged.\n if (isStreamingBody(config.body)) {\n safeCall(() =>\n context.warn?.(\n '[fetch-layers] withAuth: the request body is a stream and cannot be ' +\n 'replayed after token refresh. The token was refreshed; resend the ' +\n 'request with a new body or use skipAuth for this call.',\n ),\n );\n throw err;\n }\n\n // cooldown: retry with current headers, no refresh. A\n // second 401 means a dead session - same as success.\n if (outcome.status === 'cooldown') {\n throwIfAborted(config.signal);\n const currentHeaders = await safeGetAuthHeaders(provider);\n\n try {\n return await next<T>({\n ...config,\n headers: mergeHeaders(config.headers, currentHeaders),\n });\n } catch (retryError) {\n const retryErr = toApiError(retryError);\n\n if (retryErr.status === 401) {\n safeClear(provider);\n safeCall(() => onSessionExpired?.('token-rejected'));\n }\n\n throw retryErr;\n }\n }\n\n // success: retry with headers from refresh if present:\n // closes the race when state is not updated yet. An empty\n // object is not headers: fall back to the provider, otherwise\n // the retry would go out without Authorization.\n throwIfAborted(config.signal);\n\n const newHeaders = hasHeaders(outcome.headers)\n ? outcome.headers\n : await safeGetAuthHeaders(provider);\n\n try {\n return await next<T>({\n ...config,\n headers: mergeHeaders(config.headers, newHeaders),\n });\n } catch (retryError) {\n const retryErr = toApiError(retryError);\n\n if (retryErr.status === 401) {\n safeClear(provider);\n safeCall(() => onSessionExpired?.('token-rejected'));\n }\n\n throw retryErr;\n }\n }\n };\n\n return { fn, state: manager };\n },\n\n attach(client, state): void {\n if (!(state instanceof RefreshManager)) return;\n attachReset(client, () => state.reset());\n },\n };\n}\n\n/** Empty object means \"no headers\", not \"no auth\": ask the provider. */\nfunction hasHeaders(value: Record<string, string> | undefined): value is Record<string, string> {\n return value !== undefined && Object.keys(value).length > 0;\n}\n\n/**\n * A getAuthHeaders failure turns into ApiError with code\n * AUTH_PROVIDER_ERROR: the request is not sent. AbortError is\n * rethrown as abort.\n */\nasync function safeGetAuthHeaders(provider: SessionProvider): Promise<Record<string, string>> {\n try {\n const headers = await provider.getAuthHeaders();\n if (!headers || typeof headers !== 'object') return {};\n return headers;\n } catch (e) {\n if (isNamedError(e, 'AbortError')) {\n throw new ApiError({\n kind: 'abort',\n code: 'ABORTED',\n message: 'Request aborted',\n cause: e,\n });\n }\n throw new ApiError({\n kind: 'unknown',\n code: 'AUTH_PROVIDER_ERROR',\n message: 'Auth provider failed to return headers',\n cause: e,\n });\n }\n}\n\nfunction safeClear(provider: SessionProvider): void {\n try {\n provider.clear?.();\n } catch {\n // A clear failure does not replace the original error.\n }\n}\n","import { ApiError, toApiError } from '../../core/errors';\nimport { isMutatingMethod } from '../../shared/method';\nimport { getHeader, mergeHeaders, setHeader } from '../../transport/headers';\n\nimport type { IdempotencyContext, IdempotencyOutcome, IdempotencySource } from './types';\nimport type { Layer, LayerWrapResult } from '../../core/layer';\nimport type { RequestFn, ResolvedRequestConfig } from '../../core/types';\n\nexport interface IdempotencyOptions {\n /**\n * Header name. Defaults to Idempotency-Key. Some servers use\n * X-Idempotency-Key.\n */\n headerName?: string;\n}\n\n/**\n * For mutating methods adds the idempotency header with the value\n * from the source. If the app set the header itself, the layer does\n * not interfere. After completion reports the outcome to the source.\n *\n * Sits outside the retry layer: the key is generated once for the\n * whole operation, including retries, resolve is called once.\n *\n * Marks the config with an idempotency marker so withRetry does not\n * emit a false unsafe retry warning. The marker is set both for a\n * generated key and for a manual one.\n */\nexport function withIdempotency(\n source: IdempotencySource,\n options: IdempotencyOptions = {},\n): Layer {\n const { headerName = 'Idempotency-Key' } = options;\n\n return {\n name: 'withIdempotency',\n stage: 3,\n\n wrap(next: RequestFn): LayerWrapResult {\n const fn: RequestFn = async function idempotencyRequest<T>(\n config: ResolvedRequestConfig,\n ): Promise<T> {\n const method = config.method ?? 'GET';\n\n if (!isMutatingMethod(method) || config.skipIdempotency) {\n return next<T>(config);\n }\n\n // Empty string and whitespace-only count as \"not set\".\n const existingKey = getHeader(config.headers, headerName);\n if (existingKey !== undefined && existingKey.trim() !== '') {\n return next<T>({\n ...config,\n idempotency: { headerName, key: existingKey },\n });\n }\n\n const context: IdempotencyContext = {\n path: config.path,\n method,\n body: config.body,\n query: config.query,\n scope: config.idempotencyScope,\n origin: config.origin,\n };\n\n // Storage error: without a saved key the request must not be\n // sent, otherwise a retry creates a duplicate.\n let key: string;\n try {\n key = source.nextKey(context);\n } catch (e) {\n throw toApiError(e);\n }\n\n // A custom source is app code: an empty or non-string key\n // would go into the header as \"undefined\" or \"[object Object]\".\n if (typeof key !== 'string' || key.trim() === '') {\n throw new ApiError({\n kind: 'serialize',\n code: 'IDEMPOTENCY_KEY_INVALID',\n message: 'Idempotency source returned an empty or non-string key',\n });\n }\n\n // mergeHeaders normalizes Headers and array of pairs to an\n // object. Spread on Headers would give {}.\n const enrichedHeaders = mergeHeaders(config.headers);\n setHeader(enrichedHeaders, headerName, key);\n\n const enriched: ResolvedRequestConfig = {\n ...config,\n headers: enrichedHeaders,\n idempotency: { headerName, key },\n };\n\n try {\n const result = await next<T>(enriched);\n safeResolve(source, context, 'success');\n return result;\n } catch (e) {\n const err = toApiError(e);\n safeResolve(source, context, classifyOutcome(err));\n throw err;\n }\n };\n\n return { fn };\n },\n };\n}\n\n/**\n * 4xx except 408 and 429: the server explicitly rejected the\n * operation, a retry will not help. Anything else - operation state\n * is unknown.\n */\nfunction classifyOutcome(error: ApiError): IdempotencyOutcome {\n if (error.status >= 400 && error.status < 500 && error.status !== 408 && error.status !== 429) {\n return 'definite-failure';\n }\n return 'indefinite-failure';\n}\n\nfunction safeResolve(\n source: IdempotencySource,\n context: IdempotencyContext,\n outcome: IdempotencyOutcome,\n): void {\n if (!source.resolve) return;\n try {\n source.resolve(context, outcome);\n } catch {\n // A resolve failure does not replace the operation result.\n }\n}\n","import { createMemoryStorage, fromWebStorage } from '../../shared/storage';\n\nimport { createSessionSource, type StorageSourceOptions } from './session';\n\nimport type { IdempotencySource } from './types';\n\n/**\n * Key source on top of sessionStorage. Storage is isolated between\n * tabs: two orders from two tabs get different keys. The guarantee\n * holds within one tab, which is also true for localStorageSource:\n * nextKey is synchronous, so its read-modify-write is not atomic\n * across tabs.\n *\n * Records hold the serialized body, query and baseUrl as plain text\n * with no TTL, readable by any script on the origin. Do not use for\n * card data, credentials or personal data.\n *\n * Outside a browser use memoryStorageSource or your own source on\n * top of Redis, KV, IndexedDB.\n *\n * @param options - storageKey, maxEntries and generateKey. Pass a\n * distinct storageKey when one origin talks to several APIs:\n * by default all clients share the `idempotency:session` record.\n * @throws Error if sessionStorage is not available: SSR, Workers,\n * disabled cookies. The error is thrown when the factory is\n * called, not on the first request.\n */\nexport function sessionStorageSource(options: StorageSourceOptions = {}): IdempotencySource {\n return createSessionSource({\n ...options,\n storage: fromWebStorage(getSessionStorage()),\n });\n}\n\n/**\n * Key source on top of localStorage. Shared between tabs, but the\n * read-modify-write in nextKey is not atomic across them: two tabs\n * can generate two keys for one operation. The guarantee holds\n * within one tab. For cross-tab deduplication use a source on top of\n * a storage with atomic writes.\n *\n * Records hold the serialized body, query and baseUrl as plain text\n * with no TTL. Do not use for card data, credentials or personal\n * data: any script on the origin can read it.\n *\n * Outside a browser use memoryStorageSource or your own source on\n * top of Redis, KV, IndexedDB.\n *\n * @param options - storageKey, maxEntries and generateKey. Pass a\n * distinct storageKey when one origin talks to several APIs:\n * by default all clients share the `idempotency:session` record.\n * @throws Error if localStorage is not available: SSR, Workers,\n * disabled cookies. The error is thrown when the factory is\n * called, not on the first request.\n */\nexport function localStorageSource(options: StorageSourceOptions = {}): IdempotencySource {\n return createSessionSource({\n ...options,\n storage: fromWebStorage(getLocalStorage()),\n });\n}\n\n/**\n * In-memory key source. Lives as long as the process; data is lost\n * on page reload. Nothing leaves the process heap: the safe choice\n * for card data, credentials and personal data.\n *\n * With several SSR instances each process has its own store, so a\n * retry routed to another instance gets a new key. Use a shared\n * source for that case.\n */\nexport function memoryStorageSource(options: StorageSourceOptions = {}): IdempotencySource {\n return createSessionSource({\n ...options,\n storage: createMemoryStorage(),\n });\n}\n\nfunction getSessionStorage(): Storage {\n if (typeof sessionStorage === 'undefined') {\n throw new Error(\n 'sessionStorageSource is not available outside a browser. ' +\n 'For SSR and tests use memoryStorageSource.',\n );\n }\n return sessionStorage;\n}\n\nfunction getLocalStorage(): Storage {\n if (typeof localStorage === 'undefined') {\n throw new Error(\n 'localStorageSource is not available outside a browser. ' +\n 'For SSR and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BAEF,oBACT,CAEA,SAAS,EACP,EACA,EACA,EACM,CACD,KAAO,QACZ,GAAI,CACF,EAAO,QAAQ,EAAS,CAAO,CACjC,MAAQ,CAER,CACF,CC5GA,SAAgB,EAAqB,EAAgC,CAAC,EAAsB,CAC1F,OAAO,EAAoB,CACzB,GAAG,EACH,QAAS,EAAe,EAAkB,CAAC,CAC7C,CAAC,CACH,CAuBA,SAAgB,EAAmB,EAAgC,CAAC,EAAsB,CACxF,OAAO,EAAoB,CACzB,GAAG,EACH,QAAS,EAAe,EAAgB,CAAC,CAC3C,CAAC,CACH,CAWA,SAAgB,EAAoB,EAAgC,CAAC,EAAsB,CACzF,OAAO,EAAoB,CACzB,GAAG,EACH,QAAS,EAAoB,CAC/B,CAAC,CACH,CAEA,SAAS,GAA6B,CACpC,GAAI,OAAO,eAAmB,IAC5B,MAAU,MACR,qGAEF,EAEF,OAAO,cACT,CAEA,SAAS,GAA2B,CAClC,GAAI,OAAO,aAAiB,IAC1B,MAAU,MACR,mGAEF,EAEF,OAAO,YACT"}
@@ -1,2 +1,2 @@
1
- import { n as withRetry, t as RetryOptions } from "../../layer-DRRyGTne.mjs";
1
+ import { n as withRetry, t as RetryOptions } from "../../layer-BvZMV3L4.mjs";
2
2
  export { type RetryOptions, withRetry };
@@ -1 +1 @@
1
- import{t as e}from"../../layer-Dhb1y_u6.mjs";export{e as withRetry};
1
+ import{t as e}from"../../layer-DQ0xiRMN.mjs";export{e as withRetry};
@@ -1 +1,2 @@
1
- const e=new WeakMap;function t(t,n){e.set(t,n)}function n(t){let n=e.get(t);return n?(n(),!0):!1}export{n,t};
1
+ const e=new WeakMap;function t(t,n){e.set(t,n)}function n(t){let n=e.get(t);return n?(n(),!0):!1}export{n,t};
2
+ //# sourceMappingURL=reset-registry-CQPiZVBB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reset-registry-CQPiZVBB.mjs","names":[],"sources":["../src/layers/auth/reset-registry.ts"],"sourcesContent":["import type { Client } from '../../core/types';\n\n/**\n * Registry of reset functions keyed by client object. WeakMap, not a\n * property on the client: the registry does not overlap with public\n * API, binding is to the object itself, not to a copy. Two library\n * versions in one bundle get a registry each.\n */\nconst registry = new WeakMap<Client, () => void>();\n\n/**\n * Binds a reset function to the client object. Called from withAuth\n * via Layer.attach after client creation.\n *\n * @internal\n */\nexport function attachReset(client: Client, reset: () => void): void {\n registry.set(client, reset);\n}\n\n/**\n * Resets the token refresh breaker on the given client.\n *\n * @returns true if the reset ran. false if the client has no auth or\n * is not the object returned by createClient (e.g. a spread copy).\n */\nexport function resetRefreshCircuit(client: Client): boolean {\n const fn = registry.get(client);\n if (!fn) return false;\n fn();\n return true;\n}\n"],"mappings":"AAQA,MAAM,EAAW,IAAI,QAQrB,SAAgB,EAAY,EAAgB,EAAyB,CACnE,EAAS,IAAI,EAAQ,CAAK,CAC5B,CAQA,SAAgB,EAAoB,EAAyB,CAC3D,IAAM,EAAK,EAAS,IAAI,CAAM,EAG9B,OAFK,GACL,EAAG,EACI,IAFS,EAGlB"}
@@ -0,0 +1,2 @@
1
+ import{f as e,i as t,n,r,s as i,t as a}from"./classify-body-DOG6Vbf_.mjs";function o(t){try{return s(t,new WeakSet)??`null`}catch(t){throw t instanceof e?t:new e({kind:`serialize`,code:`BODY_SERIALIZATION_ERROR`,message:`Failed to serialize value`,cause:t})}}function s(e,r){let i=a(e);if(!t(i))throw TypeError(`Cannot serialize ${n(e)} to a stable JSON string`);if(e&&typeof e==`object`){let r=e.toJSON;if(typeof r==`function`){e=r.call(e);let i=a(e);if(!t(i))throw TypeError(`toJSON returned ${n(e)}: cannot serialize`)}}if(e===void 0||typeof e==`function`||typeof e==`symbol`)return;if(typeof e!=`object`||!e)return JSON.stringify(e);let o=e;if(r.has(o))throw TypeError(`Converting circular structure to JSON`);r.add(o);try{if(Array.isArray(o)){let e=Array(o.length);for(let t=0;t<o.length;t++){let n=o[t];e[t]=s(n,r)??`null`}return`[`+e.join(`,`)+`]`}let e=o,t=Object.keys(e).sort(),n=[];for(let i of t){let t=s(e[i],r);t!==void 0&&n.push(JSON.stringify(i)+`:`+t)}return`{`+n.join(`,`)+`}`}finally{r.delete(o)}}function c(t){let{storage:n,storageKey:a=`idempotency:session`,generateKey:s=f,maxEntries:c=100}=t;i(c,`createSessionSource: maxEntries`,1);let p=()=>{let e=n.getItem(a);if(!e)return{};let t;try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!=`object`||Array.isArray(t))return{};let r={};for(let[e,n]of Object.entries(t))u(n)&&(r[e]={key:n.key,lastUsedAt:n.lastUsedAt});return r},m=t=>{try{n.setItem(a,JSON.stringify(t))}catch(t){throw new e({kind:`storage`,code:`IDEMPOTENCY_STORAGE_ERROR`,message:`Failed to save idempotency key to storage`,cause:t})}},h=e=>{if(!r(e.body))return null;let t=e.scope??`${e.method} ${e.path}`,n=d(e.query),i=[];return e.origin&&i.push(e.origin),i.push(t),n!==``&&i.push(n),i.push(o(e.body)),JSON.stringify(i)},g=t=>{if(typeof t!=`string`||t.trim()===``)throw new e({kind:`serialize`,code:`IDEMPOTENCY_KEY_INVALID`,message:`Idempotency key generator returned an empty string`});return t},_=new WeakMap,v=new Map,y=0,b=e=>{if(!(v.size<=c))for(let t of v.keys())e[t]===void 0&&v.delete(t)},x=(e,t)=>{y+=1,v.set(e,{at:t,seq:y})};return{nextKey(e){let t=h(e);if(t===null)return g(s());let n=p();b(n);let r=n[t];if(r){let i=Date.now(),a=r.lastUsedAt;if(x(t,i),!Number.isFinite(a)||i-a>=1e3){n[t]={key:r.key,lastUsedAt:i};try{m(n)}catch{}}return _.set(e,{entryKey:t,key:r.key}),r.key}let i=Date.now(),a=g(s());n[t]={key:a,lastUsedAt:i},x(t,i);let o=Object.keys(n);if(o.length>c){o.sort((e,t)=>l(n,v,e,t));let e=o.slice(0,o.length-c);for(let t of e)delete n[t],v.delete(t)}return _.set(e,{entryKey:t,key:a}),m(n),a},resolve(e,t){if(t===`indefinite-failure`)return;let n=_.get(e);if(n===void 0)return;let r=p(),i=r[n.entryKey];i!==void 0&&i.key===n.key&&(delete r[n.entryKey],v.delete(n.entryKey),m(r))}}}function l(e,t,n,r){let i=t.get(n),a=t.get(r),o=Math.max(e[n]?.lastUsedAt??0,i?.at??0),s=Math.max(e[r]?.lastUsedAt??0,a?.at??0);return o===s?(i?.seq??0)-(a?.seq??0):o-s}function u(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.key==`string`&&t.key.trim()!==``&&typeof t.lastUsedAt==`number`}function d(e){if(!e)return``;let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?o(t):``}function f(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID();throw Error(`crypto.randomUUID is not available. fetch-layers requires Node >= 22.18 or a modern browser.`)}export{o as n,c as t};
2
+ //# sourceMappingURL=session-CcBNIxp4.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-CcBNIxp4.mjs","names":[],"sources":["../src/layers/idempotency/serialize.ts","../src/layers/idempotency/session.ts"],"sourcesContent":["import { ApiError } from '../../core/errors';\nimport { classifyBody, getTypeName, isSerializableKind } from '../../shared/classify-body';\n\n/**\n * Stable value serialization. Object keys are sorted alphabetically:\n * the result does not depend on insertion order. Otherwise behavior\n * matches JSON.stringify, including toJSON returning undefined.\n *\n * @throws ApiError with code BODY_SERIALIZATION_ERROR on circular\n * refs, BigInt and non-serializable types: FormData, Blob, File,\n * ArrayBuffer, TypedArray, ReadableStream, Node.js stream.Readable,\n * URLSearchParams, Map, Set, WeakMap, WeakSet, RegExp, Error.\n */\nexport function stableSerialize(value: unknown): string {\n try {\n return serialize(value, new WeakSet<object>()) ?? 'null';\n } catch (e) {\n if (e instanceof ApiError) throw e;\n throw new ApiError({\n kind: 'serialize',\n code: 'BODY_SERIALIZATION_ERROR',\n message: 'Failed to serialize value',\n cause: e,\n });\n }\n}\n\n/**\n * Returns undefined for values JSON.stringify skips: undefined,\n * functions, Symbol. seen is the recursion stack: it tells a shared\n * reference (allowed) from a cycle (forbidden).\n */\nfunction serialize(value: unknown, seen: WeakSet<object>): string | undefined {\n // Check before toJSON: the \"non-serializable types are rejected\"\n // contract must not be bypassed via a custom toJSON.\n const kind = classifyBody(value);\n if (!isSerializableKind(kind)) {\n throw new TypeError(`Cannot serialize ${getTypeName(value)} to a stable JSON string`);\n }\n\n // Same as JSON.stringify: works with Date, URL and other types\n // that have toJSON.\n if (value && typeof value === 'object') {\n const toJSON = (value as { toJSON?: () => unknown }).toJSON;\n if (typeof toJSON === 'function') {\n value = toJSON.call(value);\n\n // toJSON may return Map, Set, Blob or another non-serializable\n // type. Without the check the value would go through recursion\n // and turn into {}, giving different bodies the same fingerprint.\n const afterKind = classifyBody(value);\n if (!isSerializableKind(afterKind)) {\n throw new TypeError(`toJSON returned ${getTypeName(value)}: cannot serialize`);\n }\n }\n }\n\n if (value === undefined) return undefined;\n if (typeof value === 'function' || typeof value === 'symbol') return undefined;\n\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n\n const obj = value as object;\n if (seen.has(obj)) {\n throw new TypeError('Converting circular structure to JSON');\n }\n seen.add(obj);\n\n try {\n if (Array.isArray(obj)) {\n const parts: string[] = new Array(obj.length);\n for (let i = 0; i < obj.length; i++) {\n const item = obj[i];\n parts[i] = serialize(item, seen) ?? 'null';\n }\n return '[' + parts.join(',') + ']';\n }\n\n const record = obj as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n const parts: string[] = [];\n for (const key of keys) {\n const serialized = serialize(record[key], seen);\n if (serialized === undefined) continue;\n parts.push(JSON.stringify(key) + ':' + serialized);\n }\n return '{' + parts.join(',') + '}';\n } finally {\n // Remove from the stack: this allows shared references and\n // forbids real cycles.\n seen.delete(obj);\n }\n}\n","import { ApiError } from '../../core/errors';\nimport { isSerializableBody } from '../../shared/classify-body';\nimport { assertInteger } from '../../shared/validators';\n\nimport { stableSerialize } from './serialize';\n\nimport type { IdempotencyContext, IdempotencyOutcome, IdempotencySource } from './types';\nimport type { QueryParams } from '../../core/types';\nimport type { StorageLike } from '../../shared/storage';\n\nexport interface SessionSourceOptions {\n /**\n * Storage. Wrap localStorage and sessionStorage in fromWebStorage,\n * use createMemoryStorage for Node.\n */\n storage: StorageLike;\n\n /** Key of the record object. Defaults to idempotency:session. */\n storageKey?: string;\n\n /**\n * Key generator. Defaults to crypto.randomUUID. Can be replaced\n * for tests or non-standard schemes.\n */\n generateKey?: () => string;\n\n /**\n * Max entries, defaults to 100. When exceeded, the least recently\n * used record is dropped.\n *\n * A record is a triple (scope, query, fingerprint): one scope with\n * different bodies takes several.\n */\n maxEntries?: number;\n}\n\n/** createSessionSource options without storage. */\nexport type StorageSourceOptions = Omit<SessionSourceOptions, 'storage'>;\n\ninterface StoredEntry {\n key: string;\n lastUsedAt: number;\n}\n\n/**\n * What a single request actually sent: the fingerprint it was stored\n * under and the key it got. Needed by resolve: the fingerprint must\n * not be recomputed, and only the key that was sent may be released.\n */\ninterface IssuedKey {\n entryKey: string;\n key: string;\n}\n\n/**\n * Storage format: JSON.stringify([origin, scope, query, body]) ->\n * record. The tuple is JSON-escaped, so field boundaries are\n * unambiguous and separators inside values cannot collide.\n *\n * The fingerprint is stored as is, not hashed: the record contains\n * the serialized body, query and baseUrl in plain text, with no TTL.\n */\ntype Store = Record<string, StoredEntry>;\n\n/**\n * lastUsedAt is written at most once per second per key.\n * localStorage writes are synchronous and fire a storage event in\n * every tab, so touching the record on every request is wasteful.\n */\nconst TOUCH_INTERVAL_MS = 1000;\n\n/**\n * Key source on top of a synchronous StorageLike.\n *\n * If a key exists for the tuple (origin, scope, query, body), it is\n * returned and its last-used time is updated. If the body or query\n * changed, or the tuple is new, a new key is generated. On success\n * and definite-failure the record is deleted, on indefinite-failure\n * it is kept for the retry.\n *\n * Ready factories for sessionStorage, localStorage and memory live\n * in fetch-layers/layers.\n *\n * @throws Error if maxEntries is below 1.\n */\nexport function createSessionSource(options: SessionSourceOptions): IdempotencySource {\n const {\n storage,\n storageKey = 'idempotency:session',\n generateKey = defaultGenerateKey,\n maxEntries = 100,\n } = options;\n\n assertInteger(maxEntries, 'createSessionSource: maxEntries', 1);\n\n /**\n * On corrupt data starts from an empty object: the key will be\n * generated anew. Records with the wrong shape are dropped: another\n * version or another library could write under the same key, and a\n * missing key field would go into the header as \"undefined\".\n */\n const read = (): Store => {\n const raw = storage.getItem(storageKey);\n if (!raw) return {};\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return {};\n }\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};\n\n const store: Store = {};\n for (const [fingerprint, value] of Object.entries(parsed)) {\n if (isStoredEntry(value)) {\n store[fingerprint] = { key: value.key, lastUsedAt: value.lastUsedAt };\n }\n }\n return store;\n };\n\n /**\n * On write error throws ApiError with kind storage: the client\n * must not send a request without a way to retry correctly.\n */\n const write = (store: Store): void => {\n try {\n storage.setItem(storageKey, JSON.stringify(store));\n } catch (e) {\n throw new ApiError({\n kind: 'storage',\n code: 'IDEMPOTENCY_STORAGE_ERROR',\n message: 'Failed to save idempotency key to storage',\n cause: e,\n });\n }\n };\n\n /**\n * null for a non-serializable body: a stable fingerprint is\n * impossible, the source generates a new key without saving it.\n */\n const entryKey = (context: IdempotencyContext): string | null => {\n if (!isSerializableBody(context.body)) return null;\n\n const scope = context.scope ?? `${context.method} ${context.path}`;\n const queryPart = serializeQueryForFingerprint(context.query);\n\n const parts: string[] = [];\n if (context.origin) parts.push(context.origin);\n parts.push(scope);\n if (queryPart !== '') parts.push(queryPart);\n parts.push(stableSerialize(context.body));\n\n return JSON.stringify(parts);\n };\n\n const validateKey = (key: unknown): string => {\n if (typeof key !== 'string' || key.trim() === '') {\n throw new ApiError({\n kind: 'serialize',\n code: 'IDEMPOTENCY_KEY_INVALID',\n message: 'Idempotency key generator returned an empty string',\n });\n }\n return key;\n };\n\n /**\n * context is created per request in withIdempotency, so a WeakMap\n * ties the issued key to the exact operation without extending the\n * public IdempotencySource contract.\n */\n const issued = new WeakMap<IdempotencyContext, IssuedKey>();\n\n /**\n * Last use per fingerprint, fresher than the stored one: touching\n * the record is throttled, so storage may lag behind by up to\n * TOUCH_INTERVAL_MS. Eviction must order by the real last use,\n * otherwise a key used a moment ago looks older than one that was\n * never touched since and gets dropped.\n *\n * seq breaks ties inside one millisecond: without it the order\n * falls back to key order and the oldest inserted key, possibly\n * the active one, is evicted first.\n */\n const recentUse = new Map<string, { at: number; seq: number }>();\n let useSeq = 0;\n\n const pruneRecentUse = (store: Store): void => {\n if (recentUse.size <= maxEntries) return;\n for (const fingerprint of recentUse.keys()) {\n if (store[fingerprint] === undefined) recentUse.delete(fingerprint);\n }\n };\n\n const touch = (fingerprint: string, now: number): void => {\n useSeq += 1;\n recentUse.set(fingerprint, { at: now, seq: useSeq });\n };\n\n return {\n nextKey(context) {\n const key = entryKey(context);\n\n // For a non-serializable body a new key on every call, not\n // stored: otherwise a retry with a different body of the same\n // type could reuse the key.\n if (key === null) {\n return validateKey(generateKey());\n }\n\n const store = read();\n pruneRecentUse(store);\n const existing = store[key];\n\n if (existing) {\n const now = Date.now();\n const lastUsedAt = existing.lastUsedAt;\n\n touch(key, now);\n\n if (!Number.isFinite(lastUsedAt) || now - lastUsedAt >= TOUCH_INTERVAL_MS) {\n store[key] = { key: existing.key, lastUsedAt: now };\n try {\n write(store);\n } catch {\n // Touch failure is non-fatal: recentUse keeps the\n // correct order for the current session.\n }\n }\n\n issued.set(context, { entryKey: key, key: existing.key });\n return existing.key;\n }\n\n const now = Date.now();\n const newKey = validateKey(generateKey());\n store[key] = { key: newKey, lastUsedAt: now };\n touch(key, now);\n\n const keys = Object.keys(store);\n if (keys.length > maxEntries) {\n keys.sort((a, b) => compareLastUse(store, recentUse, a, b));\n const toRemove = keys.slice(0, keys.length - maxEntries);\n for (const k of toRemove) {\n delete store[k];\n recentUse.delete(k);\n }\n }\n\n issued.set(context, { entryKey: key, key: newKey });\n write(store);\n return newKey;\n },\n\n resolve(context, outcome: IdempotencyOutcome) {\n if (outcome === 'indefinite-failure') return;\n\n // A non-serializable body was not stored, nothing to release.\n // The fingerprint is taken from what the request sent, not\n // recomputed: a body mutated after nextKey would give a\n // different key.\n const record = issued.get(context);\n if (record === undefined) return;\n\n const store = read();\n const current = store[record.entryKey];\n\n // A late response from an older operation must not delete the\n // record of a newer operation with the same fingerprint.\n if (current === undefined || current.key !== record.key) return;\n\n delete store[record.entryKey];\n recentUse.delete(record.entryKey);\n write(store);\n },\n };\n}\n\n/**\n * Eviction order: the stored time may be stale because touching is\n * throttled, so the freshest known time wins. Equal times are\n * ordered by the in-memory sequence, which keeps \"used a moment\n * ago\" ahead of \"inserted earlier in the same millisecond\".\n */\nfunction compareLastUse(\n store: Store,\n recentUse: ReadonlyMap<string, { at: number; seq: number }>,\n a: string,\n b: string,\n): number {\n const aMemory = recentUse.get(a);\n const bMemory = recentUse.get(b);\n\n const aAt = Math.max(store[a]?.lastUsedAt ?? 0, aMemory?.at ?? 0);\n const bAt = Math.max(store[b]?.lastUsedAt ?? 0, bMemory?.at ?? 0);\n\n if (aAt !== bAt) return aAt - bAt;\n return (aMemory?.seq ?? 0) - (bMemory?.seq ?? 0);\n}\n\nfunction isStoredEntry(value: unknown): value is StoredEntry {\n if (!value || typeof value !== 'object') return false;\n\n const entry = value as { key?: unknown; lastUsedAt?: unknown };\n return (\n typeof entry.key === 'string' && entry.key.trim() !== '' && typeof entry.lastUsedAt === 'number'\n );\n}\n\n/**\n * Query params fingerprint. undefined and null are skipped: they do\n * not go into the URL and so do not affect the fingerprint. An empty\n * result means query is not part of the fingerprint.\n */\nfunction serializeQueryForFingerprint(query: QueryParams | undefined): string {\n if (!query) return '';\n\n const filtered: Record<string, unknown> = {};\n let hasAny = false;\n\n for (const key of Object.keys(query)) {\n const value = query[key];\n if (value !== undefined && value !== null) {\n filtered[key] = value;\n hasAny = true;\n }\n }\n\n return hasAny ? stableSerialize(filtered) : '';\n}\n\n/** @throws Error if crypto.randomUUID is not available. */\nfunction defaultGenerateKey(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n throw new Error(\n 'crypto.randomUUID is not available. fetch-layers requires Node >= 22.18 or a modern browser.',\n );\n}\n"],"mappings":"0EAaA,SAAgB,EAAgB,EAAwB,CACtD,GAAI,CACF,OAAO,EAAU,EAAO,IAAI,OAAiB,GAAK,MACpD,OAAS,EAAG,CAEV,MADI,aAAa,EAAgB,EAC3B,IAAI,EAAS,CACjB,KAAM,YACN,KAAM,2BACN,QAAS,4BACT,MAAO,CACT,CAAC,CACH,CACF,CAOA,SAAS,EAAU,EAAgB,EAA2C,CAG5E,IAAM,EAAO,EAAa,CAAK,EAC/B,GAAI,CAAC,EAAmB,CAAI,EAC1B,MAAU,UAAU,oBAAoB,EAAY,CAAK,EAAE,yBAAyB,EAKtF,GAAI,GAAS,OAAO,GAAU,SAAU,CACtC,IAAM,EAAU,EAAqC,OACrD,GAAI,OAAO,GAAW,WAAY,CAChC,EAAQ,EAAO,KAAK,CAAK,EAKzB,IAAM,EAAY,EAAa,CAAK,EACpC,GAAI,CAAC,EAAmB,CAAS,EAC/B,MAAU,UAAU,mBAAmB,EAAY,CAAK,EAAE,mBAAmB,CAEjF,CACF,CAGA,GADI,IAAU,IAAA,IACV,OAAO,GAAU,YAAc,OAAO,GAAU,SAAU,OAE9D,GAAsB,OAAO,GAAU,WAAnC,EACF,OAAO,KAAK,UAAU,CAAK,EAG7B,IAAM,EAAM,EACZ,GAAI,EAAK,IAAI,CAAG,EACd,MAAU,UAAU,uCAAuC,EAE7D,EAAK,IAAI,CAAG,EAEZ,GAAI,CACF,GAAI,MAAM,QAAQ,CAAG,EAAG,CACtB,IAAM,EAAsB,MAAM,EAAI,MAAM,EAC5C,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,IAAK,CACnC,IAAM,EAAO,EAAI,GACjB,EAAM,GAAK,EAAU,EAAM,CAAI,GAAK,MACtC,CACA,MAAO,IA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AAY,EAAM,IAAI,KAAK,IAAM,IAAM,OAAO,EAAM,YAAe,QAE5F,CAOA,SAAS,EAA6B,EAAwC,CAC5E,GAAI,CAAC,EAAO,MAAO,GAEnB,IAAM,EAAoC,CAAC,EACvC,EAAS,GAEb,IAAK,IAAM,KAAO,OAAO,KAAK,CAAK,EAAG,CACpC,IAAM,EAAQ,EAAM,GAChB,GAAiC,OACnC,EAAS,GAAO,EAChB,EAAS,GAEb,CAEA,OAAO,EAAS,EAAgB,CAAQ,EAAI,EAC9C,CAGA,SAAS,GAA6B,CACpC,GAAI,OAAO,OAAW,KAAe,OAAO,OAAO,YAAe,WAChE,OAAO,OAAO,WAAW,EAE3B,MAAU,MACR,8FACF,CACF"}
@@ -1 +1,2 @@
1
- function e(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}}function t(e){return{getItem:t=>{try{return e.getItem(t)}catch{return null}},setItem:(t,n)=>{e.setItem(t,n)},removeItem:t=>{try{e.removeItem(t)}catch{}}}}export{e as createMemoryStorage,t as fromWebStorage};
1
+ function e(){let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>{e.set(t,n)},removeItem:t=>{e.delete(t)}}}function t(e){return{getItem:t=>{try{return e.getItem(t)}catch{return null}},setItem:(t,n)=>{e.setItem(t,n)},removeItem:t=>{try{e.removeItem(t)}catch{}}}}export{e as createMemoryStorage,t as fromWebStorage};
2
+ //# sourceMappingURL=storage.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.mjs","names":[],"sources":["../../src/shared/storage.ts"],"sourcesContent":["/**\n * Synchronous key-value storage. Compatible with localStorage and\n * sessionStorage. Async storages (IndexedDB, AsyncStorage) need an\n * adapter with a synchronous API.\n *\n * setItem must throw on write failure: without a saved key, a retry\n * after a lost response creates a duplicate. Reads and deletes are\n * not critical: getItem returns null, removeItem ignores errors.\n */\nexport interface StorageLike {\n /**\n * Value by key or null. Also null on read error: missing key and\n * read error cannot be told apart.\n */\n getItem(key: string): string | null;\n\n /**\n * Saves a value.\n *\n * @throws When the write is impossible (QuotaExceededError,\n * read-only mode). The caller must abort the operation.\n */\n setItem(key: string, value: string): void;\n\n /** Removes a value. Missing key and delete errors are ignored. */\n removeItem(key: string): void;\n}\n\n/**\n * In-memory storage. Lives as long as the process; data is lost\n * after page reload.\n */\nexport function createMemoryStorage(): StorageLike {\n const map = new Map<string, string>();\n\n return {\n getItem: (key) => map.get(key) ?? null,\n setItem: (key, value) => {\n map.set(key, value);\n },\n removeItem: (key) => {\n map.delete(key);\n },\n };\n}\n\n/**\n * Adapter over localStorage or sessionStorage.\n *\n * Browser storages may be unavailable or misbehave: Safari private\n * mode, quota overflow, disabled cookies.\n *\n * - getItem: null on error, the old record is not reused;\n * - removeItem: errors are ignored, cleanup is not critical;\n * - setItem: throws, the operation must be aborted.\n */\nexport function fromWebStorage(webStorage: Storage): StorageLike {\n return {\n getItem: (key) => {\n try {\n return webStorage.getItem(key);\n } catch {\n return null;\n }\n },\n\n setItem: (key, value) => {\n webStorage.setItem(key, value);\n },\n\n removeItem: (key) => {\n try {\n webStorage.removeItem(key);\n } catch {\n // Ignored: cleanup is not critical.\n }\n },\n };\n}\n"],"mappings":"AAgCA,SAAgB,GAAmC,CACjD,IAAM,EAAM,IAAI,IAEhB,MAAO,CACL,QAAU,GAAQ,EAAI,IAAI,CAAG,GAAK,KAClC,SAAU,EAAK,IAAU,CACvB,EAAI,IAAI,EAAK,CAAK,CACpB,EACA,WAAa,GAAQ,CACnB,EAAI,OAAO,CAAG,CAChB,CACF,CACF,CAYA,SAAgB,EAAe,EAAkC,CAC/D,MAAO,CACL,QAAU,GAAQ,CAChB,GAAI,CACF,OAAO,EAAW,QAAQ,CAAG,CAC/B,MAAQ,CACN,OAAO,IACT,CACF,EAEA,SAAU,EAAK,IAAU,CACvB,EAAW,QAAQ,EAAK,CAAK,CAC/B,EAEA,WAAa,GAAQ,CACnB,GAAI,CACF,EAAW,WAAW,CAAG,CAC3B,MAAQ,CAER,CACF,CACF,CACF"}
@@ -1 +1,2 @@
1
- function e(e){return typeof Headers<`u`&&Object.prototype.toString.call(e)===`[object Headers]`}function t(e){return Array.isArray(e)}function n(n){if(e(n)){let e={};return n.forEach((t,n)=>{e[n]=t}),e}if(t(n)){let e={};for(let t of n)Array.isArray(t)&&t.length>=2&&(e[t[0]]=t[1]);return e}return n??{}}function r(e,t){if(!e)return;let r=n(e),i=t.toLowerCase();for(let e of Object.keys(r))if(e.toLowerCase()===i)return r[e]}function i(e,t,n){let r=t.toLowerCase();for(let n of Object.keys(e))n.toLowerCase()===r&&n!==t&&delete e[n];e[t]=n}function a(...r){let i={},a=new Map;for(let s of r)if(s){if(e(s)||t(s)){let e=n(s);for(let t of Object.keys(e))o(i,a,t,e[t]);continue}if(typeof s==`object`)for(let e of Object.keys(s)){let t=s[e];o(i,a,e,t)}}return i}function o(e,t,n,r){if(r===void 0)return;let i=n.toLowerCase(),a=t.get(i);a!==void 0&&a!==n&&delete e[a],t.set(i,n),e[n]=r}function s(e){typeof e==`object`&&e&&typeof e.unref==`function`&&e.unref()}function c(e){if(e?.aborted)throw new DOMException(`Request aborted`,`AbortError`)}function l(e,t){let n=e.reason;return n instanceof Error?n:new DOMException(t,`AbortError`)}function u(e,t){return t?.aborted?Promise.reject(l(t,`Sleep aborted`)):t?new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(l(t,`Sleep aborted`))};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>{setTimeout(t,e)})}function d(e){let t=new AbortController,n=setTimeout(()=>t.abort(new DOMException(`Timeout`,`TimeoutError`)),e);return s(n),{signal:t.signal,clear:()=>clearTimeout(n)}}export{r as a,s as i,u as n,a as o,c as r,i as s,d as t};
1
+ function e(e){return typeof Headers<`u`&&Object.prototype.toString.call(e)===`[object Headers]`}function t(e){return Array.isArray(e)}function n(n){if(e(n)){let e={};return n.forEach((t,n)=>{e[n]=t}),e}if(t(n)){let e={};for(let t of n)Array.isArray(t)&&t.length>=2&&(e[t[0]]=t[1]);return e}return n??{}}function r(e,t){if(!e)return;let r=n(e),i=t.toLowerCase();for(let e of Object.keys(r))if(e.toLowerCase()===i)return r[e]}function i(e,t,n){let r=t.toLowerCase();for(let n of Object.keys(e))n.toLowerCase()===r&&n!==t&&delete e[n];e[t]=n}function a(...r){let i={},a=new Map;for(let s of r)if(s){if(e(s)||t(s)){let e=n(s);for(let t of Object.keys(e))o(i,a,t,e[t]);continue}if(typeof s==`object`)for(let e of Object.keys(s)){let t=s[e];o(i,a,e,t)}}return i}function o(e,t,n,r){if(r===void 0)return;let i=n.toLowerCase(),a=t.get(i);a!==void 0&&a!==n&&delete e[a],t.set(i,n),e[n]=r}function s(e){typeof e==`object`&&e&&typeof e.unref==`function`&&e.unref()}function c(e){if(e?.aborted)throw new DOMException(`Request aborted`,`AbortError`)}function l(e,t){let n=e.reason;return n instanceof Error?n:new DOMException(t,`AbortError`)}function u(e,t){return t?.aborted?Promise.reject(l(t,`Sleep aborted`)):t?new Promise((n,r)=>{let i=setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(l(t,`Sleep aborted`))};t.addEventListener(`abort`,a,{once:!0})}):new Promise(t=>{setTimeout(t,e)})}function d(e){let t=new AbortController,n=setTimeout(()=>t.abort(new DOMException(`Timeout`,`TimeoutError`)),e);return s(n),{signal:t.signal,clear:()=>clearTimeout(n)}}export{r as a,s as i,u as n,a as o,c as r,i as s,d as t};
2
+ //# sourceMappingURL=signals-DQjF6ojU.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"signals-DQjF6ojU.mjs","names":[],"sources":["../src/transport/headers.ts","../src/shared/timers.ts","../src/shared/signals.ts"],"sourcesContent":["/**\n * Header name case does not matter per spec: the module normalizes\n * it when reading and merging, keeping the original name in the\n * result.\n */\n\nfunction isHeaders(value: unknown): value is Headers {\n return (\n typeof Headers !== 'undefined' && Object.prototype.toString.call(value) === '[object Headers]'\n );\n}\n\nfunction isPairArray(value: unknown): value is ReadonlyArray<readonly [string, string]> {\n return Array.isArray(value);\n}\n\n/**\n * Converts Headers or an array of pairs to Record<string, string>.\n * Record is returned as is, no copy: callers that mutate the result\n * must copy it first (setHeader mutates in place).\n */\nfunction normalizeHeaders(input: unknown): Record<string, string> {\n if (isHeaders(input)) {\n const result: Record<string, string> = {};\n input.forEach((value, key) => {\n result[key] = value;\n });\n return result;\n }\n\n if (isPairArray(input)) {\n const result: Record<string, string> = {};\n for (const pair of input) {\n if (Array.isArray(pair) && pair.length >= 2) {\n result[pair[0]] = pair[1];\n }\n }\n return result;\n }\n\n return (input ?? {}) as Record<string, string>;\n}\n\n/**\n * Header value. Inherited properties are not read.\n */\nexport function getHeader(headers: unknown, name: string): string | undefined {\n if (!headers) return undefined;\n\n const record = normalizeHeaders(headers);\n const lower = name.toLowerCase();\n for (const key of Object.keys(record)) {\n if (key.toLowerCase() === lower) return record[key];\n }\n return undefined;\n}\n\n/**\n * Sets a header, removing variants with a different case. Two headers\n * with the same meaning must not exist.\n */\nexport function setHeader(headers: Record<string, string>, name: string, value: string): void {\n const lower = name.toLowerCase();\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === lower && key !== name) {\n delete headers[key];\n }\n }\n headers[name] = value;\n}\n\n/**\n * Merges header sets. Later sources override earlier ones, case is\n * normalized. If the first had content-type and the second\n * Content-Type, only one remains - from the second source.\n */\nexport function mergeHeaders(...sources: unknown[]): Record<string, string> {\n const result: Record<string, string> = {};\n const seen = new Map<string, string>();\n\n for (const source of sources) {\n if (!source) continue;\n\n if (isHeaders(source) || isPairArray(source)) {\n const record = normalizeHeaders(source);\n for (const key of Object.keys(record)) {\n mergeEntry(result, seen, key, record[key]);\n }\n continue;\n }\n\n if (typeof source !== 'object') continue;\n for (const key of Object.keys(source as Record<string, string>)) {\n const value = (source as Record<string, string>)[key];\n mergeEntry(result, seen, key, value);\n }\n }\n\n return result;\n}\n\nfunction mergeEntry(\n result: Record<string, string>,\n seen: Map<string, string>,\n key: string,\n value: string | undefined,\n): void {\n if (value === undefined) return;\n\n const lower = key.toLowerCase();\n const previousKey = seen.get(lower);\n\n if (previousKey !== undefined && previousKey !== key) {\n delete result[previousKey];\n }\n\n seen.set(lower, key);\n result[key] = value;\n}\n","/**\n * Calls unref on the timer if present. In Node this lets the process\n * exit without waiting for the timer. In the browser setTimeout\n * returns a number with no unref.\n */\nexport function unrefTimer(timer: ReturnType<typeof setTimeout>): void {\n if (\n typeof timer === 'object' &&\n timer !== null &&\n typeof (timer as { unref?: unknown }).unref === 'function'\n ) {\n (timer as { unref: () => void }).unref();\n }\n}\n","import { unrefTimer } from './timers';\n\nexport function throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) {\n throw new DOMException('Request aborted', 'AbortError');\n }\n}\n\n/**\n * Abort reason. AbortController.abort accepts any value, so reason\n * can be a string or a number. Such values get AbortError instead:\n * the error classifier detects abort by name, otherwise it would\n * become kind unknown.\n */\nfunction abortReason(signal: AbortSignal, fallback: string): unknown {\n const reason = signal.reason;\n if (reason instanceof Error) return reason;\n return new DOMException(fallback, 'AbortError');\n}\n\n/**\n * Cancellable pause. Preserves signal reason: timeout stays kind\n * timeout, not kind abort.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(abortReason(signal, 'Sleep aborted'));\n }\n\n if (!signal) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n const onAbort = () => {\n clearTimeout(timer);\n reject(abortReason(signal, 'Sleep aborted'));\n };\n\n signal.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * AbortSignal with timeout. In Node the timer does not hold the\n * event loop (unref), so the process does not wait for full\n * timeoutMs after the request completes. Abort reason: TimeoutError.\n */\nexport function setAbortTimeout(ms: number): { signal: AbortSignal; clear: () => void } {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(new DOMException('Timeout', 'TimeoutError')), ms);\n\n unrefTimer(timer);\n\n return {\n signal: controller.signal,\n clear: () => clearTimeout(timer),\n };\n}\n"],"mappings":"AAMA,SAAS,EAAU,EAAkC,CACnD,OACE,OAAO,QAAY,KAAe,OAAO,UAAU,SAAS,KAAK,CAAK,IAAM,kBAEhF,CAEA,SAAS,EAAY,EAAmE,CACtF,OAAO,MAAM,QAAQ,CAAK,CAC5B,CAOA,SAAS,EAAiB,EAAwC,CAChE,GAAI,EAAU,CAAK,EAAG,CACpB,IAAM,EAAiC,CAAC,EAIxC,OAHA,EAAM,SAAS,EAAO,IAAQ,CAC5B,EAAO,GAAO,CAChB,CAAC,EACM,CACT,CAEA,GAAI,EAAY,CAAK,EAAG,CACtB,IAAM,EAAiC,CAAC,EACxC,IAAK,IAAM,KAAQ,EACb,MAAM,QAAQ,CAAI,GAAK,EAAK,QAAU,IACxC,EAAO,EAAK,IAAM,EAAK,IAG3B,OAAO,CACT,CAEA,OAAQ,GAAS,CAAC,CACpB,CAKA,SAAgB,EAAU,EAAkB,EAAkC,CAC5E,GAAI,CAAC,EAAS,OAEd,IAAM,EAAS,EAAiB,CAAO,EACjC,EAAQ,EAAK,YAAY,EAC/B,IAAK,IAAM,KAAO,OAAO,KAAK,CAAM,EAClC,GAAI,EAAI,YAAY,IAAM,EAAO,OAAO,EAAO,EAGnD,CAMA,SAAgB,EAAU,EAAiC,EAAc,EAAqB,CAC5F,IAAM,EAAQ,EAAK,YAAY,EAC/B,IAAK,IAAM,KAAO,OAAO,KAAK,CAAO,EAC/B,EAAI,YAAY,IAAM,GAAS,IAAQ,GACzC,OAAO,EAAQ,GAGnB,EAAQ,GAAQ,CAClB,CAOA,SAAgB,EAAa,GAAG,EAA4C,CAC1E,IAAM,EAAiC,CAAC,EAClC,EAAO,IAAI,IAEjB,IAAK,IAAM,KAAU,EACd,K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AK,CAAC,CAC1D,CAAC,EAjBQ,IAAI,QAAS,GAAY,CAC9B,WAAW,EAAS,CAAE,CACxB,CAAC,CAgBL,CAOA,SAAgB,EAAgB,EAAwD,CACtF,IAAM,EAAa,IAAI,gBACjB,EAAQ,eAAiB,EAAW,MAAM,IAAI,aAAa,UAAW,cAAc,CAAC,EAAG,CAAE,EAIhG,OAFA,EAAW,CAAK,EAET,CACL,OAAQ,EAAW,OACnB,UAAa,aAAa,CAAK,CACjC,CACF"}
@@ -41,4 +41,5 @@ declare function createMemoryStorage(): StorageLike;
41
41
  */
42
42
  declare function fromWebStorage(webStorage: Storage): StorageLike;
43
43
  //#endregion
44
- export { createMemoryStorage as n, fromWebStorage as r, StorageLike as t };
44
+ export { createMemoryStorage as n, fromWebStorage as r, StorageLike as t };
45
+ //# sourceMappingURL=storage-C0XsVkz-.d.mts.map