@x402/extensions 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,547 @@
1
+ import { QueryParamMethods, BodyMethods, HTTPFacilitatorClient } from '@x402/core/http';
2
+ import { ResourceServerExtension, PaymentPayload, PaymentRequirements, PaymentRequirementsV1 } from '@x402/core/types';
3
+
4
+ /**
5
+ * Shared type utilities for x402 extensions
6
+ */
7
+ /**
8
+ * Type utility to merge extensions properly when chaining.
9
+ * If T already has extensions, merge them; otherwise add new extensions.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * // Chaining multiple extensions preserves all types:
14
+ * const client = withBazaar(withOtherExtension(new HTTPFacilitatorClient()));
15
+ * // Type: HTTPFacilitatorClient & { extensions: OtherExtension & BazaarExtension }
16
+ * ```
17
+ */
18
+ type WithExtensions<T, E> = T extends {
19
+ extensions: infer Existing;
20
+ } ? Omit<T, "extensions"> & {
21
+ extensions: Existing & E;
22
+ } : T & {
23
+ extensions: E;
24
+ };
25
+
26
+ /**
27
+ * Type definitions for the Bazaar Discovery Extension
28
+ */
29
+
30
+ /**
31
+ * Extension identifier constant for the Bazaar discovery extension
32
+ */
33
+ declare const BAZAAR = "bazaar";
34
+ /**
35
+ * Discovery info for query parameter methods (GET, HEAD, DELETE)
36
+ */
37
+ interface QueryDiscoveryInfo {
38
+ input: {
39
+ type: "http";
40
+ method: QueryParamMethods;
41
+ queryParams?: Record<string, unknown>;
42
+ headers?: Record<string, string>;
43
+ };
44
+ output?: {
45
+ type?: string;
46
+ format?: string;
47
+ example?: unknown;
48
+ };
49
+ }
50
+ /**
51
+ * Discovery info for body methods (POST, PUT, PATCH)
52
+ */
53
+ interface BodyDiscoveryInfo {
54
+ input: {
55
+ type: "http";
56
+ method: BodyMethods;
57
+ bodyType: "json" | "form-data" | "text";
58
+ body: Record<string, unknown>;
59
+ queryParams?: Record<string, unknown>;
60
+ headers?: Record<string, string>;
61
+ };
62
+ output?: {
63
+ type?: string;
64
+ format?: string;
65
+ example?: unknown;
66
+ };
67
+ }
68
+ /**
69
+ * Combined discovery info type
70
+ */
71
+ type DiscoveryInfo = QueryDiscoveryInfo | BodyDiscoveryInfo;
72
+ /**
73
+ * Discovery extension for query parameter methods (GET, HEAD, DELETE)
74
+ */
75
+ interface QueryDiscoveryExtension {
76
+ info: QueryDiscoveryInfo;
77
+ schema: {
78
+ $schema: "https://json-schema.org/draft/2020-12/schema";
79
+ type: "object";
80
+ properties: {
81
+ input: {
82
+ type: "object";
83
+ properties: {
84
+ type: {
85
+ type: "string";
86
+ const: "http";
87
+ };
88
+ method: {
89
+ type: "string";
90
+ enum: QueryParamMethods[];
91
+ };
92
+ queryParams?: {
93
+ type: "object";
94
+ properties?: Record<string, unknown>;
95
+ required?: string[];
96
+ additionalProperties?: boolean;
97
+ };
98
+ headers?: {
99
+ type: "object";
100
+ additionalProperties: {
101
+ type: "string";
102
+ };
103
+ };
104
+ };
105
+ required: ("type" | "method")[];
106
+ additionalProperties?: boolean;
107
+ };
108
+ output?: {
109
+ type: "object";
110
+ properties?: Record<string, unknown>;
111
+ required?: readonly string[];
112
+ additionalProperties?: boolean;
113
+ };
114
+ };
115
+ required: ["input"];
116
+ };
117
+ }
118
+ /**
119
+ * Discovery extension for body methods (POST, PUT, PATCH)
120
+ */
121
+ interface BodyDiscoveryExtension {
122
+ info: BodyDiscoveryInfo;
123
+ schema: {
124
+ $schema: "https://json-schema.org/draft/2020-12/schema";
125
+ type: "object";
126
+ properties: {
127
+ input: {
128
+ type: "object";
129
+ properties: {
130
+ type: {
131
+ type: "string";
132
+ const: "http";
133
+ };
134
+ method: {
135
+ type: "string";
136
+ enum: BodyMethods[];
137
+ };
138
+ bodyType: {
139
+ type: "string";
140
+ enum: ["json", "form-data", "text"];
141
+ };
142
+ body: Record<string, unknown>;
143
+ queryParams?: {
144
+ type: "object";
145
+ properties?: Record<string, unknown>;
146
+ required?: string[];
147
+ additionalProperties?: boolean;
148
+ };
149
+ headers?: {
150
+ type: "object";
151
+ additionalProperties: {
152
+ type: "string";
153
+ };
154
+ };
155
+ };
156
+ required: ("type" | "method" | "bodyType" | "body")[];
157
+ additionalProperties?: boolean;
158
+ };
159
+ output?: {
160
+ type: "object";
161
+ properties?: Record<string, unknown>;
162
+ required?: readonly string[];
163
+ additionalProperties?: boolean;
164
+ };
165
+ };
166
+ required: ["input"];
167
+ };
168
+ }
169
+ /**
170
+ * Combined discovery extension type
171
+ */
172
+ type DiscoveryExtension = QueryDiscoveryExtension | BodyDiscoveryExtension;
173
+ interface DeclareQueryDiscoveryExtensionConfig {
174
+ method?: QueryParamMethods;
175
+ input?: Record<string, unknown>;
176
+ inputSchema?: Record<string, unknown>;
177
+ output?: {
178
+ example?: unknown;
179
+ schema?: Record<string, unknown>;
180
+ };
181
+ }
182
+ interface DeclareBodyDiscoveryExtensionConfig {
183
+ method?: BodyMethods;
184
+ input?: Record<string, unknown>;
185
+ inputSchema?: Record<string, unknown>;
186
+ bodyType?: "json" | "form-data" | "text";
187
+ output?: {
188
+ example?: unknown;
189
+ schema?: Record<string, unknown>;
190
+ };
191
+ }
192
+ type DeclareDiscoveryExtensionConfig = DeclareQueryDiscoveryExtensionConfig | DeclareBodyDiscoveryExtensionConfig;
193
+
194
+ /**
195
+ * Resource Service functions for creating Bazaar discovery extensions
196
+ *
197
+ * These functions help servers declare the shape of their endpoints
198
+ * for facilitator discovery and cataloging in the Bazaar.
199
+ */
200
+
201
+ /**
202
+ * Create a discovery extension for any HTTP method
203
+ *
204
+ * This function helps servers declare how their endpoint should be called,
205
+ * including the expected input parameters/body and output format.
206
+ *
207
+ * @param config - Configuration object for the discovery extension
208
+ * @returns A discovery extension object with both info and schema
209
+ *
210
+ * @example
211
+ * ```typescript
212
+ * // For a GET endpoint with no input
213
+ * const getExtension = declareDiscoveryExtension({
214
+ * method: "GET",
215
+ * output: {
216
+ * example: { message: "Success", timestamp: "2024-01-01T00:00:00Z" }
217
+ * }
218
+ * });
219
+ *
220
+ * // For a GET endpoint with query params
221
+ * const getWithParams = declareDiscoveryExtension({
222
+ * method: "GET",
223
+ * input: { query: "example" },
224
+ * inputSchema: {
225
+ * properties: {
226
+ * query: { type: "string" }
227
+ * },
228
+ * required: ["query"]
229
+ * }
230
+ * });
231
+ *
232
+ * // For a POST endpoint with JSON body
233
+ * const postExtension = declareDiscoveryExtension({
234
+ * method: "POST",
235
+ * input: { name: "John", age: 30 },
236
+ * inputSchema: {
237
+ * properties: {
238
+ * name: { type: "string" },
239
+ * age: { type: "number" }
240
+ * },
241
+ * required: ["name"]
242
+ * },
243
+ * bodyType: "json",
244
+ * output: {
245
+ * example: { success: true, id: "123" }
246
+ * }
247
+ * });
248
+ * ```
249
+ */
250
+ declare function declareDiscoveryExtension(config: Omit<DeclareDiscoveryExtensionConfig, "method">): Record<string, DiscoveryExtension>;
251
+
252
+ declare const bazaarResourceServerExtension: ResourceServerExtension;
253
+
254
+ /**
255
+ * Facilitator functions for validating and extracting Bazaar discovery extensions
256
+ *
257
+ * These functions help facilitators validate extension data against schemas
258
+ * and extract the discovery information for cataloging in the Bazaar.
259
+ *
260
+ * Supports both v2 (extensions in PaymentRequired) and v1 (outputSchema in PaymentRequirements).
261
+ */
262
+
263
+ /**
264
+ * Validation result for discovery extensions
265
+ */
266
+ interface ValidationResult {
267
+ valid: boolean;
268
+ errors?: string[];
269
+ }
270
+ /**
271
+ * Validates a discovery extension's info against its schema
272
+ *
273
+ * @param extension - The discovery extension containing info and schema
274
+ * @returns Validation result indicating if the info matches the schema
275
+ *
276
+ * @example
277
+ * ```typescript
278
+ * const extension = declareDiscoveryExtension(...);
279
+ * const result = validateDiscoveryExtension(extension);
280
+ *
281
+ * if (result.valid) {
282
+ * console.log("Extension is valid");
283
+ * } else {
284
+ * console.error("Validation errors:", result.errors);
285
+ * }
286
+ * ```
287
+ */
288
+ declare function validateDiscoveryExtension(extension: DiscoveryExtension): ValidationResult;
289
+ /**
290
+ * Extracts the discovery info from payment payload and requirements
291
+ *
292
+ * This function handles both v2 (extensions) and v1 (outputSchema) formats.
293
+ *
294
+ * For v2: Discovery info is in PaymentPayload.extensions (client copied it from PaymentRequired)
295
+ * For v1: Discovery info is in PaymentRequirements.outputSchema
296
+ *
297
+ * V1 data is automatically transformed to v2 DiscoveryInfo format, making smart
298
+ * assumptions about field names (queryParams/query/params for GET, bodyFields/body/data for POST, etc.)
299
+ *
300
+ * @param paymentPayload - The payment payload containing extensions (v2) and version info
301
+ * @param paymentRequirements - The payment requirements (contains outputSchema for v1)
302
+ * @param validate - Whether to validate v2 extensions before extracting (default: true)
303
+ * @returns The discovery info in v2 format if present, or null if not discoverable
304
+ *
305
+ * @example
306
+ * ```typescript
307
+ * // V2 - extensions are in PaymentPayload
308
+ * const info = extractDiscoveryInfo(paymentPayload, paymentRequirements);
309
+ *
310
+ * // V1 - discovery info is in PaymentRequirements.outputSchema
311
+ * const info = extractDiscoveryInfo(paymentPayloadV1, paymentRequirementsV1);
312
+ *
313
+ * if (info) {
314
+ * // Both v1 and v2 return the same DiscoveryInfo structure
315
+ * console.log("Method:", info.input.method);
316
+ * }
317
+ * ```
318
+ */
319
+ interface DiscoveredResource {
320
+ resourceUrl: string;
321
+ method: string;
322
+ x402Version: number;
323
+ discoveryInfo: DiscoveryInfo;
324
+ }
325
+ /**
326
+ * Extracts discovery information from payment payload and requirements.
327
+ * Combines resource URL, HTTP method, version, and discovery info into a single object.
328
+ *
329
+ * @param paymentPayload - The payment payload containing extensions and resource info
330
+ * @param paymentRequirements - The payment requirements to validate against
331
+ * @param validate - Whether to validate the discovery info against the schema (default: true)
332
+ * @returns Discovered resource info with URL, method, version and discovery data, or null if not found
333
+ */
334
+ declare function extractDiscoveryInfo(paymentPayload: PaymentPayload, paymentRequirements: PaymentRequirements | PaymentRequirementsV1, validate?: boolean): DiscoveredResource | null;
335
+ /**
336
+ * Extracts discovery info from a v2 extension directly
337
+ *
338
+ * This is a lower-level function for when you already have the extension object.
339
+ * For general use, prefer the main extractDiscoveryInfo function.
340
+ *
341
+ * @param extension - The discovery extension to extract info from
342
+ * @param validate - Whether to validate before extracting (default: true)
343
+ * @returns The discovery info if valid
344
+ * @throws Error if validation fails and validate is true
345
+ */
346
+ declare function extractDiscoveryInfoFromExtension(extension: DiscoveryExtension, validate?: boolean): DiscoveryInfo;
347
+ /**
348
+ * Validates and extracts discovery info in one step
349
+ *
350
+ * This is a convenience function that combines validation and extraction,
351
+ * returning both the validation result and the info if valid.
352
+ *
353
+ * @param extension - The discovery extension to validate and extract
354
+ * @returns Object containing validation result and info (if valid)
355
+ *
356
+ * @example
357
+ * ```typescript
358
+ * const extension = declareDiscoveryExtension(...);
359
+ * const { valid, info, errors } = validateAndExtract(extension);
360
+ *
361
+ * if (valid && info) {
362
+ * // Store info in Bazaar catalog
363
+ * } else {
364
+ * console.error("Validation errors:", errors);
365
+ * }
366
+ * ```
367
+ */
368
+ declare function validateAndExtract(extension: DiscoveryExtension): {
369
+ valid: boolean;
370
+ info?: DiscoveryInfo;
371
+ errors?: string[];
372
+ };
373
+
374
+ /**
375
+ * V1 Facilitator functions for extracting Bazaar discovery information
376
+ *
377
+ * In v1, discovery information is stored in the `outputSchema` field
378
+ * of PaymentRequirements, which has a different structure than v2.
379
+ *
380
+ * This module transforms v1 data into v2 DiscoveryInfo format.
381
+ */
382
+
383
+ /**
384
+ * Extracts discovery info from v1 PaymentRequirements and transforms to v2 format
385
+ *
386
+ * In v1, the discovery information is stored in the `outputSchema` field,
387
+ * which contains both input (endpoint shape) and output (response schema) information.
388
+ *
389
+ * This function makes smart assumptions to normalize v1 data into v2 DiscoveryInfo format:
390
+ * - For GET/HEAD/DELETE: Looks for queryParams, query, or params fields
391
+ * - For POST/PUT/PATCH: Looks for bodyFields, body, or data fields and normalizes bodyType
392
+ * - Extracts optional headers if present
393
+ *
394
+ * @param paymentRequirements - V1 payment requirements
395
+ * @returns Discovery info in v2 format if present and valid, or null if not discoverable
396
+ *
397
+ * @example
398
+ * ```typescript
399
+ * const requirements: PaymentRequirementsV1 = {
400
+ * scheme: "exact",
401
+ * network: "eip155:8453",
402
+ * maxAmountRequired: "100000",
403
+ * resource: "https://api.example.com/data",
404
+ * description: "Get data",
405
+ * mimeType: "application/json",
406
+ * outputSchema: {
407
+ * input: {
408
+ * type: "http",
409
+ * method: "GET",
410
+ * discoverable: true,
411
+ * queryParams: { query: "string" }
412
+ * },
413
+ * output: { type: "object" }
414
+ * },
415
+ * payTo: "0x...",
416
+ * maxTimeoutSeconds: 300,
417
+ * asset: "0x...",
418
+ * extra: {}
419
+ * };
420
+ *
421
+ * const info = extractDiscoveryInfoV1(requirements);
422
+ * if (info) {
423
+ * console.log("Endpoint method:", info.input.method);
424
+ * }
425
+ * ```
426
+ */
427
+ declare function extractDiscoveryInfoV1(paymentRequirements: PaymentRequirementsV1): DiscoveryInfo | null;
428
+ /**
429
+ * Checks if v1 PaymentRequirements contains discoverable information
430
+ *
431
+ * @param paymentRequirements - V1 payment requirements
432
+ * @returns True if the requirements contain valid discovery info
433
+ *
434
+ * @example
435
+ * ```typescript
436
+ * if (isDiscoverableV1(requirements)) {
437
+ * const info = extractDiscoveryInfoV1(requirements);
438
+ * // Catalog info in Bazaar
439
+ * }
440
+ * ```
441
+ */
442
+ declare function isDiscoverableV1(paymentRequirements: PaymentRequirementsV1): boolean;
443
+ /**
444
+ * Extracts resource metadata from v1 PaymentRequirements
445
+ *
446
+ * In v1, resource information is embedded directly in the payment requirements
447
+ * rather than in a separate resource object.
448
+ *
449
+ * @param paymentRequirements - V1 payment requirements
450
+ * @returns Resource metadata
451
+ *
452
+ * @example
453
+ * ```typescript
454
+ * const metadata = extractResourceMetadataV1(requirements);
455
+ * console.log("Resource URL:", metadata.url);
456
+ * console.log("Description:", metadata.description);
457
+ * ```
458
+ */
459
+ declare function extractResourceMetadataV1(paymentRequirements: PaymentRequirementsV1): {
460
+ url: string;
461
+ description: string;
462
+ mimeType: string;
463
+ };
464
+
465
+ /**
466
+ * Client extensions for querying Bazaar discovery resources
467
+ */
468
+
469
+ /**
470
+ * Parameters for listing discovery resources.
471
+ * All parameters are optional and used for filtering/pagination.
472
+ */
473
+ interface ListDiscoveryResourcesParams {
474
+ /**
475
+ * Filter by protocol type (e.g., "http", "mcp").
476
+ * Currently, the only supported protocol type is "http".
477
+ */
478
+ type?: string;
479
+ /**
480
+ * The number of discovered x402 resources to return per page.
481
+ */
482
+ limit?: number;
483
+ /**
484
+ * The offset of the first discovered x402 resource to return.
485
+ */
486
+ offset?: number;
487
+ }
488
+ /**
489
+ * A discovered x402 resource from the bazaar.
490
+ */
491
+ interface DiscoveryResource {
492
+ /** The URL of the discovered resource */
493
+ url: string;
494
+ /** The protocol type of the resource */
495
+ type: string;
496
+ /** Additional metadata about the resource */
497
+ metadata?: Record<string, unknown>;
498
+ }
499
+ /**
500
+ * Response from listing discovery resources.
501
+ */
502
+ interface DiscoveryResourcesResponse {
503
+ /** The list of discovered resources */
504
+ resources: DiscoveryResource[];
505
+ /** Total count of resources matching the query */
506
+ total?: number;
507
+ /** The limit used for this query */
508
+ limit?: number;
509
+ /** The offset used for this query */
510
+ offset?: number;
511
+ }
512
+ /**
513
+ * Bazaar client extension interface providing discovery query functionality.
514
+ */
515
+ interface BazaarClientExtension {
516
+ discovery: {
517
+ /**
518
+ * List x402 discovery resources from the bazaar.
519
+ *
520
+ * @param params - Optional filtering and pagination parameters
521
+ * @returns A promise resolving to the discovery resources response
522
+ */
523
+ listResources(params?: ListDiscoveryResourcesParams): Promise<DiscoveryResourcesResponse>;
524
+ };
525
+ }
526
+ /**
527
+ * Extends a facilitator client with Bazaar discovery query functionality.
528
+ * Preserves and merges with any existing extensions from prior chaining.
529
+ *
530
+ * @param client - The facilitator client to extend
531
+ * @returns The client extended with bazaar discovery capabilities
532
+ *
533
+ * @example
534
+ * ```ts
535
+ * // Basic usage
536
+ * const client = withBazaar(new HTTPFacilitatorClient());
537
+ * const resources = await client.extensions.discovery.listResources({ type: "http" });
538
+ *
539
+ * // Chaining with other extensions
540
+ * const client = withBazaar(withOtherExtension(new HTTPFacilitatorClient()));
541
+ * await client.extensions.other.someMethod();
542
+ * await client.extensions.discovery.listResources();
543
+ * ```
544
+ */
545
+ declare function withBazaar<T extends HTTPFacilitatorClient>(client: T): WithExtensions<T, BazaarClientExtension>;
546
+
547
+ export { BAZAAR, type BazaarClientExtension, type BodyDiscoveryExtension, type BodyDiscoveryInfo, type DiscoveryExtension, type DiscoveryInfo, type DiscoveryResource, type DiscoveryResourcesResponse, type ListDiscoveryResourcesParams, type QueryDiscoveryExtension, type QueryDiscoveryInfo, type ValidationResult, type WithExtensions as W, bazaarResourceServerExtension, declareDiscoveryExtension, extractDiscoveryInfo, extractDiscoveryInfoFromExtension, extractDiscoveryInfoV1, extractResourceMetadataV1, isDiscoverableV1, validateAndExtract, validateDiscoveryExtension, withBazaar };
@@ -0,0 +1,27 @@
1
+ import {
2
+ BAZAAR,
3
+ bazaarResourceServerExtension,
4
+ declareDiscoveryExtension,
5
+ extractDiscoveryInfo,
6
+ extractDiscoveryInfoFromExtension,
7
+ extractDiscoveryInfoV1,
8
+ extractResourceMetadataV1,
9
+ isDiscoverableV1,
10
+ validateAndExtract,
11
+ validateDiscoveryExtension,
12
+ withBazaar
13
+ } from "../chunk-STXY3Q5R.mjs";
14
+ export {
15
+ BAZAAR,
16
+ bazaarResourceServerExtension,
17
+ declareDiscoveryExtension,
18
+ extractDiscoveryInfo,
19
+ extractDiscoveryInfoFromExtension,
20
+ extractDiscoveryInfoV1,
21
+ extractResourceMetadataV1,
22
+ isDiscoverableV1,
23
+ validateAndExtract,
24
+ validateDiscoveryExtension,
25
+ withBazaar
26
+ };
27
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-MKFJ5AA3.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}