fetch-layers 0.0.0-stage → 1.0.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.
@@ -0,0 +1,132 @@
1
+ import { t as Layer } from "./layer-D1S2Wlu1.mjs";
2
+ //#region src/layers/auth/types.d.ts
3
+ /**
4
+ * Session expiry reason. Passed to onSessionExpired.
5
+ *
6
+ * - refresh-rejected: server rejected token refresh (401);
7
+ * - refresh-forbidden: server forbade refresh (403);
8
+ * - token-rejected: after a successful refresh the new token was
9
+ * rejected too.
10
+ */
11
+ type SessionExpiredReason = 'refresh-rejected' | 'refresh-forbidden' | 'token-rejected';
12
+ /**
13
+ * Session refresh result.
14
+ *
15
+ * success. Token refreshed. If headers is set, the client uses it for
16
+ * the retry, otherwise calls getAuthHeaders. Prefer returning
17
+ * headers: this closes the race when the state is not updated yet
18
+ * but the request is already retrying.
19
+ *
20
+ * definitely-failed. Session is dead. The client calls
21
+ * onSessionExpired and rethrows the original 401.
22
+ *
23
+ * temporarily-failed. Session may still be alive. The client
24
+ * rethrows the error but does not call onSessionExpired or clear.
25
+ *
26
+ * error is any value. The client normalizes it: TypeError becomes
27
+ * network, AbortError and TimeoutError - the matching kind,
28
+ * everything else - unknown.
29
+ */
30
+ type RefreshResult = {
31
+ status: 'success';
32
+ headers?: Record<string, string>;
33
+ } | {
34
+ status: 'definitely-failed';
35
+ reason: SessionExpiredReason;
36
+ } | {
37
+ status: 'temporarily-failed';
38
+ error: unknown;
39
+ };
40
+ /**
41
+ * Auth provider. Implemented by the app: the library does not store
42
+ * tokens, it only asks for ready headers.
43
+ *
44
+ * refresh must not use the client with withAuth: a 401 from the
45
+ * refresh endpoint would go back into withAuth. A separate client
46
+ * without layers is described in RECIPES.
47
+ */
48
+ interface SessionProvider {
49
+ /**
50
+ * Auth headers: one or several (Authorization, X-CSRF-Token,
51
+ * X-API-Key). May be async.
52
+ *
53
+ * @throws On error the client wraps the exception in ApiError with
54
+ * code AUTH_PROVIDER_ERROR and does not send the request.
55
+ */
56
+ getAuthHeaders(): Record<string, string> | Promise<Record<string, string>>;
57
+ /**
58
+ * Refreshes the session. Called on 401. Concurrent 401s produce one
59
+ * refresh call, the rest wait for its result.
60
+ *
61
+ * @param signal - abort on refreshTimeoutMs. Pass it to your fetch:
62
+ * fetch(url, { signal }). Optional: a provider without it still
63
+ * matches the interface, but will not be aborted on timeout.
64
+ */
65
+ refresh(signal?: AbortSignal): Promise<RefreshResult>;
66
+ /**
67
+ * Resets session state. Called on definitely-failed. Exceptions
68
+ * are ignored. Must be idempotent.
69
+ */
70
+ clear?(): void;
71
+ }
72
+ //#endregion
73
+ //#region src/layers/auth/layer.d.ts
74
+ interface AuthOptions {
75
+ /** Required. */
76
+ provider: SessionProvider;
77
+ /**
78
+ * Called on final session expiry. The app decides what to do:
79
+ * show a modal, redirect, nothing. Exceptions are ignored: a
80
+ * callback failure does not replace the original 401.
81
+ */
82
+ onSessionExpired?: (reason: SessionExpiredReason) => void;
83
+ /**
84
+ * Blocking duration after a temporary refresh failure, in
85
+ * milliseconds. Defaults to 5000. Must be positive.
86
+ *
87
+ * Used by the breaker (blocks new refreshes after a failure) and
88
+ * by cooldown (blocks a second refresh right after a successful
89
+ * one).
90
+ */
91
+ circuitBreakerMs?: number;
92
+ /**
93
+ * Timeout of a single refresh attempt, in milliseconds. Defaults
94
+ * to 30000.
95
+ *
96
+ * The provider gets an AbortSignal and may pass it to its fetch.
97
+ * If the signal is ignored, the library-side timeout does not
98
+ * fire: bound refresh in SessionProvider.refresh instead.
99
+ */
100
+ refreshTimeoutMs?: number;
101
+ /**
102
+ * Called when the token refresh breaker opens. The breaker opens
103
+ * after a temporary refresh failure and blocks new attempts for
104
+ * circuitBreakerMs.
105
+ */
106
+ onCircuitOpen?: () => void;
107
+ /**
108
+ * Called when the breaker closes. Closes either after
109
+ * circuitBreakerMs or manually via resetRefreshCircuit(client).
110
+ */
111
+ onCircuitClose?: () => void;
112
+ }
113
+ /**
114
+ * Auth layer.
115
+ *
116
+ * Adds headers from provider before each request. On 401 starts a
117
+ * token refresh and retries the original request once. On a temporary
118
+ * refresh failure rethrows the error without logging the user out. On
119
+ * a final failure calls onSessionExpired.
120
+ *
121
+ * Refresh starts only on 401: 403 does not trigger it.
122
+ *
123
+ * If a successful refresh happened less than circuitBreakerMs ago and
124
+ * the request got 401 again, the layer retries with the current
125
+ * headers without a new refresh.
126
+ *
127
+ * Layer is a template: if the same object is passed to two
128
+ * createClient calls, each gets its own RefreshManager.
129
+ */
130
+ declare function withAuth(options: AuthOptions): Layer;
131
+ //#endregion
132
+ export { SessionProvider as a, SessionExpiredReason as i, withAuth as n, RefreshResult as r, AuthOptions as t };
@@ -0,0 +1 @@
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};
@@ -0,0 +1,12 @@
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";
3
+ //#region src/layers/auth/reset-registry.d.ts
4
+ /**
5
+ * Resets the token refresh breaker on the given client.
6
+ *
7
+ * @returns true if the reset ran. false if the client has no auth or
8
+ * is not the object returned by createClient (e.g. a spread copy).
9
+ */
10
+ declare function resetRefreshCircuit(client: Client): boolean;
11
+ //#endregion
12
+ export { type AuthOptions, type RefreshResult, type SessionExpiredReason, type SessionProvider, resetRefreshCircuit };
@@ -0,0 +1 @@
1
+ import{n as e}from"../../reset-registry-CQPiZVBB.mjs";export{e as resetRefreshCircuit};
@@ -0,0 +1,55 @@
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
42
+ //#region src/layers/idempotency/serialize.d.ts
43
+ /**
44
+ * Stable value serialization. Object keys are sorted alphabetically:
45
+ * the result does not depend on insertion order. Otherwise behavior
46
+ * matches JSON.stringify, including toJSON returning undefined.
47
+ *
48
+ * @throws ApiError with code BODY_SERIALIZATION_ERROR on circular
49
+ * refs, BigInt and non-serializable types: FormData, Blob, File,
50
+ * ArrayBuffer, TypedArray, ReadableStream, Node.js stream.Readable,
51
+ * URLSearchParams, Map, Set, WeakMap, WeakSet, RegExp, Error.
52
+ */
53
+ declare function stableSerialize(value: unknown): string;
54
+ //#endregion
55
+ export { type IdempotencyContext, type IdempotencyOptions, type IdempotencyOutcome, type IdempotencySource, type SessionSourceOptions, createSessionSource, stableSerialize };
@@ -0,0 +1 @@
1
+ import{n as e,t}from"../../session-Dm-H-5hJ.mjs";export{t as createSessionSource,e as stableSerialize};
@@ -0,0 +1,38 @@
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";
5
+ //#region src/layers/idempotency/sources.d.ts
6
+ /**
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.
10
+ *
11
+ * Outside a browser use memoryStorageSource or your own source on
12
+ * top of Redis, KV, IndexedDB.
13
+ *
14
+ * @throws Error if sessionStorage is not available: SSR, Workers,
15
+ * disabled cookies. The error is thrown when the factory is
16
+ * called, not on the first request.
17
+ */
18
+ declare function sessionStorageSource(): IdempotencySource;
19
+ /**
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.
23
+ *
24
+ * Outside a browser use memoryStorageSource or your own source on
25
+ * top of Redis, KV, IndexedDB.
26
+ *
27
+ * @throws Error if localStorage is not available: SSR, Workers,
28
+ * disabled cookies. The error is thrown when the factory is
29
+ * called, not on the first request.
30
+ */
31
+ declare function localStorageSource(): IdempotencySource;
32
+ /**
33
+ * 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.
35
+ */
36
+ declare function memoryStorageSource(): IdempotencySource;
37
+ //#endregion
38
+ export { type AuthOptions, type IdempotencyOptions, type Layer, type LayerContext, type RetryOptions, localStorageSource, memoryStorageSource, sessionStorageSource, withAuth, withIdempotency, withRetry };
@@ -0,0 +1 @@
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};
@@ -0,0 +1,2 @@
1
+ import { n as withRetry, t as RetryOptions } from "../../layer-DRRyGTne.mjs";
2
+ export { type RetryOptions, withRetry };
@@ -0,0 +1 @@
1
+ import{t as e}from"../../layer-Dhb1y_u6.mjs";export{e as withRetry};
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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=u,maxEntries:c=100}=t;i(c,`createSessionSource: maxEntries`,1);let d=()=>{let e=n.getItem(a);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}},f=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})}},p=e=>{if(!r(e.body))return null;let t=e.scope??`${e.method} ${e.path}`,n=l(e.query),i=[JSON.stringify(t)];return n!==``&&i.push(n),i.push(o(e.body)),i.join(`|`)},m=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};return{nextKey(e){let t=p(e);if(t===null)return m(s());let n=d(),r=n[t];if(r)return n[t]={key:r.key,lastUsedAt:Date.now()},f(n),r.key;let i=m(s());n[t]={key:i,lastUsedAt:Date.now()};let a=Object.keys(n);if(a.length>c){a.sort((e,t)=>(n[e]?.lastUsedAt??0)-(n[t]?.lastUsedAt??0));let e=a.slice(0,a.length-c);for(let t of e)delete n[t]}return f(n),i},resolve(e,t){if(t===`indefinite-failure`)return;let n=p(e);if(n===null)return;let r=d();r[n]&&(delete r[n],f(r))}}}function l(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 u(){if(typeof crypto<`u`&&typeof crypto.randomUUID==`function`)return crypto.randomUUID();throw Error(`crypto.randomUUID is not available. fetch-layers requires Node >= 20 or a modern browser.`)}export{o as n,c as t};
@@ -0,0 +1,2 @@
1
+ import { n as createMemoryStorage, r as fromWebStorage, t as StorageLike } from "../storage-C0XsVkz-.mjs";
2
+ export { StorageLike, createMemoryStorage, fromWebStorage };
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,44 @@
1
+ //#region src/shared/storage.d.ts
2
+ /**
3
+ * Synchronous key-value storage. Compatible with localStorage and
4
+ * sessionStorage. Async storages (IndexedDB, AsyncStorage) need an
5
+ * adapter with a synchronous API.
6
+ *
7
+ * setItem must throw on write failure: without a saved key, a retry
8
+ * after a lost response creates a duplicate. Reads and deletes are
9
+ * not critical: getItem returns null, removeItem ignores errors.
10
+ */
11
+ interface StorageLike {
12
+ /**
13
+ * Value by key or null. Also null on read error: missing key and
14
+ * read error cannot be told apart.
15
+ */
16
+ getItem(key: string): string | null;
17
+ /**
18
+ * Saves a value.
19
+ *
20
+ * @throws When the write is impossible (QuotaExceededError,
21
+ * read-only mode). The caller must abort the operation.
22
+ */
23
+ setItem(key: string, value: string): void;
24
+ /** Removes a value. Missing key and delete errors are ignored. */
25
+ removeItem(key: string): void;
26
+ }
27
+ /**
28
+ * In-memory storage. Lives as long as the process; data is lost
29
+ * after page reload.
30
+ */
31
+ declare function createMemoryStorage(): StorageLike;
32
+ /**
33
+ * Adapter over localStorage or sessionStorage.
34
+ *
35
+ * Browser storages may be unavailable or misbehave: Safari private
36
+ * mode, quota overflow, disabled cookies.
37
+ *
38
+ * - getItem: null on error, the old record is not reused;
39
+ * - removeItem: errors are ignored, cleanup is not critical;
40
+ * - setItem: throws, the operation must be aborted.
41
+ */
42
+ declare function fromWebStorage(webStorage: Storage): StorageLike;
43
+ //#endregion
44
+ export { createMemoryStorage as n, fromWebStorage as r, StorageLike as t };
package/package.json CHANGED
@@ -1,6 +1,102 @@
1
1
  {
2
2
  "name": "fetch-layers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Thin typed HTTP client for browser and Node with composable layers: auth, idempotency, retry. Zero dependencies, ESM only.",
5
+ "keywords": [
6
+ "fetch",
7
+ "http",
8
+ "api",
9
+ "client",
10
+ "typescript",
11
+ "esm",
12
+ "auth",
13
+ "refresh-token",
14
+ "idempotency",
15
+ "retry",
16
+ "layers"
17
+ ],
18
+ "license": "MIT",
19
+ "author": {
20
+ "name": "smlnkv",
21
+ "email": "smlnkv79@gmail.com",
22
+ "url": "https://github.com/smlnkv"
23
+ },
24
+ "homepage": "https://github.com/smlnkv/fetch-layers#readme",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/smlnkv/fetch-layers.git"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/smlnkv/fetch-layers/issues"
31
+ },
32
+ "type": "module",
33
+ "sideEffects": false,
34
+ "engines": {
35
+ "node": ">=20.6"
36
+ },
37
+ "main": "./dist/index.mjs",
38
+ "types": "./dist/index.d.mts",
39
+ "exports": {
40
+ ".": {
41
+ "types": "./dist/index.d.mts",
42
+ "import": "./dist/index.mjs"
43
+ },
44
+ "./layers": {
45
+ "types": "./dist/layers/index.d.mts",
46
+ "import": "./dist/layers/index.mjs"
47
+ },
48
+ "./auth": {
49
+ "types": "./dist/layers/auth/index.d.mts",
50
+ "import": "./dist/layers/auth/index.mjs"
51
+ },
52
+ "./idempotency": {
53
+ "types": "./dist/layers/idempotency/index.d.mts",
54
+ "import": "./dist/layers/idempotency/index.mjs"
55
+ },
56
+ "./retry": {
57
+ "types": "./dist/layers/retry/index.d.mts",
58
+ "import": "./dist/layers/retry/index.mjs"
59
+ },
60
+ "./storage": {
61
+ "types": "./dist/shared/storage.d.mts",
62
+ "import": "./dist/shared/storage.mjs"
63
+ },
64
+ "./package.json": "./package.json"
65
+ },
66
+ "files": [
67
+ "dist",
68
+ "README.md",
69
+ "README.ru.md",
70
+ "LICENSE",
71
+ "CHANGELOG.md"
72
+ ],
73
+ "scripts": {
74
+ "build": "tsdown",
75
+ "dev": "tsdown --watch",
76
+ "typecheck": "tsc --noEmit",
77
+ "lint": "eslint src tests",
78
+ "lint:fix": "eslint src tests --fix",
79
+ "format": "prettier --write .",
80
+ "format:check": "prettier --check .",
81
+ "test": "vitest run",
82
+ "test:watch": "vitest",
83
+ "test:coverage": "vitest run --coverage",
84
+ "prepublishOnly": "npm run typecheck && npm run lint && npm run test && npm run build"
85
+ },
86
+ "devDependencies": {
87
+ "@eslint/js": "^10.0.1",
88
+ "@types/node": "^22.10.0",
89
+ "@typescript-eslint/eslint-plugin": "^8.69.0",
90
+ "@typescript-eslint/parser": "^8.69.0",
91
+ "@vitest/coverage-v8": "^5.0.0",
92
+ "eslint": "^10.9.0",
93
+ "eslint-config-prettier": "^10.1.8",
94
+ "eslint-plugin-import-x": "^4.17.1",
95
+ "globals": "^17.12.0",
96
+ "msw": "^2.15.0",
97
+ "prettier": "^3.9.6",
98
+ "tsdown": "^0.22.3",
99
+ "typescript": "^6.0.0",
100
+ "vitest": "^5.0.0"
101
+ }
102
+ }