edge-throttle 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PetheanRaj
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,250 @@
1
- # Temporary Holding Version
1
+ # edge-throttle
2
2
 
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.
3
+ A **zero-dependency**, **multi-runtime** rate-limiting library for **Node.js (20+)**, **Bun**, **Deno**, **Cloudflare Workers**, and **Vercel Edge Runtime**.
4
+
5
+ Built with standard Web APIs only (`fetch`, `Date.now()`, `setTimeout`)—no Node-specific modules, no heavy SDKs, and atomic Lua script support out of the box.
6
+
7
+ ![edge-throttle demo](https://raw.githubusercontent.com/PetheanRaj/edge-throttle/main/demo/edge-throttle-demo.gif)
8
+
9
+ ---
10
+
11
+ ## Why `edge-throttle`?
12
+
13
+ - **Runs everywhere:** One codebase works identically on Node.js, Bun, Deno, Cloudflare Workers, and Vercel Edge.
14
+ - **Zero dependencies:** Keeps your edge bundle tiny and cold starts fast.
15
+ - **Two proven algorithms:** Weighted **Sliding Window** (smooth, burst-safe) and **Token Bucket** (burst-friendly, weighted request costs).
16
+ - **Pluggable storage:** Built-in adapters for **In-Memory (LRU)**, **Upstash Redis (REST)**, **Cloudflare KV**, and **Redis (`ioredis` / `node-redis`)**, plus a simple interface for custom stores.
17
+ - **Production-ready resilience:** Built-in `failOpen`, `timeoutMs`, `onError` hook, and standard `X-RateLimit-*` / `Retry-After` HTTP headers.
18
+
19
+ ---
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install edge-throttle
25
+ # or
26
+ pnpm add edge-throttle
27
+ # or
28
+ bun add edge-throttle
29
+ ```
30
+
31
+ > **Note:** If you use `RedisAdapter`, install your preferred Redis client (`ioredis` or `redis`) as well. All other adapters require no extra packages.
32
+
33
+ ---
34
+
35
+ ## Quick Start
36
+
37
+ ```ts
38
+ import { createRateLimiter, slidingWindow } from 'edge-throttle';
39
+ import { MemoryAdapter } from 'edge-throttle/adapters/memory';
40
+
41
+ const limiter = createRateLimiter({
42
+ adapter: new MemoryAdapter(),
43
+ algorithm: slidingWindow({ limit: 10, window: '1m' }),
44
+ prefix: 'rl:api',
45
+ });
46
+
47
+ const result = await limiter.limit('user_123');
48
+
49
+ if (!result.success) {
50
+ return new Response('Too Many Requests', {
51
+ status: 429,
52
+ headers: result.headers,
53
+ });
54
+ }
55
+
56
+ return new Response('OK', { headers: result.headers });
57
+ ```
58
+
59
+ ---
60
+
61
+ ## Choosing an Algorithm
62
+
63
+ ### 1. Sliding Window (`slidingWindow`)
64
+
65
+ Best for **general API rate limiting** (e.g., *"100 requests per minute"*).
66
+
67
+ Unlike a fixed window—which can allow 2× traffic right across a minute boundary—`slidingWindow` blends the previous window's count with the current window based on how much time has elapsed.
68
+
69
+ ```ts
70
+ import { slidingWindow } from 'edge-throttle';
71
+
72
+ const algorithm = slidingWindow({
73
+ limit: 100, // Max requests allowed
74
+ window: '1m', // Rolling window duration
75
+ });
76
+ ```
77
+
78
+ ### 2. Token Bucket (`tokenBucket`)
79
+
80
+ Best when you want to **allow short bursts** or **charge different costs** per endpoint (e.g., AI generation costs `5` tokens, normal read costs `1` token).
81
+
82
+ ```ts
83
+ import { tokenBucket } from 'edge-throttle';
84
+
85
+ const algorithm = tokenBucket({
86
+ capacity: 20, // Max burst size
87
+ refillRate: 2, // Tokens added per interval
88
+ refillInterval: '1s',
89
+ });
90
+
91
+ // Normal request (costs 1 token by default)
92
+ await limiter.limit('user_123');
93
+
94
+ // Expensive request (costs 5 tokens)
95
+ await limiter.limit('user_123', { cost: 5 });
96
+ ```
97
+
98
+ ---
99
+
100
+ ## Storage Adapters
101
+
102
+ Import only the adapter you need from `edge-throttle/adapters/*`:
103
+
104
+ | Adapter | Import Path | Best For | Atomic Lua |
105
+ | :--- | :--- | :--- | :--- |
106
+ | `MemoryAdapter` | `edge-throttle/adapters/memory` | Single-server Node/Bun, local dev, tests | In-process lock |
107
+ | `UpstashAdapter` | `edge-throttle/adapters/upstash` | Edge runtimes (Vercel Edge, CF Workers, Deno) | Yes (`EVAL`) |
108
+ | `CloudflareKVAdapter` | `edge-throttle/adapters/cloudflare-kv` | Cloudflare Workers with KV bindings | No |
109
+ | `RedisAdapter` | `edge-throttle/adapters/redis` | Node.js / Bun with `ioredis` or `node-redis` | Yes (`EVAL`) |
110
+
111
+ ### Memory (`MemoryAdapter`)
112
+
113
+ Uses an LRU-bounded `Map` with lazy TTL expiration so memory stays bounded in long-running processes.
114
+
115
+ ```ts
116
+ import { MemoryAdapter } from 'edge-throttle/adapters/memory';
117
+
118
+ const adapter = new MemoryAdapter({
119
+ maxSize: 10_000, // Optional, defaults to 10,000 keys
120
+ });
121
+ ```
122
+
123
+ ### Upstash Redis (`UpstashAdapter`)
124
+
125
+ Uses standard `fetch` against the Upstash REST API—no `@upstash/redis` SDK required.
126
+
127
+ ```ts
128
+ import { UpstashAdapter } from 'edge-throttle/adapters/upstash';
129
+
130
+ const adapter = new UpstashAdapter({
131
+ url: process.env.UPSTASH_REDIS_REST_URL!,
132
+ token: process.env.UPSTASH_REDIS_REST_TOKEN!,
133
+ });
134
+ ```
135
+
136
+ ### Cloudflare KV (`CloudflareKVAdapter`)
137
+
138
+ Accepts a Cloudflare `KVNamespace` binding. Cloudflare KV enforces a minimum 60-second TTL, so `CloudflareKVAdapter` clamps the KV TTL to 60s while tracking exact millisecond expiration inside the stored value (so short windows like `'10s'` still work accurately).
139
+
140
+ ```ts
141
+ import { CloudflareKVAdapter } from 'edge-throttle/adapters/cloudflare-kv';
142
+
143
+ // Inside a Cloudflare Worker fetch(request, env) handler:
144
+ const adapter = new CloudflareKVAdapter({ namespace: env.RATE_LIMIT_KV });
145
+ ```
146
+
147
+ ### Redis (`RedisAdapter`)
148
+
149
+ Works with both `ioredis` and `node-redis` (v4+) clients, executing atomic Lua scripts to prevent race conditions under high concurrency.
150
+
151
+ ```ts
152
+ import Redis from 'ioredis';
153
+ import { RedisAdapter } from 'edge-throttle/adapters/redis';
154
+
155
+ const redis = new Redis(process.env.REDIS_URL!);
156
+ const adapter = new RedisAdapter({ client: redis });
157
+ ```
158
+
159
+ ### Custom Adapter
160
+
161
+ Implement the `StorageAdapter` interface to plug in any database (PostgreSQL, DynamoDB, Durable Objects, etc.):
162
+
163
+ ```ts
164
+ import type { StorageAdapter } from 'edge-throttle';
165
+
166
+ const customAdapter: StorageAdapter = {
167
+ async get<T>(key: string): Promise<T | null> {
168
+ // Return stored value or null if missing/expired
169
+ },
170
+ async set<T>(key: string, value: T, ttlMs: number): Promise<void> {
171
+ // Persist value with a TTL in milliseconds
172
+ },
173
+ // Optional: implement `eval` for atomic Lua execution
174
+ // Optional: implement `increment` for atomic counters
175
+ };
176
+ ```
177
+
178
+ ---
179
+
180
+ ## Configuration & Resilience
181
+
182
+ `createRateLimiter(config)` accepts the following options:
183
+
184
+ | Option | Type | Default | Description |
185
+ | :--- | :--- | :--- | :--- |
186
+ | `adapter` | `StorageAdapter` | *Required* | Storage backend instance. |
187
+ | `algorithm` | `RateLimitAlgorithm` | *Required* | `slidingWindow(...)` or `tokenBucket(...)`. |
188
+ | `prefix` | `string` | `'rl'` | Key prefix for namespacing in storage. |
189
+ | `failOpen` | `boolean` | `false` | If `true`, allows requests when storage throws or times out. |
190
+ | `timeoutMs` | `number` | `undefined` | Max wait time (ms) for storage calls before timing out. |
191
+ | `onError` | `(err, id) => void` | `undefined` | Hook called when storage errors or times out (great for logging). |
192
+
193
+ Example with resilience enabled:
194
+
195
+ ```ts
196
+ const limiter = createRateLimiter({
197
+ adapter: new UpstashAdapter({ url: '...', token: '...' }),
198
+ algorithm: slidingWindow({ limit: 100, window: '1m' }),
199
+ prefix: 'rl:public-api',
200
+ failOpen: true,
201
+ timeoutMs: 1500,
202
+ onError: (err, identifier) => {
203
+ console.error(`Rate limiter error for ${identifier}:`, err);
204
+ },
205
+ });
206
+ ```
207
+
208
+ ---
209
+
210
+ ## Return Value & HTTP Headers
211
+
212
+ `await limiter.limit(identifier, options?)` returns a `RateLimitResult`:
213
+
214
+ ```ts
215
+ {
216
+ success: boolean; // true if allowed, false if rate-limited
217
+ limit: number; // configured limit or capacity
218
+ remaining: number; // remaining requests/tokens
219
+ reset: number; // Unix timestamp (ms) when limit resets
220
+ headers: Record<string, string>; // Ready-to-use HTTP headers
221
+ }
222
+ ```
223
+
224
+ ### Included Headers
225
+
226
+ | Header | Value | When Included |
227
+ | :--- | :--- | :--- |
228
+ | `X-RateLimit-Limit` | Maximum allowed requests/tokens | Always |
229
+ | `X-RateLimit-Remaining` | Remaining requests/tokens | Always |
230
+ | `X-RateLimit-Reset` | Unix epoch timestamp in **seconds** | Always |
231
+ | `Retry-After` | Seconds until the client can retry | Only when `success` is `false` |
232
+
233
+ ---
234
+
235
+ ## Duration Formats
236
+
237
+ Any `window` or `refillInterval` accepts either a positive number (milliseconds) or a duration string:
238
+
239
+ - `'500ms'` — 500 milliseconds
240
+ - `'10s'` — 10 seconds
241
+ - `'1m'` — 1 minute
242
+ - `'2h'` — 2 hours
243
+ - `'1d'` — 1 day
244
+ - `60000` — 60,000 milliseconds
245
+
246
+ ---
247
+
248
+ ## License
249
+
250
+ MIT
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ // src/adapters/cloudflare-kv.ts
4
+ var MIN_KV_TTL_SECONDS = 60;
5
+ var CloudflareKVAdapter = class {
6
+ kv;
7
+ constructor(options) {
8
+ this.kv = "namespace" in options ? options.namespace : options;
9
+ }
10
+ async get(key) {
11
+ const raw = await this.kv.get(key);
12
+ if (raw === null) {
13
+ return null;
14
+ }
15
+ try {
16
+ const envelope = JSON.parse(raw);
17
+ if (typeof envelope.e === "number" && Date.now() >= envelope.e) {
18
+ return null;
19
+ }
20
+ return envelope.v;
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+ async set(key, value, ttlMs) {
26
+ if (ttlMs <= 0) {
27
+ return;
28
+ }
29
+ const envelope = {
30
+ v: value,
31
+ e: Date.now() + ttlMs
32
+ };
33
+ const expirationTtl = Math.max(MIN_KV_TTL_SECONDS, Math.ceil(ttlMs / 1e3));
34
+ await this.kv.put(key, JSON.stringify(envelope), { expirationTtl });
35
+ }
36
+ };
37
+
38
+ exports.CloudflareKVAdapter = CloudflareKVAdapter;
39
+ //# sourceMappingURL=cloudflare-kv.cjs.map
40
+ //# sourceMappingURL=cloudflare-kv.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/adapters/cloudflare-kv.ts"],"names":[],"mappings":";;;AAwBA,IAAM,kBAAA,GAAqB,EAAA;AASpB,IAAM,sBAAN,MAAoD;AAAA,EACxC,EAAA;AAAA,EAEjB,YAAY,OAAA,EAAuD;AACjE,IAAA,IAAA,CAAK,EAAA,GAAK,WAAA,IAAe,OAAA,GAAU,OAAA,CAAQ,SAAA,GAAY,OAAA;AAAA,EACzD;AAAA,EAEA,MAAM,IAAO,GAAA,EAAgC;AAC3C,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,EAAA,CAAG,IAAI,GAAG,CAAA;AACjC,IAAA,IAAI,QAAQ,IAAA,EAAM;AAChB,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,IAAI;AACF,MAAA,MAAM,QAAA,GAAW,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC/B,MAAA,IAAI,OAAO,SAAS,CAAA,KAAM,QAAA,IAAY,KAAK,GAAA,EAAI,IAAK,SAAS,CAAA,EAAG;AAC9D,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,OAAO,QAAA,CAAS,CAAA;AAAA,IAClB,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAM,GAAA,CAAO,GAAA,EAAa,KAAA,EAAU,KAAA,EAA8B;AAChE,IAAA,IAAI,SAAS,CAAA,EAAG;AACd,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,QAAA,GAA0B;AAAA,MAC9B,CAAA,EAAG,KAAA;AAAA,MACH,CAAA,EAAG,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,KAClB;AAEA,IAAA,MAAM,aAAA,GAAgB,KAAK,GAAA,CAAI,kBAAA,EAAoB,KAAK,IAAA,CAAK,KAAA,GAAQ,GAAI,CAAC,CAAA;AAC1E,IAAA,MAAM,IAAA,CAAK,EAAA,CAAG,GAAA,CAAI,GAAA,EAAK,IAAA,CAAK,UAAU,QAAQ,CAAA,EAAG,EAAE,aAAA,EAAe,CAAA;AAAA,EACpE;AACF","file":"cloudflare-kv.cjs","sourcesContent":["import type { StorageAdapter } from '../types.js';\n\n/**\n * Minimal structural interface matching Cloudflare Workers `KVNamespace`.\n * Avoids requiring `@cloudflare/workers-types` as a dependency.\n */\nexport interface KVNamespaceLike {\n get(key: string): Promise<string | null>;\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;\n}\n\n/**\n * Configuration options for `CloudflareKVAdapter`.\n */\nexport interface CloudflareKVAdapterOptions {\n /** Cloudflare Workers KV namespace binding. */\n namespace: KVNamespaceLike;\n}\n\ninterface KVEnvelope<T> {\n v: T;\n e: number;\n}\n\nconst MIN_KV_TTL_SECONDS = 60;\n\n/**\n * Cloudflare Workers KV `StorageAdapter`.\n *\n * Gracefully handles Cloudflare KV's 60-second minimum `expirationTtl` constraint\n * by clamping the KV TTL to 60s while tracking the exact millisecond expiration\n * timestamp inside the stored payload.\n */\nexport class CloudflareKVAdapter implements StorageAdapter {\n private readonly kv: KVNamespaceLike;\n\n constructor(options: CloudflareKVAdapterOptions | KVNamespaceLike) {\n this.kv = 'namespace' in options ? options.namespace : options;\n }\n\n async get<T>(key: string): Promise<T | null> {\n const raw = await this.kv.get(key);\n if (raw === null) {\n return null;\n }\n\n try {\n const envelope = JSON.parse(raw) as KVEnvelope<T>;\n if (typeof envelope.e === 'number' && Date.now() >= envelope.e) {\n return null;\n }\n return envelope.v;\n } catch {\n return null;\n }\n }\n\n async set<T>(key: string, value: T, ttlMs: number): Promise<void> {\n if (ttlMs <= 0) {\n return;\n }\n\n const envelope: KVEnvelope<T> = {\n v: value,\n e: Date.now() + ttlMs,\n };\n\n const expirationTtl = Math.max(MIN_KV_TTL_SECONDS, Math.ceil(ttlMs / 1000));\n await this.kv.put(key, JSON.stringify(envelope), { expirationTtl });\n }\n}\n"]}
@@ -0,0 +1,34 @@
1
+ import { S as StorageAdapter } from '../types-Ca_Pa4mZ.cjs';
2
+
3
+ /**
4
+ * Minimal structural interface matching Cloudflare Workers `KVNamespace`.
5
+ * Avoids requiring `@cloudflare/workers-types` as a dependency.
6
+ */
7
+ interface KVNamespaceLike {
8
+ get(key: string): Promise<string | null>;
9
+ put(key: string, value: string, options?: {
10
+ expirationTtl?: number;
11
+ }): Promise<void>;
12
+ }
13
+ /**
14
+ * Configuration options for `CloudflareKVAdapter`.
15
+ */
16
+ interface CloudflareKVAdapterOptions {
17
+ /** Cloudflare Workers KV namespace binding. */
18
+ namespace: KVNamespaceLike;
19
+ }
20
+ /**
21
+ * Cloudflare Workers KV `StorageAdapter`.
22
+ *
23
+ * Gracefully handles Cloudflare KV's 60-second minimum `expirationTtl` constraint
24
+ * by clamping the KV TTL to 60s while tracking the exact millisecond expiration
25
+ * timestamp inside the stored payload.
26
+ */
27
+ declare class CloudflareKVAdapter implements StorageAdapter {
28
+ private readonly kv;
29
+ constructor(options: CloudflareKVAdapterOptions | KVNamespaceLike);
30
+ get<T>(key: string): Promise<T | null>;
31
+ set<T>(key: string, value: T, ttlMs: number): Promise<void>;
32
+ }
33
+
34
+ export { CloudflareKVAdapter, type CloudflareKVAdapterOptions, type KVNamespaceLike };
@@ -0,0 +1,34 @@
1
+ import { S as StorageAdapter } from '../types-Ca_Pa4mZ.js';
2
+
3
+ /**
4
+ * Minimal structural interface matching Cloudflare Workers `KVNamespace`.
5
+ * Avoids requiring `@cloudflare/workers-types` as a dependency.
6
+ */
7
+ interface KVNamespaceLike {
8
+ get(key: string): Promise<string | null>;
9
+ put(key: string, value: string, options?: {
10
+ expirationTtl?: number;
11
+ }): Promise<void>;
12
+ }
13
+ /**
14
+ * Configuration options for `CloudflareKVAdapter`.
15
+ */
16
+ interface CloudflareKVAdapterOptions {
17
+ /** Cloudflare Workers KV namespace binding. */
18
+ namespace: KVNamespaceLike;
19
+ }
20
+ /**
21
+ * Cloudflare Workers KV `StorageAdapter`.
22
+ *
23
+ * Gracefully handles Cloudflare KV's 60-second minimum `expirationTtl` constraint
24
+ * by clamping the KV TTL to 60s while tracking the exact millisecond expiration
25
+ * timestamp inside the stored payload.
26
+ */
27
+ declare class CloudflareKVAdapter implements StorageAdapter {
28
+ private readonly kv;
29
+ constructor(options: CloudflareKVAdapterOptions | KVNamespaceLike);
30
+ get<T>(key: string): Promise<T | null>;
31
+ set<T>(key: string, value: T, ttlMs: number): Promise<void>;
32
+ }
33
+
34
+ export { CloudflareKVAdapter, type CloudflareKVAdapterOptions, type KVNamespaceLike };
@@ -0,0 +1,38 @@
1
+ // src/adapters/cloudflare-kv.ts
2
+ var MIN_KV_TTL_SECONDS = 60;
3
+ var CloudflareKVAdapter = class {
4
+ kv;
5
+ constructor(options) {
6
+ this.kv = "namespace" in options ? options.namespace : options;
7
+ }
8
+ async get(key) {
9
+ const raw = await this.kv.get(key);
10
+ if (raw === null) {
11
+ return null;
12
+ }
13
+ try {
14
+ const envelope = JSON.parse(raw);
15
+ if (typeof envelope.e === "number" && Date.now() >= envelope.e) {
16
+ return null;
17
+ }
18
+ return envelope.v;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+ async set(key, value, ttlMs) {
24
+ if (ttlMs <= 0) {
25
+ return;
26
+ }
27
+ const envelope = {
28
+ v: value,
29
+ e: Date.now() + ttlMs
30
+ };
31
+ const expirationTtl = Math.max(MIN_KV_TTL_SECONDS, Math.ceil(ttlMs / 1e3));
32
+ await this.kv.put(key, JSON.stringify(envelope), { expirationTtl });
33
+ }
34
+ };
35
+
36
+ export { CloudflareKVAdapter };
37
+ //# sourceMappingURL=cloudflare-kv.js.map
38
+ //# sourceMappingURL=cloudflare-kv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/adapters/cloudflare-kv.ts"],"names":[],"mappings":";AAwBA,IAAM,kBAAA,GAAqB,EAAA;AASpB,IAAM,sBAAN,MAAoD;AAAA,EACxC,EAAA;AAAA,EAEjB,YAAY,OAAA,EAAuD;AACjE,IAAA,IAAA,CAAK,EAAA,GAAK,WAAA,IAAe,OAAA,GAAU,OAAA,CAAQ,SAAA,GAAY,OAAA;AAAA,EACzD;AAAA,EAEA,MAAM,IAAO,GAAA,EAAgC;AAC3C,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,EAAA,CAAG,IAAI,GAAG,CAAA;AACjC,IAAA,IAAI,QAAQ,IAAA,EAAM;AAChB,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,IAAI;AACF,MAAA,MAAM,QAAA,GAAW,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA;AAC/B,MAAA,IAAI,OAAO,SAAS,CAAA,KAAM,QAAA,IAAY,KAAK,GAAA,EAAI,IAAK,SAAS,CAAA,EAAG;AAC9D,QAAA,OAAO,IAAA;AAAA,MACT;AACA,MAAA,OAAO,QAAA,CAAS,CAAA;AAAA,IAClB,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAM,GAAA,CAAO,GAAA,EAAa,KAAA,EAAU,KAAA,EAA8B;AAChE,IAAA,IAAI,SAAS,CAAA,EAAG;AACd,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,QAAA,GAA0B;AAAA,MAC9B,CAAA,EAAG,KAAA;AAAA,MACH,CAAA,EAAG,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,KAClB;AAEA,IAAA,MAAM,aAAA,GAAgB,KAAK,GAAA,CAAI,kBAAA,EAAoB,KAAK,IAAA,CAAK,KAAA,GAAQ,GAAI,CAAC,CAAA;AAC1E,IAAA,MAAM,IAAA,CAAK,EAAA,CAAG,GAAA,CAAI,GAAA,EAAK,IAAA,CAAK,UAAU,QAAQ,CAAA,EAAG,EAAE,aAAA,EAAe,CAAA;AAAA,EACpE;AACF","file":"cloudflare-kv.js","sourcesContent":["import type { StorageAdapter } from '../types.js';\n\n/**\n * Minimal structural interface matching Cloudflare Workers `KVNamespace`.\n * Avoids requiring `@cloudflare/workers-types` as a dependency.\n */\nexport interface KVNamespaceLike {\n get(key: string): Promise<string | null>;\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>;\n}\n\n/**\n * Configuration options for `CloudflareKVAdapter`.\n */\nexport interface CloudflareKVAdapterOptions {\n /** Cloudflare Workers KV namespace binding. */\n namespace: KVNamespaceLike;\n}\n\ninterface KVEnvelope<T> {\n v: T;\n e: number;\n}\n\nconst MIN_KV_TTL_SECONDS = 60;\n\n/**\n * Cloudflare Workers KV `StorageAdapter`.\n *\n * Gracefully handles Cloudflare KV's 60-second minimum `expirationTtl` constraint\n * by clamping the KV TTL to 60s while tracking the exact millisecond expiration\n * timestamp inside the stored payload.\n */\nexport class CloudflareKVAdapter implements StorageAdapter {\n private readonly kv: KVNamespaceLike;\n\n constructor(options: CloudflareKVAdapterOptions | KVNamespaceLike) {\n this.kv = 'namespace' in options ? options.namespace : options;\n }\n\n async get<T>(key: string): Promise<T | null> {\n const raw = await this.kv.get(key);\n if (raw === null) {\n return null;\n }\n\n try {\n const envelope = JSON.parse(raw) as KVEnvelope<T>;\n if (typeof envelope.e === 'number' && Date.now() >= envelope.e) {\n return null;\n }\n return envelope.v;\n } catch {\n return null;\n }\n }\n\n async set<T>(key: string, value: T, ttlMs: number): Promise<void> {\n if (ttlMs <= 0) {\n return;\n }\n\n const envelope: KVEnvelope<T> = {\n v: value,\n e: Date.now() + ttlMs,\n };\n\n const expirationTtl = Math.max(MIN_KV_TTL_SECONDS, Math.ceil(ttlMs / 1000));\n await this.kv.put(key, JSON.stringify(envelope), { expirationTtl });\n }\n}\n"]}
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ // src/adapters/memory.ts
4
+ var MemoryAdapter = class {
5
+ store = /* @__PURE__ */ new Map();
6
+ maxSize;
7
+ constructor(options = {}) {
8
+ const maxSize = options.maxSize ?? 1e4;
9
+ if (!Number.isInteger(maxSize) || maxSize <= 0) {
10
+ throw new RangeError(`MemoryAdapter "maxSize" must be a positive integer, got ${maxSize}.`);
11
+ }
12
+ this.maxSize = maxSize;
13
+ }
14
+ /**
15
+ * Current number of entries stored (including entries pending lazy expiration).
16
+ */
17
+ get size() {
18
+ return this.store.size;
19
+ }
20
+ async get(key) {
21
+ const entry = this.store.get(key);
22
+ if (!entry) {
23
+ return null;
24
+ }
25
+ if (Date.now() >= entry.expiresAt) {
26
+ this.store.delete(key);
27
+ return null;
28
+ }
29
+ this.store.delete(key);
30
+ this.store.set(key, entry);
31
+ return entry.value;
32
+ }
33
+ async set(key, value, ttlMs) {
34
+ if (ttlMs <= 0) {
35
+ this.store.delete(key);
36
+ return;
37
+ }
38
+ if (this.store.has(key)) {
39
+ this.store.delete(key);
40
+ } else if (this.store.size >= this.maxSize) {
41
+ const oldestKey = this.store.keys().next().value;
42
+ if (oldestKey !== void 0) {
43
+ this.store.delete(oldestKey);
44
+ }
45
+ }
46
+ this.store.set(key, {
47
+ value,
48
+ expiresAt: Date.now() + ttlMs
49
+ });
50
+ }
51
+ async increment(key, amount, ttlMs) {
52
+ const existing = await this.get(key);
53
+ const next = (existing ?? 0) + amount;
54
+ await this.set(key, next, ttlMs);
55
+ return next;
56
+ }
57
+ /**
58
+ * Remove all entries from memory.
59
+ */
60
+ clear() {
61
+ this.store.clear();
62
+ }
63
+ };
64
+
65
+ exports.MemoryAdapter = MemoryAdapter;
66
+ //# sourceMappingURL=memory.cjs.map
67
+ //# sourceMappingURL=memory.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/adapters/memory.ts"],"names":[],"mappings":";;;AAyBO,IAAM,gBAAN,MAA8C;AAAA,EAClC,KAAA,uBAAY,GAAA,EAAiC;AAAA,EAC7C,OAAA;AAAA,EAEjB,WAAA,CAAY,OAAA,GAAgC,EAAC,EAAG;AAC9C,IAAA,MAAM,OAAA,GAAU,QAAQ,OAAA,IAAW,GAAA;AACnC,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,OAAO,CAAA,IAAK,WAAW,CAAA,EAAG;AAC9C,MAAA,MAAM,IAAI,UAAA,CAAW,CAAA,wDAAA,EAA2D,OAAO,CAAA,CAAA,CAAG,CAAA;AAAA,IAC5F;AACA,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,KAAA,CAAM,IAAA;AAAA,EACpB;AAAA,EAEA,MAAM,IAAO,GAAA,EAAgC;AAC3C,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA;AAChC,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,IAAI,IAAA,CAAK,GAAA,EAAI,IAAK,KAAA,CAAM,SAAA,EAAW;AACjC,MAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AACrB,MAAA,OAAO,IAAA;AAAA,IACT;AAGA,IAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AACrB,IAAA,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACzB,IAAA,OAAO,KAAA,CAAM,KAAA;AAAA,EACf;AAAA,EAEA,MAAM,GAAA,CAAO,GAAA,EAAa,KAAA,EAAU,KAAA,EAA8B;AAChE,IAAA,IAAI,SAAS,CAAA,EAAG;AACd,MAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AACrB,MAAA;AAAA,IACF;AAEA,IAAA,IAAI,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AAAA,IACvB,CAAA,MAAA,IAAW,IAAA,CAAK,KAAA,CAAM,IAAA,IAAQ,KAAK,OAAA,EAAS;AAC1C,MAAA,MAAM,YAAY,IAAA,CAAK,KAAA,CAAM,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AAC3C,MAAA,IAAI,cAAc,MAAA,EAAW;AAC3B,QAAA,IAAA,CAAK,KAAA,CAAM,OAAO,SAAS,CAAA;AAAA,MAC7B;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,KAAA,CAAM,IAAI,GAAA,EAAK;AAAA,MAClB,KAAA;AAAA,MACA,SAAA,EAAW,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,KACzB,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,SAAA,CAAU,GAAA,EAAa,MAAA,EAAgB,KAAA,EAAgC;AAC3E,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,GAAA,CAAY,GAAG,CAAA;AAC3C,IAAA,MAAM,IAAA,GAAA,CAAQ,YAAY,CAAA,IAAK,MAAA;AAC/B,IAAA,MAAM,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,KAAK,CAAA;AAC/B,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,MAAM,KAAA,EAAM;AAAA,EACnB;AACF","file":"memory.cjs","sourcesContent":["import type { StorageAdapter } from '../types.js';\n\n/**\n * Configuration options for `MemoryAdapter`.\n */\nexport interface MemoryAdapterOptions {\n /**\n * Maximum number of entries retained in the LRU cache.\n * When exceeded, the least-recently-used entry is evicted.\n * @default 10000\n */\n maxSize?: number;\n}\n\ninterface CacheEntry<T> {\n value: T;\n expiresAt: number;\n}\n\n/**\n * LRU-bounded in-memory `StorageAdapter` with lazy TTL expiration.\n *\n * Ideal for single-instance Node.js, Bun, Deno, or testing environments.\n * Uses only standard JavaScript `Map` and `Date.now()` with bounded memory.\n */\nexport class MemoryAdapter implements StorageAdapter {\n private readonly store = new Map<string, CacheEntry<unknown>>();\n private readonly maxSize: number;\n\n constructor(options: MemoryAdapterOptions = {}) {\n const maxSize = options.maxSize ?? 10_000;\n if (!Number.isInteger(maxSize) || maxSize <= 0) {\n throw new RangeError(`MemoryAdapter \"maxSize\" must be a positive integer, got ${maxSize}.`);\n }\n this.maxSize = maxSize;\n }\n\n /**\n * Current number of entries stored (including entries pending lazy expiration).\n */\n get size(): number {\n return this.store.size;\n }\n\n async get<T>(key: string): Promise<T | null> {\n const entry = this.store.get(key);\n if (!entry) {\n return null;\n }\n\n if (Date.now() >= entry.expiresAt) {\n this.store.delete(key);\n return null;\n }\n\n // Refresh LRU recency by re-inserting at the end of Map iteration order.\n this.store.delete(key);\n this.store.set(key, entry);\n return entry.value as T;\n }\n\n async set<T>(key: string, value: T, ttlMs: number): Promise<void> {\n if (ttlMs <= 0) {\n this.store.delete(key);\n return;\n }\n\n if (this.store.has(key)) {\n this.store.delete(key);\n } else if (this.store.size >= this.maxSize) {\n const oldestKey = this.store.keys().next().value;\n if (oldestKey !== undefined) {\n this.store.delete(oldestKey);\n }\n }\n\n this.store.set(key, {\n value,\n expiresAt: Date.now() + ttlMs,\n });\n }\n\n async increment(key: string, amount: number, ttlMs: number): Promise<number> {\n const existing = await this.get<number>(key);\n const next = (existing ?? 0) + amount;\n await this.set(key, next, ttlMs);\n return next;\n }\n\n /**\n * Remove all entries from memory.\n */\n clear(): void {\n this.store.clear();\n }\n}\n"]}
@@ -0,0 +1,37 @@
1
+ import { S as StorageAdapter } from '../types-Ca_Pa4mZ.cjs';
2
+
3
+ /**
4
+ * Configuration options for `MemoryAdapter`.
5
+ */
6
+ interface MemoryAdapterOptions {
7
+ /**
8
+ * Maximum number of entries retained in the LRU cache.
9
+ * When exceeded, the least-recently-used entry is evicted.
10
+ * @default 10000
11
+ */
12
+ maxSize?: number;
13
+ }
14
+ /**
15
+ * LRU-bounded in-memory `StorageAdapter` with lazy TTL expiration.
16
+ *
17
+ * Ideal for single-instance Node.js, Bun, Deno, or testing environments.
18
+ * Uses only standard JavaScript `Map` and `Date.now()` with bounded memory.
19
+ */
20
+ declare class MemoryAdapter implements StorageAdapter {
21
+ private readonly store;
22
+ private readonly maxSize;
23
+ constructor(options?: MemoryAdapterOptions);
24
+ /**
25
+ * Current number of entries stored (including entries pending lazy expiration).
26
+ */
27
+ get size(): number;
28
+ get<T>(key: string): Promise<T | null>;
29
+ set<T>(key: string, value: T, ttlMs: number): Promise<void>;
30
+ increment(key: string, amount: number, ttlMs: number): Promise<number>;
31
+ /**
32
+ * Remove all entries from memory.
33
+ */
34
+ clear(): void;
35
+ }
36
+
37
+ export { MemoryAdapter, type MemoryAdapterOptions };
@@ -0,0 +1,37 @@
1
+ import { S as StorageAdapter } from '../types-Ca_Pa4mZ.js';
2
+
3
+ /**
4
+ * Configuration options for `MemoryAdapter`.
5
+ */
6
+ interface MemoryAdapterOptions {
7
+ /**
8
+ * Maximum number of entries retained in the LRU cache.
9
+ * When exceeded, the least-recently-used entry is evicted.
10
+ * @default 10000
11
+ */
12
+ maxSize?: number;
13
+ }
14
+ /**
15
+ * LRU-bounded in-memory `StorageAdapter` with lazy TTL expiration.
16
+ *
17
+ * Ideal for single-instance Node.js, Bun, Deno, or testing environments.
18
+ * Uses only standard JavaScript `Map` and `Date.now()` with bounded memory.
19
+ */
20
+ declare class MemoryAdapter implements StorageAdapter {
21
+ private readonly store;
22
+ private readonly maxSize;
23
+ constructor(options?: MemoryAdapterOptions);
24
+ /**
25
+ * Current number of entries stored (including entries pending lazy expiration).
26
+ */
27
+ get size(): number;
28
+ get<T>(key: string): Promise<T | null>;
29
+ set<T>(key: string, value: T, ttlMs: number): Promise<void>;
30
+ increment(key: string, amount: number, ttlMs: number): Promise<number>;
31
+ /**
32
+ * Remove all entries from memory.
33
+ */
34
+ clear(): void;
35
+ }
36
+
37
+ export { MemoryAdapter, type MemoryAdapterOptions };
@@ -0,0 +1,65 @@
1
+ // src/adapters/memory.ts
2
+ var MemoryAdapter = class {
3
+ store = /* @__PURE__ */ new Map();
4
+ maxSize;
5
+ constructor(options = {}) {
6
+ const maxSize = options.maxSize ?? 1e4;
7
+ if (!Number.isInteger(maxSize) || maxSize <= 0) {
8
+ throw new RangeError(`MemoryAdapter "maxSize" must be a positive integer, got ${maxSize}.`);
9
+ }
10
+ this.maxSize = maxSize;
11
+ }
12
+ /**
13
+ * Current number of entries stored (including entries pending lazy expiration).
14
+ */
15
+ get size() {
16
+ return this.store.size;
17
+ }
18
+ async get(key) {
19
+ const entry = this.store.get(key);
20
+ if (!entry) {
21
+ return null;
22
+ }
23
+ if (Date.now() >= entry.expiresAt) {
24
+ this.store.delete(key);
25
+ return null;
26
+ }
27
+ this.store.delete(key);
28
+ this.store.set(key, entry);
29
+ return entry.value;
30
+ }
31
+ async set(key, value, ttlMs) {
32
+ if (ttlMs <= 0) {
33
+ this.store.delete(key);
34
+ return;
35
+ }
36
+ if (this.store.has(key)) {
37
+ this.store.delete(key);
38
+ } else if (this.store.size >= this.maxSize) {
39
+ const oldestKey = this.store.keys().next().value;
40
+ if (oldestKey !== void 0) {
41
+ this.store.delete(oldestKey);
42
+ }
43
+ }
44
+ this.store.set(key, {
45
+ value,
46
+ expiresAt: Date.now() + ttlMs
47
+ });
48
+ }
49
+ async increment(key, amount, ttlMs) {
50
+ const existing = await this.get(key);
51
+ const next = (existing ?? 0) + amount;
52
+ await this.set(key, next, ttlMs);
53
+ return next;
54
+ }
55
+ /**
56
+ * Remove all entries from memory.
57
+ */
58
+ clear() {
59
+ this.store.clear();
60
+ }
61
+ };
62
+
63
+ export { MemoryAdapter };
64
+ //# sourceMappingURL=memory.js.map
65
+ //# sourceMappingURL=memory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/adapters/memory.ts"],"names":[],"mappings":";AAyBO,IAAM,gBAAN,MAA8C;AAAA,EAClC,KAAA,uBAAY,GAAA,EAAiC;AAAA,EAC7C,OAAA;AAAA,EAEjB,WAAA,CAAY,OAAA,GAAgC,EAAC,EAAG;AAC9C,IAAA,MAAM,OAAA,GAAU,QAAQ,OAAA,IAAW,GAAA;AACnC,IAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,OAAO,CAAA,IAAK,WAAW,CAAA,EAAG;AAC9C,MAAA,MAAM,IAAI,UAAA,CAAW,CAAA,wDAAA,EAA2D,OAAO,CAAA,CAAA,CAAG,CAAA;AAAA,IAC5F;AACA,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,KAAA,CAAM,IAAA;AAAA,EACpB;AAAA,EAEA,MAAM,IAAO,GAAA,EAAgC;AAC3C,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA;AAChC,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,OAAO,IAAA;AAAA,IACT;AAEA,IAAA,IAAI,IAAA,CAAK,GAAA,EAAI,IAAK,KAAA,CAAM,SAAA,EAAW;AACjC,MAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AACrB,MAAA,OAAO,IAAA;AAAA,IACT;AAGA,IAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AACrB,IAAA,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACzB,IAAA,OAAO,KAAA,CAAM,KAAA;AAAA,EACf;AAAA,EAEA,MAAM,GAAA,CAAO,GAAA,EAAa,KAAA,EAAU,KAAA,EAA8B;AAChE,IAAA,IAAI,SAAS,CAAA,EAAG;AACd,MAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AACrB,MAAA;AAAA,IACF;AAEA,IAAA,IAAI,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAG,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,KAAA,CAAM,OAAO,GAAG,CAAA;AAAA,IACvB,CAAA,MAAA,IAAW,IAAA,CAAK,KAAA,CAAM,IAAA,IAAQ,KAAK,OAAA,EAAS;AAC1C,MAAA,MAAM,YAAY,IAAA,CAAK,KAAA,CAAM,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AAC3C,MAAA,IAAI,cAAc,MAAA,EAAW;AAC3B,QAAA,IAAA,CAAK,KAAA,CAAM,OAAO,SAAS,CAAA;AAAA,MAC7B;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,KAAA,CAAM,IAAI,GAAA,EAAK;AAAA,MAClB,KAAA;AAAA,MACA,SAAA,EAAW,IAAA,CAAK,GAAA,EAAI,GAAI;AAAA,KACzB,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,SAAA,CAAU,GAAA,EAAa,MAAA,EAAgB,KAAA,EAAgC;AAC3E,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,GAAA,CAAY,GAAG,CAAA;AAC3C,IAAA,MAAM,IAAA,GAAA,CAAQ,YAAY,CAAA,IAAK,MAAA;AAC/B,IAAA,MAAM,IAAA,CAAK,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,KAAK,CAAA;AAC/B,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,MAAM,KAAA,EAAM;AAAA,EACnB;AACF","file":"memory.js","sourcesContent":["import type { StorageAdapter } from '../types.js';\n\n/**\n * Configuration options for `MemoryAdapter`.\n */\nexport interface MemoryAdapterOptions {\n /**\n * Maximum number of entries retained in the LRU cache.\n * When exceeded, the least-recently-used entry is evicted.\n * @default 10000\n */\n maxSize?: number;\n}\n\ninterface CacheEntry<T> {\n value: T;\n expiresAt: number;\n}\n\n/**\n * LRU-bounded in-memory `StorageAdapter` with lazy TTL expiration.\n *\n * Ideal for single-instance Node.js, Bun, Deno, or testing environments.\n * Uses only standard JavaScript `Map` and `Date.now()` with bounded memory.\n */\nexport class MemoryAdapter implements StorageAdapter {\n private readonly store = new Map<string, CacheEntry<unknown>>();\n private readonly maxSize: number;\n\n constructor(options: MemoryAdapterOptions = {}) {\n const maxSize = options.maxSize ?? 10_000;\n if (!Number.isInteger(maxSize) || maxSize <= 0) {\n throw new RangeError(`MemoryAdapter \"maxSize\" must be a positive integer, got ${maxSize}.`);\n }\n this.maxSize = maxSize;\n }\n\n /**\n * Current number of entries stored (including entries pending lazy expiration).\n */\n get size(): number {\n return this.store.size;\n }\n\n async get<T>(key: string): Promise<T | null> {\n const entry = this.store.get(key);\n if (!entry) {\n return null;\n }\n\n if (Date.now() >= entry.expiresAt) {\n this.store.delete(key);\n return null;\n }\n\n // Refresh LRU recency by re-inserting at the end of Map iteration order.\n this.store.delete(key);\n this.store.set(key, entry);\n return entry.value as T;\n }\n\n async set<T>(key: string, value: T, ttlMs: number): Promise<void> {\n if (ttlMs <= 0) {\n this.store.delete(key);\n return;\n }\n\n if (this.store.has(key)) {\n this.store.delete(key);\n } else if (this.store.size >= this.maxSize) {\n const oldestKey = this.store.keys().next().value;\n if (oldestKey !== undefined) {\n this.store.delete(oldestKey);\n }\n }\n\n this.store.set(key, {\n value,\n expiresAt: Date.now() + ttlMs,\n });\n }\n\n async increment(key: string, amount: number, ttlMs: number): Promise<number> {\n const existing = await this.get<number>(key);\n const next = (existing ?? 0) + amount;\n await this.set(key, next, ttlMs);\n return next;\n }\n\n /**\n * Remove all entries from memory.\n */\n clear(): void {\n this.store.clear();\n }\n}\n"]}