@blaze-cache/ky 0.0.0-stage → 0.3.0-beta.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Blaze Cache
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,219 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/blaze-cache/blaze-cache/main/docs/blaze-cache-logo.png" alt="Blaze Cache logo" width="150">
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <h1 align="center">@blaze-cache/ky</h1>
6
+
7
+ ky hooks that cache HTTP responses through a WebAssembly cache — TTLs, tags,
8
+ `Cache-Control` and an `x-blaze-cache: HIT | MISS` marker.
9
+
10
+ Works on **ky v1 and v2**, whose hook signatures differ: the hooks recognise whichever
11
+ shape they are called with, from one implementation.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install @blaze-cache/ky@beta @blaze-cache/core@beta
17
+ ```
18
+
19
+ `@beta` is npm's dist-tag for the prerelease; drop it to install the last stable
20
+ release. `ky` ≥ 1.14 is a peer dependency — v1 and v2 both work.
21
+
22
+ ## Quick start
23
+
24
+ ky is designed around hooks, so caching is two of them: one that answers a request from
25
+ the cache by returning a `Response` — ky skips the network entirely — and one that stores
26
+ the response worth keeping.
27
+
28
+ ```ts
29
+ import ky from 'ky';
30
+ import { blazeKyHook } from '@blaze-cache/ky';
31
+ import { createCache } from '@blaze-cache/core';
32
+
33
+ const cache = await createCache({ capacity: 1000 });
34
+
35
+ const api = ky.extend({
36
+ hooks: {
37
+ ...blazeKyHook(cache, {
38
+ ttlMs: 30_000,
39
+ methods: ['GET'],
40
+ tags: (response, request) => ['api'],
41
+ }),
42
+ },
43
+ });
44
+
45
+ const response = await api.get('https://api.example.com/users');
46
+ response.headers.get('x-blaze-cache'); // 'MISS' …
47
+ ```
48
+
49
+ ```ts
50
+ const again = await api.get('https://api.example.com/users');
51
+ again.headers.get('x-blaze-cache'); // … then 'HIT'
52
+ await again.json(); // the body replayed from the cache
53
+ ```
54
+
55
+ The helper form wraps the same hooks around a pre-configured instance — every ky option
56
+ passes through:
57
+
58
+ ```ts
59
+ import { createBlazeKy } from '@blaze-cache/ky';
60
+
61
+ const api = createBlazeKy(cache, {
62
+ prefixUrl: 'https://api.example.com', // ky v1; ky v2 spells this `baseUrl`
63
+ ttlMs: 30_000,
64
+ });
65
+
66
+ const users = await api.get('users').json();
67
+ ```
68
+
69
+ ## Behaviour
70
+
71
+ * **Only `GET` is cached** — pass `methods: ['GET', 'HEAD']` to include `HEAD`. Everything
72
+ else always goes to the network and is never stored.
73
+ * **Only successful responses are stored** — the default `shouldCache` keeps `2xx`;
74
+ replace it to widen or narrow that. A cached non-`2xx` (reachable with a custom
75
+ `shouldCache`) still throws ky's `HTTPError` on replay exactly like the network one.
76
+ * **`Cache-Control` is honoured on both sides** when `cacheControl` is on (the default):
77
+ on the request, `no-store`/`no-cache` and `max-age=0` skip the read, and `no-store`
78
+ also skips the write; on the response, `max-age` overrides `ttlMs`, `Age` is deducted,
79
+ and `no-store`/`no-cache` — the per-field `no-cache="set-cookie"` form included — stop
80
+ it being stored. The parser is the same one `@blaze-cache/fetch` uses: malformed
81
+ directives (`max-age=` with no value) are ignored rather than read as zero, and a
82
+ duplicated directive keeps its first value (RFC 9111 §5.2.3).
83
+ * **`Authorization` participates in the default key** (hashed, never stored verbatim), so
84
+ a personalized response is never replayed to a different user. Tune with `varyHeaders`.
85
+ * **The response's own `Vary` is honoured** — `Vary: *` is never stored (RFC 9111 §3), and
86
+ a response varying on a header you have not put in `varyHeaders` is left uncached rather
87
+ than replay a variant to the wrong caller. Server headers missing from `varyHeaders`?
88
+ That is the safe default working as intended — list them to opt in. The check runs
89
+ before *every* store, `cacheControl: false` included: variant correctness is not a
90
+ freshness preference.
91
+ * **Your hooks keep working** — `ky.extend` appends hooks, so your `beforeRequest` hooks
92
+ run **before** the cache (any header they set is folded into the key), and your
93
+ `afterResponse` hooks run before the response is stored. With `createBlazeKy`, pass
94
+ them in `options.hooks` and they are merged for you.
95
+ * **A hit is a real `Response`** — status, status text, headers, body, `url` after a
96
+ redirect and `redirected` are replayed exactly, so your code cannot tell the difference
97
+ apart from the marker header. Body shortcuts (`.json()`, `.blob()`, `.text()`) work on
98
+ hits as on any response.
99
+ * **A hit never re-stores itself** — ky runs `afterResponse` on a `beforeRequest`-returned
100
+ response too; the adapter tracks its own replays by request identity, so every read
101
+ leaves the entry's TTL exactly where it was.
102
+ * **Buffering never delays a response** — the body is stored on a teed clone in the
103
+ background, and the record is complete before it is written, so a hit can never
104
+ half-load. Transport headers are corrected to the stored bytes (`content-encoding` and
105
+ `transfer-encoding` dropped, `content-length` rewritten), exactly as
106
+ `@blaze-cache/fetch` does.
107
+ * **Failures behave like plain ky** — a rejected network call still rejects; a cache that
108
+ cannot read or store a response never breaks the request that produced it. Reads,
109
+ writes, `shouldCache`, `key` and the clone step are all guarded: the first cache-layer
110
+ failure is announced once on the console, then the adapter keeps working *without* the
111
+ cache rather than warning on every call.
112
+ * **Cache activity is observable** — the adapter reads with `cache.get` and writes with
113
+ `cache.set`, so the shared cache's typed event system sees every request it serves:
114
+
115
+ ```ts
116
+ cache.on('hit', ({ key }) => console.log('replayed', key));
117
+ cache.on('miss', ({ key }) => console.log('fetched', key));
118
+ cache.on('evict', ({ key }) => console.log('dropped', key));
119
+ ```
120
+
121
+ `on` returns its own unsubscribe function; the full event table is in the
122
+ [repository README](https://github.com/blaze-cache/blaze-cache#events).
123
+
124
+ ## Options
125
+
126
+ ```ts
127
+ const hooks = blazeKyHook(cache, {
128
+ ttlMs: 30_000, // number | (response, request) => number
129
+ methods: ['GET'], // which methods are cacheable
130
+ cacheControl: true, // honour Cache-Control on request + response
131
+ key: (request) => request.url, // custom cache key
132
+ shouldCache: (response) => response.ok, // which responses are stored
133
+ tags: (response, request) => ['api'], // tags on stored entries
134
+ varyHeaders: ['authorization'], // headers folded into the default key
135
+ markerHeader: 'x-blaze-cache', // or false to disable the marker
136
+ });
137
+ ```
138
+
139
+ `createBlazeKy(cache, options)` accepts these **plus** every ky option.
140
+
141
+ | Option | Default | What it does |
142
+ | --- | --- | --- |
143
+ | `ttlMs` | `60_000` | Freshness window. Overridden by a response `max-age`. |
144
+ | `methods` | `['GET']` | Methods eligible for caching. |
145
+ | `cacheControl` | `true` | Honour `Cache-Control`/`Age` on both sides. |
146
+ | `key` | method + URL + vary hash | Custom cache key. |
147
+ | `shouldCache` | `2xx` | Which responses are stored. |
148
+ | `tags` | `['ky', '<method> <url>']` | Tags for `cache.invalidateTags(...)`. |
149
+ | `varyHeaders` | `['authorization']` | Request headers folded into the default key. |
150
+ | `markerHeader` | `'x-blaze-cache'` | Header carrying `HIT`/`MISS`; `false` disables it. |
151
+
152
+ Requests can force the behaviour per call:
153
+
154
+ ```ts
155
+ await api.get(url, { cache: 'no-cache' }); // skip the read, still store the response
156
+ await api.get(url, { cache: 'no-store' }); // neither read nor write
157
+ ```
158
+
159
+ ## Invalidating
160
+
161
+ Stored responses carry two tags, so they plug straight into the cache's tag API:
162
+
163
+ ```ts
164
+ cache.invalidateTags('ky'); // everything this adapter stored
165
+ cache.invalidateTags('get https://api.example.com/users'); // one resource
166
+ ```
167
+
168
+ The per-resource tag is `'<method> <url>'` — the same spelling `@blaze-cache/fetch` and
169
+ `@blaze-cache/axios` use, so integrations sharing one cache invalidate together.
170
+
171
+ ## Custom keys
172
+
173
+ ```ts
174
+ import { blazeKyHook, defaultCacheKey } from '@blaze-cache/ky';
175
+
176
+ const api = ky.extend({
177
+ hooks: {
178
+ ...blazeKyHook(cache, {
179
+ // Keep the default (method + URL + vary hash) and add a version prefix:
180
+ key: (request) => `v2:${defaultCacheKey(request, ['authorization'])}`,
181
+ }),
182
+ },
183
+ });
184
+ ```
185
+
186
+ ## ky v1 and ky v2
187
+
188
+ ky 2 changed every hook from positional arguments (`(request, options, response, state)`)
189
+ to a single state object (`({request, options, response, retryCount})`). `blazeKyHook`
190
+ detects which shape it is called with, so the same code runs on either major — use the
191
+ spelling your installed ky expects (`prefixUrl` in v1, `baseUrl`/`prefix` in v2) and
192
+ ignore the rest. Both are covered by the test suite.
193
+
194
+ ## Testing
195
+
196
+ ```sh
197
+ pnpm --filter @blaze-cache/ky test
198
+ ```
199
+
200
+ The suite runs against the built package with a stubbed network — deterministic, offline
201
+ — and executes **every test twice**, once on ky v1 and once on ky v2 (installed under an
202
+ npm alias), because the two majors take their hooks in completely different shapes.
203
+
204
+ ## Documentation
205
+
206
+ Setup, core concepts and the complete API reference live in the
207
+ [repository README](https://github.com/blaze-cache/blaze-cache#readme).
208
+
209
+ ## Part of Blaze Cache
210
+
211
+ * [`@blaze-cache/core`](https://www.npmjs.com/package/@blaze-cache/core) — the cache itself
212
+ * [`@blaze-cache/fetch`](https://www.npmjs.com/package/@blaze-cache/fetch) — the drop-in `fetch()` replacement (stale-while-revalidate included)
213
+ * [`@blaze-cache/axios`](https://www.npmjs.com/package/@blaze-cache/axios) — the axios adapter
214
+ * [`@blaze-cache/react-query`](https://www.npmjs.com/package/@blaze-cache/react-query) — TanStack Query v5 mirror
215
+ * [`@blaze-cache/swr`](https://www.npmjs.com/package/@blaze-cache/swr) — SWR middleware + hook
216
+
217
+ ## License
218
+
219
+ [MIT](https://github.com/blaze-cache/blaze-cache/blob/main/LICENSE) © Blaze Cache
@@ -0,0 +1,53 @@
1
+ /**
2
+ * What `Cache-Control` (and the related `Age`) say about a request or a response — plus the
3
+ * one `Vary` question a keying client must answer before storing anything.
4
+ *
5
+ * Package-local on purpose: this adapter deliberately reads only the directives it acts
6
+ * on. `stale-while-revalidate` and `must-revalidate` are *not* parsed here — they shape
7
+ * the stale window of `@blaze-cache/fetch`, which has one; this adapter never serves a
8
+ * stale entry at all, so for it they are equivalent to plain expiry. Each package is free
9
+ * to grow its own directives without dragging the others along.
10
+ */
11
+ export interface CacheControl {
12
+ /** `no-store` — neither read nor write the cache. */
13
+ noStore: boolean;
14
+ /** `no-cache` — must not be served without revalidating, per-field spellings (`no-cache="…"`) included. */
15
+ noCache: boolean;
16
+ /** `max-age=<seconds>`, converted to milliseconds. */
17
+ maxAgeMs: number | undefined;
18
+ }
19
+ /** The value used when parsing is switched off (`cacheControl: false`) or a header is absent. */
20
+ export declare const NO_DIRECTIVES: CacheControl;
21
+ /**
22
+ * Minimal `Cache-Control` parser — only the directives a client-side cache acts on.
23
+ *
24
+ * ```ts
25
+ * parseCacheControl('max-age=30, private').maxAgeMs; // 30_000
26
+ * ```
27
+ */
28
+ export declare function parseCacheControl(value: string | undefined | null): CacheControl;
29
+ /**
30
+ * Whether a response carrying `Vary: <responseVary>` may be stored under a key that already
31
+ * folds in `varyHeaders`.
32
+ *
33
+ * `Vary` names the *request* headers the response's identity depends on — `Cookie`,
34
+ * `Accept-Language`, `Origin`. A cache may only replay a stored response to a request whose
35
+ * keyed headers match, so a response varying on anything **not** folded into the key cannot
36
+ * be keyed correctly, and the only safe verdict is "store nothing": storing anyway would
37
+ * replay one caller's variant — another user's private payload, another locale's page — to
38
+ * the next caller whose unkeyed header happens to differ. `Vary: *` advertises variants
39
+ * that are unknowable by construction and is never cacheable (RFC 9111 §3).
40
+ *
41
+ * An absent, empty or unparsable header varies on nothing and is always storable; a listed
42
+ * name that *is* folded in (case-insensitively, as header names are) makes the response
43
+ * storable.
44
+ */
45
+ export declare function varyIsStorable(responseVary: string | null, varyHeaders: readonly string[]): boolean;
46
+ /**
47
+ * `Age: <seconds>` — how long an intermediate cache has been holding the response.
48
+ *
49
+ * The freshness window shrinks by this much: a response that is already halfway to its
50
+ * `max-age` deadline must not look brand new to us. Anything unparsable counts as zero.
51
+ */
52
+ export declare function parseAgeMs(value: string | undefined | null): number;
53
+ //# sourceMappingURL=cache-control.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-control.d.ts","sourceRoot":"","sources":["../src/cache-control.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,WAAW,YAAY;IAC3B,qDAAqD;IACrD,OAAO,EAAE,OAAO,CAAC;IACjB,2GAA2G;IAC3G,OAAO,EAAE,OAAO,CAAC;IACjB,sDAAsD;IACtD,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;CAC9B;AAED,iGAAiG;AACjG,eAAO,MAAM,aAAa,EAAE,YAI1B,CAAC;AAEH;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,YAAY,CA4BhF;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,cAAc,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI,EAAE,WAAW,EAAE,SAAS,MAAM,EAAE,GAAG,OAAO,CAYnG;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAInE"}
@@ -0,0 +1,109 @@
1
+ /**
2
+ * What `Cache-Control` (and the related `Age`) say about a request or a response — plus the
3
+ * one `Vary` question a keying client must answer before storing anything.
4
+ *
5
+ * Package-local on purpose: this adapter deliberately reads only the directives it acts
6
+ * on. `stale-while-revalidate` and `must-revalidate` are *not* parsed here — they shape
7
+ * the stale window of `@blaze-cache/fetch`, which has one; this adapter never serves a
8
+ * stale entry at all, so for it they are equivalent to plain expiry. Each package is free
9
+ * to grow its own directives without dragging the others along.
10
+ */
11
+ /** The value used when parsing is switched off (`cacheControl: false`) or a header is absent. */
12
+ export const NO_DIRECTIVES = Object.freeze({
13
+ noStore: false,
14
+ noCache: false,
15
+ maxAgeMs: undefined,
16
+ });
17
+ /**
18
+ * Minimal `Cache-Control` parser — only the directives a client-side cache acts on.
19
+ *
20
+ * ```ts
21
+ * parseCacheControl('max-age=30, private').maxAgeMs; // 30_000
22
+ * ```
23
+ */
24
+ export function parseCacheControl(value) {
25
+ const result = {
26
+ noStore: false,
27
+ noCache: false,
28
+ maxAgeMs: undefined,
29
+ };
30
+ if (!value)
31
+ return result;
32
+ for (const rawDirective of value.split(',')) {
33
+ const directive = rawDirective.trim().toLowerCase();
34
+ if (directive === 'no-store') {
35
+ result.noStore = true;
36
+ }
37
+ else if (directive === 'no-cache') {
38
+ result.noCache = true;
39
+ }
40
+ else if (directive.startsWith('no-cache=')) {
41
+ // `no-cache="set-cookie, field2"` — reuse is forbidden until *those fields* have been
42
+ // revalidated, and this cache cannot revalidate individual fields, so it must read as
43
+ // the whole-response spelling. Matching only the bare directive would silently turn
44
+ // this opt-out back into "cacheable".
45
+ result.noCache = true;
46
+ }
47
+ else if (directive.startsWith('max-age=')) {
48
+ // First occurrence wins (RFC 9111 §5.2.3).
49
+ if (result.maxAgeMs === undefined) {
50
+ result.maxAgeMs = seconds(directive.slice('max-age='.length));
51
+ }
52
+ }
53
+ }
54
+ return result;
55
+ }
56
+ /**
57
+ * Whether a response carrying `Vary: <responseVary>` may be stored under a key that already
58
+ * folds in `varyHeaders`.
59
+ *
60
+ * `Vary` names the *request* headers the response's identity depends on — `Cookie`,
61
+ * `Accept-Language`, `Origin`. A cache may only replay a stored response to a request whose
62
+ * keyed headers match, so a response varying on anything **not** folded into the key cannot
63
+ * be keyed correctly, and the only safe verdict is "store nothing": storing anyway would
64
+ * replay one caller's variant — another user's private payload, another locale's page — to
65
+ * the next caller whose unkeyed header happens to differ. `Vary: *` advertises variants
66
+ * that are unknowable by construction and is never cacheable (RFC 9111 §3).
67
+ *
68
+ * An absent, empty or unparsable header varies on nothing and is always storable; a listed
69
+ * name that *is* folded in (case-insensitively, as header names are) makes the response
70
+ * storable.
71
+ */
72
+ export function varyIsStorable(responseVary, varyHeaders) {
73
+ if (responseVary === null)
74
+ return true;
75
+ const names = responseVary
76
+ .split(',')
77
+ .map((name) => name.trim().toLowerCase())
78
+ .filter((name) => name.length > 0);
79
+ if (names.length === 0)
80
+ return true; // `Vary:` with no names varies on nothing
81
+ if (names.includes('*'))
82
+ return false; // RFC 9111 §3: never usable from a cache
83
+ const keyed = new Set(varyHeaders.map((name) => name.toLowerCase()));
84
+ return names.every((name) => keyed.has(name));
85
+ }
86
+ /**
87
+ * `Age: <seconds>` — how long an intermediate cache has been holding the response.
88
+ *
89
+ * The freshness window shrinks by this much: a response that is already halfway to its
90
+ * `max-age` deadline must not look brand new to us. Anything unparsable counts as zero.
91
+ */
92
+ export function parseAgeMs(value) {
93
+ if (!value)
94
+ return 0;
95
+ const secondsValue = Number(value.trim());
96
+ return Number.isFinite(secondsValue) && secondsValue >= 0 ? secondsValue * 1000 : 0;
97
+ }
98
+ /** Seconds → milliseconds, or `undefined` when the value is not a usable non-negative number. */
99
+ function seconds(raw) {
100
+ const trimmed = raw.trim();
101
+ // An empty value (`max-age=`) is malformed, not zero: `Number('')` is `0`, and reading
102
+ // "instantly stale" out of a malformed directive would defeat the header entirely.
103
+ // RFC 9111 §5.2.3 says ignore it — which here means `undefined`, the no-directive answer.
104
+ if (trimmed === '')
105
+ return undefined;
106
+ const value = Number(trimmed);
107
+ return Number.isFinite(value) && value >= 0 ? value * 1000 : undefined;
108
+ }
109
+ //# sourceMappingURL=cache-control.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache-control.js","sourceRoot":"","sources":["../src/cache-control.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,26 @@
1
+ import type { KyInstance } from 'ky';
2
+ import type { BlazeKyCacheLike, CreateBlazeKyOptions } from './types.js';
3
+ /**
4
+ * A ky instance with Blaze Cache built in — the helper form of {@link blazeKyHook}.
5
+ *
6
+ * ```ts
7
+ * import { createBlazeKy } from '@blaze-cache/ky';
8
+ *
9
+ * const api = createBlazeKy(cache, {
10
+ * prefixUrl: 'https://api.example.com', // any ky option, as usual
11
+ * ttlMs: 30_000, // …plus the cache options
12
+ * });
13
+ *
14
+ * const users = await api.get('users').json();
15
+ * ```
16
+ *
17
+ * Every option ky accepts is passed through untouched (`prefixUrl`/`baseUrl`, `headers`,
18
+ * `retry`, `timeout`, `fetch`, …). Hooks you add are preserved and run **before** the
19
+ * cache's own: a header your `beforeRequest` sets is folded into the cache key, and an
20
+ * `afterResponse` of yours sees the response before it is stored.
21
+ *
22
+ * @param cache The Blaze Cache instance (or any {@link BlazeKyCacheLike}).
23
+ * @param options ky options mixed with {@link BlazeKyCacheOptions} — split apart here.
24
+ */
25
+ export declare function createBlazeKy(cache: BlazeKyCacheLike, options?: CreateBlazeKyOptions): KyInstance;
26
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAGrC,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAEzE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,gBAAgB,EACvB,OAAO,GAAE,oBAAyB,GACjC,UAAU,CA2BZ"}
package/dist/client.js ADDED
@@ -0,0 +1,42 @@
1
+ import ky from 'ky';
2
+ import { blazeKyHook } from './hook.js';
3
+ /**
4
+ * A ky instance with Blaze Cache built in — the helper form of {@link blazeKyHook}.
5
+ *
6
+ * ```ts
7
+ * import { createBlazeKy } from '@blaze-cache/ky';
8
+ *
9
+ * const api = createBlazeKy(cache, {
10
+ * prefixUrl: 'https://api.example.com', // any ky option, as usual
11
+ * ttlMs: 30_000, // …plus the cache options
12
+ * });
13
+ *
14
+ * const users = await api.get('users').json();
15
+ * ```
16
+ *
17
+ * Every option ky accepts is passed through untouched (`prefixUrl`/`baseUrl`, `headers`,
18
+ * `retry`, `timeout`, `fetch`, …). Hooks you add are preserved and run **before** the
19
+ * cache's own: a header your `beforeRequest` sets is folded into the cache key, and an
20
+ * `afterResponse` of yours sees the response before it is stored.
21
+ *
22
+ * @param cache The Blaze Cache instance (or any {@link BlazeKyCacheLike}).
23
+ * @param options ky options mixed with {@link BlazeKyCacheOptions} — split apart here.
24
+ */
25
+ export function createBlazeKy(cache, options = {}) {
26
+ const { ttlMs, methods, cacheControl, key, shouldCache, tags, varyHeaders, markerHeader, ...kyOptions } = options;
27
+ // `extend` merges hooks by appending, so chaining gives exactly the documented order:
28
+ // the user's hooks from the first call run before the cache's hooks from the second.
29
+ return ky.extend(kyOptions).extend({
30
+ hooks: blazeKyHook(cache, {
31
+ ttlMs,
32
+ methods,
33
+ cacheControl,
34
+ key,
35
+ shouldCache,
36
+ tags,
37
+ varyHeaders,
38
+ markerHeader,
39
+ }),
40
+ });
41
+ }
42
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AAGpB,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAGxC;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,UAAU,aAAa,CAC3B,KAAuB,EACvB,UAAgC,EAAE;IAElC,MAAM,EACJ,KAAK,EACL,OAAO,EACP,YAAY,EACZ,GAAG,EACH,WAAW,EACX,IAAI,EACJ,WAAW,EACX,YAAY,EACZ,GAAG,SAAS,EACb,GAAG,OAAO,CAAC;IAEZ,sFAAsF;IACtF,qFAAqF;IACrF,OAAO,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,MAAM,CAAC;QACjC,KAAK,EAAE,WAAW,CAAC,KAAK,EAAE;YACxB,KAAK;YACL,OAAO;YACP,YAAY;YACZ,GAAG;YACH,WAAW;YACX,IAAI;YACJ,WAAW;YACX,YAAY;SACb,CAAC;KACH,CAAC,CAAC;AACL,CAAC"}
package/dist/hook.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import type { BlazeKyCacheLike, BlazeKyCacheOptions, BlazeKyHooks } from './types.js';
2
+ /**
3
+ * ky hooks that cache HTTP responses through Blaze Cache.
4
+ *
5
+ * Two hooks, matched to ky's own architecture: `beforeRequest` may answer a request from
6
+ * the cache by returning a `Response` (ky skips the network), and `afterResponse` — which
7
+ * receives a *clone* of every response — stores what is worth keeping and stamps the
8
+ * `x-blaze-cache` marker.
9
+ *
10
+ * ```ts
11
+ * import ky from 'ky';
12
+ * import { blazeKyHook } from '@blaze-cache/ky';
13
+ *
14
+ * const api = ky.extend({
15
+ * hooks: {
16
+ * ...blazeKyHook(cache, { ttlMs: 30_000 }),
17
+ * },
18
+ * });
19
+ * ```
20
+ *
21
+ * Works on **ky v1 and v2**: their hooks take different shapes — `(request, options, …)` in
22
+ * v1, a single `{request, options, …}` state object in v2 — and these hooks recognise
23
+ * whichever they are called with, from the first argument alone.
24
+ *
25
+ * Ordering: `ky.extend` appends hooks, so with `blazeKyHook`'s hooks spread in last (the
26
+ * usual `hooks: {...blazeKyHook(cache)}` spelling), *your* `beforeRequest` hooks run first
27
+ * — any header they add is folded into the cache key — and *your* `afterResponse` hooks
28
+ * run before the store sees the response.
29
+ */
30
+ export declare function blazeKyHook(cache: BlazeKyCacheLike, options?: BlazeKyCacheOptions): BlazeKyHooks;
31
+ //# sourceMappingURL=hook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook.d.ts","sourceRoot":"","sources":["../src/hook.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAGV,gBAAgB,EAChB,mBAAmB,EAEnB,YAAY,EAGb,MAAM,YAAY,CAAC;AAsBpB;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,EAAE,OAAO,GAAE,mBAAwB,GAAG,YAAY,CAoPpG"}