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.
@@ -0,0 +1,59 @@
1
+ import Stripe from 'stripe';
2
+
3
+ /**
4
+ * Produce a `Stripe-Signature` header value (`t=...,v1=...`) for `payload`.
5
+ *
6
+ * @param timestamp Unix seconds. Defaults to now — override to test tolerance
7
+ * handling (e.g. a timestamp older than 300s should fail verification).
8
+ */
9
+ declare const signStripePayload: (payload: string, secret: string, timestamp?: number) => Promise<string>;
10
+ interface TestEventOptions {
11
+ /** Event id. Default: `evt_test_<uuid>`. */
12
+ id?: string;
13
+ /** `created` timestamp (Unix seconds). Default: now. */
14
+ created?: number;
15
+ /** Default: false. */
16
+ livemode?: boolean;
17
+ /** `previous_attributes` on `event.data`. */
18
+ previousAttributes?: Record<string, unknown>;
19
+ /** `api_version` field. Default: null. */
20
+ apiVersion?: string | null;
21
+ /** `request` field. Default: `{ id: null, idempotency_key: null }`. */
22
+ request?: Stripe.Event['request'];
23
+ /** `pending_webhooks` count. Default: 1. */
24
+ pendingWebhooks?: number;
25
+ }
26
+ /** A `Stripe.Event` whose `data.object` carries the type of the fixture object. */
27
+ type TestStripeEvent<O extends object> = Omit<Stripe.Event, 'data'> & {
28
+ data: Omit<Stripe.Event['data'], 'object'> & {
29
+ object: O;
30
+ };
31
+ };
32
+ /**
33
+ * Build a fake `Stripe.Event`-shaped object around a `data.object` payload.
34
+ *
35
+ * Pass as much of the resource as your handler needs — the fixture is not
36
+ * validated against Stripe's schema. For a fully-typed object, shape it to the
37
+ * resource type (e.g. `Partial<Stripe.PaymentIntent>`).
38
+ */
39
+ declare const createTestEvent: <O extends object>(type: Stripe.Event["type"], object: O, options?: TestEventOptions) => TestStripeEvent<O>;
40
+ interface CreateWebhookRequestOptions {
41
+ /** Endpoint signing secret — must match what the app verifies against. */
42
+ secret: string;
43
+ /** Request URL. Default: `http://localhost/webhook`. */
44
+ url?: string | URL;
45
+ /** Signature timestamp (Unix seconds). Default: now. */
46
+ timestamp?: number;
47
+ /** Extra request headers (merged after the signature header is set). */
48
+ headers?: HeadersInit;
49
+ }
50
+ /**
51
+ * Wrap a payload in a `Request` with a valid `Stripe-Signature` header —
52
+ * ready for `app.request(req)` in tests or a `fetch` against local dev.
53
+ *
54
+ * `event` may be a `createTestEvent` result, any object (JSON.stringify'd), or
55
+ * a pre-serialized payload string — the signature covers the exact bytes sent.
56
+ */
57
+ declare const createWebhookRequest: (event: object | string, options: CreateWebhookRequestOptions) => Promise<Request>;
58
+
59
+ export { type CreateWebhookRequestOptions, type TestEventOptions, type TestStripeEvent, createTestEvent, createWebhookRequest, signStripePayload };
@@ -0,0 +1,59 @@
1
+ import Stripe from 'stripe';
2
+
3
+ /**
4
+ * Produce a `Stripe-Signature` header value (`t=...,v1=...`) for `payload`.
5
+ *
6
+ * @param timestamp Unix seconds. Defaults to now — override to test tolerance
7
+ * handling (e.g. a timestamp older than 300s should fail verification).
8
+ */
9
+ declare const signStripePayload: (payload: string, secret: string, timestamp?: number) => Promise<string>;
10
+ interface TestEventOptions {
11
+ /** Event id. Default: `evt_test_<uuid>`. */
12
+ id?: string;
13
+ /** `created` timestamp (Unix seconds). Default: now. */
14
+ created?: number;
15
+ /** Default: false. */
16
+ livemode?: boolean;
17
+ /** `previous_attributes` on `event.data`. */
18
+ previousAttributes?: Record<string, unknown>;
19
+ /** `api_version` field. Default: null. */
20
+ apiVersion?: string | null;
21
+ /** `request` field. Default: `{ id: null, idempotency_key: null }`. */
22
+ request?: Stripe.Event['request'];
23
+ /** `pending_webhooks` count. Default: 1. */
24
+ pendingWebhooks?: number;
25
+ }
26
+ /** A `Stripe.Event` whose `data.object` carries the type of the fixture object. */
27
+ type TestStripeEvent<O extends object> = Omit<Stripe.Event, 'data'> & {
28
+ data: Omit<Stripe.Event['data'], 'object'> & {
29
+ object: O;
30
+ };
31
+ };
32
+ /**
33
+ * Build a fake `Stripe.Event`-shaped object around a `data.object` payload.
34
+ *
35
+ * Pass as much of the resource as your handler needs — the fixture is not
36
+ * validated against Stripe's schema. For a fully-typed object, shape it to the
37
+ * resource type (e.g. `Partial<Stripe.PaymentIntent>`).
38
+ */
39
+ declare const createTestEvent: <O extends object>(type: Stripe.Event["type"], object: O, options?: TestEventOptions) => TestStripeEvent<O>;
40
+ interface CreateWebhookRequestOptions {
41
+ /** Endpoint signing secret — must match what the app verifies against. */
42
+ secret: string;
43
+ /** Request URL. Default: `http://localhost/webhook`. */
44
+ url?: string | URL;
45
+ /** Signature timestamp (Unix seconds). Default: now. */
46
+ timestamp?: number;
47
+ /** Extra request headers (merged after the signature header is set). */
48
+ headers?: HeadersInit;
49
+ }
50
+ /**
51
+ * Wrap a payload in a `Request` with a valid `Stripe-Signature` header —
52
+ * ready for `app.request(req)` in tests or a `fetch` against local dev.
53
+ *
54
+ * `event` may be a `createTestEvent` result, any object (JSON.stringify'd), or
55
+ * a pre-serialized payload string — the signature covers the exact bytes sent.
56
+ */
57
+ declare const createWebhookRequest: (event: object | string, options: CreateWebhookRequestOptions) => Promise<Request>;
58
+
59
+ export { type CreateWebhookRequestOptions, type TestEventOptions, type TestStripeEvent, createTestEvent, createWebhookRequest, signStripePayload };
@@ -0,0 +1,58 @@
1
+ // src/testing.ts
2
+ var encoder = new TextEncoder();
3
+ var toHex = (buf) => Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, "0")).join("");
4
+ var requireSubtleCrypto = () => {
5
+ const subtle = globalThis.crypto?.subtle;
6
+ if (!subtle) {
7
+ throw new Error(
8
+ "hono-stripe/testing: crypto.subtle is not available in this runtime; webhook fixtures cannot be signed."
9
+ );
10
+ }
11
+ return subtle;
12
+ };
13
+ var signStripePayload = async (payload, secret, timestamp = Math.floor(Date.now() / 1e3)) => {
14
+ const key = await requireSubtleCrypto().importKey(
15
+ "raw",
16
+ encoder.encode(secret),
17
+ { name: "HMAC", hash: "SHA-256" },
18
+ false,
19
+ ["sign"]
20
+ );
21
+ const signature = await requireSubtleCrypto().sign(
22
+ "HMAC",
23
+ key,
24
+ encoder.encode(`${timestamp}.${payload}`)
25
+ );
26
+ return `t=${timestamp},v1=${toHex(signature)}`;
27
+ };
28
+ var createTestEvent = (type, object, options = {}) => ({
29
+ id: options.id ?? `evt_test_${globalThis.crypto.randomUUID()}`,
30
+ object: "event",
31
+ api_version: options.apiVersion ?? null,
32
+ created: options.created ?? Math.floor(Date.now() / 1e3),
33
+ data: { object, previous_attributes: options.previousAttributes },
34
+ livemode: options.livemode ?? false,
35
+ pending_webhooks: options.pendingWebhooks ?? 1,
36
+ request: options.request ?? { id: null, idempotency_key: null },
37
+ type
38
+ });
39
+ var createWebhookRequest = async (event, options) => {
40
+ const payload = typeof event === "string" ? event : JSON.stringify(event);
41
+ const signature = await signStripePayload(payload, options.secret, options.timestamp);
42
+ const headers = new Headers({
43
+ "content-type": "application/json",
44
+ "stripe-signature": signature
45
+ });
46
+ new Headers(options.headers).forEach((value, key) => {
47
+ headers.set(key, value);
48
+ });
49
+ return new Request(options.url ?? "http://localhost/webhook", {
50
+ method: "POST",
51
+ headers,
52
+ body: payload
53
+ });
54
+ };
55
+
56
+ export { createTestEvent, createWebhookRequest, signStripePayload };
57
+ //# sourceMappingURL=testing.js.map
58
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing.ts"],"names":[],"mappings":"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","file":"testing.js","sourcesContent":["import type Stripe from 'stripe'\n\n/**\n * Testing utilities: build Stripe webhook requests with valid signatures, no\n * `stripe listen`, no Stripe client, no network.\n *\n * The signing scheme is Stripe's documented `t=<ts>,v1=<hmac-sha256>` over\n * `${t}.${payload}`, implemented with WebCrypto (`crypto.subtle`) so it runs on\n * Node, Workers, Deno, Bun — anywhere Hono runs. Signatures produced here pass\n * `stripe.webhooks.constructEventAsync`.\n *\n * @example\n * ```ts\n * const req = await createWebhookRequest(\n * createTestEvent('payment_intent.succeeded', { id: 'pi_1', amount: 1400 }),\n * { secret: 'whsec_test' },\n * )\n * const res = await app.request(req)\n * ```\n */\n\nconst encoder = new TextEncoder()\n\nconst toHex = (buf: ArrayBuffer): string =>\n Array.from(new Uint8Array(buf), (b) => b.toString(16).padStart(2, '0')).join('')\n\nconst requireSubtleCrypto = (): SubtleCrypto => {\n const subtle = globalThis.crypto?.subtle\n if (!subtle) {\n throw new Error(\n 'hono-stripe/testing: crypto.subtle is not available in this runtime; webhook fixtures cannot be signed.',\n )\n }\n return subtle\n}\n\n/**\n * Produce a `Stripe-Signature` header value (`t=...,v1=...`) for `payload`.\n *\n * @param timestamp Unix seconds. Defaults to now — override to test tolerance\n * handling (e.g. a timestamp older than 300s should fail verification).\n */\nexport const signStripePayload = async (\n payload: string,\n secret: string,\n timestamp: number = Math.floor(Date.now() / 1000),\n): Promise<string> => {\n const key = await requireSubtleCrypto().importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign'],\n )\n const signature = await requireSubtleCrypto().sign(\n 'HMAC',\n key,\n encoder.encode(`${timestamp}.${payload}`),\n )\n return `t=${timestamp},v1=${toHex(signature)}`\n}\n\nexport interface TestEventOptions {\n /** Event id. Default: `evt_test_<uuid>`. */\n id?: string\n /** `created` timestamp (Unix seconds). Default: now. */\n created?: number\n /** Default: false. */\n livemode?: boolean\n /** `previous_attributes` on `event.data`. */\n previousAttributes?: Record<string, unknown>\n /** `api_version` field. Default: null. */\n apiVersion?: string | null\n /** `request` field. Default: `{ id: null, idempotency_key: null }`. */\n request?: Stripe.Event['request']\n /** `pending_webhooks` count. Default: 1. */\n pendingWebhooks?: number\n}\n\n/** A `Stripe.Event` whose `data.object` carries the type of the fixture object. */\nexport type TestStripeEvent<O extends object> = Omit<Stripe.Event, 'data'> & {\n data: Omit<Stripe.Event['data'], 'object'> & { object: O }\n}\n\n/**\n * Build a fake `Stripe.Event`-shaped object around a `data.object` payload.\n *\n * Pass as much of the resource as your handler needs — the fixture is not\n * validated against Stripe's schema. For a fully-typed object, shape it to the\n * resource type (e.g. `Partial<Stripe.PaymentIntent>`).\n */\nexport const createTestEvent = <O extends object>(\n type: Stripe.Event['type'],\n object: O,\n options: TestEventOptions = {},\n): TestStripeEvent<O> => ({\n id: options.id ?? `evt_test_${globalThis.crypto.randomUUID()}`,\n object: 'event',\n api_version: options.apiVersion ?? null,\n created: options.created ?? Math.floor(Date.now() / 1000),\n data: { object, previous_attributes: options.previousAttributes },\n livemode: options.livemode ?? false,\n pending_webhooks: options.pendingWebhooks ?? 1,\n request: options.request ?? { id: null, idempotency_key: null },\n type,\n})\n\nexport interface CreateWebhookRequestOptions {\n /** Endpoint signing secret — must match what the app verifies against. */\n secret: string\n /** Request URL. Default: `http://localhost/webhook`. */\n url?: string | URL\n /** Signature timestamp (Unix seconds). Default: now. */\n timestamp?: number\n /** Extra request headers (merged after the signature header is set). */\n headers?: HeadersInit\n}\n\n/**\n * Wrap a payload in a `Request` with a valid `Stripe-Signature` header —\n * ready for `app.request(req)` in tests or a `fetch` against local dev.\n *\n * `event` may be a `createTestEvent` result, any object (JSON.stringify'd), or\n * a pre-serialized payload string — the signature covers the exact bytes sent.\n */\nexport const createWebhookRequest = async (\n event: object | string,\n options: CreateWebhookRequestOptions,\n): Promise<Request> => {\n const payload = typeof event === 'string' ? event : JSON.stringify(event)\n const signature = await signStripePayload(payload, options.secret, options.timestamp)\n const headers = new Headers({\n 'content-type': 'application/json',\n 'stripe-signature': signature,\n })\n // `HeadersInit` may be a Headers instance or tuple array, which object\n // spread would silently drop.\n new Headers(options.headers).forEach((value, key) => {\n headers.set(key, value)\n })\n return new Request(options.url ?? 'http://localhost/webhook', {\n method: 'POST',\n headers,\n body: payload,\n })\n}\n"]}
@@ -0,0 +1,80 @@
1
+ import Stripe from 'stripe';
2
+
3
+ /**
4
+ * The Stripe client config type (second constructor argument).
5
+ *
6
+ * `StripeConfig` is a top-level export of `stripe` rather than a member of the
7
+ * `Stripe` namespace, so we derive it from the constructor to stay robust
8
+ * across the supported peer range.
9
+ */
10
+ type StripeClientConfig = NonNullable<ConstructorParameters<typeof Stripe>[1]>;
11
+ /**
12
+ * True when running on a Node.js runtime.
13
+ *
14
+ * Delegates to Hono's `getRuntimeKey()` so this stays consistent with the
15
+ * runtime detection used by `env()` for secret-key resolution.
16
+ */
17
+ declare const isNodeRuntime: () => boolean;
18
+ /**
19
+ * True when running on Cloudflare Workers (`workerd`).
20
+ */
21
+ declare const isWorkersRuntime: () => boolean;
22
+ /**
23
+ * Whether the Stripe SDK should use the Fetch-based HTTP client.
24
+ *
25
+ * On Cloudflare Workers (and other non-Node edge runtimes) the default Node
26
+ * `http`/`https` client is unavailable, so Stripe must be initialized with
27
+ * `Stripe.createFetchHttpClient()`. This is the single most common "gotcha"
28
+ * when running stripe-node on the edge, and hono-stripe handles it for you.
29
+ */
30
+ declare const shouldUseFetchHttpClient: () => boolean;
31
+
32
+ /**
33
+ * Variables injected into the Hono context by {@link stripeMiddleware}.
34
+ * Use together with {@link StripeEnv} so `c.var.stripe` is typed.
35
+ */
36
+ type StripeVariables = {
37
+ stripe: Stripe;
38
+ };
39
+ /**
40
+ * Hono `Env` fragment contributed by hono-stripe.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { Hono } from 'hono'
45
+ * import { stripeMiddleware, type StripeEnv } from 'hono-stripe'
46
+ *
47
+ * const app = new Hono<StripeEnv>()
48
+ * app.use(stripeMiddleware())
49
+ * app.post('/api/payment-intent', (c) => {
50
+ * c.var.stripe // typed as Stripe
51
+ * // ...
52
+ * })
53
+ * ```
54
+ */
55
+ type StripeEnv = {
56
+ Variables: StripeVariables;
57
+ };
58
+ /**
59
+ * Options for {@link stripeMiddleware}.
60
+ *
61
+ * The secret key is resolved in this order:
62
+ * 1. {@link StripeMiddlewareOptions.apiKey} (explicit)
63
+ * 2. Cloudflare Workers env binding `c.env[secretKeyVar]`
64
+ * 3. `process.env[secretKeyVar]` (Node)
65
+ */
66
+ interface StripeMiddlewareOptions {
67
+ /** Secret key passed directly. Skips env-binding / process.env resolution. */
68
+ apiKey?: string;
69
+ /** Name of the env binding / `process.env` key holding the secret key. Default: `STRIPE_SECRET_KEY`. */
70
+ secretKeyVar?: string;
71
+ /** Stripe API version override. Defaults to the SDK's pinned version. */
72
+ apiVersion?: StripeClientConfig['apiVersion'];
73
+ /**
74
+ * Extra Stripe config. Merged last, so an explicit `httpClient` here
75
+ * overrides the automatic Workers `createFetchHttpClient()` selection.
76
+ */
77
+ config?: StripeClientConfig;
78
+ }
79
+
80
+ export { type StripeMiddlewareOptions as S, type StripeEnv as a, type StripeVariables as b, isWorkersRuntime as c, isNodeRuntime as i, shouldUseFetchHttpClient as s };
@@ -0,0 +1,80 @@
1
+ import Stripe from 'stripe';
2
+
3
+ /**
4
+ * The Stripe client config type (second constructor argument).
5
+ *
6
+ * `StripeConfig` is a top-level export of `stripe` rather than a member of the
7
+ * `Stripe` namespace, so we derive it from the constructor to stay robust
8
+ * across the supported peer range.
9
+ */
10
+ type StripeClientConfig = NonNullable<ConstructorParameters<typeof Stripe>[1]>;
11
+ /**
12
+ * True when running on a Node.js runtime.
13
+ *
14
+ * Delegates to Hono's `getRuntimeKey()` so this stays consistent with the
15
+ * runtime detection used by `env()` for secret-key resolution.
16
+ */
17
+ declare const isNodeRuntime: () => boolean;
18
+ /**
19
+ * True when running on Cloudflare Workers (`workerd`).
20
+ */
21
+ declare const isWorkersRuntime: () => boolean;
22
+ /**
23
+ * Whether the Stripe SDK should use the Fetch-based HTTP client.
24
+ *
25
+ * On Cloudflare Workers (and other non-Node edge runtimes) the default Node
26
+ * `http`/`https` client is unavailable, so Stripe must be initialized with
27
+ * `Stripe.createFetchHttpClient()`. This is the single most common "gotcha"
28
+ * when running stripe-node on the edge, and hono-stripe handles it for you.
29
+ */
30
+ declare const shouldUseFetchHttpClient: () => boolean;
31
+
32
+ /**
33
+ * Variables injected into the Hono context by {@link stripeMiddleware}.
34
+ * Use together with {@link StripeEnv} so `c.var.stripe` is typed.
35
+ */
36
+ type StripeVariables = {
37
+ stripe: Stripe;
38
+ };
39
+ /**
40
+ * Hono `Env` fragment contributed by hono-stripe.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { Hono } from 'hono'
45
+ * import { stripeMiddleware, type StripeEnv } from 'hono-stripe'
46
+ *
47
+ * const app = new Hono<StripeEnv>()
48
+ * app.use(stripeMiddleware())
49
+ * app.post('/api/payment-intent', (c) => {
50
+ * c.var.stripe // typed as Stripe
51
+ * // ...
52
+ * })
53
+ * ```
54
+ */
55
+ type StripeEnv = {
56
+ Variables: StripeVariables;
57
+ };
58
+ /**
59
+ * Options for {@link stripeMiddleware}.
60
+ *
61
+ * The secret key is resolved in this order:
62
+ * 1. {@link StripeMiddlewareOptions.apiKey} (explicit)
63
+ * 2. Cloudflare Workers env binding `c.env[secretKeyVar]`
64
+ * 3. `process.env[secretKeyVar]` (Node)
65
+ */
66
+ interface StripeMiddlewareOptions {
67
+ /** Secret key passed directly. Skips env-binding / process.env resolution. */
68
+ apiKey?: string;
69
+ /** Name of the env binding / `process.env` key holding the secret key. Default: `STRIPE_SECRET_KEY`. */
70
+ secretKeyVar?: string;
71
+ /** Stripe API version override. Defaults to the SDK's pinned version. */
72
+ apiVersion?: StripeClientConfig['apiVersion'];
73
+ /**
74
+ * Extra Stripe config. Merged last, so an explicit `httpClient` here
75
+ * overrides the automatic Workers `createFetchHttpClient()` selection.
76
+ */
77
+ config?: StripeClientConfig;
78
+ }
79
+
80
+ export { type StripeMiddlewareOptions as S, type StripeEnv as a, type StripeVariables as b, isWorkersRuntime as c, isNodeRuntime as i, shouldUseFetchHttpClient as s };
package/dist/ui.cjs ADDED
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+
3
+ var jsxRuntime = require('hono/jsx/jsx-runtime');
4
+
5
+ // src/ui.tsx
6
+ var STRIPE_ELEMENTS_CDN_URL = "https://cdn.jsdelivr.net/npm/stripe-pwa-elements@3/dist/stripe-elements/stripe-elements.esm.js";
7
+ var StripeElementsScript = ({ src }) => /* @__PURE__ */ jsxRuntime.jsx("script", { type: "module", src: src ?? STRIPE_ELEMENTS_CDN_URL });
8
+ var StripePaymentForm = (props) => {
9
+ if (!props.clientSecret && !props.endpoint) {
10
+ throw new Error(
11
+ "hono-stripe/ui: <StripePaymentForm> requires either `clientSecret` (SSR) or `endpoint` (client fetch)."
12
+ );
13
+ }
14
+ const id = props.id ?? `hono-stripe-payment-${globalThis.crypto.randomUUID()}`;
15
+ const isCheckout = props.intent === "checkout";
16
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
17
+ /* @__PURE__ */ jsxRuntime.jsx(
18
+ "stripe-payment-element",
19
+ {
20
+ id,
21
+ class: props.class,
22
+ "publishable-key": props.publishableKey,
23
+ "intent-client-secret": !isCheckout ? props.clientSecret : void 0,
24
+ "checkout-session-client-secret": isCheckout ? props.clientSecret : void 0
25
+ }
26
+ ),
27
+ /* @__PURE__ */ jsxRuntime.jsx(StripeElementsScript, { src: props.src }),
28
+ props.endpoint ? /* @__PURE__ */ jsxRuntime.jsx("script", { type: "module", dangerouslySetInnerHTML: { __html: bootstrapScript(id, props) } }) : null
29
+ ] });
30
+ };
31
+ var jsLiteral = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
32
+ var bootstrapScript = (id, props) => {
33
+ const secretProp = props.intent === "checkout" ? "checkoutSessionClientSecret" : "intentClientSecret";
34
+ const fallbackKey = jsLiteral(props.publishableKey ?? null);
35
+ return `const res = await fetch(${jsLiteral(props.endpoint)}, { method: 'POST' });
36
+ if (!res.ok) throw new Error('[hono-stripe] payment endpoint failed: ' + res.status);
37
+ const data = await res.json();
38
+ const el = document.getElementById(${jsLiteral(id)});
39
+ el.publishableKey = data.publishableKey ?? ${fallbackKey};
40
+ el.${secretProp} = data.clientSecret;`;
41
+ };
42
+
43
+ exports.STRIPE_ELEMENTS_CDN_URL = STRIPE_ELEMENTS_CDN_URL;
44
+ exports.StripeElementsScript = StripeElementsScript;
45
+ exports.StripePaymentForm = StripePaymentForm;
46
+ //# sourceMappingURL=ui.cjs.map
47
+ //# sourceMappingURL=ui.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ui.tsx"],"names":["jsx","jsxs","Fragment"],"mappings":";;;;;AAgBO,IAAM,uBAAA,GACX;AA8BK,IAAM,oBAAA,GAAsD,CAAC,EAAE,GAAA,EAAI,qBACxEA,cAAA,CAAC,QAAA,EAAA,EAAO,IAAA,EAAK,QAAA,EAAS,GAAA,EAAK,GAAA,IAAO,uBAAA,EAAyB;AAgDtD,IAAM,iBAAA,GAAgD,CAAC,KAAA,KAAU;AACtE,EAAA,IAAI,CAAC,KAAA,CAAM,YAAA,IAAgB,CAAC,MAAM,QAAA,EAAU;AAC1C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,MAAM,KAAK,KAAA,CAAM,EAAA,IAAM,uBAAuB,UAAA,CAAW,MAAA,CAAO,YAAY,CAAA,CAAA;AAC5E,EAAA,MAAM,UAAA,GAAa,MAAM,MAAA,KAAW,UAAA;AACpC,EAAA,uBACEC,eAAA,CAAAC,mBAAA,EAAA,EACE,QAAA,EAAA;AAAA,oBAAAF,cAAA;AAAA,MAAC,wBAAA;AAAA,MAAA;AAAA,QACC,EAAA;AAAA,QACA,OAAO,KAAA,CAAM,KAAA;AAAA,QACb,mBAAiB,KAAA,CAAM,cAAA;AAAA,QACvB,sBAAA,EAAsB,CAAC,UAAA,GAAa,KAAA,CAAM,YAAA,GAAe,MAAA;AAAA,QACzD,gCAAA,EAAgC,UAAA,GAAa,KAAA,CAAM,YAAA,GAAe;AAAA;AAAA,KACpE;AAAA,oBACAA,cAAA,CAAC,oBAAA,EAAA,EAAqB,GAAA,EAAK,KAAA,CAAM,GAAA,EAAK,CAAA;AAAA,IACrC,KAAA,CAAM,QAAA,mBACLA,cAAA,CAAC,QAAA,EAAA,EAAO,MAAK,QAAA,EAAS,uBAAA,EAAyB,EAAE,MAAA,EAAQ,eAAA,CAAgB,EAAA,EAAI,KAAK,CAAA,IAAK,CAAA,GACrF;AAAA,GAAA,EACN,CAAA;AAEJ;AAGA,IAAM,SAAA,GAAY,CAAC,KAAA,KAA2B,IAAA,CAAK,UAAU,KAAK,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,SAAS,CAAA;AAE3F,IAAM,eAAA,GAAkB,CAAC,EAAA,EAAY,KAAA,KAA0C;AAC7E,EAAA,MAAM,UAAA,GACJ,KAAA,CAAM,MAAA,KAAW,UAAA,GAAa,6BAAA,GAAgC,oBAAA;AAChE,EAAA,MAAM,WAAA,GAAc,SAAA,CAAU,KAAA,CAAM,cAAA,IAAkB,IAAI,CAAA;AAC1D,EAAA,OAAO,CAAA,wBAAA,EAA2B,SAAA,CAAU,KAAA,CAAM,QAAQ,CAAC,CAAA;AAAA;AAAA;AAAA,mCAAA,EAGxB,SAAA,CAAU,EAAE,CAAC,CAAA;AAAA,2CAAA,EACL,WAAW,CAAA;AAAA,GAAA,EACnD,UAAU,CAAA,qBAAA,CAAA;AACf,CAAA","file":"ui.cjs","sourcesContent":["import type { Child, FC } from 'hono/jsx'\n\n/**\n * Server-side JSX helpers (hono/jsx, HonoX-compatible) that render the\n * [stripe-pwa-elements](https://github.com/stripe/stripe-pwa-elements) web\n * components — Payment Element without React.\n *\n * The browser-side component code is NOT bundled here: it is loaded as an ES\n * module from a CDN (default jsDelivr) or wherever {@link StripeElementsScript}'s\n * `src` points. This module only produces the markup + bootstrap script.\n */\n\n/**\n * Module URL for the stripe-pwa-elements lazy loader (registers all\n * `stripe-*` custom elements). Pinned to major version 3.\n */\nexport const STRIPE_ELEMENTS_CDN_URL =\n 'https://cdn.jsdelivr.net/npm/stripe-pwa-elements@3/dist/stripe-elements/stripe-elements.esm.js'\n\ninterface StripePaymentElementAttributes {\n id?: string\n class?: string\n style?: string\n 'publishable-key'?: string\n 'intent-client-secret'?: string\n 'checkout-session-client-secret'?: string\n children?: Child\n}\n\ndeclare module 'hono/jsx' {\n namespace JSX {\n interface IntrinsicElements {\n 'stripe-payment-element': StripePaymentElementAttributes\n }\n }\n}\n\nexport interface StripeElementsScriptProps {\n /** Module URL for the elements bundle. Default: {@link STRIPE_ELEMENTS_CDN_URL}. */\n src?: string\n}\n\n/**\n * `<script type=\"module\">` tag that registers the stripe-pwa-elements custom\n * elements. Rendering it more than once is harmless — module scripts are\n * deduplicated by URL — so components below include it unconditionally.\n */\nexport const StripeElementsScript: FC<StripeElementsScriptProps> = ({ src }) => (\n <script type=\"module\" src={src ?? STRIPE_ELEMENTS_CDN_URL} />\n)\n\nexport interface StripePaymentFormProps {\n /**\n * Server endpoint (POST) returning `{ clientSecret, publishableKey? }` —\n * typically backed by `getStripe(c).paymentIntents.create` /\n * `getStripe(c).checkout.sessions.create`.\n * Required unless `clientSecret` is given.\n */\n endpoint?: string\n /**\n * A `client_secret` created during SSR (via `getStripe(c)` in the same\n * request). When set, no fetch is made and the secret is rendered as an\n * element attribute directly.\n */\n clientSecret?: string\n /**\n * Stripe publishable key (`pk_...`). In endpoint mode it is only a fallback —\n * a `publishableKey` in the endpoint response wins.\n */\n publishableKey?: string\n /** Which kind of secret drives the element. Default: `payment`. */\n intent?: 'payment' | 'checkout'\n /** DOM id for the `<stripe-payment-element>`. Default: a unique generated id. */\n id?: string\n class?: string\n /** Passed through to {@link StripeElementsScript}. */\n src?: string\n}\n\n/**\n * Renders a `<stripe-payment-element>` wired to a PaymentIntent or embedded\n * Checkout Session client_secret.\n *\n * Two modes:\n * - **`endpoint`** (client fetch): the browser POSTs to `endpoint`, expects\n * `{ clientSecret, publishableKey? }` back, and assigns it to the element.\n * - **`clientSecret`** (SSR): the secret is rendered as an attribute — no\n * client-side fetch.\n *\n * @example\n * ```tsx\n * app.get('/', (c) => c.html(\n * <StripePaymentForm endpoint=\"/api/payment-intent\" publishableKey={c.env.STRIPE_PK} />\n * ))\n * ```\n */\nexport const StripePaymentForm: FC<StripePaymentFormProps> = (props) => {\n if (!props.clientSecret && !props.endpoint) {\n throw new Error(\n 'hono-stripe/ui: <StripePaymentForm> requires either `clientSecret` (SSR) or `endpoint` (client fetch).',\n )\n }\n const id = props.id ?? `hono-stripe-payment-${globalThis.crypto.randomUUID()}`\n const isCheckout = props.intent === 'checkout'\n return (\n <>\n <stripe-payment-element\n id={id}\n class={props.class}\n publishable-key={props.publishableKey}\n intent-client-secret={!isCheckout ? props.clientSecret : undefined}\n checkout-session-client-secret={isCheckout ? props.clientSecret : undefined}\n />\n <StripeElementsScript src={props.src} />\n {props.endpoint ? (\n <script type=\"module\" dangerouslySetInnerHTML={{ __html: bootstrapScript(id, props) }} />\n ) : null}\n </>\n )\n}\n\n/** JSON-encode for embedding in an inline `<script>`: `<` is escaped so a value containing `</script>` cannot close the element. */\nconst jsLiteral = (value: unknown): string => JSON.stringify(value).replace(/</g, '\\\\u003c')\n\nconst bootstrapScript = (id: string, props: StripePaymentFormProps): string => {\n const secretProp =\n props.intent === 'checkout' ? 'checkoutSessionClientSecret' : 'intentClientSecret'\n const fallbackKey = jsLiteral(props.publishableKey ?? null)\n return `const res = await fetch(${jsLiteral(props.endpoint)}, { method: 'POST' });\nif (!res.ok) throw new Error('[hono-stripe] payment endpoint failed: ' + res.status);\nconst data = await res.json();\nconst el = document.getElementById(${jsLiteral(id)});\nel.publishableKey = data.publishableKey ?? ${fallbackKey};\nel.${secretProp} = data.clientSecret;`\n}\n"]}
package/dist/ui.d.cts ADDED
@@ -0,0 +1,89 @@
1
+ import { Child, FC } from 'hono/jsx';
2
+
3
+ /**
4
+ * Server-side JSX helpers (hono/jsx, HonoX-compatible) that render the
5
+ * [stripe-pwa-elements](https://github.com/stripe/stripe-pwa-elements) web
6
+ * components — Payment Element without React.
7
+ *
8
+ * The browser-side component code is NOT bundled here: it is loaded as an ES
9
+ * module from a CDN (default jsDelivr) or wherever {@link StripeElementsScript}'s
10
+ * `src` points. This module only produces the markup + bootstrap script.
11
+ */
12
+ /**
13
+ * Module URL for the stripe-pwa-elements lazy loader (registers all
14
+ * `stripe-*` custom elements). Pinned to major version 3.
15
+ */
16
+ declare const STRIPE_ELEMENTS_CDN_URL = "https://cdn.jsdelivr.net/npm/stripe-pwa-elements@3/dist/stripe-elements/stripe-elements.esm.js";
17
+ interface StripePaymentElementAttributes {
18
+ id?: string;
19
+ class?: string;
20
+ style?: string;
21
+ 'publishable-key'?: string;
22
+ 'intent-client-secret'?: string;
23
+ 'checkout-session-client-secret'?: string;
24
+ children?: Child;
25
+ }
26
+ declare module 'hono/jsx' {
27
+ namespace JSX {
28
+ interface IntrinsicElements {
29
+ 'stripe-payment-element': StripePaymentElementAttributes;
30
+ }
31
+ }
32
+ }
33
+ interface StripeElementsScriptProps {
34
+ /** Module URL for the elements bundle. Default: {@link STRIPE_ELEMENTS_CDN_URL}. */
35
+ src?: string;
36
+ }
37
+ /**
38
+ * `<script type="module">` tag that registers the stripe-pwa-elements custom
39
+ * elements. Rendering it more than once is harmless — module scripts are
40
+ * deduplicated by URL — so components below include it unconditionally.
41
+ */
42
+ declare const StripeElementsScript: FC<StripeElementsScriptProps>;
43
+ interface StripePaymentFormProps {
44
+ /**
45
+ * Server endpoint (POST) returning `{ clientSecret, publishableKey? }` —
46
+ * typically backed by `getStripe(c).paymentIntents.create` /
47
+ * `getStripe(c).checkout.sessions.create`.
48
+ * Required unless `clientSecret` is given.
49
+ */
50
+ endpoint?: string;
51
+ /**
52
+ * A `client_secret` created during SSR (via `getStripe(c)` in the same
53
+ * request). When set, no fetch is made and the secret is rendered as an
54
+ * element attribute directly.
55
+ */
56
+ clientSecret?: string;
57
+ /**
58
+ * Stripe publishable key (`pk_...`). In endpoint mode it is only a fallback —
59
+ * a `publishableKey` in the endpoint response wins.
60
+ */
61
+ publishableKey?: string;
62
+ /** Which kind of secret drives the element. Default: `payment`. */
63
+ intent?: 'payment' | 'checkout';
64
+ /** DOM id for the `<stripe-payment-element>`. Default: a unique generated id. */
65
+ id?: string;
66
+ class?: string;
67
+ /** Passed through to {@link StripeElementsScript}. */
68
+ src?: string;
69
+ }
70
+ /**
71
+ * Renders a `<stripe-payment-element>` wired to a PaymentIntent or embedded
72
+ * Checkout Session client_secret.
73
+ *
74
+ * Two modes:
75
+ * - **`endpoint`** (client fetch): the browser POSTs to `endpoint`, expects
76
+ * `{ clientSecret, publishableKey? }` back, and assigns it to the element.
77
+ * - **`clientSecret`** (SSR): the secret is rendered as an attribute — no
78
+ * client-side fetch.
79
+ *
80
+ * @example
81
+ * ```tsx
82
+ * app.get('/', (c) => c.html(
83
+ * <StripePaymentForm endpoint="/api/payment-intent" publishableKey={c.env.STRIPE_PK} />
84
+ * ))
85
+ * ```
86
+ */
87
+ declare const StripePaymentForm: FC<StripePaymentFormProps>;
88
+
89
+ export { STRIPE_ELEMENTS_CDN_URL, StripeElementsScript, type StripeElementsScriptProps, StripePaymentForm, type StripePaymentFormProps };
package/dist/ui.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ import { Child, FC } from 'hono/jsx';
2
+
3
+ /**
4
+ * Server-side JSX helpers (hono/jsx, HonoX-compatible) that render the
5
+ * [stripe-pwa-elements](https://github.com/stripe/stripe-pwa-elements) web
6
+ * components — Payment Element without React.
7
+ *
8
+ * The browser-side component code is NOT bundled here: it is loaded as an ES
9
+ * module from a CDN (default jsDelivr) or wherever {@link StripeElementsScript}'s
10
+ * `src` points. This module only produces the markup + bootstrap script.
11
+ */
12
+ /**
13
+ * Module URL for the stripe-pwa-elements lazy loader (registers all
14
+ * `stripe-*` custom elements). Pinned to major version 3.
15
+ */
16
+ declare const STRIPE_ELEMENTS_CDN_URL = "https://cdn.jsdelivr.net/npm/stripe-pwa-elements@3/dist/stripe-elements/stripe-elements.esm.js";
17
+ interface StripePaymentElementAttributes {
18
+ id?: string;
19
+ class?: string;
20
+ style?: string;
21
+ 'publishable-key'?: string;
22
+ 'intent-client-secret'?: string;
23
+ 'checkout-session-client-secret'?: string;
24
+ children?: Child;
25
+ }
26
+ declare module 'hono/jsx' {
27
+ namespace JSX {
28
+ interface IntrinsicElements {
29
+ 'stripe-payment-element': StripePaymentElementAttributes;
30
+ }
31
+ }
32
+ }
33
+ interface StripeElementsScriptProps {
34
+ /** Module URL for the elements bundle. Default: {@link STRIPE_ELEMENTS_CDN_URL}. */
35
+ src?: string;
36
+ }
37
+ /**
38
+ * `<script type="module">` tag that registers the stripe-pwa-elements custom
39
+ * elements. Rendering it more than once is harmless — module scripts are
40
+ * deduplicated by URL — so components below include it unconditionally.
41
+ */
42
+ declare const StripeElementsScript: FC<StripeElementsScriptProps>;
43
+ interface StripePaymentFormProps {
44
+ /**
45
+ * Server endpoint (POST) returning `{ clientSecret, publishableKey? }` —
46
+ * typically backed by `getStripe(c).paymentIntents.create` /
47
+ * `getStripe(c).checkout.sessions.create`.
48
+ * Required unless `clientSecret` is given.
49
+ */
50
+ endpoint?: string;
51
+ /**
52
+ * A `client_secret` created during SSR (via `getStripe(c)` in the same
53
+ * request). When set, no fetch is made and the secret is rendered as an
54
+ * element attribute directly.
55
+ */
56
+ clientSecret?: string;
57
+ /**
58
+ * Stripe publishable key (`pk_...`). In endpoint mode it is only a fallback —
59
+ * a `publishableKey` in the endpoint response wins.
60
+ */
61
+ publishableKey?: string;
62
+ /** Which kind of secret drives the element. Default: `payment`. */
63
+ intent?: 'payment' | 'checkout';
64
+ /** DOM id for the `<stripe-payment-element>`. Default: a unique generated id. */
65
+ id?: string;
66
+ class?: string;
67
+ /** Passed through to {@link StripeElementsScript}. */
68
+ src?: string;
69
+ }
70
+ /**
71
+ * Renders a `<stripe-payment-element>` wired to a PaymentIntent or embedded
72
+ * Checkout Session client_secret.
73
+ *
74
+ * Two modes:
75
+ * - **`endpoint`** (client fetch): the browser POSTs to `endpoint`, expects
76
+ * `{ clientSecret, publishableKey? }` back, and assigns it to the element.
77
+ * - **`clientSecret`** (SSR): the secret is rendered as an attribute — no
78
+ * client-side fetch.
79
+ *
80
+ * @example
81
+ * ```tsx
82
+ * app.get('/', (c) => c.html(
83
+ * <StripePaymentForm endpoint="/api/payment-intent" publishableKey={c.env.STRIPE_PK} />
84
+ * ))
85
+ * ```
86
+ */
87
+ declare const StripePaymentForm: FC<StripePaymentFormProps>;
88
+
89
+ export { STRIPE_ELEMENTS_CDN_URL, StripeElementsScript, type StripeElementsScriptProps, StripePaymentForm, type StripePaymentFormProps };
package/dist/ui.js ADDED
@@ -0,0 +1,43 @@
1
+ import { jsx, jsxs, Fragment } from 'hono/jsx/jsx-runtime';
2
+
3
+ // src/ui.tsx
4
+ var STRIPE_ELEMENTS_CDN_URL = "https://cdn.jsdelivr.net/npm/stripe-pwa-elements@3/dist/stripe-elements/stripe-elements.esm.js";
5
+ var StripeElementsScript = ({ src }) => /* @__PURE__ */ jsx("script", { type: "module", src: src ?? STRIPE_ELEMENTS_CDN_URL });
6
+ var StripePaymentForm = (props) => {
7
+ if (!props.clientSecret && !props.endpoint) {
8
+ throw new Error(
9
+ "hono-stripe/ui: <StripePaymentForm> requires either `clientSecret` (SSR) or `endpoint` (client fetch)."
10
+ );
11
+ }
12
+ const id = props.id ?? `hono-stripe-payment-${globalThis.crypto.randomUUID()}`;
13
+ const isCheckout = props.intent === "checkout";
14
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
15
+ /* @__PURE__ */ jsx(
16
+ "stripe-payment-element",
17
+ {
18
+ id,
19
+ class: props.class,
20
+ "publishable-key": props.publishableKey,
21
+ "intent-client-secret": !isCheckout ? props.clientSecret : void 0,
22
+ "checkout-session-client-secret": isCheckout ? props.clientSecret : void 0
23
+ }
24
+ ),
25
+ /* @__PURE__ */ jsx(StripeElementsScript, { src: props.src }),
26
+ props.endpoint ? /* @__PURE__ */ jsx("script", { type: "module", dangerouslySetInnerHTML: { __html: bootstrapScript(id, props) } }) : null
27
+ ] });
28
+ };
29
+ var jsLiteral = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
30
+ var bootstrapScript = (id, props) => {
31
+ const secretProp = props.intent === "checkout" ? "checkoutSessionClientSecret" : "intentClientSecret";
32
+ const fallbackKey = jsLiteral(props.publishableKey ?? null);
33
+ return `const res = await fetch(${jsLiteral(props.endpoint)}, { method: 'POST' });
34
+ if (!res.ok) throw new Error('[hono-stripe] payment endpoint failed: ' + res.status);
35
+ const data = await res.json();
36
+ const el = document.getElementById(${jsLiteral(id)});
37
+ el.publishableKey = data.publishableKey ?? ${fallbackKey};
38
+ el.${secretProp} = data.clientSecret;`;
39
+ };
40
+
41
+ export { STRIPE_ELEMENTS_CDN_URL, StripeElementsScript, StripePaymentForm };
42
+ //# sourceMappingURL=ui.js.map
43
+ //# sourceMappingURL=ui.js.map
package/dist/ui.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/ui.tsx"],"names":[],"mappings":";;;AAgBO,IAAM,uBAAA,GACX;AA8BK,IAAM,oBAAA,GAAsD,CAAC,EAAE,GAAA,EAAI,qBACxE,GAAA,CAAC,QAAA,EAAA,EAAO,IAAA,EAAK,QAAA,EAAS,GAAA,EAAK,GAAA,IAAO,uBAAA,EAAyB;AAgDtD,IAAM,iBAAA,GAAgD,CAAC,KAAA,KAAU;AACtE,EAAA,IAAI,CAAC,KAAA,CAAM,YAAA,IAAgB,CAAC,MAAM,QAAA,EAAU;AAC1C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,MAAM,KAAK,KAAA,CAAM,EAAA,IAAM,uBAAuB,UAAA,CAAW,MAAA,CAAO,YAAY,CAAA,CAAA;AAC5E,EAAA,MAAM,UAAA,GAAa,MAAM,MAAA,KAAW,UAAA;AACpC,EAAA,uBACE,IAAA,CAAA,QAAA,EAAA,EACE,QAAA,EAAA;AAAA,oBAAA,GAAA;AAAA,MAAC,wBAAA;AAAA,MAAA;AAAA,QACC,EAAA;AAAA,QACA,OAAO,KAAA,CAAM,KAAA;AAAA,QACb,mBAAiB,KAAA,CAAM,cAAA;AAAA,QACvB,sBAAA,EAAsB,CAAC,UAAA,GAAa,KAAA,CAAM,YAAA,GAAe,MAAA;AAAA,QACzD,gCAAA,EAAgC,UAAA,GAAa,KAAA,CAAM,YAAA,GAAe;AAAA;AAAA,KACpE;AAAA,oBACA,GAAA,CAAC,oBAAA,EAAA,EAAqB,GAAA,EAAK,KAAA,CAAM,GAAA,EAAK,CAAA;AAAA,IACrC,KAAA,CAAM,QAAA,mBACL,GAAA,CAAC,QAAA,EAAA,EAAO,MAAK,QAAA,EAAS,uBAAA,EAAyB,EAAE,MAAA,EAAQ,eAAA,CAAgB,EAAA,EAAI,KAAK,CAAA,IAAK,CAAA,GACrF;AAAA,GAAA,EACN,CAAA;AAEJ;AAGA,IAAM,SAAA,GAAY,CAAC,KAAA,KAA2B,IAAA,CAAK,UAAU,KAAK,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,SAAS,CAAA;AAE3F,IAAM,eAAA,GAAkB,CAAC,EAAA,EAAY,KAAA,KAA0C;AAC7E,EAAA,MAAM,UAAA,GACJ,KAAA,CAAM,MAAA,KAAW,UAAA,GAAa,6BAAA,GAAgC,oBAAA;AAChE,EAAA,MAAM,WAAA,GAAc,SAAA,CAAU,KAAA,CAAM,cAAA,IAAkB,IAAI,CAAA;AAC1D,EAAA,OAAO,CAAA,wBAAA,EAA2B,SAAA,CAAU,KAAA,CAAM,QAAQ,CAAC,CAAA;AAAA;AAAA;AAAA,mCAAA,EAGxB,SAAA,CAAU,EAAE,CAAC,CAAA;AAAA,2CAAA,EACL,WAAW,CAAA;AAAA,GAAA,EACnD,UAAU,CAAA,qBAAA,CAAA;AACf,CAAA","file":"ui.js","sourcesContent":["import type { Child, FC } from 'hono/jsx'\n\n/**\n * Server-side JSX helpers (hono/jsx, HonoX-compatible) that render the\n * [stripe-pwa-elements](https://github.com/stripe/stripe-pwa-elements) web\n * components — Payment Element without React.\n *\n * The browser-side component code is NOT bundled here: it is loaded as an ES\n * module from a CDN (default jsDelivr) or wherever {@link StripeElementsScript}'s\n * `src` points. This module only produces the markup + bootstrap script.\n */\n\n/**\n * Module URL for the stripe-pwa-elements lazy loader (registers all\n * `stripe-*` custom elements). Pinned to major version 3.\n */\nexport const STRIPE_ELEMENTS_CDN_URL =\n 'https://cdn.jsdelivr.net/npm/stripe-pwa-elements@3/dist/stripe-elements/stripe-elements.esm.js'\n\ninterface StripePaymentElementAttributes {\n id?: string\n class?: string\n style?: string\n 'publishable-key'?: string\n 'intent-client-secret'?: string\n 'checkout-session-client-secret'?: string\n children?: Child\n}\n\ndeclare module 'hono/jsx' {\n namespace JSX {\n interface IntrinsicElements {\n 'stripe-payment-element': StripePaymentElementAttributes\n }\n }\n}\n\nexport interface StripeElementsScriptProps {\n /** Module URL for the elements bundle. Default: {@link STRIPE_ELEMENTS_CDN_URL}. */\n src?: string\n}\n\n/**\n * `<script type=\"module\">` tag that registers the stripe-pwa-elements custom\n * elements. Rendering it more than once is harmless — module scripts are\n * deduplicated by URL — so components below include it unconditionally.\n */\nexport const StripeElementsScript: FC<StripeElementsScriptProps> = ({ src }) => (\n <script type=\"module\" src={src ?? STRIPE_ELEMENTS_CDN_URL} />\n)\n\nexport interface StripePaymentFormProps {\n /**\n * Server endpoint (POST) returning `{ clientSecret, publishableKey? }` —\n * typically backed by `getStripe(c).paymentIntents.create` /\n * `getStripe(c).checkout.sessions.create`.\n * Required unless `clientSecret` is given.\n */\n endpoint?: string\n /**\n * A `client_secret` created during SSR (via `getStripe(c)` in the same\n * request). When set, no fetch is made and the secret is rendered as an\n * element attribute directly.\n */\n clientSecret?: string\n /**\n * Stripe publishable key (`pk_...`). In endpoint mode it is only a fallback —\n * a `publishableKey` in the endpoint response wins.\n */\n publishableKey?: string\n /** Which kind of secret drives the element. Default: `payment`. */\n intent?: 'payment' | 'checkout'\n /** DOM id for the `<stripe-payment-element>`. Default: a unique generated id. */\n id?: string\n class?: string\n /** Passed through to {@link StripeElementsScript}. */\n src?: string\n}\n\n/**\n * Renders a `<stripe-payment-element>` wired to a PaymentIntent or embedded\n * Checkout Session client_secret.\n *\n * Two modes:\n * - **`endpoint`** (client fetch): the browser POSTs to `endpoint`, expects\n * `{ clientSecret, publishableKey? }` back, and assigns it to the element.\n * - **`clientSecret`** (SSR): the secret is rendered as an attribute — no\n * client-side fetch.\n *\n * @example\n * ```tsx\n * app.get('/', (c) => c.html(\n * <StripePaymentForm endpoint=\"/api/payment-intent\" publishableKey={c.env.STRIPE_PK} />\n * ))\n * ```\n */\nexport const StripePaymentForm: FC<StripePaymentFormProps> = (props) => {\n if (!props.clientSecret && !props.endpoint) {\n throw new Error(\n 'hono-stripe/ui: <StripePaymentForm> requires either `clientSecret` (SSR) or `endpoint` (client fetch).',\n )\n }\n const id = props.id ?? `hono-stripe-payment-${globalThis.crypto.randomUUID()}`\n const isCheckout = props.intent === 'checkout'\n return (\n <>\n <stripe-payment-element\n id={id}\n class={props.class}\n publishable-key={props.publishableKey}\n intent-client-secret={!isCheckout ? props.clientSecret : undefined}\n checkout-session-client-secret={isCheckout ? props.clientSecret : undefined}\n />\n <StripeElementsScript src={props.src} />\n {props.endpoint ? (\n <script type=\"module\" dangerouslySetInnerHTML={{ __html: bootstrapScript(id, props) }} />\n ) : null}\n </>\n )\n}\n\n/** JSON-encode for embedding in an inline `<script>`: `<` is escaped so a value containing `</script>` cannot close the element. */\nconst jsLiteral = (value: unknown): string => JSON.stringify(value).replace(/</g, '\\\\u003c')\n\nconst bootstrapScript = (id: string, props: StripePaymentFormProps): string => {\n const secretProp =\n props.intent === 'checkout' ? 'checkoutSessionClientSecret' : 'intentClientSecret'\n const fallbackKey = jsLiteral(props.publishableKey ?? null)\n return `const res = await fetch(${jsLiteral(props.endpoint)}, { method: 'POST' });\nif (!res.ok) throw new Error('[hono-stripe] payment endpoint failed: ' + res.status);\nconst data = await res.json();\nconst el = document.getElementById(${jsLiteral(id)});\nel.publishableKey = data.publishableKey ?? ${fallbackKey};\nel.${secretProp} = data.clientSecret;`\n}\n"]}