@20baht/elysia-idempotency 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # @20baht/elysia-idempotency changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release (NOTES 2026-11-24). `idempotency({ store, scope })` and the route option `idempotent` (`true` or
6
+ `'required'`): a retry with the same key and request gets the first answer back (`Idempotent-Replayed: true`); 409
7
+ while the first runs, 422 for another request on the key, 400 for a missing or overlong key. The framework-free
8
+ `createIdempotency` (`begin`, `purge`), `fingerprint`, and the stores `memoryStore()`, `/pg` `pgStore` and
9
+ `/sqlite` `sqliteStore` on drizzle-orm.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nattapong Promthong
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,111 @@
1
- # Temporary Holding Version
1
+ # @20baht/elysia-idempotency
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
+ `Idempotency-Key` for Elysia routes. A client that sends a `POST` and loses the answer (a timeout, a dropped
4
+ connection, a phone going into a tunnel) sends it again with the same key, and gets the first answer back instead of
5
+ a second payment, a second ticket, a second transfer. It follows the IETF draft
6
+ [The Idempotency-Key HTTP Header Field](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/).
7
+
8
+ ```bash
9
+ bun add @20baht/elysia-idempotency
10
+ ```
11
+
12
+ ```ts
13
+ import { Elysia, t } from 'elysia';
14
+ import { idempotency } from '@20baht/elysia-idempotency';
15
+ import { idempotencyTable, pgStore } from '@20baht/elysia-idempotency/pg';
16
+
17
+ export const idempotencyKeys = idempotencyTable(); // in your drizzle schema: drizzle-kit makes the migration
18
+
19
+ new Elysia()
20
+ .use(resourceServer({ resource, authorizationServers }))
21
+ .use(idempotency({ store: pgStore({ db, table: idempotencyKeys }), scope: ({ caller }) => (caller as Caller).subject }))
22
+ .post('/transfers', ({ body }) => transfers.create(body), {
23
+ scope: 'transfers:write',
24
+ idempotent: true,
25
+ body: t.Object({ from: t.String(), to: t.String(), amount: t.Number() }),
26
+ });
27
+ ```
28
+
29
+ ## What a request gets
30
+
31
+ The route option is `idempotent: true` (a key is taken when one is sent) or `idempotent: 'required'` (a request
32
+ without one is refused).
33
+
34
+ | The request | The answer |
35
+ | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
36
+ | No `Idempotency-Key` | The handler runs, as without this package. With `'required'`: **400** `IDEMPOTENCY_KEY_MISSING` |
37
+ | A key longer than `maxKeyLength` (255) | **400** `IDEMPOTENCY_KEY_INVALID` |
38
+ | A new key | The handler runs; its answer is kept |
39
+ | The same key and the same request, after the first answered | The first answer again (status, `content-type`, `location`, body), with `Idempotent-Replayed: true`. The handler does not run |
40
+ | The same key, while the first is still running | **409** `IDEMPOTENCY_IN_PROGRESS`: retry a little later |
41
+ | The same key with a different request | **422** `IDEMPOTENCY_KEY_REUSED`: a client bug, not a retry |
42
+
43
+ A refusal's body is `{ code, message }`. "The same request" is the method, the path with its query, and the body:
44
+ a SHA-256 of them is kept, never the body itself.
45
+
46
+ - **A handler that throws, or answers 5xx, gives its key up**: nothing is kept, and a retry runs again. A 4xx it
47
+ returns on purpose (a 409 for a duplicate name) is kept and replayed like a 2xx.
48
+ - **A body that fails the route's schema reserves nothing**: Elysia refuses it before the key is read.
49
+ - **A streamed answer** (a generator, a `ReadableStream`) is not kept: a retry runs again. Return a value from a
50
+ route you mark `idempotent`.
51
+ - Only `content-type` and `location` are replayed (`replayHeaders` to choose); never a `set-cookie`.
52
+
53
+ ## Whose key
54
+
55
+ Keys are the client's own words, so two callers can pick the same one. Give `scope` the caller's identity and their
56
+ keys never meet:
57
+
58
+ ```ts
59
+ idempotency({ store, scope: ({ caller }) => (caller as Caller).subject });
60
+ ```
61
+
62
+ `scope` is handed the route's context after every `resolve` has run: the `caller` that `auth` / `scope` from
63
+ `@20baht/elysia-resource-server` resolve is there, whatever their order on the route. Without `scope`, every caller
64
+ shares one set of keys, and one who sends another's key and the same request gets the other's answer.
65
+
66
+ ## How long a key holds
67
+
68
+ - `ttl` (default 24 hours): how long an answer is replayed. After it, the key is free again.
69
+ - `pendingTimeout` (default 5 minutes): how long a key whose request has not answered holds. A process killed
70
+ mid-request never gives its key up; after this the key counts as free. A handler that runs longer than this can
71
+ run twice.
72
+ - Old rows are not deleted on their own. Run `createIdempotency({ store }).purge()` now and then (a cron, a
73
+ scheduled Worker): it deletes every key past `ttl`.
74
+
75
+ ## Stores
76
+
77
+ | Store | Import | Table |
78
+ | ----------------------------------------------------------------------- | ------------------------------------------- | ------------------------------- |
79
+ | Memory: tests, one process that may lose its keys on restart | `memoryStore()` | — |
80
+ | Postgres through drizzle-orm (node-postgres, postgres.js, PGlite, Neon) | `pgStore({ db, table })` from `/pg` | `idempotencyTable(name?)` |
81
+ | SQLite through drizzle-orm (Cloudflare D1, bun:sqlite, libsql) | `sqliteStore({ db, table })` from `/sqlite` | `sqliteIdempotencyTable(name?)` |
82
+
83
+ Each table is `key` (primary key), `fingerprint`, `status`, `response` (JSON) and `created_at` (indexed), named
84
+ `idempotency_keys` unless you name it. Every store call is one statement: a key is reserved by an insert on the
85
+ primary key, so of two requests racing with one key exactly one runs. `drizzle-orm` is an optional peer, needed only
86
+ for `/pg` and `/sqlite`.
87
+
88
+ Another database is the `IdempotencyStore` interface: `get`, `reserve` (insert if absent), `complete`, `remove` and
89
+ `purge`, five calls.
90
+
91
+ ## Without Elysia
92
+
93
+ The work is `createIdempotency`, which knows nothing of HTTP. An MCP tool, a queue consumer or another framework
94
+ uses it the same way:
95
+
96
+ ```ts
97
+ import { createIdempotency, fingerprint } from '@20baht/elysia-idempotency';
98
+
99
+ const keys = createIdempotency({ store });
100
+ const begun = await keys.begin({ key, scope: userId, fingerprint: await fingerprint('POST', '/transfers', body) });
101
+ if (begun.kind === 'replay') return begun.response; // { status, headers, body }
102
+ if (begun.kind === 'conflict') return begun.reason; // 'in-progress' | 'mismatch'
103
+ try {
104
+ const result = await transfers.create(body);
105
+ await begun.complete({ status: 201, headers: {}, body: JSON.stringify(result) });
106
+ return result;
107
+ } catch (error) {
108
+ await begun.abandon();
109
+ throw error;
110
+ }
111
+ ```
package/dist/core.d.ts ADDED
@@ -0,0 +1,95 @@
1
+ /** A response as it is kept, to be sent again for a retry. */
2
+ export interface StoredResponse {
3
+ status: number;
4
+ /** The headers worth sending again (`content-type`, `location`), lower case. */
5
+ headers: Record<string, string>;
6
+ /** The body as text, or base64 when `base64` is set (a body that is not text). */
7
+ body: string;
8
+ base64?: true;
9
+ }
10
+ /** A key as a store keeps it. */
11
+ export interface IdempotencyRecord {
12
+ key: string;
13
+ /** What the first request was: a retry with another one is refused. */
14
+ fingerprint: string;
15
+ status: 'pending' | 'completed';
16
+ /** With `completed`. */
17
+ response?: StoredResponse;
18
+ createdAt: Date;
19
+ }
20
+ /**
21
+ * Where keys are kept: `memoryStore()` for one process and tests, `pgStore` (`/pg`) and `sqliteStore`
22
+ * (`/sqlite`, D1 too) for drizzle. Each call is one statement; `reserve` must be atomic, which an
23
+ * insert on the primary key is.
24
+ */
25
+ export interface IdempotencyStore {
26
+ get(key: string): Promise<IdempotencyRecord | undefined>;
27
+ /** Insert a `pending` record; `false` when the key is there already. */
28
+ reserve(key: string, fingerprint: string, createdAt: Date): Promise<boolean>;
29
+ /** The response of the key reserved at `createdAt`: it is `completed`. A key reserved since is left alone. */
30
+ complete(key: string, createdAt: Date, response: StoredResponse): Promise<void>;
31
+ /** Delete the key, only if it is still the record made at `createdAt` (not one reserved since). */
32
+ remove(key: string, createdAt: Date): Promise<void>;
33
+ /** Delete every record made before `before`; how many went. */
34
+ purge(before: Date): Promise<number>;
35
+ }
36
+ export interface IdempotencyOptions {
37
+ store: IdempotencyStore;
38
+ /** How long a key's response is sent again, in milliseconds. Default 24 hours. */
39
+ ttl?: number;
40
+ /**
41
+ * How long a `pending` key holds before it counts as a request that died (a process killed mid-write
42
+ * never releases its key), in milliseconds. Default 5 minutes. A handler running longer than this can
43
+ * run twice.
44
+ */
45
+ pendingTimeout?: number;
46
+ /** The clock. */
47
+ now?: () => Date;
48
+ }
49
+ /** Why a request with a key does not run. */
50
+ export type IdempotencyConflict =
51
+ /** The first request with the key has not finished. Retry later. */
52
+ 'in-progress'
53
+ /** The key was used for a different request. A client bug, not a retry. */
54
+ | 'mismatch';
55
+ /** What a request with a key is to do. */
56
+ export type Begun = {
57
+ kind: 'run';
58
+ /** Keep the response, for a retry. */
59
+ complete(response: StoredResponse): Promise<void>;
60
+ /** Give the key up (the handler threw): a retry runs again. */
61
+ abandon(): Promise<void>;
62
+ } | {
63
+ kind: 'replay';
64
+ response: StoredResponse;
65
+ } | {
66
+ kind: 'conflict';
67
+ reason: IdempotencyConflict;
68
+ };
69
+ export interface BeginInput {
70
+ /** The client's key. */
71
+ key: string;
72
+ /**
73
+ * Whose key it is (a user, a client): two callers' keys never meet. Without one, a caller who sends
74
+ * another's key and the same request gets the other's response.
75
+ */
76
+ scope?: string | undefined;
77
+ /** What the request is: `fingerprint(method, path, body)`. */
78
+ fingerprint: string;
79
+ }
80
+ /** The key a store keeps: the scope's length first, so no scope and key run into another pair. */
81
+ export declare const storeKey: (scope: string | undefined, key: string) => string;
82
+ /** SHA-256 of the request: its method, its path with the query, and its body as JSON. */
83
+ export declare const fingerprint: (method: string, path: string, body: unknown) => Promise<string>;
84
+ /** Keys worked out against a store. */
85
+ export interface Idempotency {
86
+ begin(input: BeginInput): Promise<Begun>;
87
+ /** Delete the keys past `ttl`: for a job that runs now and then. How many went. */
88
+ purge(): Promise<number>;
89
+ }
90
+ export declare const createIdempotency: (options: IdempotencyOptions) => Idempotency;
91
+ /** Keys kept in this process's memory: for tests, and a single process that may lose them on restart. */
92
+ export declare const memoryStore: () => IdempotencyStore & {
93
+ readonly size: number;
94
+ };
95
+ //# sourceMappingURL=core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAKA,8DAA8D;AAC9D,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,gFAAgF;IAChF,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,IAAI,CAAC;CACf;AAED,iCAAiC;AACjC,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,uEAAuE;IACvE,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,SAAS,GAAG,WAAW,CAAC;IAChC,wBAAwB;IACxB,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,SAAS,EAAE,IAAI,CAAC;CACjB;AAED;;;;GAIG;AACH,M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EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,mBAAmB,CAAA;CAAE,CAAC;AAEtD,MAAM,WAAW,UAAU;IACzB,wBAAwB;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,8DAA8D;IAC9D,WAAW,EAAE,MAAM,CAAC;CACrB;AAID,kGAAkG;AAClG,eAAO,MAAM,QAAQ,GAAI,OAAO,MAAM,GAAG,SAAS,EAAE,KAAK,MAAM,KAAG,MACW,CAAC;AAK9E,yFAAyF;AACzF,eAAO,MAAM,WAAW,GAAU,QAAQ,MAAM,EAAE,MAAM,MAAM,EAAE,MAAM,OAAO,KAAG,OAAO,CAAC,MAAM,CAG7F,CAAC;AAEF,uCAAuC;AACvC,MAAM,WAAW,WAAW;IAC1B,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;IACzC,mFAAmF;IACnF,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1B;AAED,eAAO,MAAM,iBAAiB,GAAI,SAAS,kBAAkB,KAAG,WAqC/D,CAAC;AAEF,yGAAyG;AACzG,eAAO,MAAM,WAAW,QAAO,gBAAgB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CAkCxE,CAAC"}
@@ -0,0 +1,3 @@
1
+ export { createIdempotency, fingerprint, memoryStore, storeKey, type BeginInput, type Begun, type Idempotency, type IdempotencyConflict, type IdempotencyOptions, type IdempotencyRecord, type IdempotencyStore, type StoredResponse, } from './core.js';
2
+ export { idempotency, type IdempotencyError, type IdempotencyPluginOptions, type ScopeContext, } from './plugin.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,iBAAiB,EACjB,WAAW,EACX,WAAW,EACX,QAAQ,EACR,KAAK,UAAU,EACf,KAAK,KAAK,EACV,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,cAAc,GACpB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,WAAW,EACX,KAAK,gBAAgB,EACrB,KAAK,wBAAwB,EAC7B,KAAK,YAAY,GAClB,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,219 @@
1
+ // @bun
2
+ // src/core.ts
3
+ var HOUR = 3600000;
4
+ var storeKey = (scope, key) => scope === undefined ? `:${key}` : `${String(scope.length)}:${scope}:${key}`;
5
+ var hex = (bytes) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
6
+ var fingerprint = async (method, path, body) => {
7
+ const json = JSON.stringify([method.toUpperCase(), path, body ?? null]);
8
+ return hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(json)));
9
+ };
10
+ var createIdempotency = (options) => {
11
+ const { store } = options;
12
+ const ttl = options.ttl ?? 24 * HOUR;
13
+ const pendingTimeout = options.pendingTimeout ?? HOUR / 12;
14
+ const now = options.now ?? (() => new Date);
15
+ const lapsed = (record, at) => {
16
+ const age = at - record.createdAt.getTime();
17
+ return age >= ttl || record.status === "pending" && age >= pendingTimeout;
18
+ };
19
+ const begin = async ({ key, scope, fingerprint: fingerprint2 }) => {
20
+ const id = storeKey(scope, key);
21
+ const at = now();
22
+ const found = await store.get(id);
23
+ if (found && lapsed(found, at.getTime()))
24
+ await store.remove(id, found.createdAt);
25
+ else if (found) {
26
+ if (found.fingerprint !== fingerprint2)
27
+ return { kind: "conflict", reason: "mismatch" };
28
+ if (found.status === "completed" && found.response)
29
+ return { kind: "replay", response: found.response };
30
+ return { kind: "conflict", reason: "in-progress" };
31
+ }
32
+ if (!await store.reserve(id, fingerprint2, at))
33
+ return { kind: "conflict", reason: "in-progress" };
34
+ return {
35
+ kind: "run",
36
+ complete: (response) => store.complete(id, at, response),
37
+ abandon: () => store.remove(id, at)
38
+ };
39
+ };
40
+ return {
41
+ begin,
42
+ purge: () => store.purge(new Date(now().getTime() - ttl))
43
+ };
44
+ };
45
+ var memoryStore = () => {
46
+ const records = new Map;
47
+ const copy = (record) => structuredClone(record);
48
+ return {
49
+ get size() {
50
+ return records.size;
51
+ },
52
+ get: (key) => Promise.resolve(records.has(key) ? copy(records.get(key)) : undefined),
53
+ reserve: (key, fingerprint2, createdAt) => {
54
+ if (records.has(key))
55
+ return Promise.resolve(false);
56
+ records.set(key, { key, fingerprint: fingerprint2, status: "pending", createdAt: new Date(createdAt) });
57
+ return Promise.resolve(true);
58
+ },
59
+ complete: (key, createdAt, response) => {
60
+ const record = records.get(key);
61
+ if (record?.createdAt.getTime() === createdAt.getTime())
62
+ records.set(key, { ...record, status: "completed", response: structuredClone(response) });
63
+ return Promise.resolve();
64
+ },
65
+ remove: (key, createdAt) => {
66
+ if (records.get(key)?.createdAt.getTime() === createdAt.getTime())
67
+ records.delete(key);
68
+ return Promise.resolve();
69
+ },
70
+ purge: (before) => {
71
+ let n = 0;
72
+ for (const [key, record] of records)
73
+ if (record.createdAt.getTime() < before.getTime()) {
74
+ records.delete(key);
75
+ n++;
76
+ }
77
+ return Promise.resolve(n);
78
+ }
79
+ };
80
+ };
81
+ // src/plugin.ts
82
+ import { Elysia, ElysiaCustomStatusResponse } from "elysia";
83
+ var TEXT = /^(text\/|application\/([\w.+-]*\+)?(json|xml|javascript|x-www-form-urlencoded))/i;
84
+ var base64 = (bytes) => {
85
+ let binary = "";
86
+ for (const byte of bytes)
87
+ binary += String.fromCharCode(byte);
88
+ return btoa(binary);
89
+ };
90
+ var fromBase64 = (text) => Uint8Array.from(atob(text), (char) => char.charCodeAt(0));
91
+ var storedResponse = async (value, keep) => {
92
+ const headers = {};
93
+ for (const name of keep) {
94
+ const header = value.headers.get(name);
95
+ if (header !== null)
96
+ headers[name] = header;
97
+ }
98
+ const bytes = new Uint8Array(await value.clone().arrayBuffer());
99
+ return TEXT.test(headers["content-type"] ?? "text/plain") ? { status: value.status, headers, body: new TextDecoder().decode(bytes) } : { status: value.status, headers, body: base64(bytes), base64: true };
100
+ };
101
+ var storedBody = async (body, headers, typed) => {
102
+ if (body === undefined || body === null)
103
+ return { body: "" };
104
+ if (body instanceof Blob) {
105
+ if (typed && body.type)
106
+ headers["content-type"] ??= body.type;
107
+ return { body: base64(new Uint8Array(await body.arrayBuffer())), base64: true };
108
+ }
109
+ if (typeof body === "object") {
110
+ if (typed)
111
+ headers["content-type"] ??= "application/json;charset=utf-8";
112
+ return { body: JSON.stringify(body) };
113
+ }
114
+ if (typeof body === "number" || typeof body === "boolean" || typeof body === "bigint")
115
+ return { body: body.toString() };
116
+ return { body: typeof body === "string" ? body : "" };
117
+ };
118
+ var isStream = (body) => typeof body === "object" && body !== null && ((Symbol.asyncIterator in body) || body instanceof ReadableStream);
119
+ var stored = async (value, set, keep) => {
120
+ if (value instanceof Response)
121
+ return storedResponse(value, keep);
122
+ const custom = value instanceof ElysiaCustomStatusResponse;
123
+ const body = custom ? value.response : value;
124
+ if (isStream(body))
125
+ return;
126
+ const status = custom ? Number(value.code) : typeof set.status === "number" ? set.status : 200;
127
+ const headers = {};
128
+ for (const name of keep) {
129
+ const header = set.headers[name];
130
+ if (typeof header === "string")
131
+ headers[name] = header;
132
+ }
133
+ return { status, headers, ...await storedBody(body, headers, keep.includes("content-type")) };
134
+ };
135
+ var replay = (response) => {
136
+ const headers = new Headers(response.headers);
137
+ headers.set("idempotent-replayed", "true");
138
+ const body = response.base64 ? fromBase64(response.body) : response.body;
139
+ const empty = response.status === 204 || response.status === 304 || response.body === "" && !response.base64;
140
+ return new Response(empty ? null : body, { status: response.status, headers });
141
+ };
142
+ var refusal = (status, error) => Response.json(error, { status });
143
+ var idempotency = (options) => {
144
+ const keys = createIdempotency(options);
145
+ const header = (options.header ?? "idempotency-key").toLowerCase();
146
+ const maxKeyLength = options.maxKeyLength ?? 255;
147
+ const keep = (options.replayHeaders ?? ["content-type", "location"]).map((name) => name.toLowerCase());
148
+ const running = new WeakMap;
149
+ return new Elysia({ name: "@20baht/elysia-idempotency", seed: header }).macro({
150
+ idempotent: (mode) => ({
151
+ async beforeHandle(context) {
152
+ if (mode === false)
153
+ return;
154
+ const key = context.headers[header];
155
+ if (key === undefined || key === "") {
156
+ return mode === "required" ? refusal(400, {
157
+ code: "IDEMPOTENCY_KEY_MISSING",
158
+ message: `this request needs an ${header} header`
159
+ }) : undefined;
160
+ }
161
+ if (key.length > maxKeyLength)
162
+ return refusal(400, {
163
+ code: "IDEMPOTENCY_KEY_INVALID",
164
+ message: `an ${header} is at most ${String(maxKeyLength)} characters`
165
+ });
166
+ const url = new URL(context.request.url);
167
+ const scope = await options.scope?.(context);
168
+ const begun = await keys.begin({
169
+ key,
170
+ scope,
171
+ fingerprint: await fingerprint(context.request.method, url.pathname + url.search, context.body)
172
+ });
173
+ switch (begun.kind) {
174
+ case "run":
175
+ running.set(context.request, begun);
176
+ return;
177
+ case "replay":
178
+ return replay(begun.response);
179
+ case "conflict":
180
+ return begun.reason === "mismatch" ? refusal(422, {
181
+ code: "IDEMPOTENCY_KEY_REUSED",
182
+ message: `this ${header} was used for a different request`
183
+ }) : refusal(409, {
184
+ code: "IDEMPOTENCY_IN_PROGRESS",
185
+ message: `a request with this ${header} is still running`
186
+ });
187
+ }
188
+ },
189
+ async afterHandle({ request, responseValue, set }) {
190
+ const run = running.get(request);
191
+ if (!run)
192
+ return;
193
+ running.delete(request);
194
+ const response = await stored(responseValue, set, keep);
195
+ if (!response || response.status >= 500)
196
+ await run.abandon();
197
+ else
198
+ await run.complete(response);
199
+ },
200
+ async error({ request }) {
201
+ const run = running.get(request);
202
+ if (!run)
203
+ return;
204
+ running.delete(request);
205
+ await run.abandon();
206
+ }
207
+ })
208
+ });
209
+ };
210
+ export {
211
+ storeKey,
212
+ memoryStore,
213
+ idempotency,
214
+ fingerprint,
215
+ createIdempotency
216
+ };
217
+
218
+ //# debugId=139A5E8251FE9BAD64756E2164756E21
219
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/core.ts", "../src/plugin.ts"],
4
+ "sourcesContent": [
5
+ "// An `Idempotency-Key` (IETF draft-ietf-httpapi-idempotency-key-header) worked out without a web\n// framework: the first request with a key reserves it and runs; its response is kept; a retry with the\n// same key and the same request gets that response back instead of a second write. The same key with a\n// different request, or while the first is still running, is a conflict.\n\n/** A response as it is kept, to be sent again for a retry. */\nexport interface StoredResponse {\n status: number;\n /** The headers worth sending again (`content-type`, `location`), lower case. */\n headers: Record<string, string>;\n /** The body as text, or base64 when `base64` is set (a body that is not text). */\n body: string;\n base64?: true;\n}\n\n/** A key as a store keeps it. */\nexport interface IdempotencyRecord {\n key: string;\n /** What the first request was: a retry with another one is refused. */\n fingerprint: string;\n status: 'pending' | 'completed';\n /** With `completed`. */\n response?: StoredResponse;\n createdAt: Date;\n}\n\n/**\n * Where keys are kept: `memoryStore()` for one process and tests, `pgStore` (`/pg`) and `sqliteStore`\n * (`/sqlite`, D1 too) for drizzle. Each call is one statement; `reserve` must be atomic, which an\n * insert on the primary key is.\n */\nexport interface IdempotencyStore {\n get(key: string): Promise<IdempotencyRecord | undefined>;\n /** Insert a `pending` record; `false` when the key is there already. */\n reserve(key: string, fingerprint: string, createdAt: Date): Promise<boolean>;\n /** The response of the key reserved at `createdAt`: it is `completed`. A key reserved since is left alone. */\n complete(key: string, createdAt: Date, response: StoredResponse): Promise<void>;\n /** Delete the key, only if it is still the record made at `createdAt` (not one reserved since). */\n remove(key: string, createdAt: Date): Promise<void>;\n /** Delete every record made before `before`; how many went. */\n purge(before: Date): Promise<number>;\n}\n\nexport interface IdempotencyOptions {\n store: IdempotencyStore;\n /** How long a key's response is sent again, in milliseconds. Default 24 hours. */\n ttl?: number;\n /**\n * How long a `pending` key holds before it counts as a request that died (a process killed mid-write\n * never releases its key), in milliseconds. Default 5 minutes. A handler running longer than this can\n * run twice.\n */\n pendingTimeout?: number;\n /** The clock. */\n now?: () => Date;\n}\n\n/** Why a request with a key does not run. */\nexport type IdempotencyConflict =\n /** The first request with the key has not finished. Retry later. */\n | 'in-progress'\n /** The key was used for a different request. A client bug, not a retry. */\n | 'mismatch';\n\n/** What a request with a key is to do. */\nexport type Begun =\n | {\n kind: 'run';\n /** Keep the response, for a retry. */\n complete(response: StoredResponse): Promise<void>;\n /** Give the key up (the handler threw): a retry runs again. */\n abandon(): Promise<void>;\n }\n | { kind: 'replay'; response: StoredResponse }\n | { kind: 'conflict'; reason: IdempotencyConflict };\n\nexport interface BeginInput {\n /** The client's key. */\n key: string;\n /**\n * Whose key it is (a user, a client): two callers' keys never meet. Without one, a caller who sends\n * another's key and the same request gets the other's response.\n */\n scope?: string | undefined;\n /** What the request is: `fingerprint(method, path, body)`. */\n fingerprint: string;\n}\n\nconst HOUR = 3_600_000;\n\n/** The key a store keeps: the scope's length first, so no scope and key run into another pair. */\nexport const storeKey = (scope: string | undefined, key: string): string =>\n scope === undefined ? `:${key}` : `${String(scope.length)}:${scope}:${key}`;\n\nconst hex = (bytes: ArrayBuffer): string =>\n [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n\n/** SHA-256 of the request: its method, its path with the query, and its body as JSON. */\nexport const fingerprint = async (method: string, path: string, body: unknown): Promise<string> => {\n const json = JSON.stringify([method.toUpperCase(), path, body ?? null]);\n return hex(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(json)));\n};\n\n/** Keys worked out against a store. */\nexport interface Idempotency {\n begin(input: BeginInput): Promise<Begun>;\n /** Delete the keys past `ttl`: for a job that runs now and then. How many went. */\n purge(): Promise<number>;\n}\n\nexport const createIdempotency = (options: IdempotencyOptions): Idempotency => {\n const { store } = options;\n const ttl = options.ttl ?? 24 * HOUR;\n const pendingTimeout = options.pendingTimeout ?? HOUR / 12;\n const now = options.now ?? (() => new Date());\n\n /** A record that no longer counts: past `ttl`, or a pending one past `pendingTimeout`. */\n const lapsed = (record: IdempotencyRecord, at: number): boolean => {\n const age = at - record.createdAt.getTime();\n return age >= ttl || (record.status === 'pending' && age >= pendingTimeout);\n };\n\n const begin = async ({ key, scope, fingerprint }: BeginInput): Promise<Begun> => {\n const id = storeKey(scope, key);\n const at = now();\n const found = await store.get(id);\n if (found && lapsed(found, at.getTime())) await store.remove(id, found.createdAt);\n else if (found) {\n if (found.fingerprint !== fingerprint) return { kind: 'conflict', reason: 'mismatch' };\n if (found.status === 'completed' && found.response)\n return { kind: 'replay', response: found.response };\n return { kind: 'conflict', reason: 'in-progress' };\n }\n // two requests may both have found nothing: the insert lets one through\n if (!(await store.reserve(id, fingerprint, at)))\n return { kind: 'conflict', reason: 'in-progress' };\n return {\n kind: 'run',\n complete: (response) => store.complete(id, at, response),\n abandon: () => store.remove(id, at),\n };\n };\n\n return {\n begin,\n purge: () => store.purge(new Date(now().getTime() - ttl)),\n };\n};\n\n/** Keys kept in this process's memory: for tests, and a single process that may lose them on restart. */\nexport const memoryStore = (): IdempotencyStore & { readonly size: number } => {\n const records = new Map<string, IdempotencyRecord>();\n const copy = (record: IdempotencyRecord): IdempotencyRecord => structuredClone(record);\n return {\n get size() {\n return records.size;\n },\n get: (key) =>\n Promise.resolve(records.has(key) ? copy(records.get(key) as IdempotencyRecord) : undefined),\n reserve: (key, fingerprint, createdAt) => {\n if (records.has(key)) return Promise.resolve(false);\n records.set(key, { key, fingerprint, status: 'pending', createdAt: new Date(createdAt) });\n return Promise.resolve(true);\n },\n complete: (key, createdAt, response) => {\n const record = records.get(key);\n if (record?.createdAt.getTime() === createdAt.getTime())\n records.set(key, { ...record, status: 'completed', response: structuredClone(response) });\n return Promise.resolve();\n },\n remove: (key, createdAt) => {\n if (records.get(key)?.createdAt.getTime() === createdAt.getTime()) records.delete(key);\n return Promise.resolve();\n },\n purge: (before) => {\n let n = 0;\n for (const [key, record] of records)\n if (record.createdAt.getTime() < before.getTime()) {\n records.delete(key);\n n++;\n }\n return Promise.resolve(n);\n },\n };\n};\n",
6
+ "// `Idempotency-Key` on Elysia routes: the route option `idempotent` makes a route take the header.\n// The work is `createIdempotency`'s; this file reads the request and keeps the response.\nimport { Elysia, ElysiaCustomStatusResponse } from 'elysia';\nimport {\n createIdempotency,\n fingerprint,\n type Begun,\n type IdempotencyOptions,\n type StoredResponse,\n} from './core.ts';\n\n/** What `scope` is handed: the route's context, with whatever earlier plugins put on it (a `caller`). */\nexport type ScopeContext = Readonly<Record<string, unknown>> & {\n readonly request: Request;\n readonly headers: Readonly<Record<string, string | undefined>>;\n};\n\nexport interface IdempotencyPluginOptions extends IdempotencyOptions {\n /** The header the key comes in. Default `idempotency-key`. */\n header?: string;\n /** The longest key taken. Default 255. */\n maxKeyLength?: number;\n /**\n * Whose key it is: the signed-in caller (`({ caller }) => caller.subject`), so two callers' keys\n * never meet. It is handed the route's context after every `resolve` (an `auth` or `scope` option\n * included, whatever their order on the route). Without one, every caller shares one set of keys.\n */\n scope?: (context: ScopeContext) => string | undefined | Promise<string | undefined>;\n /** The response headers kept and sent again. Default `content-type` and `location`. */\n replayHeaders?: readonly string[];\n}\n\n/** The body of a refusal: a code to branch on, and a sentence. */\nexport interface IdempotencyError {\n code:\n | 'IDEMPOTENCY_KEY_MISSING'\n | 'IDEMPOTENCY_KEY_INVALID'\n | 'IDEMPOTENCY_KEY_REUSED'\n | 'IDEMPOTENCY_IN_PROGRESS';\n message: string;\n}\n\nconst TEXT = /^(text\\/|application\\/([\\w.+-]*\\+)?(json|xml|javascript|x-www-form-urlencoded))/i;\n\nconst base64 = (bytes: Uint8Array): string => {\n let binary = '';\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n};\n\nconst fromBase64 = (text: string): Uint8Array =>\n Uint8Array.from(atob(text), (char) => char.charCodeAt(0));\n\n/** A `Response` as it is kept: its body as text, or base64 when its type is not text. */\nconst storedResponse = async (\n value: Response,\n keep: readonly string[],\n): Promise<StoredResponse> => {\n const headers: Record<string, string> = {};\n for (const name of keep) {\n const header = value.headers.get(name);\n if (header !== null) headers[name] = header;\n }\n const bytes = new Uint8Array(await value.clone().arrayBuffer());\n return TEXT.test(headers['content-type'] ?? 'text/plain')\n ? { status: value.status, headers, body: new TextDecoder().decode(bytes) }\n : { status: value.status, headers, body: base64(bytes), base64: true };\n};\n\n/** A value's body, as Elysia sends it: an object as JSON, a Blob as its bytes, anything else as text. */\nconst storedBody = async (\n body: unknown,\n headers: Record<string, string>,\n typed: boolean,\n): Promise<Pick<StoredResponse, 'body' | 'base64'>> => {\n if (body === undefined || body === null) return { body: '' };\n if (body instanceof Blob) {\n if (typed && body.type) headers['content-type'] ??= body.type;\n return { body: base64(new Uint8Array(await body.arrayBuffer())), base64: true };\n }\n if (typeof body === 'object') {\n if (typed) headers['content-type'] ??= 'application/json;charset=utf-8';\n return { body: JSON.stringify(body) };\n }\n if (typeof body === 'number' || typeof body === 'boolean' || typeof body === 'bigint')\n return { body: body.toString() };\n return { body: typeof body === 'string' ? body : '' };\n};\n\nconst isStream = (body: unknown): boolean =>\n typeof body === 'object' &&\n body !== null &&\n (Symbol.asyncIterator in body || body instanceof ReadableStream);\n\n/** The parts of a response kept for a retry, as Elysia would have sent it; `undefined` for a stream. */\nconst stored = async (\n value: unknown,\n set: { status?: number | string; headers: Record<string, unknown> },\n keep: readonly string[],\n): Promise<StoredResponse | undefined> => {\n if (value instanceof Response) return storedResponse(value, keep);\n const custom = value instanceof ElysiaCustomStatusResponse;\n const body: unknown = custom ? value.response : value;\n if (isStream(body)) return undefined;\n const status = custom ? Number(value.code) : typeof set.status === 'number' ? set.status : 200;\n const headers: Record<string, string> = {};\n for (const name of keep) {\n const header = set.headers[name];\n if (typeof header === 'string') headers[name] = header;\n }\n return { status, headers, ...(await storedBody(body, headers, keep.includes('content-type'))) };\n};\n\nconst replay = (response: StoredResponse): Response => {\n const headers = new Headers(response.headers);\n headers.set('idempotent-replayed', 'true');\n const body = response.base64 ? fromBase64(response.body) : response.body;\n // a 204 or a 304 has no body at all, not an empty one\n const empty =\n response.status === 204 ||\n response.status === 304 ||\n (response.body === '' && !response.base64);\n return new Response(empty ? null : (body as BodyInit), { status: response.status, headers });\n};\n\nconst refusal = (status: number, error: IdempotencyError): Response =>\n Response.json(error, { status });\n\n/**\n * The route option `idempotent`: `true` takes an `Idempotency-Key` when one is sent, `'required'`\n * refuses a request without one (400). A retry with the same key and request gets the first response\n * again (`Idempotent-Replayed: true`); the same key with another request is a 422, and while the first\n * is running a 409. A handler that throws, or answers 5xx, gives its key up so a retry runs again.\n */\nexport const idempotency = (options: IdempotencyPluginOptions) => {\n const keys = createIdempotency(options);\n const header = (options.header ?? 'idempotency-key').toLowerCase();\n const maxKeyLength = options.maxKeyLength ?? 255;\n const keep = (options.replayHeaders ?? ['content-type', 'location']).map((name) =>\n name.toLowerCase(),\n );\n /** The run a request is part of, from `beforeHandle` to the response. */\n const running = new WeakMap<Request, Extract<Begun, { kind: 'run' }>>();\n\n return new Elysia({ name: '@20baht/elysia-idempotency', seed: header }).macro({\n idempotent: (mode: boolean | 'required') => ({\n async beforeHandle(context) {\n if (mode === false) return undefined;\n const key = context.headers[header];\n if (key === undefined || key === '') {\n return mode === 'required'\n ? refusal(400, {\n code: 'IDEMPOTENCY_KEY_MISSING',\n message: `this request needs an ${header} header`,\n })\n : undefined;\n }\n if (key.length > maxKeyLength)\n return refusal(400, {\n code: 'IDEMPOTENCY_KEY_INVALID',\n message: `an ${header} is at most ${String(maxKeyLength)} characters`,\n });\n const url = new URL(context.request.url);\n const scope = await options.scope?.(context);\n const begun = await keys.begin({\n key,\n scope,\n fingerprint: await fingerprint(\n context.request.method,\n url.pathname + url.search,\n context.body,\n ),\n });\n switch (begun.kind) {\n case 'run':\n running.set(context.request, begun);\n return undefined;\n case 'replay':\n return replay(begun.response);\n case 'conflict':\n return begun.reason === 'mismatch'\n ? refusal(422, {\n code: 'IDEMPOTENCY_KEY_REUSED',\n message: `this ${header} was used for a different request`,\n })\n : refusal(409, {\n code: 'IDEMPOTENCY_IN_PROGRESS',\n message: `a request with this ${header} is still running`,\n });\n }\n },\n async afterHandle({ request, responseValue, set }) {\n const run = running.get(request);\n if (!run) return;\n running.delete(request);\n const response = await stored(responseValue, set, keep);\n if (!response || response.status >= 500) await run.abandon();\n else await run.complete(response);\n },\n async error({ request }) {\n const run = running.get(request);\n if (!run) return;\n running.delete(request);\n await run.abandon();\n },\n }),\n });\n};\n"
7
+ ],
8
+ "mappings": ";;AAwFA,IAAM,OAAO;AAGN,IAAM,WAAW,CAAC,OAA2B,QAClD,UAAU,YAAY,IAAI,QAAQ,GAAG,OAAO,MAAM,MAAM,KAAK,SAAS;AAExE,IAAM,MAAM,CAAC,UACX,CAAC,GAAG,IAAI,WAAW,KAAK,CAAC,EAAE,IAAI,CAAC,SAAS,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE;AAG/E,IAAM,cAAc,OAAO,QAAgB,MAAc,SAAmC;AAAA,EACjG,MAAM,OAAO,KAAK,UAAU,CAAC,OAAO,YAAY,GAAG,MAAM,QAAQ,IAAI,CAAC;AAAA,EACtE,OAAO,IAAI,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,YAAY,EAAE,OAAO,IAAI,CAAC,CAAC;AAAA;AAU3E,IAAM,oBAAoB,CAAC,YAA6C;AAAA,EAC7E,QAAQ,UAAU;AAAA,EAClB,MAAM,MAAM,QAAQ,OAAO,KAAK;AAAA,EAChC,MAAM,iBAAiB,QAAQ,kBAAkB,OAAO;AAAA,EACxD,MAAM,MAAM,QAAQ,QAAQ,MAAM,IAAI;AAAA,EAGtC,MAAM,SAAS,CAAC,QAA2B,OAAwB;AAAA,IACjE,MAAM,MAAM,KAAK,OAAO,UAAU,QAAQ;AAAA,IAC1C,OAAO,OAAO,OAAQ,OAAO,WAAW,aAAa,OAAO;AAAA;AAAA,EAG9D,MAAM,QAAQ,SAAS,KAAK,OAAO,gCAA8C;AAAA,I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AAA;AAAA;AAAA,WAGL,YAAW,GAAG,SAAS,eAAe,OAAO;AAAA,QACjD,MAAM,MAAM,QAAQ,IAAI,OAAO;AAAA,QAC/B,IAAI,CAAC;AAAA,UAAK;AAAA,QACV,QAAQ,OAAO,OAAO;AAAA,QACtB,MAAM,WAAW,MAAM,OAAO,eAAe,KAAK,IAAI;AAAA,QACtD,IAAI,CAAC,YAAY,SAAS,UAAU;AAAA,UAAK,MAAM,IAAI,QAAQ;AAAA,QACtD;AAAA,gBAAM,IAAI,SAAS,QAAQ;AAAA;AAAA,WAE5B,MAAK,GAAG,WAAW;AAAA,QACvB,MAAM,MAAM,QAAQ,IAAI,OAAO;AAAA,QAC/B,IAAI,CAAC;AAAA,UAAK;AAAA,QACV,QAAQ,OAAO,OAAO;AAAA,QACtB,MAAM,IAAI,QAAQ;AAAA;AAAA,IAEtB;AAAA,EACF,CAAC;AAAA;",
9
+ "debugId": "139A5E8251FE9BAD64756E2164756E21",
10
+ "names": []
11
+ }
package/dist/pg.d.ts ADDED
@@ -0,0 +1,106 @@
1
+ import { type PgDatabase, type PgQueryResultHKT } from 'drizzle-orm/pg-core';
2
+ import type { IdempotencyStore, StoredResponse } from './core.js';
3
+ /** The table of keys, for the host's drizzle schema. */
4
+ export declare const idempotencyTable: (name?: string) => import("drizzle-orm/pg-core").PgTableWithColumns<{
5
+ name: string;
6
+ schema: undefined;
7
+ columns: {
8
+ key: import("drizzle-orm/pg-core").PgColumn<{
9
+ name: "key";
10
+ tableName: string;
11
+ dataType: "string";
12
+ columnType: "PgText";
13
+ data: string;
14
+ driverParam: string;
15
+ notNull: true;
16
+ hasDefault: false;
17
+ isPrimaryKey: true;
18
+ isAutoincrement: false;
19
+ hasRuntimeDefault: false;
20
+ enumValues: [string, ...string[]];
21
+ baseColumn: never;
22
+ identity: undefined;
23
+ generated: undefined;
24
+ }, {}, {}>;
25
+ fingerprint: import("drizzle-orm/pg-core").PgColumn<{
26
+ name: "fingerprint";
27
+ tableName: string;
28
+ dataType: "string";
29
+ columnType: "PgText";
30
+ data: string;
31
+ driverParam: string;
32
+ notNull: true;
33
+ hasDefault: false;
34
+ isPrimaryKey: false;
35
+ isAutoincrement: false;
36
+ hasRuntimeDefault: false;
37
+ enumValues: [string, ...string[]];
38
+ baseColumn: never;
39
+ identity: undefined;
40
+ generated: undefined;
41
+ }, {}, {}>;
42
+ status: import("drizzle-orm/pg-core").PgColumn<{
43
+ name: "status";
44
+ tableName: string;
45
+ dataType: "string";
46
+ columnType: "PgText";
47
+ data: "pending" | "completed";
48
+ driverParam: string;
49
+ notNull: true;
50
+ hasDefault: false;
51
+ isPrimaryKey: false;
52
+ isAutoincrement: false;
53
+ hasRuntimeDefault: false;
54
+ enumValues: ["pending", "completed"];
55
+ baseColumn: never;
56
+ identity: undefined;
57
+ generated: undefined;
58
+ }, {}, {}>;
59
+ response: import("drizzle-orm/pg-core").PgColumn<{
60
+ name: "response";
61
+ tableName: string;
62
+ dataType: "json";
63
+ columnType: "PgJsonb";
64
+ data: StoredResponse;
65
+ driverParam: unknown;
66
+ notNull: false;
67
+ hasDefault: false;
68
+ isPrimaryKey: false;
69
+ isAutoincrement: false;
70
+ hasRuntimeDefault: false;
71
+ enumValues: undefined;
72
+ baseColumn: never;
73
+ identity: undefined;
74
+ generated: undefined;
75
+ }, {}, {
76
+ $type: StoredResponse;
77
+ }>;
78
+ createdAt: import("drizzle-orm/pg-core").PgColumn<{
79
+ name: "created_at";
80
+ tableName: string;
81
+ dataType: "date";
82
+ columnType: "PgTimestamp";
83
+ data: Date;
84
+ driverParam: string;
85
+ notNull: true;
86
+ hasDefault: false;
87
+ isPrimaryKey: false;
88
+ isAutoincrement: false;
89
+ hasRuntimeDefault: false;
90
+ enumValues: undefined;
91
+ baseColumn: never;
92
+ identity: undefined;
93
+ generated: undefined;
94
+ }, {}, {}>;
95
+ };
96
+ dialect: "pg";
97
+ }>;
98
+ export type IdempotencyTable = ReturnType<typeof idempotencyTable>;
99
+ /** Any drizzle Postgres database (node-postgres, postgres.js, PGlite, Neon, …), whatever its schema. */
100
+ export type IdempotencyDatabase = PgDatabase<PgQueryResultHKT, any>;
101
+ /** The store on a drizzle Postgres database. */
102
+ export declare const pgStore: ({ db, table, }: {
103
+ db: IdempotencyDatabase;
104
+ table: IdempotencyTable;
105
+ }) => IdempotencyStore;
106
+ //# sourceMappingURL=pg.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pg.d.ts","sourceRoot":"","sources":["../src/pg.ts"],"names":[],"mappings":"AAGA,OAAO,EAML,KAAK,UAAU,EACf,KAAK,gBAAgB,EACtB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAqB,gBAAgB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAErF,wDAAwD;AACxD,eAAO,MAAM,gBAAgB,GAAI,aAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWvD,CAAC;AAEJ,MAAM,MAAM,gBAAgB,GAAG,UAAU,CAAC,OAAO,gBAAgB,CAAC,CAAC;AAEnE,wGAAwG;AAExG,MAAM,MAAM,mBAAmB,GAAG,UAAU,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;AAEpE,gDAAgD;AAChD,eAAO,MAAM,OAAO,GAAI,gBAGrB;IACD,EAAE,EAAE,mBAAmB,CAAC;IACxB,KAAK,EAAE,gBAAgB,CAAC;CACzB,KAAG,gBAqCF,CAAC"}