@x402/next 0.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,189 @@
1
+ import { HTTPAdapter, RoutesConfig, x402ResourceServer, PaywallConfig, PaywallProvider, FacilitatorClient, RouteConfig } from '@x402/core/server';
2
+ export { PaywallConfig, PaywallProvider, RouteConfig, RouteConfigurationError, RouteValidationError } from '@x402/core/server';
3
+ import { Network, SchemeNetworkServer } from '@x402/core/types';
4
+ export { Network, PaymentPayload, PaymentRequired, PaymentRequirements, SchemeNetworkServer } from '@x402/core/types';
5
+ import { NextRequest, NextResponse } from 'next/server';
6
+
7
+ /**
8
+ * Next.js adapter implementation
9
+ */
10
+ declare class NextAdapter implements HTTPAdapter {
11
+ private req;
12
+ /**
13
+ * Creates a new NextAdapter instance.
14
+ *
15
+ * @param req - The Next.js request object
16
+ */
17
+ constructor(req: NextRequest);
18
+ /**
19
+ * Gets a header value from the request.
20
+ *
21
+ * @param name - The header name
22
+ * @returns The header value or undefined
23
+ */
24
+ getHeader(name: string): string | undefined;
25
+ /**
26
+ * Gets the HTTP method of the request.
27
+ *
28
+ * @returns The HTTP method
29
+ */
30
+ getMethod(): string;
31
+ /**
32
+ * Gets the path of the request.
33
+ *
34
+ * @returns The request path
35
+ */
36
+ getPath(): string;
37
+ /**
38
+ * Gets the full URL of the request.
39
+ *
40
+ * @returns The full request URL
41
+ */
42
+ getUrl(): string;
43
+ /**
44
+ * Gets the Accept header from the request.
45
+ *
46
+ * @returns The Accept header value or empty string
47
+ */
48
+ getAcceptHeader(): string;
49
+ /**
50
+ * Gets the User-Agent header from the request.
51
+ *
52
+ * @returns The User-Agent header value or empty string
53
+ */
54
+ getUserAgent(): string;
55
+ /**
56
+ * Gets all query parameters from the request URL.
57
+ *
58
+ * @returns Record of query parameter key-value pairs
59
+ */
60
+ getQueryParams(): Record<string, string | string[]>;
61
+ /**
62
+ * Gets a specific query parameter by name.
63
+ *
64
+ * @param name - The query parameter name
65
+ * @returns The query parameter value(s) or undefined
66
+ */
67
+ getQueryParam(name: string): string | string[] | undefined;
68
+ /**
69
+ * Gets the parsed request body.
70
+ *
71
+ * @returns Promise resolving to the parsed request body
72
+ */
73
+ getBody(): Promise<unknown>;
74
+ }
75
+
76
+ /**
77
+ * Configuration for registering a payment scheme with a specific network
78
+ */
79
+ interface SchemeRegistration {
80
+ /**
81
+ * The network identifier (e.g., 'eip155:84532', 'solana:mainnet')
82
+ */
83
+ network: Network;
84
+ /**
85
+ * The scheme server implementation for this network
86
+ */
87
+ server: SchemeNetworkServer;
88
+ }
89
+ /**
90
+ * Next.js payment proxy for x402 protocol (direct server instance).
91
+ *
92
+ * Use this when you want to pass a pre-configured x402ResourceServer instance.
93
+ * This provides more flexibility for testing, custom configuration, and reusing
94
+ * server instances across multiple proxies.
95
+ *
96
+ * @param routes - Route configurations for protected endpoints
97
+ * @param server - Pre-configured x402ResourceServer instance
98
+ * @param paywallConfig - Optional configuration for the built-in paywall UI
99
+ * @param paywall - Optional custom paywall provider (overrides default)
100
+ * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)
101
+ * @returns Next.js proxy handler
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import { paymentProxy } from "@x402/next";
106
+ * import { x402ResourceServer } from "@x402/core/server";
107
+ * import { registerExactEvmScheme } from "@x402/evm/exact/server";
108
+ *
109
+ * const server = new x402ResourceServer(myFacilitatorClient);
110
+ * registerExactEvmScheme(server, {});
111
+ *
112
+ * export const proxy = paymentProxy(routes, server, paywallConfig);
113
+ * ```
114
+ */
115
+ declare function paymentProxy(routes: RoutesConfig, server: x402ResourceServer, paywallConfig?: PaywallConfig, paywall?: PaywallProvider, syncFacilitatorOnStart?: boolean): (req: NextRequest) => Promise<NextResponse<unknown>>;
116
+ /**
117
+ * Next.js payment proxy for x402 protocol (configuration-based).
118
+ *
119
+ * Use this when you want to quickly set up proxy with simple configuration.
120
+ * This function creates and configures the x402ResourceServer internally.
121
+ *
122
+ * @param routes - Route configurations for protected endpoints
123
+ * @param facilitatorClients - Optional facilitator client(s) for payment processing
124
+ * @param schemes - Optional array of scheme registrations for server-side payment processing
125
+ * @param paywallConfig - Optional configuration for the built-in paywall UI
126
+ * @param paywall - Optional custom paywall provider (overrides default)
127
+ * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)
128
+ * @returns Next.js proxy handler
129
+ *
130
+ * @example
131
+ * ```typescript
132
+ * import { paymentProxyFromConfig } from "@x402/next";
133
+ *
134
+ * export const proxy = paymentProxyFromConfig(
135
+ * routes,
136
+ * myFacilitatorClient,
137
+ * [{ network: "eip155:8453", server: evmSchemeServer }],
138
+ * paywallConfig
139
+ * );
140
+ * ```
141
+ */
142
+ declare function paymentProxyFromConfig(routes: RoutesConfig, facilitatorClients?: FacilitatorClient | FacilitatorClient[], schemes?: SchemeRegistration[], paywallConfig?: PaywallConfig, paywall?: PaywallProvider, syncFacilitatorOnStart?: boolean): (req: NextRequest) => Promise<NextResponse<unknown>>;
143
+ /**
144
+ * Wraps a Next.js App Router API route handler with x402 payment protection.
145
+ *
146
+ * Unlike `paymentProxy` which works as middleware, `withX402` wraps individual route handlers
147
+ * and guarantees that payment settlement only occurs after the handler returns a successful
148
+ * response (status < 400). This provides more precise control over when payments are settled.
149
+ *
150
+ * @param routeHandler - The API route handler function to wrap
151
+ * @param routeConfig - Payment configuration for this specific route
152
+ * @param server - Pre-configured x402ResourceServer instance
153
+ * @param paywallConfig - Optional configuration for the built-in paywall UI
154
+ * @param paywall - Optional custom paywall provider (overrides default)
155
+ * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)
156
+ * @returns A wrapped Next.js route handler
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * import { NextRequest, NextResponse } from "next/server";
161
+ * import { withX402 } from "@x402/next";
162
+ * import { x402ResourceServer } from "@x402/core/server";
163
+ * import { registerExactEvmScheme } from "@x402/evm/exact/server";
164
+ *
165
+ * const server = new x402ResourceServer(myFacilitatorClient);
166
+ * registerExactEvmScheme(server, {});
167
+ *
168
+ * const handler = async (request: NextRequest) => {
169
+ * return NextResponse.json({ data: "protected content" });
170
+ * };
171
+ *
172
+ * export const GET = withX402(
173
+ * handler,
174
+ * {
175
+ * accepts: {
176
+ * scheme: "exact",
177
+ * payTo: "0x123...",
178
+ * price: "$0.01",
179
+ * network: "eip155:84532",
180
+ * },
181
+ * description: "Access to protected API",
182
+ * },
183
+ * server,
184
+ * );
185
+ * ```
186
+ */
187
+ declare function withX402<T = unknown>(routeHandler: (request: NextRequest) => Promise<NextResponse<T>>, routeConfig: RouteConfig, server: x402ResourceServer, paywallConfig?: PaywallConfig, paywall?: PaywallProvider, syncFacilitatorOnStart?: boolean): (request: NextRequest) => Promise<NextResponse<T>>;
188
+
189
+ export { NextAdapter, type SchemeRegistration, paymentProxy, paymentProxyFromConfig, withX402 };
@@ -0,0 +1,189 @@
1
+ import { HTTPAdapter, RoutesConfig, x402ResourceServer, PaywallConfig, PaywallProvider, FacilitatorClient, RouteConfig } from '@x402/core/server';
2
+ export { PaywallConfig, PaywallProvider, RouteConfig, RouteConfigurationError, RouteValidationError } from '@x402/core/server';
3
+ import { Network, SchemeNetworkServer } from '@x402/core/types';
4
+ export { Network, PaymentPayload, PaymentRequired, PaymentRequirements, SchemeNetworkServer } from '@x402/core/types';
5
+ import { NextRequest, NextResponse } from 'next/server';
6
+
7
+ /**
8
+ * Next.js adapter implementation
9
+ */
10
+ declare class NextAdapter implements HTTPAdapter {
11
+ private req;
12
+ /**
13
+ * Creates a new NextAdapter instance.
14
+ *
15
+ * @param req - The Next.js request object
16
+ */
17
+ constructor(req: NextRequest);
18
+ /**
19
+ * Gets a header value from the request.
20
+ *
21
+ * @param name - The header name
22
+ * @returns The header value or undefined
23
+ */
24
+ getHeader(name: string): string | undefined;
25
+ /**
26
+ * Gets the HTTP method of the request.
27
+ *
28
+ * @returns The HTTP method
29
+ */
30
+ getMethod(): string;
31
+ /**
32
+ * Gets the path of the request.
33
+ *
34
+ * @returns The request path
35
+ */
36
+ getPath(): string;
37
+ /**
38
+ * Gets the full URL of the request.
39
+ *
40
+ * @returns The full request URL
41
+ */
42
+ getUrl(): string;
43
+ /**
44
+ * Gets the Accept header from the request.
45
+ *
46
+ * @returns The Accept header value or empty string
47
+ */
48
+ getAcceptHeader(): string;
49
+ /**
50
+ * Gets the User-Agent header from the request.
51
+ *
52
+ * @returns The User-Agent header value or empty string
53
+ */
54
+ getUserAgent(): string;
55
+ /**
56
+ * Gets all query parameters from the request URL.
57
+ *
58
+ * @returns Record of query parameter key-value pairs
59
+ */
60
+ getQueryParams(): Record<string, string | string[]>;
61
+ /**
62
+ * Gets a specific query parameter by name.
63
+ *
64
+ * @param name - The query parameter name
65
+ * @returns The query parameter value(s) or undefined
66
+ */
67
+ getQueryParam(name: string): string | string[] | undefined;
68
+ /**
69
+ * Gets the parsed request body.
70
+ *
71
+ * @returns Promise resolving to the parsed request body
72
+ */
73
+ getBody(): Promise<unknown>;
74
+ }
75
+
76
+ /**
77
+ * Configuration for registering a payment scheme with a specific network
78
+ */
79
+ interface SchemeRegistration {
80
+ /**
81
+ * The network identifier (e.g., 'eip155:84532', 'solana:mainnet')
82
+ */
83
+ network: Network;
84
+ /**
85
+ * The scheme server implementation for this network
86
+ */
87
+ server: SchemeNetworkServer;
88
+ }
89
+ /**
90
+ * Next.js payment proxy for x402 protocol (direct server instance).
91
+ *
92
+ * Use this when you want to pass a pre-configured x402ResourceServer instance.
93
+ * This provides more flexibility for testing, custom configuration, and reusing
94
+ * server instances across multiple proxies.
95
+ *
96
+ * @param routes - Route configurations for protected endpoints
97
+ * @param server - Pre-configured x402ResourceServer instance
98
+ * @param paywallConfig - Optional configuration for the built-in paywall UI
99
+ * @param paywall - Optional custom paywall provider (overrides default)
100
+ * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)
101
+ * @returns Next.js proxy handler
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * import { paymentProxy } from "@x402/next";
106
+ * import { x402ResourceServer } from "@x402/core/server";
107
+ * import { registerExactEvmScheme } from "@x402/evm/exact/server";
108
+ *
109
+ * const server = new x402ResourceServer(myFacilitatorClient);
110
+ * registerExactEvmScheme(server, {});
111
+ *
112
+ * export const proxy = paymentProxy(routes, server, paywallConfig);
113
+ * ```
114
+ */
115
+ declare function paymentProxy(routes: RoutesConfig, server: x402ResourceServer, paywallConfig?: PaywallConfig, paywall?: PaywallProvider, syncFacilitatorOnStart?: boolean): (req: NextRequest) => Promise<NextResponse<unknown>>;
116
+ /**
117
+ * Next.js payment proxy for x402 protocol (configuration-based).
118
+ *
119
+ * Use this when you want to quickly set up proxy with simple configuration.
120
+ * This function creates and configures the x402ResourceServer internally.
121
+ *
122
+ * @param routes - Route configurations for protected endpoints
123
+ * @param facilitatorClients - Optional facilitator client(s) for payment processing
124
+ * @param schemes - Optional array of scheme registrations for server-side payment processing
125
+ * @param paywallConfig - Optional configuration for the built-in paywall UI
126
+ * @param paywall - Optional custom paywall provider (overrides default)
127
+ * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)
128
+ * @returns Next.js proxy handler
129
+ *
130
+ * @example
131
+ * ```typescript
132
+ * import { paymentProxyFromConfig } from "@x402/next";
133
+ *
134
+ * export const proxy = paymentProxyFromConfig(
135
+ * routes,
136
+ * myFacilitatorClient,
137
+ * [{ network: "eip155:8453", server: evmSchemeServer }],
138
+ * paywallConfig
139
+ * );
140
+ * ```
141
+ */
142
+ declare function paymentProxyFromConfig(routes: RoutesConfig, facilitatorClients?: FacilitatorClient | FacilitatorClient[], schemes?: SchemeRegistration[], paywallConfig?: PaywallConfig, paywall?: PaywallProvider, syncFacilitatorOnStart?: boolean): (req: NextRequest) => Promise<NextResponse<unknown>>;
143
+ /**
144
+ * Wraps a Next.js App Router API route handler with x402 payment protection.
145
+ *
146
+ * Unlike `paymentProxy` which works as middleware, `withX402` wraps individual route handlers
147
+ * and guarantees that payment settlement only occurs after the handler returns a successful
148
+ * response (status < 400). This provides more precise control over when payments are settled.
149
+ *
150
+ * @param routeHandler - The API route handler function to wrap
151
+ * @param routeConfig - Payment configuration for this specific route
152
+ * @param server - Pre-configured x402ResourceServer instance
153
+ * @param paywallConfig - Optional configuration for the built-in paywall UI
154
+ * @param paywall - Optional custom paywall provider (overrides default)
155
+ * @param syncFacilitatorOnStart - Whether to sync with the facilitator on startup (defaults to true)
156
+ * @returns A wrapped Next.js route handler
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * import { NextRequest, NextResponse } from "next/server";
161
+ * import { withX402 } from "@x402/next";
162
+ * import { x402ResourceServer } from "@x402/core/server";
163
+ * import { registerExactEvmScheme } from "@x402/evm/exact/server";
164
+ *
165
+ * const server = new x402ResourceServer(myFacilitatorClient);
166
+ * registerExactEvmScheme(server, {});
167
+ *
168
+ * const handler = async (request: NextRequest) => {
169
+ * return NextResponse.json({ data: "protected content" });
170
+ * };
171
+ *
172
+ * export const GET = withX402(
173
+ * handler,
174
+ * {
175
+ * accepts: {
176
+ * scheme: "exact",
177
+ * payTo: "0x123...",
178
+ * price: "$0.01",
179
+ * network: "eip155:84532",
180
+ * },
181
+ * description: "Access to protected API",
182
+ * },
183
+ * server,
184
+ * );
185
+ * ```
186
+ */
187
+ declare function withX402<T = unknown>(routeHandler: (request: NextRequest) => Promise<NextResponse<T>>, routeConfig: RouteConfig, server: x402ResourceServer, paywallConfig?: PaywallConfig, paywall?: PaywallProvider, syncFacilitatorOnStart?: boolean): (request: NextRequest) => Promise<NextResponse<T>>;
188
+
189
+ export { NextAdapter, type SchemeRegistration, paymentProxy, paymentProxyFromConfig, withX402 };
@@ -0,0 +1,300 @@
1
+ // src/index.ts
2
+ import {
3
+ x402ResourceServer as x402ResourceServer2
4
+ } from "@x402/core/server";
5
+ import { NextResponse as NextResponse2 } from "next/server";
6
+
7
+ // src/utils.ts
8
+ import { NextResponse } from "next/server";
9
+ import {
10
+ x402HTTPResourceServer
11
+ } from "@x402/core/server";
12
+
13
+ // src/adapter.ts
14
+ var NextAdapter = class {
15
+ /**
16
+ * Creates a new NextAdapter instance.
17
+ *
18
+ * @param req - The Next.js request object
19
+ */
20
+ constructor(req) {
21
+ this.req = req;
22
+ }
23
+ /**
24
+ * Gets a header value from the request.
25
+ *
26
+ * @param name - The header name
27
+ * @returns The header value or undefined
28
+ */
29
+ getHeader(name) {
30
+ return this.req.headers.get(name) || void 0;
31
+ }
32
+ /**
33
+ * Gets the HTTP method of the request.
34
+ *
35
+ * @returns The HTTP method
36
+ */
37
+ getMethod() {
38
+ return this.req.method;
39
+ }
40
+ /**
41
+ * Gets the path of the request.
42
+ *
43
+ * @returns The request path
44
+ */
45
+ getPath() {
46
+ return this.req.nextUrl.pathname;
47
+ }
48
+ /**
49
+ * Gets the full URL of the request.
50
+ *
51
+ * @returns The full request URL
52
+ */
53
+ getUrl() {
54
+ return this.req.url;
55
+ }
56
+ /**
57
+ * Gets the Accept header from the request.
58
+ *
59
+ * @returns The Accept header value or empty string
60
+ */
61
+ getAcceptHeader() {
62
+ return this.req.headers.get("Accept") || "";
63
+ }
64
+ /**
65
+ * Gets the User-Agent header from the request.
66
+ *
67
+ * @returns The User-Agent header value or empty string
68
+ */
69
+ getUserAgent() {
70
+ return this.req.headers.get("User-Agent") || "";
71
+ }
72
+ /**
73
+ * Gets all query parameters from the request URL.
74
+ *
75
+ * @returns Record of query parameter key-value pairs
76
+ */
77
+ getQueryParams() {
78
+ const params = {};
79
+ this.req.nextUrl.searchParams.forEach((value, key) => {
80
+ const existing = params[key];
81
+ if (existing) {
82
+ if (Array.isArray(existing)) {
83
+ existing.push(value);
84
+ } else {
85
+ params[key] = [existing, value];
86
+ }
87
+ } else {
88
+ params[key] = value;
89
+ }
90
+ });
91
+ return params;
92
+ }
93
+ /**
94
+ * Gets a specific query parameter by name.
95
+ *
96
+ * @param name - The query parameter name
97
+ * @returns The query parameter value(s) or undefined
98
+ */
99
+ getQueryParam(name) {
100
+ const all = this.req.nextUrl.searchParams.getAll(name);
101
+ if (all.length === 0) return void 0;
102
+ if (all.length === 1) return all[0];
103
+ return all;
104
+ }
105
+ /**
106
+ * Gets the parsed request body.
107
+ *
108
+ * @returns Promise resolving to the parsed request body
109
+ */
110
+ async getBody() {
111
+ try {
112
+ return await this.req.json();
113
+ } catch {
114
+ return void 0;
115
+ }
116
+ }
117
+ };
118
+
119
+ // src/utils.ts
120
+ function createHttpServer(routes, server, paywall, syncFacilitatorOnStart = true) {
121
+ const httpServer = new x402HTTPResourceServer(server, routes);
122
+ if (paywall) {
123
+ httpServer.registerPaywallProvider(paywall);
124
+ }
125
+ let initPromise = syncFacilitatorOnStart ? httpServer.initialize() : null;
126
+ return {
127
+ httpServer,
128
+ async init() {
129
+ if (initPromise) {
130
+ await initPromise;
131
+ initPromise = null;
132
+ }
133
+ }
134
+ };
135
+ }
136
+ function createRequestContext(request) {
137
+ const adapter = new NextAdapter(request);
138
+ return {
139
+ adapter,
140
+ path: request.nextUrl.pathname,
141
+ method: request.method,
142
+ paymentHeader: adapter.getHeader("payment-signature") || adapter.getHeader("x-payment")
143
+ };
144
+ }
145
+ function handlePaymentError(response) {
146
+ const headers = new Headers(response.headers);
147
+ if (response.isHtml) {
148
+ headers.set("Content-Type", "text/html");
149
+ return new NextResponse(response.body, {
150
+ status: response.status,
151
+ headers
152
+ });
153
+ }
154
+ headers.set("Content-Type", "application/json");
155
+ return new NextResponse(JSON.stringify(response.body || {}), {
156
+ status: response.status,
157
+ headers
158
+ });
159
+ }
160
+ async function handleSettlement(httpServer, response, paymentPayload, paymentRequirements) {
161
+ if (response.status >= 400) {
162
+ return response;
163
+ }
164
+ try {
165
+ const result = await httpServer.processSettlement(paymentPayload, paymentRequirements);
166
+ if (!result.success) {
167
+ return new NextResponse(
168
+ JSON.stringify({
169
+ error: "Settlement failed",
170
+ details: result.errorReason
171
+ }),
172
+ {
173
+ status: 402,
174
+ headers: { "Content-Type": "application/json" }
175
+ }
176
+ );
177
+ }
178
+ Object.entries(result.headers).forEach(([key, value]) => {
179
+ response.headers.set(key, value);
180
+ });
181
+ return response;
182
+ } catch (error) {
183
+ console.error("Settlement failed:", error);
184
+ return new NextResponse(
185
+ JSON.stringify({
186
+ error: "Settlement failed",
187
+ details: error instanceof Error ? error.message : "Unknown error"
188
+ }),
189
+ {
190
+ status: 402,
191
+ headers: { "Content-Type": "application/json" }
192
+ }
193
+ );
194
+ }
195
+ }
196
+
197
+ // src/index.ts
198
+ import { RouteConfigurationError } from "@x402/core/server";
199
+ function paymentProxy(routes, server, paywallConfig, paywall, syncFacilitatorOnStart = true) {
200
+ const { httpServer, init } = createHttpServer(routes, server, paywall, syncFacilitatorOnStart);
201
+ let bazaarPromise = null;
202
+ if (checkIfBazaarNeeded(routes)) {
203
+ bazaarPromise = import(
204
+ /* webpackIgnore: true */
205
+ "@x402/extensions/bazaar"
206
+ ).then(({ bazaarResourceServerExtension }) => {
207
+ server.registerExtension(bazaarResourceServerExtension);
208
+ }).catch((err) => {
209
+ console.error("Failed to load bazaar extension:", err);
210
+ });
211
+ }
212
+ return async (req) => {
213
+ const context = createRequestContext(req);
214
+ if (!httpServer.requiresPayment(context)) {
215
+ return NextResponse2.next();
216
+ }
217
+ await init();
218
+ if (bazaarPromise) {
219
+ await bazaarPromise;
220
+ bazaarPromise = null;
221
+ }
222
+ const result = await httpServer.processHTTPRequest(context, paywallConfig);
223
+ switch (result.type) {
224
+ case "no-payment-required":
225
+ return NextResponse2.next();
226
+ case "payment-error":
227
+ return handlePaymentError(result.response);
228
+ case "payment-verified": {
229
+ const { paymentPayload, paymentRequirements } = result;
230
+ const nextResponse = NextResponse2.next();
231
+ return handleSettlement(httpServer, nextResponse, paymentPayload, paymentRequirements);
232
+ }
233
+ }
234
+ };
235
+ }
236
+ function paymentProxyFromConfig(routes, facilitatorClients, schemes, paywallConfig, paywall, syncFacilitatorOnStart = true) {
237
+ const ResourceServer = new x402ResourceServer2(facilitatorClients);
238
+ if (schemes) {
239
+ schemes.forEach(({ network, server: schemeServer }) => {
240
+ ResourceServer.register(network, schemeServer);
241
+ });
242
+ }
243
+ return paymentProxy(routes, ResourceServer, paywallConfig, paywall, syncFacilitatorOnStart);
244
+ }
245
+ function withX402(routeHandler, routeConfig, server, paywallConfig, paywall, syncFacilitatorOnStart = true) {
246
+ const routes = { "*": routeConfig };
247
+ const { httpServer, init } = createHttpServer(routes, server, paywall, syncFacilitatorOnStart);
248
+ let bazaarPromise = null;
249
+ if (checkIfBazaarNeeded(routes)) {
250
+ bazaarPromise = import(
251
+ /* webpackIgnore: true */
252
+ "@x402/extensions/bazaar"
253
+ ).then(({ bazaarResourceServerExtension }) => {
254
+ server.registerExtension(bazaarResourceServerExtension);
255
+ }).catch((err) => {
256
+ console.error("Failed to load bazaar extension:", err);
257
+ });
258
+ }
259
+ return async (request) => {
260
+ await init();
261
+ if (bazaarPromise) {
262
+ await bazaarPromise;
263
+ bazaarPromise = null;
264
+ }
265
+ const context = createRequestContext(request);
266
+ const result = await httpServer.processHTTPRequest(context, paywallConfig);
267
+ switch (result.type) {
268
+ case "no-payment-required":
269
+ return routeHandler(request);
270
+ case "payment-error":
271
+ return handlePaymentError(result.response);
272
+ case "payment-verified": {
273
+ const { paymentPayload, paymentRequirements } = result;
274
+ const handlerResponse = await routeHandler(request);
275
+ return handleSettlement(
276
+ httpServer,
277
+ handlerResponse,
278
+ paymentPayload,
279
+ paymentRequirements
280
+ );
281
+ }
282
+ }
283
+ };
284
+ }
285
+ function checkIfBazaarNeeded(routes) {
286
+ if ("accepts" in routes) {
287
+ return !!(routes.extensions && "bazaar" in routes.extensions);
288
+ }
289
+ return Object.values(routes).some((routeConfig) => {
290
+ return !!(routeConfig.extensions && "bazaar" in routeConfig.extensions);
291
+ });
292
+ }
293
+ export {
294
+ NextAdapter,
295
+ RouteConfigurationError,
296
+ paymentProxy,
297
+ paymentProxyFromConfig,
298
+ withX402
299
+ };
300
+ //# sourceMappingURL=index.js.map