@detent/sdk 0.5.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 Cyril Guillerminet
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 ADDED
@@ -0,0 +1,46 @@
1
+ # @detent/sdk
2
+
3
+ [![CI](https://github.com/cguillerminet/detent-sdk-ts/actions/workflows/ci.yml/badge.svg)](https://github.com/cguillerminet/detent-sdk-ts/actions/workflows/ci.yml)
4
+
5
+ Typed TypeScript client for the [Detent](https://detent.dev) rate-limiting API.
6
+
7
+ > Status: pre-release (v0.5.0).
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm i @detent/sdk
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ```ts
18
+ import { Detent } from '@detent/sdk'
19
+
20
+ const rg = new Detent({ apiKey: process.env.DETENT_API_KEY! })
21
+
22
+ // Rate-limit check (always resolves; fails open by default on transport error)
23
+ const { allowed } = await rg.limit({ namespace: 'api', key: userId })
24
+ if (!allowed) return res.status(429).end()
25
+
26
+ // Concurrent-limit lease
27
+ await rg.withLease({ namespace: 'jobs', key: userId }, async () => {
28
+ await runExpensiveJob()
29
+ })
30
+
31
+ // Read-only usage stats
32
+ const stats = await rg.getStats({ namespace: 'api' })
33
+ ```
34
+
35
+ ### Configuration
36
+
37
+ | Option | Default | Notes |
38
+ |-------------|----------------------------|--------------------------------------------------|
39
+ | `apiKey` | — (required) | `rg_live_…` / `rg_test_…` |
40
+ | `baseUrl` | `https://api.detent.dev` | Override for self-host / tests |
41
+ | `timeoutMs` | `1000` | Client-side transport timeout |
42
+ | `failMode` | `'open'` | `'open'` allows, `'closed'` denies on transport error |
43
+ | `onError` | — | Called on transport errors and 5xx responses before fail-open/closed |
44
+
45
+ `limit()` never throws on a transport error or a 5xx server error — it returns `{ degraded: true }` and respects `failMode`.
46
+ Only 4xx client errors (bad key, plan gate, unknown rule, malformed request) throw `DetentApiError`.
package/dist/index.cjs ADDED
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Detent: () => Detent,
24
+ DetentApiError: () => DetentApiError,
25
+ DetentError: () => DetentError,
26
+ DetentLeaseDeniedError: () => DetentLeaseDeniedError,
27
+ DetentTransportError: () => DetentTransportError
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+
31
+ // src/errors.ts
32
+ var DetentError = class extends Error {
33
+ constructor(message) {
34
+ super(message);
35
+ this.name = "DetentError";
36
+ }
37
+ };
38
+ var DetentApiError = class extends DetentError {
39
+ status;
40
+ body;
41
+ constructor(status, body) {
42
+ super(`Detent API error ${status}: ${body.error}`);
43
+ this.name = "DetentApiError";
44
+ this.status = status;
45
+ this.body = body;
46
+ }
47
+ };
48
+ var DetentTransportError = class extends DetentError {
49
+ cause;
50
+ constructor(message, cause) {
51
+ super(message);
52
+ this.name = "DetentTransportError";
53
+ this.cause = cause;
54
+ }
55
+ };
56
+ var DetentLeaseDeniedError = class extends DetentError {
57
+ result;
58
+ constructor(result) {
59
+ super("Lease denied: no concurrent slot available");
60
+ this.name = "DetentLeaseDeniedError";
61
+ this.result = result;
62
+ }
63
+ };
64
+
65
+ // src/leases.ts
66
+ async function acquireLease(request, opts) {
67
+ const body = {
68
+ namespace: opts.namespace,
69
+ key: opts.key,
70
+ ...opts.limit !== void 0 ? { limit: opts.limit } : {},
71
+ ...opts.windowMs !== void 0 ? { window_ms: opts.windowMs } : {}
72
+ };
73
+ const w = await request("POST", "/v1/leases", body);
74
+ const result = {
75
+ allowed: w.allowed,
76
+ leaseId: w.lease_id ?? void 0,
77
+ active: w.active,
78
+ limit: w.limit,
79
+ resetMs: w.reset_ms,
80
+ release: async () => {
81
+ if (!w.allowed || !w.lease_id) return;
82
+ return releaseLease(request, w.lease_id);
83
+ }
84
+ };
85
+ return result;
86
+ }
87
+ async function releaseLease(request, leaseId) {
88
+ return request("DELETE", `/v1/leases/${encodeURIComponent(leaseId)}`);
89
+ }
90
+ async function withLease(request, opts, fn) {
91
+ const lease = await acquireLease(request, opts);
92
+ if (!lease.allowed) throw new DetentLeaseDeniedError(lease);
93
+ let threw = false;
94
+ try {
95
+ return await fn();
96
+ } catch (e) {
97
+ threw = true;
98
+ throw e;
99
+ } finally {
100
+ try {
101
+ await lease.release();
102
+ } catch (releaseErr) {
103
+ if (!threw) throw releaseErr;
104
+ }
105
+ }
106
+ }
107
+
108
+ // src/stats.ts
109
+ async function getStats(request, opts) {
110
+ const w = await request(
111
+ "GET",
112
+ `/v1/namespaces/${encodeURIComponent(opts.namespace)}/stats`
113
+ );
114
+ return {
115
+ namespace: w.namespace,
116
+ total: w.total,
117
+ blocked: w.blocked,
118
+ days: w.days.map((d) => ({ day: d.day, total: d.total, blocked: d.blocked })),
119
+ month: {
120
+ month: w.month.month,
121
+ total: w.month.total,
122
+ quota: w.month.quota ?? null,
123
+ overQuota: w.month.over_quota
124
+ }
125
+ };
126
+ }
127
+
128
+ // src/client.ts
129
+ var DEFAULT_BASE_URL = "https://api.detent.dev";
130
+ var DEFAULT_TIMEOUT_MS = 1e3;
131
+ var Detent = class {
132
+ apiKey;
133
+ baseUrl;
134
+ timeoutMs;
135
+ failMode;
136
+ onError;
137
+ constructor(config) {
138
+ if (!config?.apiKey) throw new Error("Detent: apiKey is required");
139
+ this.apiKey = config.apiKey;
140
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
141
+ this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
142
+ this.failMode = config.failMode ?? "open";
143
+ this.onError = config.onError;
144
+ }
145
+ /** Single HTTP choke point. 2xx → T; 4xx/5xx → DetentApiError; network/abort/body-stall → DetentTransportError. */
146
+ async request(method, path, body) {
147
+ const controller = new AbortController();
148
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
149
+ try {
150
+ const res = await fetch(`${this.baseUrl}${path}`, {
151
+ method,
152
+ headers: {
153
+ Authorization: `Bearer ${this.apiKey}`,
154
+ "Content-Type": "application/json"
155
+ },
156
+ body: body === void 0 ? void 0 : JSON.stringify(body),
157
+ signal: controller.signal
158
+ });
159
+ if (!res.ok) {
160
+ let parsed;
161
+ try {
162
+ parsed = await res.json();
163
+ } catch {
164
+ parsed = { error: res.statusText || `HTTP ${res.status}` };
165
+ }
166
+ throw new DetentApiError(res.status, parsed);
167
+ }
168
+ return await res.json();
169
+ } catch (cause) {
170
+ if (cause instanceof DetentApiError) throw cause;
171
+ throw new DetentTransportError("Detent request failed", cause);
172
+ } finally {
173
+ clearTimeout(timer);
174
+ }
175
+ }
176
+ acquire(opts) {
177
+ return acquireLease(this.request.bind(this), opts);
178
+ }
179
+ release(leaseId) {
180
+ return releaseLease(this.request.bind(this), leaseId);
181
+ }
182
+ withLease(opts, fn) {
183
+ return withLease(this.request.bind(this), opts, fn);
184
+ }
185
+ async limit(opts) {
186
+ const body = {
187
+ namespace: opts.namespace,
188
+ key: opts.key,
189
+ ...opts.algorithm !== void 0 ? { algorithm: opts.algorithm } : {},
190
+ ...opts.limit !== void 0 ? { limit: opts.limit } : {},
191
+ ...opts.windowMs !== void 0 ? { window_ms: opts.windowMs } : {}
192
+ };
193
+ try {
194
+ const w = await this.request(
195
+ "POST",
196
+ "/v1/limit",
197
+ body
198
+ );
199
+ return { allowed: w.allowed, remaining: w.remaining, resetMs: w.reset_ms, limit: w.limit, degraded: false };
200
+ } catch (err) {
201
+ if (err instanceof DetentTransportError || err instanceof DetentApiError && err.status >= 500) {
202
+ this.onError?.(err);
203
+ return { allowed: this.failMode === "open", remaining: 0, resetMs: 0, limit: opts.limit ?? 0, degraded: true };
204
+ }
205
+ throw err;
206
+ }
207
+ }
208
+ getStats(opts) {
209
+ return getStats(this.request.bind(this), opts);
210
+ }
211
+ };
212
+ // Annotate the CommonJS export names for ESM import in node:
213
+ 0 && (module.exports = {
214
+ Detent,
215
+ DetentApiError,
216
+ DetentError,
217
+ DetentLeaseDeniedError,
218
+ DetentTransportError
219
+ });
220
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/leases.ts","../src/stats.ts","../src/client.ts"],"sourcesContent":["export { Detent } from './client'\nexport * from './types'\nexport * from './errors'\n","import type { AcquireResult } from './types'\n\nexport class DetentError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DetentError'\n }\n}\n\nexport class DetentApiError extends DetentError {\n readonly status: number\n readonly body: { error: string }\n constructor(status: number, body: { error: string }) {\n super(`Detent API error ${status}: ${body.error}`)\n this.name = 'DetentApiError'\n this.status = status\n this.body = body\n }\n}\n\nexport class DetentTransportError extends DetentError {\n readonly cause: unknown\n constructor(message: string, cause: unknown) {\n super(message)\n this.name = 'DetentTransportError'\n this.cause = cause\n }\n}\n\nexport class DetentLeaseDeniedError extends DetentError {\n readonly result: AcquireResult\n constructor(result: AcquireResult) {\n super('Lease denied: no concurrent slot available')\n this.name = 'DetentLeaseDeniedError'\n this.result = result\n }\n}\n","import { DetentLeaseDeniedError } from './errors'\nimport type { AcquireOptions, AcquireResult, ReleaseResult } from './types'\nimport type { components } from './generated/openapi'\n\ntype Requester = <T>(method: string, path: string, body?: unknown) => Promise<T>\n\ntype AcquireWire = components['schemas']['AcquireResponse']\n\nexport async function acquireLease(request: Requester, opts: AcquireOptions): Promise<AcquireResult> {\n const body = {\n namespace: opts.namespace,\n key: opts.key,\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.windowMs !== undefined ? { window_ms: opts.windowMs } : {}),\n }\n const w = await request<AcquireWire>('POST', '/v1/leases', body)\n const result: AcquireResult = {\n allowed: w.allowed,\n leaseId: w.lease_id ?? undefined,\n active: w.active,\n limit: w.limit,\n resetMs: w.reset_ms,\n release: async () => {\n if (!w.allowed || !w.lease_id) return\n return releaseLease(request, w.lease_id)\n },\n }\n return result\n}\n\nexport async function releaseLease(request: Requester, leaseId: string): Promise<ReleaseResult> {\n return request<ReleaseResult>('DELETE', `/v1/leases/${encodeURIComponent(leaseId)}`)\n}\n\nexport async function withLease<T>(\n request: Requester,\n opts: AcquireOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const lease = await acquireLease(request, opts)\n if (!lease.allowed) throw new DetentLeaseDeniedError(lease)\n let threw = false\n try {\n return await fn()\n } catch (e) {\n threw = true\n throw e\n } finally {\n // Best-effort release. If fn already threw, don't let a release error mask it.\n try {\n await lease.release()\n } catch (releaseErr) {\n if (!threw) throw releaseErr\n }\n }\n}\n","import type { StatsOptions, StatsResult } from './types'\nimport type { components } from './generated/openapi'\n\ntype Requester = <T>(method: string, path: string, body?: unknown) => Promise<T>\n\ntype StatsWire = components['schemas']['StatsResponse']\n\nexport async function getStats(request: Requester, opts: StatsOptions): Promise<StatsResult> {\n const w = await request<StatsWire>(\n 'GET', `/v1/namespaces/${encodeURIComponent(opts.namespace)}/stats`,\n )\n return {\n namespace: w.namespace,\n total: w.total,\n blocked: w.blocked,\n days: w.days.map((d) => ({ day: d.day, total: d.total, blocked: d.blocked })),\n month: {\n month: w.month.month,\n total: w.month.total,\n quota: w.month.quota ?? null,\n overQuota: w.month.over_quota,\n },\n }\n}\n","import { DetentApiError, DetentTransportError } from './errors'\nimport { acquireLease, releaseLease, withLease } from './leases'\nimport { getStats } from './stats'\nimport type {\n DetentConfig, FailMode, LimitOptions, LimitResult,\n AcquireOptions, AcquireResult, ReleaseResult,\n StatsOptions, StatsResult,\n} from './types'\nimport type { components } from './generated/openapi'\n\nconst DEFAULT_BASE_URL = 'https://api.detent.dev'\nconst DEFAULT_TIMEOUT_MS = 1000\n\nexport class Detent {\n protected readonly apiKey: string\n protected readonly baseUrl: string\n protected readonly timeoutMs: number\n protected readonly failMode: FailMode\n protected readonly onError?: DetentConfig['onError']\n\n constructor(config: DetentConfig) {\n if (!config?.apiKey) throw new Error('Detent: apiKey is required')\n this.apiKey = config.apiKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS\n this.failMode = config.failMode ?? 'open'\n this.onError = config.onError\n }\n\n /** Single HTTP choke point. 2xx → T; 4xx/5xx → DetentApiError; network/abort/body-stall → DetentTransportError. */\n protected async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeoutMs)\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: controller.signal,\n })\n if (!res.ok) {\n let parsed: { error: string }\n try {\n parsed = (await res.json()) as { error: string }\n } catch {\n parsed = { error: res.statusText || `HTTP ${res.status}` }\n }\n throw new DetentApiError(res.status, parsed)\n }\n return (await res.json()) as T\n } catch (cause) {\n if (cause instanceof DetentApiError) throw cause\n throw new DetentTransportError('Detent request failed', cause)\n } finally {\n clearTimeout(timer)\n }\n }\n\n acquire(opts: AcquireOptions): Promise<AcquireResult> {\n return acquireLease(this.request.bind(this), opts)\n }\n\n release(leaseId: string): Promise<ReleaseResult> {\n return releaseLease(this.request.bind(this), leaseId)\n }\n\n withLease<T>(opts: AcquireOptions, fn: () => Promise<T>): Promise<T> {\n return withLease(this.request.bind(this), opts, fn)\n }\n\n async limit(opts: LimitOptions): Promise<LimitResult> {\n const body = {\n namespace: opts.namespace,\n key: opts.key,\n ...(opts.algorithm !== undefined ? { algorithm: opts.algorithm } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.windowMs !== undefined ? { window_ms: opts.windowMs } : {}),\n }\n try {\n const w = await this.request<components['schemas']['LimitResponse']>(\n 'POST', '/v1/limit', body,\n )\n return { allowed: w.allowed, remaining: w.remaining, resetMs: w.reset_ms, limit: w.limit, degraded: false }\n } catch (err) {\n if (err instanceof DetentTransportError || (err instanceof DetentApiError && err.status >= 500)) {\n this.onError?.(err)\n return { allowed: this.failMode === 'open', remaining: 0, resetMs: 0, limit: opts.limit ?? 0, degraded: true }\n }\n throw err // 4xx client errors and anything else\n }\n }\n\n getStats(opts: StatsOptions): Promise<StatsResult> {\n return getStats(this.request.bind(this), opts)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,iBAAN,cAA6B,YAAY;AAAA,EACrC;AAAA,EACA;AAAA,EACT,YAAY,QAAgB,MAAyB;AACnD,UAAM,oBAAoB,MAAM,KAAK,KAAK,KAAK,EAAE;AACjD,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,uBAAN,cAAmC,YAAY;AAAA,EAC3C;AAAA,EACT,YAAY,SAAiB,OAAgB;AAC3C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ;AAAA,EACf;AACF;AAEO,IAAM,yBAAN,cAAqC,YAAY;AAAA,EAC7C;AAAA,EACT,YAAY,QAAuB;AACjC,UAAM,4CAA4C;AAClD,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;;;AC5BA,eAAsB,aAAa,SAAoB,MAA8C;AACnG,QAAM,OAAO;AAAA,IACX,WAAW,KAAK;AAAA,IAChB,KAAK,KAAK;AAAA,IACV,GAAI,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,IACxD,GAAI,KAAK,aAAa,SAAY,EAAE,WAAW,KAAK,SAAS,IAAI,CAAC;AAAA,EACpE;AACA,QAAM,IAAI,MAAM,QAAqB,QAAQ,cAAc,IAAI;AAC/D,QAAM,SAAwB;AAAA,IAC5B,SAAS,EAAE;AAAA,IACX,SAAS,EAAE,YAAY;AAAA,IACvB,QAAQ,EAAE;AAAA,IACV,OAAO,EA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,EAEA,QAAQ,SAAyC;AAC/C,WAAO,aAAa,KAAK,QAAQ,KAAK,IAAI,GAAG,OAAO;AAAA,EACtD;AAAA,EAEA,UAAa,MAAsB,IAAkC;AACnE,WAAO,UAAU,KAAK,QAAQ,KAAK,IAAI,GAAG,MAAM,EAAE;AAAA,EACpD;AAAA,EAEA,MAAM,MAAM,MAA0C;AACpD,UAAM,OAAO;AAAA,MACX,WAAW,KAAK;AAAA,MAChB,KAAK,KAAK;AAAA,MACV,GAAI,KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,MACpE,GAAI,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,MACxD,GAAI,KAAK,aAAa,SAAY,EAAE,WAAW,KAAK,SAAS,IAAI,CAAC;AAAA,IACpE;AACA,QAAI;AACF,YAAM,IAAI,MAAM,KAAK;AAAA,QACnB;AAAA,QAAQ;AAAA,QAAa;AAAA,MACvB;AACA,aAAO,EAAE,SAAS,EAAE,SAAS,WAAW,EAAE,WAAW,SAAS,EAAE,UAAU,OAAO,EAAE,OAAO,UAAU,MAAM;AAAA,IAC5G,SAAS,KAAK;AACZ,UAAI,eAAe,wBAAyB,eAAe,kBAAkB,IAAI,UAAU,KAAM;AAC/F,aAAK,UAAU,GAAG;AAClB,eAAO,EAAE,SAAS,KAAK,aAAa,QAAQ,WAAW,GAAG,SAAS,GAAG,OAAO,KAAK,SAAS,GAAG,UAAU,KAAK;AAAA,MAC/G;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,SAAS,MAA0C;AACjD,WAAO,SAAS,KAAK,QAAQ,KAAK,IAAI,GAAG,IAAI;AAAA,EAC/C;AACF;","names":[]}
@@ -0,0 +1,103 @@
1
+ declare class DetentError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ declare class DetentApiError extends DetentError {
5
+ readonly status: number;
6
+ readonly body: {
7
+ error: string;
8
+ };
9
+ constructor(status: number, body: {
10
+ error: string;
11
+ });
12
+ }
13
+ declare class DetentTransportError extends DetentError {
14
+ readonly cause: unknown;
15
+ constructor(message: string, cause: unknown);
16
+ }
17
+ declare class DetentLeaseDeniedError extends DetentError {
18
+ readonly result: AcquireResult;
19
+ constructor(result: AcquireResult);
20
+ }
21
+
22
+ type Algorithm = 'sliding_window' | 'token_bucket' | 'fixed_window';
23
+ type FailMode = 'open' | 'closed';
24
+ interface DetentConfig {
25
+ apiKey: string;
26
+ baseUrl?: string;
27
+ timeoutMs?: number;
28
+ failMode?: FailMode;
29
+ onError?: (err: DetentError) => void;
30
+ }
31
+ interface LimitOptions {
32
+ namespace: string;
33
+ key: string;
34
+ algorithm?: Algorithm;
35
+ limit?: number;
36
+ windowMs?: number;
37
+ }
38
+ interface LimitResult {
39
+ allowed: boolean;
40
+ remaining: number;
41
+ resetMs: number;
42
+ limit: number;
43
+ /** true when this is a fail-open/fail-closed result, not a real decision. */
44
+ degraded: boolean;
45
+ }
46
+ interface AcquireOptions {
47
+ namespace: string;
48
+ key: string;
49
+ limit?: number;
50
+ windowMs?: number;
51
+ }
52
+ interface AcquireResult {
53
+ allowed: boolean;
54
+ leaseId?: string;
55
+ active: number;
56
+ limit: number;
57
+ resetMs: number;
58
+ /** Release this lease; a no-op when `allowed` is false. */
59
+ release(): Promise<ReleaseResult | void>;
60
+ }
61
+ interface ReleaseResult {
62
+ released: boolean;
63
+ active: number;
64
+ }
65
+ interface StatsOptions {
66
+ namespace: string;
67
+ }
68
+ interface DayStat {
69
+ day: string;
70
+ total: number;
71
+ blocked: number;
72
+ }
73
+ interface MonthSummary {
74
+ month: string;
75
+ total: number;
76
+ quota: number | null;
77
+ overQuota: boolean;
78
+ }
79
+ interface StatsResult {
80
+ namespace: string;
81
+ total: number;
82
+ blocked: number;
83
+ days: DayStat[];
84
+ month: MonthSummary;
85
+ }
86
+
87
+ declare class Detent {
88
+ protected readonly apiKey: string;
89
+ protected readonly baseUrl: string;
90
+ protected readonly timeoutMs: number;
91
+ protected readonly failMode: FailMode;
92
+ protected readonly onError?: DetentConfig['onError'];
93
+ constructor(config: DetentConfig);
94
+ /** Single HTTP choke point. 2xx → T; 4xx/5xx → DetentApiError; network/abort/body-stall → DetentTransportError. */
95
+ protected request<T>(method: string, path: string, body?: unknown): Promise<T>;
96
+ acquire(opts: AcquireOptions): Promise<AcquireResult>;
97
+ release(leaseId: string): Promise<ReleaseResult>;
98
+ withLease<T>(opts: AcquireOptions, fn: () => Promise<T>): Promise<T>;
99
+ limit(opts: LimitOptions): Promise<LimitResult>;
100
+ getStats(opts: StatsOptions): Promise<StatsResult>;
101
+ }
102
+
103
+ export { type AcquireOptions, type AcquireResult, type Algorithm, type DayStat, Detent, DetentApiError, type DetentConfig, DetentError, DetentLeaseDeniedError, DetentTransportError, type FailMode, type LimitOptions, type LimitResult, type MonthSummary, type ReleaseResult, type StatsOptions, type StatsResult };
@@ -0,0 +1,103 @@
1
+ declare class DetentError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ declare class DetentApiError extends DetentError {
5
+ readonly status: number;
6
+ readonly body: {
7
+ error: string;
8
+ };
9
+ constructor(status: number, body: {
10
+ error: string;
11
+ });
12
+ }
13
+ declare class DetentTransportError extends DetentError {
14
+ readonly cause: unknown;
15
+ constructor(message: string, cause: unknown);
16
+ }
17
+ declare class DetentLeaseDeniedError extends DetentError {
18
+ readonly result: AcquireResult;
19
+ constructor(result: AcquireResult);
20
+ }
21
+
22
+ type Algorithm = 'sliding_window' | 'token_bucket' | 'fixed_window';
23
+ type FailMode = 'open' | 'closed';
24
+ interface DetentConfig {
25
+ apiKey: string;
26
+ baseUrl?: string;
27
+ timeoutMs?: number;
28
+ failMode?: FailMode;
29
+ onError?: (err: DetentError) => void;
30
+ }
31
+ interface LimitOptions {
32
+ namespace: string;
33
+ key: string;
34
+ algorithm?: Algorithm;
35
+ limit?: number;
36
+ windowMs?: number;
37
+ }
38
+ interface LimitResult {
39
+ allowed: boolean;
40
+ remaining: number;
41
+ resetMs: number;
42
+ limit: number;
43
+ /** true when this is a fail-open/fail-closed result, not a real decision. */
44
+ degraded: boolean;
45
+ }
46
+ interface AcquireOptions {
47
+ namespace: string;
48
+ key: string;
49
+ limit?: number;
50
+ windowMs?: number;
51
+ }
52
+ interface AcquireResult {
53
+ allowed: boolean;
54
+ leaseId?: string;
55
+ active: number;
56
+ limit: number;
57
+ resetMs: number;
58
+ /** Release this lease; a no-op when `allowed` is false. */
59
+ release(): Promise<ReleaseResult | void>;
60
+ }
61
+ interface ReleaseResult {
62
+ released: boolean;
63
+ active: number;
64
+ }
65
+ interface StatsOptions {
66
+ namespace: string;
67
+ }
68
+ interface DayStat {
69
+ day: string;
70
+ total: number;
71
+ blocked: number;
72
+ }
73
+ interface MonthSummary {
74
+ month: string;
75
+ total: number;
76
+ quota: number | null;
77
+ overQuota: boolean;
78
+ }
79
+ interface StatsResult {
80
+ namespace: string;
81
+ total: number;
82
+ blocked: number;
83
+ days: DayStat[];
84
+ month: MonthSummary;
85
+ }
86
+
87
+ declare class Detent {
88
+ protected readonly apiKey: string;
89
+ protected readonly baseUrl: string;
90
+ protected readonly timeoutMs: number;
91
+ protected readonly failMode: FailMode;
92
+ protected readonly onError?: DetentConfig['onError'];
93
+ constructor(config: DetentConfig);
94
+ /** Single HTTP choke point. 2xx → T; 4xx/5xx → DetentApiError; network/abort/body-stall → DetentTransportError. */
95
+ protected request<T>(method: string, path: string, body?: unknown): Promise<T>;
96
+ acquire(opts: AcquireOptions): Promise<AcquireResult>;
97
+ release(leaseId: string): Promise<ReleaseResult>;
98
+ withLease<T>(opts: AcquireOptions, fn: () => Promise<T>): Promise<T>;
99
+ limit(opts: LimitOptions): Promise<LimitResult>;
100
+ getStats(opts: StatsOptions): Promise<StatsResult>;
101
+ }
102
+
103
+ export { type AcquireOptions, type AcquireResult, type Algorithm, type DayStat, Detent, DetentApiError, type DetentConfig, DetentError, DetentLeaseDeniedError, DetentTransportError, type FailMode, type LimitOptions, type LimitResult, type MonthSummary, type ReleaseResult, type StatsOptions, type StatsResult };
package/dist/index.js ADDED
@@ -0,0 +1,189 @@
1
+ // src/errors.ts
2
+ var DetentError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "DetentError";
6
+ }
7
+ };
8
+ var DetentApiError = class extends DetentError {
9
+ status;
10
+ body;
11
+ constructor(status, body) {
12
+ super(`Detent API error ${status}: ${body.error}`);
13
+ this.name = "DetentApiError";
14
+ this.status = status;
15
+ this.body = body;
16
+ }
17
+ };
18
+ var DetentTransportError = class extends DetentError {
19
+ cause;
20
+ constructor(message, cause) {
21
+ super(message);
22
+ this.name = "DetentTransportError";
23
+ this.cause = cause;
24
+ }
25
+ };
26
+ var DetentLeaseDeniedError = class extends DetentError {
27
+ result;
28
+ constructor(result) {
29
+ super("Lease denied: no concurrent slot available");
30
+ this.name = "DetentLeaseDeniedError";
31
+ this.result = result;
32
+ }
33
+ };
34
+
35
+ // src/leases.ts
36
+ async function acquireLease(request, opts) {
37
+ const body = {
38
+ namespace: opts.namespace,
39
+ key: opts.key,
40
+ ...opts.limit !== void 0 ? { limit: opts.limit } : {},
41
+ ...opts.windowMs !== void 0 ? { window_ms: opts.windowMs } : {}
42
+ };
43
+ const w = await request("POST", "/v1/leases", body);
44
+ const result = {
45
+ allowed: w.allowed,
46
+ leaseId: w.lease_id ?? void 0,
47
+ active: w.active,
48
+ limit: w.limit,
49
+ resetMs: w.reset_ms,
50
+ release: async () => {
51
+ if (!w.allowed || !w.lease_id) return;
52
+ return releaseLease(request, w.lease_id);
53
+ }
54
+ };
55
+ return result;
56
+ }
57
+ async function releaseLease(request, leaseId) {
58
+ return request("DELETE", `/v1/leases/${encodeURIComponent(leaseId)}`);
59
+ }
60
+ async function withLease(request, opts, fn) {
61
+ const lease = await acquireLease(request, opts);
62
+ if (!lease.allowed) throw new DetentLeaseDeniedError(lease);
63
+ let threw = false;
64
+ try {
65
+ return await fn();
66
+ } catch (e) {
67
+ threw = true;
68
+ throw e;
69
+ } finally {
70
+ try {
71
+ await lease.release();
72
+ } catch (releaseErr) {
73
+ if (!threw) throw releaseErr;
74
+ }
75
+ }
76
+ }
77
+
78
+ // src/stats.ts
79
+ async function getStats(request, opts) {
80
+ const w = await request(
81
+ "GET",
82
+ `/v1/namespaces/${encodeURIComponent(opts.namespace)}/stats`
83
+ );
84
+ return {
85
+ namespace: w.namespace,
86
+ total: w.total,
87
+ blocked: w.blocked,
88
+ days: w.days.map((d) => ({ day: d.day, total: d.total, blocked: d.blocked })),
89
+ month: {
90
+ month: w.month.month,
91
+ total: w.month.total,
92
+ quota: w.month.quota ?? null,
93
+ overQuota: w.month.over_quota
94
+ }
95
+ };
96
+ }
97
+
98
+ // src/client.ts
99
+ var DEFAULT_BASE_URL = "https://api.detent.dev";
100
+ var DEFAULT_TIMEOUT_MS = 1e3;
101
+ var Detent = class {
102
+ apiKey;
103
+ baseUrl;
104
+ timeoutMs;
105
+ failMode;
106
+ onError;
107
+ constructor(config) {
108
+ if (!config?.apiKey) throw new Error("Detent: apiKey is required");
109
+ this.apiKey = config.apiKey;
110
+ this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
111
+ this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
112
+ this.failMode = config.failMode ?? "open";
113
+ this.onError = config.onError;
114
+ }
115
+ /** Single HTTP choke point. 2xx → T; 4xx/5xx → DetentApiError; network/abort/body-stall → DetentTransportError. */
116
+ async request(method, path, body) {
117
+ const controller = new AbortController();
118
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
119
+ try {
120
+ const res = await fetch(`${this.baseUrl}${path}`, {
121
+ method,
122
+ headers: {
123
+ Authorization: `Bearer ${this.apiKey}`,
124
+ "Content-Type": "application/json"
125
+ },
126
+ body: body === void 0 ? void 0 : JSON.stringify(body),
127
+ signal: controller.signal
128
+ });
129
+ if (!res.ok) {
130
+ let parsed;
131
+ try {
132
+ parsed = await res.json();
133
+ } catch {
134
+ parsed = { error: res.statusText || `HTTP ${res.status}` };
135
+ }
136
+ throw new DetentApiError(res.status, parsed);
137
+ }
138
+ return await res.json();
139
+ } catch (cause) {
140
+ if (cause instanceof DetentApiError) throw cause;
141
+ throw new DetentTransportError("Detent request failed", cause);
142
+ } finally {
143
+ clearTimeout(timer);
144
+ }
145
+ }
146
+ acquire(opts) {
147
+ return acquireLease(this.request.bind(this), opts);
148
+ }
149
+ release(leaseId) {
150
+ return releaseLease(this.request.bind(this), leaseId);
151
+ }
152
+ withLease(opts, fn) {
153
+ return withLease(this.request.bind(this), opts, fn);
154
+ }
155
+ async limit(opts) {
156
+ const body = {
157
+ namespace: opts.namespace,
158
+ key: opts.key,
159
+ ...opts.algorithm !== void 0 ? { algorithm: opts.algorithm } : {},
160
+ ...opts.limit !== void 0 ? { limit: opts.limit } : {},
161
+ ...opts.windowMs !== void 0 ? { window_ms: opts.windowMs } : {}
162
+ };
163
+ try {
164
+ const w = await this.request(
165
+ "POST",
166
+ "/v1/limit",
167
+ body
168
+ );
169
+ return { allowed: w.allowed, remaining: w.remaining, resetMs: w.reset_ms, limit: w.limit, degraded: false };
170
+ } catch (err) {
171
+ if (err instanceof DetentTransportError || err instanceof DetentApiError && err.status >= 500) {
172
+ this.onError?.(err);
173
+ return { allowed: this.failMode === "open", remaining: 0, resetMs: 0, limit: opts.limit ?? 0, degraded: true };
174
+ }
175
+ throw err;
176
+ }
177
+ }
178
+ getStats(opts) {
179
+ return getStats(this.request.bind(this), opts);
180
+ }
181
+ };
182
+ export {
183
+ Detent,
184
+ DetentApiError,
185
+ DetentError,
186
+ DetentLeaseDeniedError,
187
+ DetentTransportError
188
+ };
189
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/leases.ts","../src/stats.ts","../src/client.ts"],"sourcesContent":["import type { AcquireResult } from './types'\n\nexport class DetentError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DetentError'\n }\n}\n\nexport class DetentApiError extends DetentError {\n readonly status: number\n readonly body: { error: string }\n constructor(status: number, body: { error: string }) {\n super(`Detent API error ${status}: ${body.error}`)\n this.name = 'DetentApiError'\n this.status = status\n this.body = body\n }\n}\n\nexport class DetentTransportError extends DetentError {\n readonly cause: unknown\n constructor(message: string, cause: unknown) {\n super(message)\n this.name = 'DetentTransportError'\n this.cause = cause\n }\n}\n\nexport class DetentLeaseDeniedError extends DetentError {\n readonly result: AcquireResult\n constructor(result: AcquireResult) {\n super('Lease denied: no concurrent slot available')\n this.name = 'DetentLeaseDeniedError'\n this.result = result\n }\n}\n","import { DetentLeaseDeniedError } from './errors'\nimport type { AcquireOptions, AcquireResult, ReleaseResult } from './types'\nimport type { components } from './generated/openapi'\n\ntype Requester = <T>(method: string, path: string, body?: unknown) => Promise<T>\n\ntype AcquireWire = components['schemas']['AcquireResponse']\n\nexport async function acquireLease(request: Requester, opts: AcquireOptions): Promise<AcquireResult> {\n const body = {\n namespace: opts.namespace,\n key: opts.key,\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.windowMs !== undefined ? { window_ms: opts.windowMs } : {}),\n }\n const w = await request<AcquireWire>('POST', '/v1/leases', body)\n const result: AcquireResult = {\n allowed: w.allowed,\n leaseId: w.lease_id ?? undefined,\n active: w.active,\n limit: w.limit,\n resetMs: w.reset_ms,\n release: async () => {\n if (!w.allowed || !w.lease_id) return\n return releaseLease(request, w.lease_id)\n },\n }\n return result\n}\n\nexport async function releaseLease(request: Requester, leaseId: string): Promise<ReleaseResult> {\n return request<ReleaseResult>('DELETE', `/v1/leases/${encodeURIComponent(leaseId)}`)\n}\n\nexport async function withLease<T>(\n request: Requester,\n opts: AcquireOptions,\n fn: () => Promise<T>,\n): Promise<T> {\n const lease = await acquireLease(request, opts)\n if (!lease.allowed) throw new DetentLeaseDeniedError(lease)\n let threw = false\n try {\n return await fn()\n } catch (e) {\n threw = true\n throw e\n } finally {\n // Best-effort release. If fn already threw, don't let a release error mask it.\n try {\n await lease.release()\n } catch (releaseErr) {\n if (!threw) throw releaseErr\n }\n }\n}\n","import type { StatsOptions, StatsResult } from './types'\nimport type { components } from './generated/openapi'\n\ntype Requester = <T>(method: string, path: string, body?: unknown) => Promise<T>\n\ntype StatsWire = components['schemas']['StatsResponse']\n\nexport async function getStats(request: Requester, opts: StatsOptions): Promise<StatsResult> {\n const w = await request<StatsWire>(\n 'GET', `/v1/namespaces/${encodeURIComponent(opts.namespace)}/stats`,\n )\n return {\n namespace: w.namespace,\n total: w.total,\n blocked: w.blocked,\n days: w.days.map((d) => ({ day: d.day, total: d.total, blocked: d.blocked })),\n month: {\n month: w.month.month,\n total: w.month.total,\n quota: w.month.quota ?? null,\n overQuota: w.month.over_quota,\n },\n }\n}\n","import { DetentApiError, DetentTransportError } from './errors'\nimport { acquireLease, releaseLease, withLease } from './leases'\nimport { getStats } from './stats'\nimport type {\n DetentConfig, FailMode, LimitOptions, LimitResult,\n AcquireOptions, AcquireResult, ReleaseResult,\n StatsOptions, StatsResult,\n} from './types'\nimport type { components } from './generated/openapi'\n\nconst DEFAULT_BASE_URL = 'https://api.detent.dev'\nconst DEFAULT_TIMEOUT_MS = 1000\n\nexport class Detent {\n protected readonly apiKey: string\n protected readonly baseUrl: string\n protected readonly timeoutMs: number\n protected readonly failMode: FailMode\n protected readonly onError?: DetentConfig['onError']\n\n constructor(config: DetentConfig) {\n if (!config?.apiKey) throw new Error('Detent: apiKey is required')\n this.apiKey = config.apiKey\n this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, '')\n this.timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS\n this.failMode = config.failMode ?? 'open'\n this.onError = config.onError\n }\n\n /** Single HTTP choke point. 2xx → T; 4xx/5xx → DetentApiError; network/abort/body-stall → DetentTransportError. */\n protected async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeoutMs)\n try {\n const res = await fetch(`${this.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: controller.signal,\n })\n if (!res.ok) {\n let parsed: { error: string }\n try {\n parsed = (await res.json()) as { error: string }\n } catch {\n parsed = { error: res.statusText || `HTTP ${res.status}` }\n }\n throw new DetentApiError(res.status, parsed)\n }\n return (await res.json()) as T\n } catch (cause) {\n if (cause instanceof DetentApiError) throw cause\n throw new DetentTransportError('Detent request failed', cause)\n } finally {\n clearTimeout(timer)\n }\n }\n\n acquire(opts: AcquireOptions): Promise<AcquireResult> {\n return acquireLease(this.request.bind(this), opts)\n }\n\n release(leaseId: string): Promise<ReleaseResult> {\n return releaseLease(this.request.bind(this), leaseId)\n }\n\n withLease<T>(opts: AcquireOptions, fn: () => Promise<T>): Promise<T> {\n return withLease(this.request.bind(this), opts, fn)\n }\n\n async limit(opts: LimitOptions): Promise<LimitResult> {\n const body = {\n namespace: opts.namespace,\n key: opts.key,\n ...(opts.algorithm !== undefined ? { algorithm: opts.algorithm } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.windowMs !== undefined ? { window_ms: opts.windowMs } : {}),\n }\n try {\n const w = await this.request<components['schemas']['LimitResponse']>(\n 'POST', '/v1/limit', body,\n )\n return { allowed: w.allowed, remaining: w.remaining, resetMs: w.reset_ms, limit: w.limit, degraded: false }\n } catch (err) {\n if (err instanceof DetentTransportError || (err instanceof DetentApiError && err.status >= 500)) {\n this.onError?.(err)\n return { allowed: this.failMode === 'open', remaining: 0, resetMs: 0, limit: opts.limit ?? 0, degraded: true }\n }\n throw err // 4xx client errors and anything else\n }\n }\n\n getStats(opts: StatsOptions): Promise<StatsResult> {\n return getStats(this.request.bind(this), opts)\n }\n}\n"],"mappings":";AAEO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,i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AAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;AAAA,MACpE,GAAI,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,MACxD,GAAI,KAAK,aAAa,SAAY,EAAE,WAAW,KAAK,SAAS,IAAI,CAAC;AAAA,IACpE;AACA,QAAI;AACF,YAAM,IAAI,MAAM,KAAK;AAAA,QACnB;AAAA,QAAQ;AAAA,QAAa;AAAA,MACvB;AACA,aAAO,EAAE,SAAS,EAAE,SAAS,WAAW,EAAE,WAAW,SAAS,EAAE,UAAU,OAAO,EAAE,OAAO,UAAU,MAAM;AAAA,IAC5G,SAAS,KAAK;AACZ,UAAI,eAAe,wBAAyB,eAAe,kBAAkB,IAAI,UAAU,KAAM;AAC/F,aAAK,UAAU,GAAG;AAClB,eAAO,EAAE,SAAS,KAAK,aAAa,QAAQ,WAAW,GAAG,SAAS,GAAG,OAAO,KAAK,SAAS,GAAG,UAAU,KAAK;AAAA,MAC/G;AACA,YAAM;AAAA,IACR;AAAA,EACF;AAAA,EAEA,SAAS,MAA0C;AACjD,WAAO,SAAS,KAAK,QAAQ,KAAK,IAAI,GAAG,IAAI;AAAA,EAC/C;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@detent/sdk",
3
+ "version": "0.5.0",
4
+ "description": "Typed TypeScript client for the Detent rate-limiting API.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "rate-limit",
8
+ "rate-limiter",
9
+ "detent",
10
+ "sdk",
11
+ "api-client",
12
+ "ratelimit"
13
+ ],
14
+ "homepage": "https://github.com/cguillerminet/detent-sdk-ts#readme",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/cguillerminet/detent-sdk-ts.git"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/cguillerminet/detent-sdk-ts/issues"
21
+ },
22
+ "type": "module",
23
+ "engines": {
24
+ "node": ">=18"
25
+ },
26
+ "main": "./dist/index.cjs",
27
+ "module": "./dist/index.js",
28
+ "types": "./dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "require": "./dist/index.cjs"
34
+ }
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "tsup",
44
+ "test": "vitest run",
45
+ "test:watch": "vitest",
46
+ "typecheck": "tsc --noEmit",
47
+ "gen:types": "tsx scripts/gen-types.ts",
48
+ "prepublishOnly": "npm run build"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "^20.11.0",
52
+ "openapi-typescript": "^7.4.0",
53
+ "tsup": "^8.0.0",
54
+ "tsx": "^4.7.0",
55
+ "typescript": "^5.4.0",
56
+ "vitest": "^1.4.0"
57
+ }
58
+ }