hono-stripe 0.0.1 → 1.0.2

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/README.md CHANGED
@@ -1,31 +1,21 @@
1
1
  # hono-stripe
2
2
 
3
- > Stripe middleware and helpers for [Hono](https://hono.dev) — works on Cloudflare Workers and Node.
3
+ > The all-in-one Stripe toolkit for [Hono](https://hono.dev) and HonoX — works on Cloudflare Workers and Node.
4
4
 
5
- `hono-stripe` injects a configured Stripe client into your Hono context and gives
6
- you thin helpers for the two things a payment backend needs first: creating a
7
- **PaymentIntent / Checkout Session** (to hand a `client_secret` to the frontend)
8
- and **verifying webhook signatures**. It handles the edge-runtime gotchas
9
- (`createFetchHttpClient`, async webhook verification) for you.
5
+ One install covers the whole server-side Stripe integration:
10
6
 
11
- > **Status:** early development (`0.0.1`). The goal is to upstream this as
12
- > `@hono/stripe` to [honojs/middleware](https://github.com/honojs/middleware)
13
- > once it has proven itself — see [Upstream plan](#upstream-plan). The current
14
- > maintainer intends to keep maintaining it through and after that move.
7
+ | Module | What you get |
8
+ | -- | -- |
9
+ | `hono-stripe` | Stripe client middleware (`c.var.stripe`), Stripe→HTTP error mapping for `app.onError` |
10
+ | `hono-stripe/webhook` | `stripeWebhook` — verify + **typed per-event routing** + delivery dedupe (in-memory, or your own atomic store) |
11
+ | `hono-stripe/testing` | Real-signature webhook fixtures for tests and local dev — no `stripe listen` required |
12
+ | `hono-stripe/ui` | hono/jsx (HonoX) components that render a working Payment Element form — no React |
15
13
 
16
- ## Where it fits — the 3 layers
14
+ It handles the edge-runtime gotchas for you (`createFetchHttpClient`, async
15
+ webhook verification via WebCrypto) and keeps `stripe`/`hono` as peer
16
+ dependencies — you bring your own versions.
17
17
 
18
- A full Hono + Stripe stack is three small pieces, each owning one job:
19
-
20
- | Layer | Package | Responsibility |
21
- | -- | -- | -- |
22
- | **Backend — client + intent/session** | **`hono-stripe`** (this) | Inject `c.var.stripe`; create PaymentIntents / Checkout Sessions; verify webhook signatures |
23
- | Backend — webhook routing | [`@kotodayori/hono`](https://www.npmjs.com/package/@kotodayori/hono) | Typed, per-event webhook routing on top of a verified event |
24
- | Frontend — payment UI | [stripe-pwa-elements](https://github.com/stripe/stripe-pwa-elements) | `<stripe-payment-element>` web components (no React required) |
25
-
26
- `hono-stripe` deliberately stops at **verifying** the webhook. Event dispatch /
27
- typed routing is the job of `@kotodayori/hono` — reach for it when you outgrow
28
- the primitive here.
18
+ > **Status:** early development (`0.x`). API may change between minor versions.
29
19
 
30
20
  ## Install
31
21
 
@@ -33,15 +23,6 @@ the primitive here.
33
23
  npm install hono-stripe stripe hono
34
24
  ```
35
25
 
36
- `stripe` and `hono` are peer dependencies — you bring your own versions.
37
-
38
- ## Starter template
39
-
40
- A runnable full-stack example (Hono + Cloudflare Workers + stripe-pwa-elements UI,
41
- with both PaymentIntent and Checkout Session flows) lives in
42
- [`examples/cloudflare-workers`](./examples/cloudflare-workers). Clone, set your
43
- test keys, `pnpm dev`.
44
-
45
26
  ## Quick start
46
27
 
47
28
  ### Cloudflare Workers
@@ -50,15 +31,23 @@ test keys, `pnpm dev`.
50
31
  import { Hono } from 'hono'
51
32
  import {
52
33
  stripeMiddleware,
53
- createPaymentIntent,
54
- verifyStripeSignature,
34
+ getStripe,
35
+ stripeErrorHandler,
55
36
  type StripeEnv,
56
37
  } from 'hono-stripe'
38
+ import { stripeWebhook } from 'hono-stripe/webhook'
57
39
 
58
- type Bindings = { STRIPE_SECRET_KEY: string; STRIPE_WEBHOOK_SECRET: string }
40
+ type Bindings = {
41
+ STRIPE_SECRET_KEY: string
42
+ STRIPE_WEBHOOK_SECRET: string
43
+ DB: D1Database // backs the dedupe store — see "Deduplication stores" in the webhooks guide
44
+ }
59
45
 
60
46
  const app = new Hono<{ Bindings: Bindings } & StripeEnv>()
61
47
 
48
+ // Stripe SDK errors → right HTTP statuses (card decline → 402, not 500).
49
+ app.onError(stripeErrorHandler())
50
+
62
51
  // Reads STRIPE_SECRET_KEY from the Workers env binding.
63
52
  // On Workers, Stripe.createFetchHttpClient() is applied automatically.
64
53
  app.use(stripeMiddleware())
@@ -66,15 +55,28 @@ app.use(stripeMiddleware())
66
55
  app.post('/api/payment-intent', async (c) => {
67
56
  // Decide the amount on the server (e.g. from a price id / cart lookup),
68
57
  // never trust an amount sent by the client.
69
- const intent = await createPaymentIntent(c, { amount: 1400, currency: 'usd' })
58
+ const intent = await getStripe(c).paymentIntents.create({ amount: 1400, currency: 'usd' })
70
59
  return c.json({ clientSecret: intent.client_secret })
71
60
  })
72
61
 
73
- app.post('/api/webhook', async (c) => {
74
- const event = await verifyStripeSignature(c, { secret: c.env.STRIPE_WEBHOOK_SECRET })
75
- // Hand `event` to @kotodayori/hono for typed routing, or switch on event.type.
76
- return c.body(null, 200)
77
- })
62
+ // Verify + route + dedupe in one middleware. `event.data.object` is typed
63
+ // per event name — the stripe SDK discriminates events by `type`.
64
+ app.post(
65
+ '/api/webhook',
66
+ stripeWebhook({
67
+ // c.env only exists at request time — resolve the store lazily per request.
68
+ // Your atomic StripeEventStore (D1 example in the webhooks guide).
69
+ dedupe: (c) => d1EventStore(c.env.DB),
70
+ on: {
71
+ 'payment_intent.succeeded': (event) => {
72
+ console.log('paid', event.data.object.id) // Stripe.PaymentIntent
73
+ },
74
+ 'checkout.session.completed': async (event) => {
75
+ await fulfillOrder(event.data.object) // Stripe.Checkout.Session
76
+ },
77
+ },
78
+ }),
79
+ )
78
80
 
79
81
  export default app
80
82
  ```
@@ -91,20 +93,158 @@ STRIPE_WEBHOOK_SECRET=whsec_...
91
93
  ```ts
92
94
  import { serve } from '@hono/node-server'
93
95
  import { Hono } from 'hono'
94
- import { stripeMiddleware, createPaymentIntent, type StripeEnv } from 'hono-stripe'
96
+ import { stripeMiddleware, getStripe, type StripeEnv } from 'hono-stripe'
95
97
 
96
98
  const app = new Hono<StripeEnv>()
97
99
  app.use(stripeMiddleware()) // reads process.env.STRIPE_SECRET_KEY
98
100
 
99
101
  app.post('/api/payment-intent', async (c) => {
100
- const intent = await createPaymentIntent(c, { amount: 1400, currency: 'usd' })
102
+ const intent = await getStripe(c).paymentIntents.create({ amount: 1400, currency: 'usd' })
101
103
  return c.json({ clientSecret: intent.client_secret })
102
104
  })
103
105
 
104
106
  serve(app)
105
107
  ```
106
108
 
107
- ## API
109
+ ## Webhooks — `hono-stripe/webhook`
110
+
111
+ `stripeWebhook` composes the three things every Stripe webhook endpoint needs:
112
+
113
+ 1. **Verify** — `constructEventAsync` (async WebCrypto, Workers-safe). Missing
114
+ or bad signatures get a `400`, not a `500`, so Stripe doesn't retry
115
+ invalid requests.
116
+ 2. **Route** — handlers keyed by event type, with `event.data.object` narrowed
117
+ to the concrete resource type for every event type the SDK knows.
118
+ 3. **Dedupe** — Stripe retries deliveries for up to ~3 days. Pass a store to
119
+ acknowledge repeat deliveries without re-running the handler.
120
+
121
+ ```ts
122
+ import { stripeWebhook, memoryEventStore } from 'hono-stripe/webhook'
123
+
124
+ app.post('/webhook', stripeWebhook({
125
+ // Secret resolution order: `secret` (string or (c) => string) →
126
+ // env binding / process.env[webhookSecretVar] (default STRIPE_WEBHOOK_SECRET)
127
+ secret: (c) => c.env.STRIPE_WEBHOOK_SECRET,
128
+
129
+ // memoryEventStore() for dev / single-isolate Node; production needs an
130
+ // atomic store (see "Deduplication stores").
131
+ dedupe: memoryEventStore(),
132
+
133
+ on: {
134
+ 'customer.subscription.deleted': async (event, c) => {
135
+ await downgrade(event.data.object.customer)
136
+ },
137
+ },
138
+
139
+ // Optional: override the default 200 for verified-but-unhandled events.
140
+ onUnhandled: (event, c) => c.json({ ignored: event.type }),
141
+ }))
142
+ ```
143
+
144
+ The Stripe client for verification comes from `c.var.stripe` when
145
+ `stripeMiddleware()` has run; otherwise `stripeWebhook` builds one from
146
+ `apiKey` / `STRIPE_SECRET_KEY` (verification is local HMAC — no API call).
147
+
148
+ - A handler may `return c.json(...)` / `Response` (sent verbatim) or return
149
+ nothing (`200 { received: true }`).
150
+ - A handler that throws surfaces as a `500` via Hono's error handling, so
151
+ Stripe retries — and since dedupe records only after a successful handler,
152
+ retries are processed normally.
153
+ - `verifyStripeSignature(c, { secret })` remains available from
154
+ `hono-stripe/webhook` as the bare primitive if you want a `switch` instead
155
+ of a router.
156
+
157
+ ### `StripeEventStore`
158
+
159
+ Bring your own backend (D1, Upstash, DB) by implementing two methods:
160
+
161
+ ```ts
162
+ interface StripeEventStore {
163
+ claim(eventId: string, ttlSeconds: number): Promise<boolean> // atomic
164
+ release(eventId: string): Promise<void>
165
+ }
166
+ ```
167
+
168
+ `claim` must be atomic (conditional insert, Durable Object, `SET NX`, …), so
169
+ concurrent deliveries of one event run the handler once; the claim is released
170
+ if the handler throws or returns non-2xx. `memoryEventStore()` is provided for
171
+ dev and single-process use. **Workers KV is eventually consistent and cannot
172
+ provide an atomic claim — do not use it for dedupe.** See the
173
+ [webhooks guide](docs/src/content/docs/guides/webhooks.md) for D1 /
174
+ DynamoDB examples. Default retention is 3 days.
175
+
176
+ ## Testing — `hono-stripe/testing`
177
+
178
+ Webhook signatures are just HMAC-SHA256 over `${timestamp}.${payload}`. This
179
+ module produces **real** signatures with WebCrypto, so they verify against the
180
+ actual Stripe SDK on every runtime — run the full verify → route → dedupe path
181
+ in `vitest` without `stripe listen` or network access.
182
+
183
+ ```ts
184
+ import { Hono } from 'hono'
185
+ import { stripeWebhook } from 'hono-stripe/webhook'
186
+ import { createTestEvent, createWebhookRequest } from 'hono-stripe/testing'
187
+
188
+ const app = new Hono().post('/webhook', stripeWebhook({
189
+ apiKey: 'sk_test_x',
190
+ secret: 'whsec_test',
191
+ on: { 'payment_intent.succeeded': handler },
192
+ }))
193
+
194
+ const res = await app.request(await createWebhookRequest(
195
+ createTestEvent('payment_intent.succeeded', { id: 'pi_1', amount: 1400 }),
196
+ { secret: 'whsec_test' },
197
+ ))
198
+ expect(res.status).toBe(200)
199
+ ```
200
+
201
+ | Export | Purpose |
202
+ | -- | -- |
203
+ | `signStripePayload(payload, secret, timestamp?)` | `t=...,v1=...` header value; backdate `timestamp` to test tolerance handling |
204
+ | `createTestEvent(type, object, options?)` | `Stripe.Event`-shaped fixture around your `data.object` |
205
+ | `createWebhookRequest(event \| payload, { secret, url?, timestamp? })` | `Request` with a valid signature, ready for `app.request()` or `fetch` |
206
+
207
+ ## Payment UI — `hono-stripe/ui`
208
+
209
+ Server-render a working [stripe-pwa-elements](https://github.com/stripe/stripe-pwa-elements)
210
+ `<stripe-payment-element>` from hono/jsx or HonoX — no React, no frontend build
211
+ step. The component code loads from a CDN as an ES module.
212
+
213
+ ```tsx
214
+ import { StripePaymentForm } from 'hono-stripe/ui'
215
+
216
+ app.get('/', (c) =>
217
+ c.html(<StripePaymentForm
218
+ endpoint="/api/payment-intent" // POST → { clientSecret, publishableKey? }
219
+ publishableKey={c.env.STRIPE_PUBLISHABLE_KEY}
220
+ />)
221
+ )
222
+ ```
223
+
224
+ Two modes:
225
+
226
+ - **`endpoint`**: the browser POSTs to your endpoint and assigns the returned
227
+ `clientSecret` to the element (e.g. a PaymentIntent or Checkout Session
228
+ created via `getStripe(c)` above).
229
+ - **`clientSecret`**: pass a secret created during SSR — rendered as an element
230
+ attribute, no client-side fetch.
231
+
232
+ ```tsx
233
+ app.get('/', async (c) => {
234
+ const intent = await getStripe(c).paymentIntents.create({ amount: 1400, currency: 'usd' })
235
+ return c.html(<StripePaymentForm
236
+ clientSecret={intent.client_secret!}
237
+ publishableKey={c.env.STRIPE_PUBLISHABLE_KEY}
238
+ />)
239
+ })
240
+ ```
241
+
242
+ `intent="checkout"` switches to Checkout Session mode
243
+ (`checkout-session-client-secret`). `StripeElementsScript` (the `<script
244
+ type="module">` loader) is rendered automatically; pass `src` to self-host
245
+ instead of using the CDN.
246
+
247
+ ## API — `hono-stripe`
108
248
 
109
249
  ### `stripeMiddleware(options?)`
110
250
 
@@ -125,19 +265,41 @@ initialized with `Stripe.createFetchHttpClient()`. Clients are cached per key.
125
265
  | `apiVersion` | `string` | Stripe API version override |
126
266
  | `config` | `Stripe.StripeConfig` | Extra config; an explicit `httpClient` here wins |
127
267
 
128
- ### `createPaymentIntent(c, params, options?)` / `createCheckoutSession(c, params, options?)`
268
+ ### `stripeErrorHandler(options?)`
129
269
 
130
- Thin wrappers over `stripe.paymentIntents.create` /
131
- `stripe.checkout.sessions.create` that forward params verbatim. To drive the
132
- frontend with a `client_secret` (the Checkout Sessions mode used by
133
- stripe-pwa-elements), pass the client-side `ui_mode` for your Stripe version
134
- (`'custom'` on recent Stripe, `'elements'` on older SDKs).
270
+ A Hono `onError` handler that maps Stripe SDK errors to the right HTTP status
271
+ instead of letting every Stripe failure become a `500`:
135
272
 
136
- ### `verifyStripeSignature(c, { secret, signatureHeader?, tolerance? })`
273
+ ```ts
274
+ import { stripeErrorHandler } from 'hono-stripe'
275
+
276
+ app.onError(stripeErrorHandler({ locale: 'ja' })) // 'en' default
277
+
278
+ // or per-request — e.g. follow Accept-Language:
279
+ app.onError(stripeErrorHandler({
280
+ locale: (c) => c.req.header('accept-language')?.startsWith('ja') ? 'ja' : 'en',
281
+ }))
282
+ ```
137
283
 
138
- Reads the raw body and verifies it with `constructEventAsync` (the async form
139
- required where WebCrypto is async, e.g. Workers), returning the verified
140
- `Stripe.Event`. Throws if the signature header is missing or invalid.
284
+ Card declines get extra fields your client can render directly —
285
+ `error.userMessage` is the localized "what to do next" text and
286
+ `error.retryable` distinguishes a soft decline (worth retrying, e.g.
287
+ `insufficient_funds`) from a hard one (`fraudulent`, `stolen_card`). Both come
288
+ from [stripe-decline-codes](https://github.com/hideokamoto/stripe-decline-codes).
289
+
290
+ | Stripe error | Status | Notes |
291
+ | -- | -- | -- |
292
+ | `StripeCardError` | 402 | `code` = decline_code, plus `userMessage` (localized via `stripe-decline-codes`) and `retryable` (soft-decline detection) |
293
+ | `StripeInvalidRequestError`, `TemporarySessionExpiredError` | 400 | |
294
+ | `StripeSignatureVerificationError` | 400 | details not leaked |
295
+ | `StripeIdempotencyError` | 409 | |
296
+ | `StripeRateLimitError` | 429 | |
297
+ | `StripeConnectionError`, `StripeAPIError` | 502 | upstream failure — safe to retry |
298
+ | `StripeAuthenticationError`, `StripePermissionError` | 500 | generic message — never leaks key details |
299
+ | Other `StripeError` with 4xx `statusCode` | that status | |
300
+ | Other `StripeError` | 502 | |
301
+ | `HTTPException` | untouched | pass-through |
302
+ | Anything else | 500 | or `options.fallback(err, c)` |
141
303
 
142
304
  ### `getStripe(c)`
143
305
 
@@ -148,27 +310,51 @@ Returns `c.var.stripe`, throwing a clear error if the middleware has not run.
148
310
  `isNodeRuntime()`, `isWorkersRuntime()`, `shouldUseFetchHttpClient()` are
149
311
  exported for advanced/diagnostic use.
150
312
 
151
- ## Bundle size
313
+ ## Starter template
152
314
 
153
- Staying thin is a feature. CI enforces a [size-limit](https://github.com/ai/size-limit)
154
- budget on the built artifacts (`.size-limit.json`) and posts the current sizes
155
- to each PR, so accidental bloat fails the build instead of slipping in. Run it
156
- locally with:
315
+ A runnable full-stack example (Hono + Cloudflare Workers + Payment Element UI,
316
+ with both PaymentIntent and Checkout Session flows) lives in
317
+ [`examples/cloudflare-workers`](./examples/cloudflare-workers). Clone, set your
318
+ test keys, `pnpm dev`.
319
+
320
+ ## Documentation
321
+
322
+ The docs site lives in [`docs/`](./docs) (Starlight + TypeDoc, deployed to
323
+ Cloudflare Workers Static Assets). Run it locally with `pnpm -C docs dev`; see
324
+ [`docs/README.md`](./docs/README.md) for build/deploy details.
325
+
326
+ ## Development
157
327
 
158
328
  ```sh
159
- pnpm run size
329
+ pnpm test # unit tests (mocked Stripe client, no network)
330
+ pnpm test:integration # integration tests against stripe-mock
331
+ ```
332
+
333
+ The integration tests (`test/integration/`) drive the real `stripe` SDK over
334
+ HTTP against [stripe-mock](https://github.com/stripe/stripe-mock), so they
335
+ catch what mocked unit tests can't: `config` reaching the SDK, the Fetch HTTP
336
+ client on Workers, and real SDK errors flowing through `stripeErrorHandler`.
337
+ Start stripe-mock first — the run fails up front if it is not reachable:
338
+
339
+ ```sh
340
+ docker run --rm -p 12111-12112:12111-12112 stripe/stripe-mock:v0.206.0
160
341
  ```
161
342
 
162
- The library itself adds ~1 kB (brotli) per format; `stripe`/`hono` are peers and
163
- are not bundled.
343
+ Override the address with `STRIPE_MOCK_HOST` / `STRIPE_MOCK_PORT`. stripe-mock
344
+ is stateless and does not simulate card declines, so those paths stay in the
345
+ unit tests.
346
+
347
+ ## Bundle size
164
348
 
165
- ## Upstream plan
349
+ Staying thin is a feature. CI enforces a
350
+ [size-limit](https://github.com/ai/size-limit) budget per entry point
351
+ (`.size-limit.json`) and posts the current sizes to each PR. `stripe`/`hono`
352
+ are peers and are never bundled. The browser-side payment components load from
353
+ a CDN, so they're not in your server bundle either.
166
354
 
167
- `hono-stripe` is built to be proposed to
168
- [honojs/middleware](https://github.com/honojs/middleware) as `@hono/stripe`.
169
- To keep that path open it depends on **`stripe` and `hono` as peers only** — no
170
- other runtime dependencies. If the proposal is accepted, `hono-stripe` will be
171
- deprecated with a pointer to `@hono/stripe`.
355
+ ```sh
356
+ pnpm run size
357
+ ```
172
358
 
173
359
  ## License
174
360
 
@@ -0,0 +1,77 @@
1
+ import { getRuntimeKey } from 'hono/adapter';
2
+ import Stripe from 'stripe';
3
+
4
+ // src/context.ts
5
+ var getStripe = (c) => {
6
+ const stripe = c.get("stripe");
7
+ if (!stripe) {
8
+ throw new Error(
9
+ "hono-stripe: Stripe client not found on context. Did you register stripeMiddleware() before this handler?"
10
+ );
11
+ }
12
+ return stripe;
13
+ };
14
+ var isNodeRuntime = () => getRuntimeKey() === "node";
15
+ var isWorkersRuntime = () => getRuntimeKey() === "workerd";
16
+ var shouldUseFetchHttpClient = () => !isNodeRuntime();
17
+ var MAX_CACHE_ENTRIES = 100;
18
+ var clientCache = /* @__PURE__ */ new Map();
19
+ var optionsTokens = /* @__PURE__ */ new WeakMap();
20
+ var optionsTokenSeq = 0;
21
+ var cryptoProvider;
22
+ var buildConfig = (options) => {
23
+ const config = { ...options.config };
24
+ if (options.apiVersion) {
25
+ config.apiVersion = options.apiVersion;
26
+ }
27
+ if (!config.httpClient && shouldUseFetchHttpClient()) {
28
+ config.httpClient = Stripe.createFetchHttpClient();
29
+ }
30
+ return config;
31
+ };
32
+ var hasNonSerializableConfig = (config) => {
33
+ if (config.httpClient !== void 0) return true;
34
+ return Object.values(config).some((value) => typeof value === "function");
35
+ };
36
+ var computeOptionsToken = (options) => {
37
+ const { apiVersion, config } = options;
38
+ if (config && hasNonSerializableConfig(config)) {
39
+ return `#${++optionsTokenSeq}`;
40
+ }
41
+ try {
42
+ return JSON.stringify({ apiVersion, config });
43
+ } catch {
44
+ return `#${++optionsTokenSeq}`;
45
+ }
46
+ };
47
+ var getCacheKey = (apiKey, options) => {
48
+ let token = optionsTokens.get(options);
49
+ if (token === void 0) {
50
+ token = computeOptionsToken(options);
51
+ optionsTokens.set(options, token);
52
+ }
53
+ return `${apiKey}:${token}`;
54
+ };
55
+ var getStripeClient = (apiKey, options) => {
56
+ const opts = options ?? {};
57
+ const cacheKey = getCacheKey(apiKey, opts);
58
+ const cached = clientCache.get(cacheKey);
59
+ if (cached) return cached;
60
+ const client = new Stripe(apiKey, buildConfig(opts));
61
+ clientCache.set(cacheKey, client);
62
+ if (clientCache.size > MAX_CACHE_ENTRIES) {
63
+ const oldest = clientCache.keys().next().value;
64
+ if (oldest !== void 0) clientCache.delete(oldest);
65
+ }
66
+ return client;
67
+ };
68
+ var getCryptoProvider = () => {
69
+ if (!cryptoProvider) {
70
+ cryptoProvider = Stripe.createSubtleCryptoProvider();
71
+ }
72
+ return cryptoProvider;
73
+ };
74
+
75
+ export { getCryptoProvider, getStripe, getStripeClient, isNodeRuntime, isWorkersRuntime, shouldUseFetchHttpClient };
76
+ //# sourceMappingURL=chunk-TV73NTMC.js.map
77
+ //# sourceMappingURL=chunk-TV73NTMC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context.ts","../src/runtime.ts"],"names":[],"mappings":";;;;AASO,IAAM,SAAA,GAAY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EAAK,CAAE,MAAK,CAAE,KAAA;AACzC,IAAA,IAAI,MAAA,KAAW,MAAA,EAAW,WAAA,CAAY,MAAA,CAAO,MAAM,CAAA;AAAA,EACrD;AACA,EAAA,OAAO,MAAA;AACT;AAMO,IAAM,oBAAoB,MAA4D;AAC3F,EAAA,IAAI,CAAC,cAAA,EAAgB;AACnB,IAAA,cAAA,GAAiB,OAAO,0BAAA,EAA2B;AAAA,EACrD;AACA,EAAA,OAAO,cAAA;AACT","file":"chunk-TV73NTMC.js","sourcesContent":["import type { Context } from 'hono'\nimport type Stripe from 'stripe'\n\n/**\n * Read the Stripe client injected by {@link stripeMiddleware} from the context.\n *\n * Throws a clear error if the middleware has not run, so misconfiguration\n * fails fast instead of surfacing as an opaque `undefined` later.\n */\nexport const getStripe = (c: Context): Stripe => {\n const stripe = c.get('stripe') as Stripe | undefined\n if (!stripe) {\n throw new Error(\n 'hono-stripe: Stripe client not found on context. Did you register stripeMiddleware() before this handler?',\n )\n }\n return stripe\n}\n","import { getRuntimeKey } from 'hono/adapter'\nimport Stripe from 'stripe'\nimport type { StripeMiddlewareOptions } from './types'\n\n/**\n * The Stripe client config type (second constructor argument).\n *\n * `StripeConfig` is a top-level export of `stripe` rather than a member of the\n * `Stripe` namespace, so we derive it from the constructor to stay robust\n * across the supported peer range.\n */\nexport type StripeClientConfig = NonNullable<ConstructorParameters<typeof Stripe>[1]>\n\n/**\n * True when running on a Node.js runtime.\n *\n * Delegates to Hono's `getRuntimeKey()` so this stays consistent with the\n * runtime detection used by `env()` for secret-key resolution.\n */\nexport const isNodeRuntime = (): boolean => getRuntimeKey() === 'node'\n\n/**\n * True when running on Cloudflare Workers (`workerd`).\n */\nexport const isWorkersRuntime = (): boolean => getRuntimeKey() === 'workerd'\n\n/**\n * Whether the Stripe SDK should use the Fetch-based HTTP client.\n *\n * On Cloudflare Workers (and other non-Node edge runtimes) the default Node\n * `http`/`https` client is unavailable, so Stripe must be initialized with\n * `Stripe.createFetchHttpClient()`. This is the single most common \"gotcha\"\n * when running stripe-node on the edge, and hono-stripe handles it for you.\n */\nexport const shouldUseFetchHttpClient = (): boolean => !isNodeRuntime()\n\n// Maximum number of Stripe clients retained. Bounds memory (and retained\n// secrets) in multi-tenant / key-rotation setups where many distinct secret\n// keys flow through the middleware over the process lifetime.\nconst MAX_CACHE_ENTRIES = 100\n\n// One Stripe client per unique (key + config) — reused across requests.\n// Insertion order is significant: `Map` preserves it, so the first-inserted\n// entry is the oldest and is evicted first (FIFO) once the cap is exceeded.\nconst clientCache = new Map<string, Stripe>()\n\n// Stable per-options-object identity token, keyed by object identity. Lets the\n// cache key distinguish two options objects whose `config` is non-serializable\n// or otherwise not comparable via `JSON.stringify` (e.g. a custom `httpClient`),\n// while a repeated call with the same options object reuses its token without\n// re-serializing. A `WeakMap` lets tokens be GC'd alongside their options.\nlet optionsTokens = new WeakMap<object, string>()\nlet optionsTokenSeq = 0\n\n// SubtleCrypto provider is required for async webhook verification on the edge.\nlet cryptoProvider: ReturnType<typeof Stripe.createSubtleCryptoProvider> | undefined\n\n/**\n * Build the Stripe client config, applying the Fetch HTTP client automatically\n * on edge runtimes unless the caller supplied their own `httpClient`.\n */\nconst buildConfig = (options: StripeMiddlewareOptions): StripeClientConfig => {\n const config: StripeClientConfig = { ...options.config }\n if (options.apiVersion) {\n config.apiVersion = options.apiVersion\n }\n if (!config.httpClient && shouldUseFetchHttpClient()) {\n config.httpClient = Stripe.createFetchHttpClient()\n }\n return config\n}\n\n/**\n * Whether a config carries values that a JSON representation cannot faithfully\n * compare, so keying by its serialized form would let distinct configs collide.\n *\n * A custom `httpClient` is a runtime object/class instance whose *identity*\n * (not its often-empty enumerable shape) determines behavior — two different\n * clients both serialize to the same string — so its mere presence is treated\n * as non-serializable. Function-valued config is likewise flagged because\n * `JSON.stringify` silently drops functions.\n */\nconst hasNonSerializableConfig = (config: StripeClientConfig): boolean => {\n if (config.httpClient !== undefined) return true\n return Object.values(config).some((value) => typeof value === 'function')\n}\n\n/**\n * Compute a stable token identifying the client-construction inputs of an\n * options object.\n *\n * For plainly serializable options the token is the JSON form, so two distinct\n * but equivalent options objects share a client. When `config` is\n * non-serializable (custom `httpClient`, functions) or `JSON.stringify` throws\n * (e.g. circular refs), a unique token is minted instead, so such options never\n * collide with one another.\n */\nconst computeOptionsToken = (options: StripeMiddlewareOptions): string => {\n const { apiVersion, config } = options\n if (config && hasNonSerializableConfig(config)) {\n return `#${++optionsTokenSeq}`\n }\n try {\n return JSON.stringify({ apiVersion, config })\n } catch {\n return `#${++optionsTokenSeq}`\n }\n}\n\n/**\n * Build the cache key from the secret key and the options that affect client\n * construction, so the same key initialized with different config does not\n * silently reuse the first client.\n *\n * The per-options token is memoized in a `WeakMap` keyed by the options object\n * identity: the same options object (the common per-middleware case) reuses its\n * token without re-running `JSON.stringify` on every request.\n */\nconst getCacheKey = (apiKey: string, options: StripeMiddlewareOptions): string => {\n let token = optionsTokens.get(options)\n if (token === undefined) {\n token = computeOptionsToken(options)\n optionsTokens.set(options, token)\n }\n return `${apiKey}:${token}`\n}\n\n/**\n * Get (or lazily create and cache) a Stripe client for the given secret key\n * and options. The cache is bounded to {@link MAX_CACHE_ENTRIES}; the oldest\n * entry is evicted (FIFO) when the cap would be exceeded.\n *\n * `options` is typed as required, but this is also a public entry point that\n * an untyped JS caller can invoke with `undefined`/`null`. Normalize to `{}`\n * up front so that never reaches the `WeakMap` used internally, which throws\n * on a non-object key.\n */\nexport const getStripeClient = (apiKey: string, options: StripeMiddlewareOptions): Stripe => {\n const opts = options ?? {}\n const cacheKey = getCacheKey(apiKey, opts)\n const cached = clientCache.get(cacheKey)\n if (cached) return cached\n const client = new Stripe(apiKey, buildConfig(opts))\n clientCache.set(cacheKey, client)\n if (clientCache.size > MAX_CACHE_ENTRIES) {\n const oldest = clientCache.keys().next().value\n if (oldest !== undefined) clientCache.delete(oldest)\n }\n return client\n}\n\n/**\n * Get (or lazily create) the shared SubtleCrypto provider used to verify\n * webhook signatures asynchronously on runtimes without Node crypto.\n */\nexport const getCryptoProvider = (): ReturnType<typeof Stripe.createSubtleCryptoProvider> => {\n if (!cryptoProvider) {\n cryptoProvider = Stripe.createSubtleCryptoProvider()\n }\n return cryptoProvider\n}\n\n/** Test-only: current number of cached Stripe clients. */\nexport const __cacheSize = (): number => clientCache.size\n\n/** Test-only: reset the internal caches. */\nexport const __resetCaches = (): void => {\n clientCache.clear()\n optionsTokens = new WeakMap<object, string>()\n optionsTokenSeq = 0\n cryptoProvider = undefined\n}\n"]}