@lunora/x402 1.0.0-alpha.9 → 1.0.0-alpha.90

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.
Files changed (32) hide show
  1. package/LICENSE.md +18 -0
  2. package/README.md +22 -4
  3. package/dist/charge/index.d.mts +82 -47
  4. package/dist/charge/index.d.ts +82 -47
  5. package/dist/charge/index.mjs +1 -1
  6. package/dist/index.d.mts +2 -5
  7. package/dist/index.d.ts +2 -5
  8. package/dist/index.mjs +1 -1
  9. package/dist/packem_shared/DEFAULT_ALLOWED_ASSETS-CX67Ktyc.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_FACILITATOR_URL-CPJNUMvi.mjs +1 -0
  11. package/dist/packem_shared/EVM_NETWORKS-CwbBEtp1.mjs +1 -0
  12. package/dist/packem_shared/createChargeMiddleware-DyOEuTCT.mjs +1 -0
  13. package/dist/packem_shared/createProcedureChargeGate-BidGWCmf.mjs +1 -0
  14. package/dist/packem_shared/{config.d-B-NYmHgG.d.ts → index.d-A-g7yKuO.d.mts} +122 -130
  15. package/dist/packem_shared/{config.d-B-NYmHgG.d.mts → index.d-A-g7yKuO.d.ts} +122 -130
  16. package/dist/packem_shared/optional-peer-BBhVxozi.mjs +1 -0
  17. package/dist/packem_shared/toPaymentEventRow-DTXuTDh0.mjs +1 -0
  18. package/dist/packem_shared/withX402-mUrRb9a2.mjs +1 -0
  19. package/dist/pay/index.d.mts +9 -58
  20. package/dist/pay/index.d.ts +9 -58
  21. package/dist/pay/index.mjs +1 -1
  22. package/package.json +21 -9
  23. package/dist/packem_shared/DEFAULT_FACILITATOR_URL-lUtljfJI.mjs +0 -1
  24. package/dist/packem_shared/DEFAULT_STABLECOIN_DECIMALS-gY9zXmGa.mjs +0 -1
  25. package/dist/packem_shared/EVM_NETWORKS-XOms9Rtk.mjs +0 -1
  26. package/dist/packem_shared/createChargeMiddleware-MQhSA6Wt.mjs +0 -1
  27. package/dist/packem_shared/createFacilitatorClient-Dj4Ll9xQ.mjs +0 -1
  28. package/dist/packem_shared/createPayFetch-CDZJaS13.mjs +0 -1
  29. package/dist/packem_shared/createProcedureChargeGate-Cfm5mD2y.mjs +0 -1
  30. package/dist/packem_shared/registerWallet-Cu4qF5tj.mjs +0 -1
  31. package/dist/packem_shared/toPaymentEventRow-D_kRVcb3.mjs +0 -1
  32. package/dist/packem_shared/withX402-D10895ct.mjs +0 -1
package/LICENSE.md CHANGED
@@ -108,4 +108,22 @@ specific language governing permissions and limitations under the License.
108
108
  <!-- /DEPENDENCIES -->
109
109
 
110
110
  <!-- TYPE_DEPENDENCIES -->
111
+
112
+ # Licenses of bundled types
113
+ The published @lunora/x402 artifact additionally contains code with the following licenses:
114
+ Apache-2.0
115
+
116
+ # Bundled types:
117
+ ## @x402/evm
118
+ License: Apache-2.0
119
+ By: x402 Foundation
120
+ Repository: https://github.com/x402-foundation/x402
121
+
122
+ ---------------------------------------
123
+
124
+ ## @x402/svm
125
+ License: Apache-2.0
126
+ By: x402 Foundation
127
+ Repository: https://github.com/x402-foundation/x402
128
+
111
129
  <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -1,7 +1,5 @@
1
1
  # @lunora/x402
2
2
 
3
- > **Experimental** — this package is outside the Lunora 1.0 stability promise: its API may change in any release, without a major version bump.
4
-
5
3
  > Agentic payments over the [x402](https://x402.org) protocol for [Lunora](https://lunora.sh).
6
4
 
7
5
  x402 turns HTTP `402 Payment Required` into a machine-payable rail: no accounts,
@@ -25,6 +23,24 @@ The root export (`@lunora/x402`) carries only the shared config/types
25
23
  (`.x402({ price })`), and MCP tools behind a USDC price; the **pay** rail signs and
26
24
  retries `402` challenges under a mandatory spend policy.
27
25
 
26
+ ## Install
27
+
28
+ The chain toolchains are **optional peers**, so an EVM-only deployment never
29
+ installs Solana's (heavy) toolchain and vice versa. Install the pair your
30
+ network family needs alongside the package:
31
+
32
+ ```bash
33
+ pnpm add @lunora/x402 # protocol core only
34
+ pnpm add @x402/evm viem # + EVM networks (Base, Arbitrum, …)
35
+ pnpm add @x402/svm @solana/kit # + Solana networks
36
+ pnpm add @coinbase/cdp-sdk # + CDP-managed custody (EVM)
37
+ ```
38
+
39
+ Missing a peer fails with an `ENV_INVALID` error naming exactly what to install.
40
+ Note that TypeScript needs the same peers present to resolve the pay rail's
41
+ signer types (`ClientSvmSigner` resolves through `@solana/kit`); with neither
42
+ family installed, compile the package's declarations under `skipLibCheck`.
43
+
28
44
  ## Networks & custody
29
45
 
30
46
  - **EVM** (Base, Arbitrum, Ethereum, Polygon, …) is signed via [`@x402/evm`](https://npmjs.com/package/@x402/evm) + [viem](https://viem.sh); pass a raw CAIP-2 id for chains without a friendly alias.
@@ -52,8 +68,10 @@ The pay rail's `signer` config selects wallet custody:
52
68
  ## Safety
53
69
 
54
70
  The **pay** rail spends real money autonomously. It is `ActionCtx`-only and
55
- fail-closed: every payment is bounded by a spend policy (per-call and per-window
56
- caps) and may require confirmation. The `policy` field is required, so you cannot
71
+ fail-closed: every payment is bounded by a spend policy (`maxPerCall`, a ceiling
72
+ on a single payment, and `maxPerRun`, a ceiling on cumulative spend by one rail:
73
+ for `ctx.x402`, one function invocation, not a budget across invocations) and may
74
+ require confirmation. The `policy` field is required, so you cannot
57
75
  wire a signer without one; an unbounded policy is refused at runtime (fail-closed)
58
76
  before any signer is resolved.
59
77
 
@@ -1,53 +1,70 @@
1
- import { F as FacilitatorConfig, c as X402ChargeConfig, f as X402Price } from "../packem_shared/config.d-B-NYmHgG.mjs";
2
- export { type C as Caip2, D as DEFAULT_FACILITATOR_URL, type a as EvmAddress, type P as PaymentEventRow, type d as X402Network, type g as X402Receipt, type h as X402ReceiptSink, type i as X402Recipient, k as isEvmNetwork, l as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2, x as toPaymentEventRow, y as toReceipt } from "../packem_shared/config.d-B-NYmHgG.mjs";
3
- import { HTTPFacilitatorClient } from '@x402/core/server';
4
- import { RouteConfig } from '@x402/core/http';
5
- import '@x402/evm';
6
- import '@x402/svm';
7
- import '@x402/core/client';
8
- import '@x402/core/types';
1
+ import { h as X402ChargeConfig, e as X402Price } from "../packem_shared/index.d-A-g7yKuO.mjs";
2
+ export { type C as Caip2, a as DEFAULT_FACILITATOR_URL,
9
3
  /**
10
- * Build an `@x402/core` facilitator client from Lunora's {@link FacilitatorConfig}.
4
+ * `@lunora/x402/charge` — the charge rail (server side).
5
+ *
6
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
7
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
8
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
9
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
11
10
  *
12
- * `config.headers` (e.g. a CDP bearer token) are applied to every facilitator
13
- * call — `@x402/core` splits auth per endpoint (`verify` / `settle` /
14
- * `supported`), so the same header map is handed to each. With no config the
15
- * client points at the public {@link resolveFacilitatorUrl default} and sends no
16
- * auth headers.
17
- * @experimental
11
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
12
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
18
13
  */
19
- declare const createFacilitatorClient: (config?: FacilitatorConfig) => HTTPFacilitatorClient;
14
+ type E as EvmAddress,
15
+ /**
16
+ * `@lunora/x402/charge` — the charge rail (server side).
17
+ *
18
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
19
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
20
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
21
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
22
+ *
23
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
24
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
25
+ */
26
+ type F as FacilitatorConfig, type P as PaymentEventRow, type d as X402Network, type j as X402Receipt, type k as X402ReceiptSink,
27
+ /**
28
+ * `@lunora/x402/charge` — the charge rail (server side).
29
+ *
30
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
31
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
32
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
33
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
34
+ *
35
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
36
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
37
+ */
38
+ type l as X402Recipient, i as isEvmNetwork, g as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2, m as toPaymentEventRow } from "../packem_shared/index.d-A-g7yKuO.mjs";
39
+ import { RouteConfig } from '@x402/core/http';
40
+ import '@x402/core/types';
41
+ import '@solana/accounts';
20
42
  /**
21
43
  * A handler shaped like a Lunora HTTP action: `(context, request) => Response`.
22
- * @experimental
23
44
  */
24
45
  type HttpActionHandler<Context> = (context: Context, request: Request) => Promise<Response> | Response;
25
46
  /**
26
47
  * Gate `handler` behind an x402 paywall described by `config`. Returns a handler
27
48
  * of the same shape, ready to pass to `httpAction`.
28
- * @experimental
29
49
  */
30
50
  declare const withX402: <Context>(config: X402ChargeConfig, handler: HttpActionHandler<Context>) => HttpActionHandler<Context>;
31
51
  /**
32
52
  * Runs the protected resource handler, producing the Response to gate.
33
- * @experimental
34
53
  */
35
54
  type ChargeHandler = () => Promise<Response> | Response;
36
55
  /**
37
56
  * Per-request platform seams `handle` can use, beyond the request/handler pair.
38
- * @experimental
39
57
  */
40
58
  interface ChargeHandlerDeps {
41
59
  /**
42
60
  * Keep background work (the receipt sink) alive past the response — the
43
61
  * request's `ctx.waitUntil`. Absent on paths with no platform execution
44
- * context reaching the middleware (e.g. today's HTTP-action rail).
62
+ * context reaching the middleware (e.g. a non-Workers test).
45
63
  */
46
64
  readonly waitUntil?: (promise: Promise<unknown>) => void;
47
65
  }
48
66
  /**
49
67
  * A prepared, initialised paywall. Build once (it fetches facilitator support), reuse per request.
50
- * @experimental
51
68
  */
52
69
  interface ChargeMiddleware {
53
70
  /** Gate `request`: challenge / verify / settle around `runHandler`. */
@@ -59,31 +76,30 @@ interface ChargeMiddleware {
59
76
  * names the paid function (x402 core falls back to the request URL otherwise —
60
77
  * every RPC POSTs to the same `/_lunora/rpc`, so the URL can't tell two paid
61
78
  * procedures apart).
62
- * @experimental
63
79
  */
64
80
  type ChargeRouteOverrides = Pick<RouteConfig, "description" | "resource">;
65
81
  /**
66
82
  * Behaviour knobs for {@link createChargeMiddleware} beyond route metadata.
67
- * @experimental
68
83
  */
69
84
  interface ChargeMiddlewareOptions {
70
85
  /**
71
86
  * Settle the verified payment **before** dispatching `runHandler`, instead
72
- * of after. Use this for a mutation/procedure gate: a settlement failure
73
- * then means the handler never runs at all, so a paid mutation's writes can
74
- * never be committed without payment (the free-execution gap X402-04
75
- * closes). Once settlement succeeds the payment is final (on-chain) — a
76
- * handler failure after that point is a normal application error, not a
77
- * payment to unwind: there is nothing left to cancel, so it is not caught
78
- * here and simply propagates.
87
+ * of after. **Default `true`** — a settlement failure then means the handler
88
+ * never runs at all, so its side effects (writes, LLM calls, mail, push) can
89
+ * never happen unpaid. This matters because `verifyPayment` only checks the
90
+ * signed intent, NOT solvency: an underfunded or facilitator-refused payment
91
+ * passes verify and fails at `/settle`. Once settlement succeeds the payment
92
+ * is final (on-chain) — a handler failure after that point is a normal
93
+ * application error, not a payment to unwind: there is nothing left to
94
+ * cancel, so it is not caught here and simply propagates.
79
95
  *
80
- * Default `false` (settle-after, the historical behaviour): the handler's
81
- * response is passed to settlement as transport context (`responseHeaders`
82
- * — read by some schemes for settlement overrides), and a handler throw
83
- * still releases the verified-but-unsettled payment via
84
- * `cancellationDispatcher.cancel`. Because settlement can still fail after
85
- * the handler already ran on this path, `.x402()` handlers gated this way
86
- * MUST be idempotent or compensatable — see the `@lunora/x402` charge docs.
96
+ * Set `false` for settle-after: the handler's response is passed to
97
+ * settlement as transport context (`responseHeaders` — read by some schemes
98
+ * for settlement overrides), and a handler throw releases the
99
+ * verified-but-unsettled payment via `cancellationDispatcher.cancel`.
100
+ * Settlement can still FAIL after the handler already ran on this path, so a
101
+ * handler gated this way MUST be idempotent or compensatable — opt in only
102
+ * when you need the response as settlement context and can accept that.
87
103
  */
88
104
  readonly settleBeforeHandler?: boolean;
89
105
  }
@@ -93,19 +109,16 @@ interface ChargeMiddlewareOptions {
93
109
  * and reuse the result across requests. `routeOverrides` layers extra route
94
110
  * metadata (e.g. `resource`) onto the generated catch-all route; `options`
95
111
  * controls settlement ordering (see {@link ChargeMiddlewareOptions}).
96
- * @experimental
97
112
  */
98
113
  declare const createChargeMiddleware: (config: X402ChargeConfig, routeOverrides?: ChargeRouteOverrides, options?: ChargeMiddlewareOptions) => Promise<ChargeMiddleware>;
99
114
  /**
100
115
  * Charge config for the procedure gate: the worker-level settlement vocabulary
101
116
  * (network, recipient, facilitator) minus `price` — price is per-procedure and
102
117
  * arrives with each {@link X402ProcedureSpec}.
103
- * @experimental
104
118
  */
105
119
  type X402ProcedureChargeConfig = Omit<X402ChargeConfig, "price">;
106
120
  /**
107
121
  * The per-RPC charge spec the runtime passes the gate for each paid dispatch.
108
- * @experimental
109
122
  */
110
123
  interface X402ProcedureSpec {
111
124
  /** The `file:function` id of the paid procedure; becomes the x402 challenge `resource`. */
@@ -115,14 +128,13 @@ interface X402ProcedureSpec {
115
128
  }
116
129
  /**
117
130
  * Gate one paid RPC. Returns a real `402` + `PAYMENT-REQUIRED` challenge when the
118
- * request is unpaid, or the dispatched response (with `X-PAYMENT-RESPONSE`
119
- * attached) once the client's `X-PAYMENT` is verified and settled. `dispatch`
131
+ * request is unpaid, or the dispatched response (with `PAYMENT-RESPONSE`
132
+ * attached) once the client's `PAYMENT-SIGNATURE` is verified and settled. `dispatch`
120
133
  * runs the actual shard forward — settlement happens **before** `dispatch` is
121
134
  * invoked (settle-first), so a settlement failure means the shard forward
122
135
  * (the mutation's commit) never runs at all — no committed-but-unpaid write is
123
136
  * possible. `deps.waitUntil`, when supplied (the request's `ctx.waitUntil`),
124
137
  * keeps the opt-in receipt sink alive past the response.
125
- * @experimental
126
138
  */
127
139
  type X402ProcedureChargeGate = (request: Request, spec: X402ProcedureSpec, dispatch: () => Promise<Response>, deps?: ChargeHandlerDeps) => Promise<Response>;
128
140
  /**
@@ -131,9 +143,32 @@ type X402ProcedureChargeGate = (request: Request, spec: X402ProcedureSpec, dispa
131
143
  * function's price + `resource`), since `createChargeMiddleware` fetches
132
144
  * facilitator support on first use. A failed init is not cached, so a transient
133
145
  * facilitator outage retries on the next request. Settlement runs before
134
- * `dispatch` (`settleBeforeHandler: true`) since `dispatch` commits the
146
+ * `dispatch` (the `settleBeforeHandler` default) since `dispatch` commits the
135
147
  * procedure's real mutation — see `createChargeMiddleware`'s `ChargeMiddlewareOptions`.
136
- * @experimental
137
148
  */
138
149
  declare const createProcedureChargeGate: (config: X402ProcedureChargeConfig) => X402ProcedureChargeGate;
139
- export { type ChargeHandler, type ChargeHandlerDeps, type ChargeMiddleware, type ChargeMiddlewareOptions, type ChargeRouteOverrides, type FacilitatorConfig, type HttpActionHandler, type X402ChargeConfig, type X402Price, type X402ProcedureChargeConfig, type X402ProcedureChargeGate, type X402ProcedureSpec, createChargeMiddleware, createFacilitatorClient, createProcedureChargeGate, withX402 };
150
+ export { type ChargeHandler, type ChargeHandlerDeps, type ChargeMiddleware, type ChargeMiddlewareOptions, type ChargeRouteOverrides, type HttpActionHandler,
151
+ /**
152
+ * `@lunora/x402/charge` — the charge rail (server side).
153
+ *
154
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
155
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
156
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
157
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
158
+ *
159
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
160
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
161
+ */
162
+ type X402ChargeConfig,
163
+ /**
164
+ * `@lunora/x402/charge` — the charge rail (server side).
165
+ *
166
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
167
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
168
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
169
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
170
+ *
171
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
172
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
173
+ */
174
+ type X402Price, type X402ProcedureChargeConfig, type X402ProcedureChargeGate, type X402ProcedureSpec, createChargeMiddleware, createProcedureChargeGate, withX402 };
@@ -1,53 +1,70 @@
1
- import { F as FacilitatorConfig, c as X402ChargeConfig, f as X402Price } from "../packem_shared/config.d-B-NYmHgG.js";
2
- export { type C as Caip2, D as DEFAULT_FACILITATOR_URL, type a as EvmAddress, type P as PaymentEventRow, type d as X402Network, type g as X402Receipt, type h as X402ReceiptSink, type i as X402Recipient, k as isEvmNetwork, l as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2, x as toPaymentEventRow, y as toReceipt } from "../packem_shared/config.d-B-NYmHgG.js";
3
- import { HTTPFacilitatorClient } from '@x402/core/server';
4
- import { RouteConfig } from '@x402/core/http';
5
- import '@x402/evm';
6
- import '@x402/svm';
7
- import '@x402/core/client';
8
- import '@x402/core/types';
1
+ import { h as X402ChargeConfig, e as X402Price } from "../packem_shared/index.d-A-g7yKuO.js";
2
+ export { type C as Caip2, a as DEFAULT_FACILITATOR_URL,
9
3
  /**
10
- * Build an `@x402/core` facilitator client from Lunora's {@link FacilitatorConfig}.
4
+ * `@lunora/x402/charge` — the charge rail (server side).
5
+ *
6
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
7
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
8
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
9
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
11
10
  *
12
- * `config.headers` (e.g. a CDP bearer token) are applied to every facilitator
13
- * call — `@x402/core` splits auth per endpoint (`verify` / `settle` /
14
- * `supported`), so the same header map is handed to each. With no config the
15
- * client points at the public {@link resolveFacilitatorUrl default} and sends no
16
- * auth headers.
17
- * @experimental
11
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
12
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
18
13
  */
19
- declare const createFacilitatorClient: (config?: FacilitatorConfig) => HTTPFacilitatorClient;
14
+ type E as EvmAddress,
15
+ /**
16
+ * `@lunora/x402/charge` — the charge rail (server side).
17
+ *
18
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
19
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
20
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
21
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
22
+ *
23
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
24
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
25
+ */
26
+ type F as FacilitatorConfig, type P as PaymentEventRow, type d as X402Network, type j as X402Receipt, type k as X402ReceiptSink,
27
+ /**
28
+ * `@lunora/x402/charge` — the charge rail (server side).
29
+ *
30
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
31
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
32
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
33
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
34
+ *
35
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
36
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
37
+ */
38
+ type l as X402Recipient, i as isEvmNetwork, g as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2, m as toPaymentEventRow } from "../packem_shared/index.d-A-g7yKuO.js";
39
+ import { RouteConfig } from '@x402/core/http';
40
+ import '@x402/core/types';
41
+ import '@solana/accounts';
20
42
  /**
21
43
  * A handler shaped like a Lunora HTTP action: `(context, request) => Response`.
22
- * @experimental
23
44
  */
24
45
  type HttpActionHandler<Context> = (context: Context, request: Request) => Promise<Response> | Response;
25
46
  /**
26
47
  * Gate `handler` behind an x402 paywall described by `config`. Returns a handler
27
48
  * of the same shape, ready to pass to `httpAction`.
28
- * @experimental
29
49
  */
30
50
  declare const withX402: <Context>(config: X402ChargeConfig, handler: HttpActionHandler<Context>) => HttpActionHandler<Context>;
31
51
  /**
32
52
  * Runs the protected resource handler, producing the Response to gate.
33
- * @experimental
34
53
  */
35
54
  type ChargeHandler = () => Promise<Response> | Response;
36
55
  /**
37
56
  * Per-request platform seams `handle` can use, beyond the request/handler pair.
38
- * @experimental
39
57
  */
40
58
  interface ChargeHandlerDeps {
41
59
  /**
42
60
  * Keep background work (the receipt sink) alive past the response — the
43
61
  * request's `ctx.waitUntil`. Absent on paths with no platform execution
44
- * context reaching the middleware (e.g. today's HTTP-action rail).
62
+ * context reaching the middleware (e.g. a non-Workers test).
45
63
  */
46
64
  readonly waitUntil?: (promise: Promise<unknown>) => void;
47
65
  }
48
66
  /**
49
67
  * A prepared, initialised paywall. Build once (it fetches facilitator support), reuse per request.
50
- * @experimental
51
68
  */
52
69
  interface ChargeMiddleware {
53
70
  /** Gate `request`: challenge / verify / settle around `runHandler`. */
@@ -59,31 +76,30 @@ interface ChargeMiddleware {
59
76
  * names the paid function (x402 core falls back to the request URL otherwise —
60
77
  * every RPC POSTs to the same `/_lunora/rpc`, so the URL can't tell two paid
61
78
  * procedures apart).
62
- * @experimental
63
79
  */
64
80
  type ChargeRouteOverrides = Pick<RouteConfig, "description" | "resource">;
65
81
  /**
66
82
  * Behaviour knobs for {@link createChargeMiddleware} beyond route metadata.
67
- * @experimental
68
83
  */
69
84
  interface ChargeMiddlewareOptions {
70
85
  /**
71
86
  * Settle the verified payment **before** dispatching `runHandler`, instead
72
- * of after. Use this for a mutation/procedure gate: a settlement failure
73
- * then means the handler never runs at all, so a paid mutation's writes can
74
- * never be committed without payment (the free-execution gap X402-04
75
- * closes). Once settlement succeeds the payment is final (on-chain) — a
76
- * handler failure after that point is a normal application error, not a
77
- * payment to unwind: there is nothing left to cancel, so it is not caught
78
- * here and simply propagates.
87
+ * of after. **Default `true`** — a settlement failure then means the handler
88
+ * never runs at all, so its side effects (writes, LLM calls, mail, push) can
89
+ * never happen unpaid. This matters because `verifyPayment` only checks the
90
+ * signed intent, NOT solvency: an underfunded or facilitator-refused payment
91
+ * passes verify and fails at `/settle`. Once settlement succeeds the payment
92
+ * is final (on-chain) — a handler failure after that point is a normal
93
+ * application error, not a payment to unwind: there is nothing left to
94
+ * cancel, so it is not caught here and simply propagates.
79
95
  *
80
- * Default `false` (settle-after, the historical behaviour): the handler's
81
- * response is passed to settlement as transport context (`responseHeaders`
82
- * — read by some schemes for settlement overrides), and a handler throw
83
- * still releases the verified-but-unsettled payment via
84
- * `cancellationDispatcher.cancel`. Because settlement can still fail after
85
- * the handler already ran on this path, `.x402()` handlers gated this way
86
- * MUST be idempotent or compensatable — see the `@lunora/x402` charge docs.
96
+ * Set `false` for settle-after: the handler's response is passed to
97
+ * settlement as transport context (`responseHeaders` — read by some schemes
98
+ * for settlement overrides), and a handler throw releases the
99
+ * verified-but-unsettled payment via `cancellationDispatcher.cancel`.
100
+ * Settlement can still FAIL after the handler already ran on this path, so a
101
+ * handler gated this way MUST be idempotent or compensatable — opt in only
102
+ * when you need the response as settlement context and can accept that.
87
103
  */
88
104
  readonly settleBeforeHandler?: boolean;
89
105
  }
@@ -93,19 +109,16 @@ interface ChargeMiddlewareOptions {
93
109
  * and reuse the result across requests. `routeOverrides` layers extra route
94
110
  * metadata (e.g. `resource`) onto the generated catch-all route; `options`
95
111
  * controls settlement ordering (see {@link ChargeMiddlewareOptions}).
96
- * @experimental
97
112
  */
98
113
  declare const createChargeMiddleware: (config: X402ChargeConfig, routeOverrides?: ChargeRouteOverrides, options?: ChargeMiddlewareOptions) => Promise<ChargeMiddleware>;
99
114
  /**
100
115
  * Charge config for the procedure gate: the worker-level settlement vocabulary
101
116
  * (network, recipient, facilitator) minus `price` — price is per-procedure and
102
117
  * arrives with each {@link X402ProcedureSpec}.
103
- * @experimental
104
118
  */
105
119
  type X402ProcedureChargeConfig = Omit<X402ChargeConfig, "price">;
106
120
  /**
107
121
  * The per-RPC charge spec the runtime passes the gate for each paid dispatch.
108
- * @experimental
109
122
  */
110
123
  interface X402ProcedureSpec {
111
124
  /** The `file:function` id of the paid procedure; becomes the x402 challenge `resource`. */
@@ -115,14 +128,13 @@ interface X402ProcedureSpec {
115
128
  }
116
129
  /**
117
130
  * Gate one paid RPC. Returns a real `402` + `PAYMENT-REQUIRED` challenge when the
118
- * request is unpaid, or the dispatched response (with `X-PAYMENT-RESPONSE`
119
- * attached) once the client's `X-PAYMENT` is verified and settled. `dispatch`
131
+ * request is unpaid, or the dispatched response (with `PAYMENT-RESPONSE`
132
+ * attached) once the client's `PAYMENT-SIGNATURE` is verified and settled. `dispatch`
120
133
  * runs the actual shard forward — settlement happens **before** `dispatch` is
121
134
  * invoked (settle-first), so a settlement failure means the shard forward
122
135
  * (the mutation's commit) never runs at all — no committed-but-unpaid write is
123
136
  * possible. `deps.waitUntil`, when supplied (the request's `ctx.waitUntil`),
124
137
  * keeps the opt-in receipt sink alive past the response.
125
- * @experimental
126
138
  */
127
139
  type X402ProcedureChargeGate = (request: Request, spec: X402ProcedureSpec, dispatch: () => Promise<Response>, deps?: ChargeHandlerDeps) => Promise<Response>;
128
140
  /**
@@ -131,9 +143,32 @@ type X402ProcedureChargeGate = (request: Request, spec: X402ProcedureSpec, dispa
131
143
  * function's price + `resource`), since `createChargeMiddleware` fetches
132
144
  * facilitator support on first use. A failed init is not cached, so a transient
133
145
  * facilitator outage retries on the next request. Settlement runs before
134
- * `dispatch` (`settleBeforeHandler: true`) since `dispatch` commits the
146
+ * `dispatch` (the `settleBeforeHandler` default) since `dispatch` commits the
135
147
  * procedure's real mutation — see `createChargeMiddleware`'s `ChargeMiddlewareOptions`.
136
- * @experimental
137
148
  */
138
149
  declare const createProcedureChargeGate: (config: X402ProcedureChargeConfig) => X402ProcedureChargeGate;
139
- export { type ChargeHandler, type ChargeHandlerDeps, type ChargeMiddleware, type ChargeMiddlewareOptions, type ChargeRouteOverrides, type FacilitatorConfig, type HttpActionHandler, type X402ChargeConfig, type X402Price, type X402ProcedureChargeConfig, type X402ProcedureChargeGate, type X402ProcedureSpec, createChargeMiddleware, createFacilitatorClient, createProcedureChargeGate, withX402 };
150
+ export { type ChargeHandler, type ChargeHandlerDeps, type ChargeMiddleware, type ChargeMiddlewareOptions, type ChargeRouteOverrides, type HttpActionHandler,
151
+ /**
152
+ * `@lunora/x402/charge` — the charge rail (server side).
153
+ *
154
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
155
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
156
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
157
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
158
+ *
159
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
160
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
161
+ */
162
+ type X402ChargeConfig,
163
+ /**
164
+ * `@lunora/x402/charge` — the charge rail (server side).
165
+ *
166
+ * A Lunora deployment gates a resource (an HTTP-action route, a procedure, or
167
+ * an MCP tool) behind a USDC price: it returns `402 Payment Required` with a
168
+ * `PAYMENT-REQUIRED` header, verifies the client's `PAYMENT-SIGNATURE` payload (via a
169
+ * facilitator), runs the handler, settles, and attaches `PAYMENT-RESPONSE`.
170
+ *
171
+ * `withX402` gates a Lunora HTTP action; `createChargeMiddleware` is the
172
+ * framework-agnostic core for other surfaces (procedures, MCP tools).
173
+ */
174
+ type X402Price, type X402ProcedureChargeConfig, type X402ProcedureChargeGate, type X402ProcedureSpec, createChargeMiddleware, createProcedureChargeGate, withX402 };
@@ -1 +1 @@
1
- import{DEFAULT_FACILITATOR_URL as t,resolveFacilitatorUrl as o}from"../packem_shared/DEFAULT_FACILITATOR_URL-lUtljfJI.mjs";import{createFacilitatorClient as i}from"../packem_shared/createFacilitatorClient-Dj4Ll9xQ.mjs";import{isEvmNetwork as p,isSvmNetwork as c,toCaip2 as f}from"../packem_shared/EVM_NETWORKS-XOms9Rtk.mjs";import{withX402 as l}from"../packem_shared/withX402-D10895ct.mjs";import{createChargeMiddleware as C}from"../packem_shared/createChargeMiddleware-MQhSA6Wt.mjs";import{createProcedureChargeGate as F}from"../packem_shared/createProcedureChargeGate-Cfm5mD2y.mjs";import{toPaymentEventRow as d,toReceipt as h}from"../packem_shared/toPaymentEventRow-D_kRVcb3.mjs";export{t as DEFAULT_FACILITATOR_URL,C as createChargeMiddleware,i as createFacilitatorClient,F as createProcedureChargeGate,p as isEvmNetwork,c as isSvmNetwork,o as resolveFacilitatorUrl,f as toCaip2,d as toPaymentEventRow,h as toReceipt,l as withX402};
1
+ import{DEFAULT_FACILITATOR_URL as o,resolveFacilitatorUrl as t}from"../packem_shared/DEFAULT_FACILITATOR_URL-CPJNUMvi.mjs";import{isEvmNetwork as m,isSvmNetwork as i,toCaip2 as p}from"../packem_shared/EVM_NETWORKS-CwbBEtp1.mjs";import{withX402 as x}from"../packem_shared/withX402-mUrRb9a2.mjs";import{createChargeMiddleware as c}from"../packem_shared/createChargeMiddleware-DyOEuTCT.mjs";import{createProcedureChargeGate as v}from"../packem_shared/createProcedureChargeGate-BidGWCmf.mjs";import{toPaymentEventRow as d}from"../packem_shared/toPaymentEventRow-DTXuTDh0.mjs";export{o as DEFAULT_FACILITATOR_URL,c as createChargeMiddleware,v as createProcedureChargeGate,m as isEvmNetwork,i as isSvmNetwork,t as resolveFacilitatorUrl,p as toCaip2,d as toPaymentEventRow,x as withX402};
package/dist/index.d.mts CHANGED
@@ -1,6 +1,3 @@
1
- export { type C as Caip2, D as DEFAULT_FACILITATOR_URL, E as EVM_NETWORKS, type a as EvmAddress, type F as FacilitatorConfig, type b as FriendlyNetwork, N as NETWORK_TO_CAIP2, S as SVM_NETWORKS, type X as X402CdpSignerConfig, type c as X402ChargeConfig, type d as X402Network, type e as X402PayConfig, type f as X402Price, type g as X402Receipt, type h as X402ReceiptSink, type i as X402Recipient, type j as X402SignerConfig, k as isEvmNetwork, l as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2 } from "./packem_shared/config.d-B-NYmHgG.mjs";
2
- import '@x402/evm';
3
- import '@x402/svm';
4
- import '@x402/core/http';
5
- import '@x402/core/client';
1
+ export { type C as Caip2, a as DEFAULT_FACILITATOR_URL, n as EVM_NETWORKS, type E as EvmAddress, type F as FacilitatorConfig, type o as FriendlyNetwork, N as NETWORK_TO_CAIP2, p as SVM_NETWORKS, type c as X402CdpSignerConfig, type h as X402ChargeConfig, type d as X402Network, type X as X402PayConfig, type e as X402Price, type j as X402Receipt, type k as X402ReceiptSink, type l as X402Recipient, type f as X402SignerConfig, i as isEvmNetwork, g as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2 } from "./packem_shared/index.d-A-g7yKuO.mjs";
6
2
  import '@x402/core/types';
3
+ import '@solana/accounts';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,3 @@
1
- export { type C as Caip2, D as DEFAULT_FACILITATOR_URL, E as EVM_NETWORKS, type a as EvmAddress, type F as FacilitatorConfig, type b as FriendlyNetwork, N as NETWORK_TO_CAIP2, S as SVM_NETWORKS, type X as X402CdpSignerConfig, type c as X402ChargeConfig, type d as X402Network, type e as X402PayConfig, type f as X402Price, type g as X402Receipt, type h as X402ReceiptSink, type i as X402Recipient, type j as X402SignerConfig, k as isEvmNetwork, l as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2 } from "./packem_shared/config.d-B-NYmHgG.js";
2
- import '@x402/evm';
3
- import '@x402/svm';
4
- import '@x402/core/http';
5
- import '@x402/core/client';
1
+ export { type C as Caip2, a as DEFAULT_FACILITATOR_URL, n as EVM_NETWORKS, type E as EvmAddress, type F as FacilitatorConfig, type o as FriendlyNetwork, N as NETWORK_TO_CAIP2, p as SVM_NETWORKS, type c as X402CdpSignerConfig, type h as X402ChargeConfig, type d as X402Network, type X as X402PayConfig, type e as X402Price, type j as X402Receipt, type k as X402ReceiptSink, type l as X402Recipient, type f as X402SignerConfig, i as isEvmNetwork, g as isSvmNetwork, r as resolveFacilitatorUrl, t as toCaip2 } from "./packem_shared/index.d-A-g7yKuO.js";
6
2
  import '@x402/core/types';
3
+ import '@solana/accounts';
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{DEFAULT_FACILITATOR_URL as t,resolveFacilitatorUrl as T}from"./packem_shared/DEFAULT_FACILITATOR_URL-lUtljfJI.mjs";import{EVM_NETWORKS as E,NETWORK_TO_CAIP2 as _,SVM_NETWORKS as i,isEvmNetwork as N,isSvmNetwork as O,toCaip2 as R}from"./packem_shared/EVM_NETWORKS-XOms9Rtk.mjs";export{t as DEFAULT_FACILITATOR_URL,E as EVM_NETWORKS,_ as NETWORK_TO_CAIP2,i as SVM_NETWORKS,N as isEvmNetwork,O as isSvmNetwork,T as resolveFacilitatorUrl,R as toCaip2};
1
+ import{DEFAULT_FACILITATOR_URL as t,resolveFacilitatorUrl as T}from"./packem_shared/DEFAULT_FACILITATOR_URL-CPJNUMvi.mjs";import{EVM_NETWORKS as E,NETWORK_TO_CAIP2 as _,SVM_NETWORKS as i,isEvmNetwork as N,isSvmNetwork as O,toCaip2 as R}from"./packem_shared/EVM_NETWORKS-CwbBEtp1.mjs";export{t as DEFAULT_FACILITATOR_URL,E as EVM_NETWORKS,_ as NETWORK_TO_CAIP2,i as SVM_NETWORKS,N as isEvmNetwork,O as isSvmNetwork,T as resolveFacilitatorUrl,R as toCaip2};
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";import{toCaip2 as f}from"./EVM_NETWORKS-CwbBEtp1.mjs";const S=/^\d+(?:\.\d+)?$/,m=(e,t)=>t.startsWith("eip155:")?e.toLowerCase():e,p=(e,t)=>`${t}|${m(e,t)}`,v=/^\d+$/,w=e=>v.test(e)?BigInt(e):void 0,x=6,E=[{asset:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",decimals:6,network:"base"},{asset:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",decimals:6,network:"base-sepolia"},{asset:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",decimals:6,network:"polygon"},{asset:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",decimals:6,network:"arbitrum"},{asset:"0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",decimals:6,network:"arbitrum-sepolia"},{asset:"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",decimals:6,network:"solana"},{asset:"4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",decimals:6,network:"solana-devnet"}],C=()=>{let e=0n;return{add:t=>{e+=t},release:t=>{e=e>t?e-t:0n},get spentAtomic(){return e}}},h=(e,t=x)=>{if(!Number.isInteger(t)||t<0)throw new d("BAD_REQUEST",`x402 policy: decimals must be a non-negative integer, got ${String(t)}.`);const n=(typeof e=="number"?e.toString():e).trim(),s=n.startsWith("$")?n.slice(1):n;if(!S.test(s))throw new d("BAD_REQUEST",`x402 policy: "${String(e)}" is not a valid USD amount (use a plain decimal like "0.01").`);const[i="0",r=""]=s.split("."),o=r.slice(0,t).padEnd(t,"0");return BigInt(i)*10n**BigInt(t)+BigInt(o===""?"0":o)},b=e=>{const t=e.allowedAssets??E;if(t.length===0)throw new d("BAD_REQUEST","x402 policy: `allowedAssets` is empty, so no payment could ever be made. Omit it to accept the default USDC assets, or list at least one asset.");const n=new Map;for(const s of t){if(!Number.isInteger(s.decimals)||s.decimals<0)throw new d("BAD_REQUEST",`x402 policy: allowedAssets[${s.asset}].decimals must be a non-negative integer, got ${String(s.decimals)}.`);const i=f(s.network),r=p(s.asset,i),o=n.get(r);if(o!==void 0&&o.decimals!==s.decimals)throw new d("BAD_REQUEST",`x402 policy: allowedAssets lists ${s.asset} on ${i} twice with different decimals (${String(o.decimals)} and ${String(s.decimals)}). One asset cannot have two precisions.`);n.set(r,{...s,network:i})}return n},g=(e,t)=>{const n=new Map;if(e===void 0)return n;for(const{decimals:s}of t.values())n.has(s)||n.set(s,h(e,s));return n},P=e=>{const t=b(e),n=g(e.maxPerCall,t),s=e.allowedNetworks?.map(r=>f(r)),{allowedRecipients:i}=e;return(r,o)=>o.filter(a=>{const c=t.get(p(a.asset,a.network));if(c===void 0)return!1;const l=w(a.amount);if(l===void 0)return!1;const u=n.get(c.decimals);if(u!==void 0&&l>u||s!==void 0&&!s.includes(a.network))return!1;if(i!==void 0){const A=m(a.payTo,a.network);return i.some(y=>m(y,a.network)===A)}return!0})},R=(e,t)=>{const n=b(e),s=g(e.maxPerRun,n);let i;return async r=>{const o=r.selectedRequirements,a=n.get(p(o.asset,o.network));if(a===void 0)return{abort:!0,reason:`x402 policy: asset ${o.asset} on ${o.network} is not in this wallet's allowed assets, so its amount cannot be priced against the caps.`};if(t.spentAtomic>0n&&i!==a.decimals)return{abort:!0,reason:`x402 policy: this payment is in a ${String(a.decimals)}-decimal asset but the run's spend is tracked in ${String(i)}-decimal units. One wallet cannot mix asset precisions under a single per-run cap.`};const c=w(o.amount);if(c===void 0)return{abort:!0,reason:`x402 policy: this payment's amount (${o.amount}) is not a canonical atomic quantity, so it cannot be checked against the caps.`};const l=s.get(a.decimals);if(l!==void 0&&t.spentAtomic+c>l)return{abort:!0,reason:`x402 policy: this payment (${o.amount}) would exceed the per-run cap (already spent ${t.spentAtomic.toString()}, cap ${l.toString()}, in atomic base units).`};t.add(c),i=a.decimals;try{return e.onPaymentRequired!==void 0&&await e.onPaymentRequired(o)!==!0?(t.release(c),{abort:!0,reason:"x402 policy: payment was declined by onPaymentRequired."}):void 0}catch(u){throw t.release(c),u}}},$=e=>t=>{const n=w(t.selectedRequirements.amount);return n!==void 0&&e.release(n),Promise.resolve()},T=e=>{if(!(e.maxPerCall!==void 0||e.maxPerRun!==void 0||e.onPaymentRequired!==void 0))throw new d("FORBIDDEN","x402 pay: refusing to build a wallet with an unbounded spend policy. Set at least one of maxPerCall, maxPerRun, or onPaymentRequired (allowedNetworks/allowedRecipients/allowedAssets narrow but do not bound spend).")};export{E as DEFAULT_ALLOWED_ASSETS,x as DEFAULT_STABLECOIN_DECIMALS,T as assertBoundedPolicy,R as buildPaymentGuard,P as buildSpendPolicy,C as createSpendState,$ as releaseSpendOnFailure,h as usdToAtomic};
@@ -0,0 +1 @@
1
+ const o="https://x402.org/facilitator",r=t=>t?.url??o;export{o as DEFAULT_FACILITATOR_URL,r as resolveFacilitatorUrl};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";const i={arbitrum:"eip155:42161","arbitrum-sepolia":"eip155:421614",base:"eip155:8453","base-sepolia":"eip155:84532",ethereum:"eip155:1",polygon:"eip155:137",solana:"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","solana-devnet":"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1"},t=["arbitrum","arbitrum-sepolia","base","base-sepolia","ethereum","polygon"],n=["solana","solana-devnet"],o=a=>{const e=i[a];if(e!==void 0)return e;if(a.includes(":"))return a;throw new s("ENV_INVALID",`Unknown x402 network "${a}". Use a friendly name (${t.join(", ")}, ${n.join(", ")}) or a raw CAIP-2 id.`)},p=a=>o(a).startsWith("eip155:"),l=a=>o(a).startsWith("solana:");export{t as EVM_NETWORKS,i as NETWORK_TO_CAIP2,n as SVM_NETWORKS,p as isEvmNetwork,l as isSvmNetwork,o as toCaip2};
@@ -0,0 +1 @@
1
+ import{LunoraError as w}from"@lunora/errors";import{x402HTTPResourceServer as A,RouteConfigurationError as C,getFacilitatorResponseError as H}from"@x402/core/http";import{toCaip2 as P,isEvmNetwork as T}from"./EVM_NETWORKS-CwbBEtp1.mjs";import{toReceipt as S}from"./toPaymentEventRow-DTXuTDh0.mjs";import{HTTPFacilitatorClient as E}from"@x402/core/server";import{resolveFacilitatorUrl as I}from"./DEFAULT_FACILITATOR_URL-CPJNUMvi.mjs";import{i as k}from"./optional-peer-BBhVxozi.mjs";const b=e=>{const r=I(e);if(e?.headers===void 0)return new E({url:r});const t={...e.headers};return new E({createAuthHeaders:()=>Promise.resolve({settle:t,supported:t,verify:t}),url:r})},L=async e=>{const{x402ResourceServer:r}=await import("@x402/core/server"),t=new r(b(e.facilitator)),a=P(e.network);if(T(e.network)){const{registerExactEvmScheme:o}=await k(()=>import("@x402/evm/exact/server"),"x402 charge: EVM networks need the optional @x402/evm + viem peers — install them, or configure an SVM network.");o(t,{networks:[a]})}else{const{registerExactSvmScheme:o}=await k(()=>import("@x402/svm/exact/server"),"x402 charge: SVM networks need the optional @x402/svm + @solana/kit peers — install them, or configure an EVM network.");o(t,{networks:[a]})}return t},M="PAYMENT-SIGNATURE",N=e=>{const r=e.toLowerCase();return r==="cdn-cache-control"||r.endsWith("-cdn-cache-control")||r==="surrogate-control"},V=e=>["private",...(e??"").split(",").map(t=>t.trim()).filter(t=>{const a=t.split("=")[0]?.trim().toLowerCase();return a!==""&&a!=="public"&&a!=="private"&&a!=="s-maxage"})].join(", "),v=async(e,r)=>{try{return await r()}catch(t){const a=H(t);throw a===null?t:new w("X402_FACILITATOR_ERROR",`x402 charge: the facilitator failed during ${e}: ${a.message}`,{cause:t,status:502})}},_=e=>{const r=Object.create(null);for(const[t,a]of e)r[t]=a;return r},x=(e,r,t,a)=>{if(e!==void 0)try{const o=Promise.resolve(e(S(r,{resource:t,ts:Date.now()}))).catch(()=>{});a?.(o)}catch{}},O=e=>{const r=T(e.network),t=r?e.recipient.evm:e.recipient.svm;if(t===void 0||t.length===0)throw new w("ENV_INVALID",`x402 charge on "${e.network}" needs recipient.${r?"evm":"svm"} set.`);return t},U=e=>({accepts:{network:P(e.network),payTo:O(e),price:e.price,scheme:"exact"}}),F=(e,r)=>({getAcceptHeader:()=>e.headers.get("accept")??"",getHeader:t=>e.headers.get(t)??void 0,getMethod:()=>e.method,getPath:()=>r.pathname,getQueryParam:t=>{const a=r.searchParams.getAll(t);if(a.length!==0)return a.length===1?a[0]:a},getQueryParams:()=>{const t=Object.create(null);for(const a of new Set(r.searchParams.keys())){const o=r.searchParams.getAll(a),[p,...d]=o;p!==void 0&&(t[a]=d.length>0?o:p)}return t},getUrl:()=>e.url,getUserAgent:()=>e.headers.get("user-agent")??""}),R=e=>{const r=new Headers(e.headers),{body:t}=e;return t==null?new Response(void 0,{headers:r,status:e.status}):typeof t=="string"?(e.isHtml&&!r.has("content-type")&&r.set("content-type","text/html; charset=utf-8"),new Response(t,{headers:r,status:e.status})):Response.json(t,{headers:r,status:e.status})},$=(e,r)=>{const t=new Headers(e.headers);for(const[a,o]of Object.entries(r))t.set(a,o);return new Response(e.body,{headers:t,status:e.status,statusText:e.statusText})},W=async(e,r,t)=>{const a=await L(e),o=new A(a,{...U(e),...r});try{await o.initialize()}catch(s){throw s instanceof C?new w("ENV_INVALID",`x402 charge: ${s.message}`,{cause:s}):new w("X402_FACILITATOR_ERROR",`x402 charge: could not load the facilitator's supported payment kinds: ${s instanceof Error?s.message:String(s)}`,{cause:s,status:502})}const p=t?.settleBeforeHandler??!0,d=(s,l)=>{const i=$(s,{...l,"cache-control":V(s.headers.get("cache-control"))});for(const m of[...i.headers.keys()].filter(h=>N(h)))i.headers.delete(m);return i};return{handle:async(s,l,i)=>{const m=new URL(s.url),h={adapter:F(s,m),method:s.method,path:m.pathname,paymentHeader:s.headers.get(M)??void 0},n=await v("verification",async()=>o.processHTTPRequest(h));if(n.type==="no-payment-required")return l();if(n.type==="payment-error")return R(n.response);const g=r?.resource??s.url;if(p){const c=await v("settlement",async()=>o.processSettlement(n.paymentPayload,n.paymentRequirements,n.declaredExtensions,{request:h}));if(!c.success)return R(c.response);x(e.onReceipt,c,g,i?.waitUntil);const y=await l();return d(y,c.headers)}let f;try{f=await l()}catch(c){try{await n.cancellationDispatcher.cancel({error:c,reason:"handler_threw"})}catch(y){console.error("x402 charge: failed to cancel payment after the handler threw",y)}throw c}const u=await v("settlement",async()=>o.processSettlement(n.paymentPayload,n.paymentRequirements,n.declaredExtensions,{request:h,responseHeaders:_(f.headers)}));return u.success?(x(e.onReceipt,u,g,i?.waitUntil),d(f,u.headers)):R(u.response)}}};export{U as buildRoute,W as createChargeMiddleware,F as createRequestAdapter,x as reportReceipt,O as resolvePayTo,R as toResponse,$ as withHeaders};
@@ -0,0 +1 @@
1
+ import{createChargeMiddleware as a}from"./createChargeMiddleware-DyOEuTCT.mjs";const d=(e,r,i,n)=>{const c=e.get(r);if(c!==void 0)return c;const t=i().catch(o=>{throw e.get(r)===t&&e.delete(r),o});return e.set(r,t),t},u=e=>{const r=new Map;return async(i,n,c,t)=>(await d(r,n.functionPath,async()=>a({...e,price:n.price},{resource:n.functionPath}))).handle(i,c,t)};export{u as createProcedureChargeGate};