@bankofai/x402-extensions 1.0.0-beta.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.
Files changed (52) hide show
  1. package/README.md +28 -0
  2. package/dist/cjs/bazaar/index.d.ts +4 -0
  3. package/dist/cjs/bazaar/index.js +1048 -0
  4. package/dist/cjs/bazaar/index.js.map +1 -0
  5. package/dist/cjs/builder-code/index.d.ts +225 -0
  6. package/dist/cjs/builder-code/index.js +369 -0
  7. package/dist/cjs/builder-code/index.js.map +1 -0
  8. package/dist/cjs/index-B8S563vv.d.ts +929 -0
  9. package/dist/cjs/index-BUV9B9f8.d.ts +929 -0
  10. package/dist/cjs/index.d.ts +373 -0
  11. package/dist/cjs/index.js +3536 -0
  12. package/dist/cjs/index.js.map +1 -0
  13. package/dist/cjs/offer-receipt/index.d.ts +702 -0
  14. package/dist/cjs/offer-receipt/index.js +909 -0
  15. package/dist/cjs/offer-receipt/index.js.map +1 -0
  16. package/dist/cjs/payment-identifier/index.d.ts +345 -0
  17. package/dist/cjs/payment-identifier/index.js +285 -0
  18. package/dist/cjs/payment-identifier/index.js.map +1 -0
  19. package/dist/cjs/sign-in-with-x/index.d.ts +1117 -0
  20. package/dist/cjs/sign-in-with-x/index.js +876 -0
  21. package/dist/cjs/sign-in-with-x/index.js.map +1 -0
  22. package/dist/esm/bazaar/index.d.mts +4 -0
  23. package/dist/esm/bazaar/index.mjs +51 -0
  24. package/dist/esm/bazaar/index.mjs.map +1 -0
  25. package/dist/esm/builder-code/index.d.mts +225 -0
  26. package/dist/esm/builder-code/index.mjs +27 -0
  27. package/dist/esm/builder-code/index.mjs.map +1 -0
  28. package/dist/esm/chunk-4IPDE3NS.mjs +990 -0
  29. package/dist/esm/chunk-4IPDE3NS.mjs.map +1 -0
  30. package/dist/esm/chunk-N74HQTNO.mjs +807 -0
  31. package/dist/esm/chunk-N74HQTNO.mjs.map +1 -0
  32. package/dist/esm/chunk-OWZP4CUR.mjs +333 -0
  33. package/dist/esm/chunk-OWZP4CUR.mjs.map +1 -0
  34. package/dist/esm/chunk-RERA4OZZ.mjs +233 -0
  35. package/dist/esm/chunk-RERA4OZZ.mjs.map +1 -0
  36. package/dist/esm/chunk-TIVMC3ZS.mjs +828 -0
  37. package/dist/esm/chunk-TIVMC3ZS.mjs.map +1 -0
  38. package/dist/esm/index-B8S563vv.d.mts +929 -0
  39. package/dist/esm/index-BUV9B9f8.d.mts +929 -0
  40. package/dist/esm/index.d.mts +373 -0
  41. package/dist/esm/index.mjs +455 -0
  42. package/dist/esm/index.mjs.map +1 -0
  43. package/dist/esm/offer-receipt/index.d.mts +702 -0
  44. package/dist/esm/offer-receipt/index.mjs +97 -0
  45. package/dist/esm/offer-receipt/index.mjs.map +1 -0
  46. package/dist/esm/payment-identifier/index.d.mts +345 -0
  47. package/dist/esm/payment-identifier/index.mjs +39 -0
  48. package/dist/esm/payment-identifier/index.mjs.map +1 -0
  49. package/dist/esm/sign-in-with-x/index.d.mts +1117 -0
  50. package/dist/esm/sign-in-with-x/index.mjs +73 -0
  51. package/dist/esm/sign-in-with-x/index.mjs.map +1 -0
  52. package/package.json +124 -0
@@ -0,0 +1,990 @@
1
+ // src/bazaar/http/types.ts
2
+ var isQueryExtensionConfig = (config) => {
3
+ return !("bodyType" in config) && !("toolName" in config);
4
+ };
5
+ var isBodyExtensionConfig = (config) => {
6
+ return "bodyType" in config;
7
+ };
8
+
9
+ // src/bazaar/mcp/types.ts
10
+ var isMcpExtensionConfig = (config) => {
11
+ return "toolName" in config;
12
+ };
13
+
14
+ // src/bazaar/types.ts
15
+ var BAZAAR = { key: "bazaar" };
16
+
17
+ // src/bazaar/http/resourceService.ts
18
+ function createQueryDiscoveryExtension({
19
+ method,
20
+ input = {},
21
+ inputSchema = { properties: {} },
22
+ pathParams,
23
+ pathParamsSchema,
24
+ output
25
+ }) {
26
+ return {
27
+ info: {
28
+ input: {
29
+ type: "http",
30
+ ...method ? { method } : {},
31
+ ...input ? { queryParams: input } : {},
32
+ ...pathParams ? { pathParams } : {}
33
+ },
34
+ ...output?.example ? {
35
+ output: {
36
+ type: "json",
37
+ example: output.example
38
+ }
39
+ } : {}
40
+ },
41
+ schema: {
42
+ $schema: "https://json-schema.org/draft/2020-12/schema",
43
+ type: "object",
44
+ properties: {
45
+ input: {
46
+ type: "object",
47
+ properties: {
48
+ type: {
49
+ type: "string",
50
+ const: "http"
51
+ },
52
+ method: {
53
+ type: "string",
54
+ enum: ["GET", "HEAD", "DELETE"]
55
+ },
56
+ ...inputSchema ? {
57
+ queryParams: {
58
+ type: "object",
59
+ ...typeof inputSchema === "object" ? inputSchema : {}
60
+ }
61
+ } : {},
62
+ ...pathParamsSchema ? {
63
+ pathParams: {
64
+ type: "object",
65
+ ...typeof pathParamsSchema === "object" ? pathParamsSchema : {}
66
+ }
67
+ } : {}
68
+ },
69
+ required: ["type", "method"],
70
+ // pathParams are not declared here at schema build time --
71
+ // the server extension's enrichDeclaration adds them to both info and schema
72
+ // atomically at request time, keeping data and schema consistent.
73
+ additionalProperties: false
74
+ },
75
+ ...output?.example ? {
76
+ output: {
77
+ type: "object",
78
+ properties: {
79
+ type: {
80
+ type: "string"
81
+ },
82
+ example: {
83
+ type: "object",
84
+ ...output.schema && typeof output.schema === "object" ? output.schema : {}
85
+ }
86
+ },
87
+ required: ["type"]
88
+ }
89
+ } : {}
90
+ },
91
+ required: ["input"]
92
+ }
93
+ };
94
+ }
95
+ function createBodyDiscoveryExtension({
96
+ method,
97
+ input = {},
98
+ inputSchema = { properties: {} },
99
+ pathParams,
100
+ pathParamsSchema,
101
+ bodyType,
102
+ output
103
+ }) {
104
+ return {
105
+ info: {
106
+ input: {
107
+ type: "http",
108
+ ...method ? { method } : {},
109
+ bodyType,
110
+ body: input,
111
+ ...pathParams ? { pathParams } : {}
112
+ },
113
+ ...output?.example ? {
114
+ output: {
115
+ type: "json",
116
+ example: output.example
117
+ }
118
+ } : {}
119
+ },
120
+ schema: {
121
+ $schema: "https://json-schema.org/draft/2020-12/schema",
122
+ type: "object",
123
+ properties: {
124
+ input: {
125
+ type: "object",
126
+ properties: {
127
+ type: {
128
+ type: "string",
129
+ const: "http"
130
+ },
131
+ method: {
132
+ type: "string",
133
+ enum: ["POST", "PUT", "PATCH"]
134
+ },
135
+ bodyType: {
136
+ type: "string",
137
+ enum: ["json", "form-data", "text"]
138
+ },
139
+ body: inputSchema,
140
+ ...pathParamsSchema ? {
141
+ pathParams: {
142
+ type: "object",
143
+ ...typeof pathParamsSchema === "object" ? pathParamsSchema : {}
144
+ }
145
+ } : {}
146
+ },
147
+ required: ["type", "method", "bodyType", "body"],
148
+ // pathParams are not declared here at schema build time --
149
+ // the server extension's enrichDeclaration adds them to both info and schema
150
+ // atomically at request time, keeping data and schema consistent.
151
+ additionalProperties: false
152
+ },
153
+ ...output?.example ? {
154
+ output: {
155
+ type: "object",
156
+ properties: {
157
+ type: {
158
+ type: "string"
159
+ },
160
+ example: {
161
+ type: "object",
162
+ ...output.schema && typeof output.schema === "object" ? output.schema : {}
163
+ }
164
+ },
165
+ required: ["type"]
166
+ }
167
+ } : {}
168
+ },
169
+ required: ["input"]
170
+ }
171
+ };
172
+ }
173
+
174
+ // src/bazaar/mcp/resourceService.ts
175
+ function createMcpDiscoveryExtension({
176
+ toolName,
177
+ description,
178
+ transport,
179
+ inputSchema,
180
+ example,
181
+ output
182
+ }) {
183
+ return {
184
+ info: {
185
+ input: {
186
+ type: "mcp",
187
+ toolName,
188
+ ...description !== void 0 ? { description } : {},
189
+ ...transport !== void 0 ? { transport } : {},
190
+ inputSchema,
191
+ ...example !== void 0 ? { example } : {}
192
+ },
193
+ ...output?.example ? {
194
+ output: {
195
+ type: "json",
196
+ example: output.example
197
+ }
198
+ } : {}
199
+ },
200
+ schema: {
201
+ $schema: "https://json-schema.org/draft/2020-12/schema",
202
+ type: "object",
203
+ properties: {
204
+ input: {
205
+ type: "object",
206
+ properties: {
207
+ type: {
208
+ type: "string",
209
+ const: "mcp"
210
+ },
211
+ toolName: {
212
+ type: "string"
213
+ },
214
+ ...description !== void 0 ? {
215
+ description: {
216
+ type: "string"
217
+ }
218
+ } : {},
219
+ ...transport !== void 0 ? {
220
+ transport: {
221
+ type: "string",
222
+ ...transport === "streamable-http" || transport === "sse" ? { enum: [transport] } : {}
223
+ }
224
+ } : {},
225
+ inputSchema: {
226
+ type: "object"
227
+ },
228
+ ...example !== void 0 ? {
229
+ example: {
230
+ type: "object"
231
+ }
232
+ } : {}
233
+ },
234
+ required: ["type", "toolName", "inputSchema"],
235
+ additionalProperties: false
236
+ },
237
+ ...output?.example ? {
238
+ output: {
239
+ type: "object",
240
+ properties: {
241
+ type: {
242
+ type: "string"
243
+ },
244
+ example: {
245
+ type: "object",
246
+ ...output.schema && typeof output.schema === "object" ? output.schema : {}
247
+ }
248
+ },
249
+ required: ["type"]
250
+ }
251
+ } : {}
252
+ },
253
+ required: ["input"]
254
+ }
255
+ };
256
+ }
257
+
258
+ // src/bazaar/resourceService.ts
259
+ function declareDiscoveryExtension(config) {
260
+ if ("toolName" in config) {
261
+ const extension2 = createMcpDiscoveryExtension(config);
262
+ return { bazaar: extension2 };
263
+ }
264
+ const bodyType = config.bodyType;
265
+ const isBodyMethod2 = bodyType !== void 0;
266
+ const extension = isBodyMethod2 ? createBodyDiscoveryExtension(config) : createQueryDiscoveryExtension(config);
267
+ return { bazaar: extension };
268
+ }
269
+
270
+ // src/bazaar/server.ts
271
+ var BRACKET_PARAM_REGEX = /\[([^\]]+)\]/;
272
+ var BRACKET_PARAM_REGEX_ALL = /\[([^\]]+)\]/g;
273
+ var COLON_PARAM_REGEX = /:([a-zA-Z_][a-zA-Z0-9_]*)/;
274
+ function isHTTPRequestContext(ctx) {
275
+ return ctx !== null && typeof ctx === "object" && "method" in ctx && "adapter" in ctx;
276
+ }
277
+ function normalizeWildcardPattern(pattern) {
278
+ if (!pattern.includes("*")) {
279
+ return pattern;
280
+ }
281
+ let counter = 0;
282
+ return pattern.split("/").map((seg) => {
283
+ if (seg === "*") {
284
+ counter++;
285
+ return `:var${counter}`;
286
+ }
287
+ return seg;
288
+ }).join("/");
289
+ }
290
+ function extractDynamicRouteInfo(routePattern, urlPath) {
291
+ const hasBracket = BRACKET_PARAM_REGEX.test(routePattern);
292
+ const hasColon = COLON_PARAM_REGEX.test(routePattern);
293
+ if (!hasBracket && !hasColon) {
294
+ return null;
295
+ }
296
+ const normalizedPattern = hasBracket ? routePattern.replace(BRACKET_PARAM_REGEX_ALL, ":$1") : routePattern;
297
+ const pathParams = extractPathParams(normalizedPattern, urlPath, false);
298
+ return { routeTemplate: normalizedPattern, pathParams };
299
+ }
300
+ function extractPathParams(routePattern, urlPath, isBracket) {
301
+ const paramNames = [];
302
+ const splitRegex = isBracket ? BRACKET_PARAM_REGEX : COLON_PARAM_REGEX;
303
+ const parts = routePattern.split(splitRegex);
304
+ const regexParts = [];
305
+ parts.forEach((part, i) => {
306
+ if (i % 2 === 0) {
307
+ regexParts.push(part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
308
+ } else {
309
+ paramNames.push(part);
310
+ regexParts.push("([^/]+)");
311
+ }
312
+ });
313
+ const regex = new RegExp(`^${regexParts.join("")}$`);
314
+ const match = urlPath.match(regex);
315
+ if (!match) return {};
316
+ const result = {};
317
+ paramNames.forEach((name, idx) => {
318
+ result[name] = match[idx + 1];
319
+ });
320
+ return result;
321
+ }
322
+ var bazaarResourceServerExtension = {
323
+ key: BAZAAR.key,
324
+ enrichDeclaration: (declaration, transportContext) => {
325
+ if (!isHTTPRequestContext(transportContext)) {
326
+ return declaration;
327
+ }
328
+ const extension = declaration;
329
+ if (extension.info?.input?.type === "mcp") {
330
+ return declaration;
331
+ }
332
+ const method = transportContext.method;
333
+ const existingInputProps = extension.schema?.properties?.input?.properties || {};
334
+ const updatedInputProps = {
335
+ ...existingInputProps,
336
+ method: {
337
+ type: "string",
338
+ enum: [method]
339
+ }
340
+ };
341
+ const enrichedResult = {
342
+ ...extension,
343
+ info: {
344
+ ...extension.info || {},
345
+ input: {
346
+ ...extension.info?.input || {},
347
+ method
348
+ }
349
+ },
350
+ schema: {
351
+ ...extension.schema || {},
352
+ properties: {
353
+ ...extension.schema?.properties || {},
354
+ input: {
355
+ ...extension.schema?.properties?.input || {},
356
+ properties: updatedInputProps,
357
+ required: [
358
+ ...extension.schema?.properties?.input?.required || [],
359
+ ...!(extension.schema?.properties?.input?.required || []).includes("method") ? ["method"] : []
360
+ ]
361
+ }
362
+ }
363
+ }
364
+ };
365
+ const rawRoutePattern = transportContext.routePattern;
366
+ const routePattern = rawRoutePattern ? normalizeWildcardPattern(rawRoutePattern) : void 0;
367
+ const dynamicRoute = routePattern ? extractDynamicRouteInfo(routePattern, transportContext.adapter.getPath()) : null;
368
+ if (dynamicRoute) {
369
+ const inputSchemaProps = enrichedResult.schema?.properties?.input?.properties || {};
370
+ const hasPathParamsInSchema = "pathParams" in inputSchemaProps;
371
+ return {
372
+ ...enrichedResult,
373
+ routeTemplate: dynamicRoute.routeTemplate,
374
+ info: {
375
+ ...enrichedResult.info,
376
+ input: { ...enrichedResult.info.input, pathParams: dynamicRoute.pathParams }
377
+ },
378
+ ...!hasPathParamsInSchema ? {
379
+ schema: {
380
+ ...enrichedResult.schema,
381
+ properties: {
382
+ ...enrichedResult.schema?.properties,
383
+ input: {
384
+ ...enrichedResult.schema?.properties?.input,
385
+ properties: {
386
+ ...inputSchemaProps,
387
+ pathParams: { type: "object" }
388
+ }
389
+ }
390
+ }
391
+ }
392
+ } : {}
393
+ };
394
+ }
395
+ return enrichedResult;
396
+ }
397
+ };
398
+
399
+ // src/bazaar/facilitator.ts
400
+ import { domainToASCII } from "url";
401
+ import Ajv from "ajv/dist/2020.js";
402
+
403
+ // src/bazaar/v1/facilitator.ts
404
+ function hasV1OutputSchema(obj) {
405
+ return obj !== null && typeof obj === "object" && "input" in obj && obj.input !== null && typeof obj.input === "object" && "type" in obj.input && obj.input.type === "http" && "method" in obj.input;
406
+ }
407
+ function isQueryMethod(method) {
408
+ const upperMethod = method.toUpperCase();
409
+ return upperMethod === "GET" || upperMethod === "HEAD" || upperMethod === "DELETE";
410
+ }
411
+ function isBodyMethod(method) {
412
+ const upperMethod = method.toUpperCase();
413
+ return upperMethod === "POST" || upperMethod === "PUT" || upperMethod === "PATCH";
414
+ }
415
+ function extractQueryParams(v1Input) {
416
+ if (v1Input.queryParams && typeof v1Input.queryParams === "object") {
417
+ return v1Input.queryParams;
418
+ }
419
+ if (v1Input.query_params && typeof v1Input.query_params === "object") {
420
+ return v1Input.query_params;
421
+ }
422
+ if (v1Input.query && typeof v1Input.query === "object") {
423
+ return v1Input.query;
424
+ }
425
+ if (v1Input.params && typeof v1Input.params === "object") {
426
+ return v1Input.params;
427
+ }
428
+ return void 0;
429
+ }
430
+ function extractBodyInfo(v1Input) {
431
+ let bodyType = "json";
432
+ const bodyTypeField = v1Input.bodyType || v1Input.body_type;
433
+ if (bodyTypeField && typeof bodyTypeField === "string") {
434
+ const type = bodyTypeField.toLowerCase();
435
+ if (type.includes("form") || type.includes("multipart")) {
436
+ bodyType = "form-data";
437
+ } else if (type.includes("text") || type.includes("plain")) {
438
+ bodyType = "text";
439
+ } else {
440
+ bodyType = "json";
441
+ }
442
+ }
443
+ let body = {};
444
+ if (v1Input.bodyFields && typeof v1Input.bodyFields === "object") {
445
+ body = v1Input.bodyFields;
446
+ } else if (v1Input.body_fields && v1Input.body_fields !== null && typeof v1Input.body_fields === "object") {
447
+ body = v1Input.body_fields;
448
+ } else if (v1Input.bodyParams && typeof v1Input.bodyParams === "object") {
449
+ body = v1Input.bodyParams;
450
+ } else if (v1Input.body && typeof v1Input.body === "object") {
451
+ body = v1Input.body;
452
+ } else if (v1Input.data && typeof v1Input.data === "object") {
453
+ body = v1Input.data;
454
+ } else if (v1Input.properties && typeof v1Input.properties === "object") {
455
+ body = v1Input.properties;
456
+ }
457
+ return { body, bodyType };
458
+ }
459
+ function extractDiscoveryInfoV1(paymentRequirements) {
460
+ const { outputSchema } = paymentRequirements;
461
+ if (!outputSchema || !hasV1OutputSchema(outputSchema)) {
462
+ return null;
463
+ }
464
+ const v1Input = outputSchema.input;
465
+ const isDiscoverable = v1Input.discoverable ?? true;
466
+ if (!isDiscoverable) {
467
+ return null;
468
+ }
469
+ const method = typeof v1Input.method === "string" ? v1Input.method.toUpperCase() : "";
470
+ const headersRaw = v1Input.headerFields || v1Input.header_fields || v1Input.headers;
471
+ const headers = headersRaw && typeof headersRaw === "object" ? headersRaw : void 0;
472
+ const output = outputSchema.output ? {
473
+ type: "json",
474
+ example: outputSchema.output
475
+ } : void 0;
476
+ if (isQueryMethod(method)) {
477
+ const queryParams = extractQueryParams(v1Input);
478
+ const discoveryInfo = {
479
+ input: {
480
+ type: "http",
481
+ method,
482
+ ...queryParams ? { queryParams } : {},
483
+ ...headers ? { headers } : {}
484
+ },
485
+ ...output ? { output } : {}
486
+ };
487
+ return discoveryInfo;
488
+ } else if (isBodyMethod(method)) {
489
+ const { body, bodyType } = extractBodyInfo(v1Input);
490
+ const queryParams = extractQueryParams(v1Input);
491
+ const discoveryInfo = {
492
+ input: {
493
+ type: "http",
494
+ method,
495
+ bodyType,
496
+ body,
497
+ ...queryParams ? { queryParams } : {},
498
+ ...headers ? { headers } : {}
499
+ },
500
+ ...output ? { output } : {}
501
+ };
502
+ return discoveryInfo;
503
+ }
504
+ return null;
505
+ }
506
+ function isDiscoverableV1(paymentRequirements) {
507
+ return extractDiscoveryInfoV1(paymentRequirements) !== null;
508
+ }
509
+ function extractResourceMetadataV1(paymentRequirements) {
510
+ return {
511
+ url: paymentRequirements.resource,
512
+ description: paymentRequirements.description,
513
+ mimeType: paymentRequirements.mimeType
514
+ };
515
+ }
516
+ function buildBazaarExtensionFromDiscoveryInfo(discoveryInfo) {
517
+ return {
518
+ info: discoveryInfo,
519
+ schema: {
520
+ $schema: "https://json-schema.org/draft/2020-12/schema",
521
+ type: "object",
522
+ properties: {
523
+ input: { type: "object" },
524
+ output: { type: "object" }
525
+ },
526
+ required: ["input"]
527
+ }
528
+ };
529
+ }
530
+ function buildV1CatalogExtensions(existingExtensions, discoveryInfo) {
531
+ if (existingExtensions?.[BAZAAR.key]) {
532
+ return existingExtensions;
533
+ }
534
+ const extensions = existingExtensions ? { ...existingExtensions } : {};
535
+ delete extensions.outputSchema;
536
+ extensions[BAZAAR.key] = buildBazaarExtensionFromDiscoveryInfo(discoveryInfo);
537
+ return extensions;
538
+ }
539
+
540
+ // src/bazaar/facilitator.ts
541
+ var ROUTE_TEMPLATE_REGEX = /^\/[a-zA-Z0-9_/:.\-~%]+$/;
542
+ function isValidRouteTemplate(value) {
543
+ if (!value) return false;
544
+ if (!ROUTE_TEMPLATE_REGEX.test(value)) return false;
545
+ let decoded;
546
+ try {
547
+ decoded = decodeURIComponent(value);
548
+ } catch {
549
+ return false;
550
+ }
551
+ if (decoded.includes("..")) return false;
552
+ if (decoded.includes("://")) return false;
553
+ return true;
554
+ }
555
+ function validateRouteTemplate(value) {
556
+ return isValidRouteTemplate(value) ? value : void 0;
557
+ }
558
+ var MAX_SERVICE_NAME_LEN = 32;
559
+ var MAX_TAG_LEN = 32;
560
+ var MAX_TAGS = 5;
561
+ var MAX_ICON_URL_LEN = 2048;
562
+ var CONTROL_CHAR_REGEX = /[\x00-\x1f\x7f]/;
563
+ var PRINTABLE_ASCII_REGEX = /^[\x20-\x7e]+$/;
564
+ var UNICODE_CONTROL_REGEX = /\p{Cc}/u;
565
+ var LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set([
566
+ "localhost",
567
+ "localhost.localdomain",
568
+ "ip6-localhost",
569
+ "ip6-loopback"
570
+ ]);
571
+ var IPV4_REGEX = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
572
+ var ALL_DIGITS_REGEX = /^\d+$/;
573
+ var HEX_LITERAL_REGEX = /^0x[0-9a-f]+$/i;
574
+ function isValidServiceName(value) {
575
+ if (typeof value !== "string") return false;
576
+ if (value.length === 0 || value.length > MAX_SERVICE_NAME_LEN) return false;
577
+ if (UNICODE_CONTROL_REGEX.test(value)) return false;
578
+ if (!PRINTABLE_ASCII_REGEX.test(value)) return false;
579
+ return true;
580
+ }
581
+ function sanitizeTags(value) {
582
+ if (!Array.isArray(value)) return void 0;
583
+ const out = [];
584
+ const seen = /* @__PURE__ */ new Set();
585
+ for (const entry of value) {
586
+ if (typeof entry !== "string") continue;
587
+ if (entry.length === 0 || entry.length > MAX_TAG_LEN) continue;
588
+ if (UNICODE_CONTROL_REGEX.test(entry)) continue;
589
+ if (!PRINTABLE_ASCII_REGEX.test(entry)) continue;
590
+ const key = entry.toLowerCase();
591
+ if (seen.has(key)) continue;
592
+ seen.add(key);
593
+ out.push(entry);
594
+ if (out.length === MAX_TAGS) break;
595
+ }
596
+ return out.length > 0 ? out : void 0;
597
+ }
598
+ function isValidIconUrl(value) {
599
+ if (typeof value !== "string") return false;
600
+ if (value.length === 0 || value.length > MAX_ICON_URL_LEN) return false;
601
+ if (CONTROL_CHAR_REGEX.test(value)) return false;
602
+ let parsed;
603
+ try {
604
+ parsed = new URL(value);
605
+ } catch {
606
+ return false;
607
+ }
608
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
609
+ if (parsed.username !== "" || parsed.password !== "") return false;
610
+ if (parsed.host.startsWith("[")) return false;
611
+ let hostname;
612
+ try {
613
+ hostname = decodeURIComponent(parsed.hostname);
614
+ } catch {
615
+ return false;
616
+ }
617
+ const asciiHost = domainToASCII(hostname);
618
+ if (asciiHost === "") return false;
619
+ hostname = asciiHost.toLowerCase();
620
+ if (hostname === "") return false;
621
+ if (LOOPBACK_HOSTNAMES.has(hostname)) return false;
622
+ if (IPV4_REGEX.test(hostname)) return false;
623
+ if (ALL_DIGITS_REGEX.test(hostname)) return false;
624
+ if (HEX_LITERAL_REGEX.test(hostname)) return false;
625
+ return true;
626
+ }
627
+ function sanitizeResourceServiceMetadata(resource) {
628
+ if (!resource) return {};
629
+ const out = {};
630
+ if (isValidServiceName(resource.serviceName)) {
631
+ out.serviceName = resource.serviceName;
632
+ }
633
+ const tags = sanitizeTags(resource.tags);
634
+ if (tags) {
635
+ out.tags = tags;
636
+ }
637
+ if (isValidIconUrl(resource.iconUrl)) {
638
+ out.iconUrl = resource.iconUrl;
639
+ }
640
+ return out;
641
+ }
642
+ function validateDiscoveryExtension(extension) {
643
+ try {
644
+ const ajv = new Ajv({ strict: false, allErrors: true });
645
+ const validate = ajv.compile(extension.schema);
646
+ const valid = validate(extension.info);
647
+ if (valid) {
648
+ return { valid: true };
649
+ }
650
+ const errors = validate.errors?.map((err) => {
651
+ const path = err.instancePath || "(root)";
652
+ return `${path}: ${err.message}`;
653
+ }) || ["Unknown validation error"];
654
+ return { valid: false, errors };
655
+ } catch (error) {
656
+ return {
657
+ valid: false,
658
+ errors: [
659
+ `Schema validation failed: ${error instanceof Error ? error.message : String(error)}`
660
+ ]
661
+ };
662
+ }
663
+ }
664
+ var VALID_QUERY_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "DELETE"]);
665
+ var VALID_BODY_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH"]);
666
+ var VALID_METHODS = /* @__PURE__ */ new Set([...VALID_QUERY_METHODS, ...VALID_BODY_METHODS]);
667
+ var VALID_BODY_TYPES = /* @__PURE__ */ new Set(["json", "form-data", "text"]);
668
+ var VALID_MCP_TRANSPORTS = /* @__PURE__ */ new Set(["streamable-http", "sse"]);
669
+ function validateDiscoveryExtensionSpec(extension) {
670
+ const errors = [];
671
+ const info = extension.info;
672
+ if (!info || typeof info !== "object") {
673
+ return { valid: false, errors: ["Missing or invalid 'info' field"] };
674
+ }
675
+ const input = info.input;
676
+ if (!input || typeof input !== "object") {
677
+ return { valid: false, errors: ["Missing or invalid 'info.input' field"] };
678
+ }
679
+ const inputObj = input;
680
+ const inputType = inputObj.type;
681
+ if (inputType !== "http" && inputType !== "mcp") {
682
+ errors.push(`info.input.type must be "http" or "mcp", got "${String(inputType)}"`);
683
+ return { valid: false, errors };
684
+ }
685
+ if (inputType === "http") {
686
+ const method = inputObj.method;
687
+ if (method !== void 0 && !VALID_METHODS.has(method)) {
688
+ errors.push(
689
+ `info.input.method must be one of ${[...VALID_METHODS].join(", ")}, got "${String(method)}"`
690
+ );
691
+ }
692
+ const bodyType = inputObj.bodyType;
693
+ if (bodyType !== void 0) {
694
+ if (!VALID_BODY_TYPES.has(bodyType)) {
695
+ errors.push(
696
+ `info.input.bodyType must be one of ${[...VALID_BODY_TYPES].join(", ")}, got "${String(bodyType)}"`
697
+ );
698
+ }
699
+ if (method !== void 0 && !VALID_BODY_METHODS.has(method)) {
700
+ errors.push(
701
+ `info.input.bodyType is set but method "${String(method)}" is not a body method (POST, PUT, PATCH)`
702
+ );
703
+ }
704
+ }
705
+ }
706
+ if (inputType === "mcp") {
707
+ if (typeof inputObj.toolName !== "string" || inputObj.toolName.length === 0) {
708
+ errors.push(
709
+ "info.input.toolName is required and must be a non-empty string for MCP extensions"
710
+ );
711
+ }
712
+ if (!inputObj.inputSchema || typeof inputObj.inputSchema !== "object") {
713
+ errors.push("info.input.inputSchema is required and must be an object for MCP extensions");
714
+ }
715
+ const transport = inputObj.transport;
716
+ if (transport !== void 0 && !VALID_MCP_TRANSPORTS.has(transport)) {
717
+ errors.push(
718
+ `info.input.transport must be one of ${[...VALID_MCP_TRANSPORTS].join(", ")}, got "${String(transport)}"`
719
+ );
720
+ }
721
+ }
722
+ return errors.length === 0 ? { valid: true } : { valid: false, errors };
723
+ }
724
+ function extractDiscoveryInfo(paymentPayload, paymentRequirements, validate = true) {
725
+ let discoveryInfo = null;
726
+ let resourceUrl;
727
+ let routeTemplate;
728
+ if (paymentPayload.x402Version === 2) {
729
+ resourceUrl = paymentPayload.resource?.url ?? "";
730
+ if (paymentPayload.extensions) {
731
+ const bazaarExtension = paymentPayload.extensions[BAZAAR.key];
732
+ if (bazaarExtension && typeof bazaarExtension === "object") {
733
+ try {
734
+ const rawExt = bazaarExtension;
735
+ const rawTemplate = typeof rawExt.routeTemplate === "string" ? rawExt.routeTemplate : void 0;
736
+ if (isValidRouteTemplate(rawTemplate)) {
737
+ routeTemplate = rawTemplate;
738
+ }
739
+ const extension = bazaarExtension;
740
+ if (validate) {
741
+ const result = validateDiscoveryExtension(extension);
742
+ if (!result.valid) {
743
+ console.warn(
744
+ `V2 discovery extension validation failed: ${result.errors?.join(", ")}`
745
+ );
746
+ } else {
747
+ discoveryInfo = extension.info;
748
+ }
749
+ } else {
750
+ discoveryInfo = extension.info;
751
+ }
752
+ } catch (error) {
753
+ console.warn(`V2 discovery extension extraction failed: ${error}`);
754
+ }
755
+ }
756
+ }
757
+ } else if (paymentPayload.x402Version === 1) {
758
+ const requirementsV1 = paymentRequirements;
759
+ resourceUrl = requirementsV1.resource;
760
+ discoveryInfo = extractDiscoveryInfoV1(requirementsV1);
761
+ } else {
762
+ return null;
763
+ }
764
+ if (!discoveryInfo) {
765
+ return null;
766
+ }
767
+ const url = new URL(resourceUrl);
768
+ const canonicalUrl = routeTemplate ? `${url.origin}${routeTemplate}` : `${url.origin}${url.pathname}`;
769
+ let description;
770
+ let mimeType;
771
+ let serviceMetadata = {};
772
+ if (paymentPayload.x402Version === 2) {
773
+ description = paymentPayload.resource?.description;
774
+ mimeType = paymentPayload.resource?.mimeType;
775
+ serviceMetadata = sanitizeResourceServiceMetadata(paymentPayload.resource);
776
+ } else if (paymentPayload.x402Version === 1) {
777
+ const requirementsV1 = paymentRequirements;
778
+ description = requirementsV1.description;
779
+ mimeType = requirementsV1.mimeType;
780
+ }
781
+ let extensions;
782
+ if (paymentPayload.x402Version === 2) {
783
+ extensions = paymentPayload.extensions;
784
+ } else if (paymentPayload.x402Version === 1) {
785
+ extensions = buildV1CatalogExtensions(paymentPayload.extensions, discoveryInfo);
786
+ }
787
+ const base = {
788
+ resourceUrl: canonicalUrl,
789
+ description,
790
+ mimeType,
791
+ ...serviceMetadata,
792
+ x402Version: paymentPayload.x402Version,
793
+ discoveryInfo,
794
+ extensions
795
+ };
796
+ if (discoveryInfo.input.type === "mcp") {
797
+ return { ...base, toolName: discoveryInfo.input.toolName };
798
+ }
799
+ return { ...base, routeTemplate, method: discoveryInfo.input.method };
800
+ }
801
+ function extractDiscoveryInfoFromExtension(extension, validate = true) {
802
+ if (validate) {
803
+ const result = validateDiscoveryExtension(extension);
804
+ if (!result.valid) {
805
+ throw new Error(
806
+ `Invalid discovery extension: ${result.errors?.join(", ") || "Unknown error"}`
807
+ );
808
+ }
809
+ }
810
+ return extension.info;
811
+ }
812
+ function validateAndExtract(extension) {
813
+ const result = validateDiscoveryExtension(extension);
814
+ if (result.valid) {
815
+ return {
816
+ valid: true,
817
+ info: extension.info
818
+ };
819
+ }
820
+ return {
821
+ valid: false,
822
+ errors: result.errors
823
+ };
824
+ }
825
+
826
+ // src/bazaar/startupValidation.ts
827
+ import { checkIfBazaarNeeded } from "@bankofai/x402-core/server";
828
+ var HTTP_VERB_RE = /^(GET|POST|PUT|PATCH|DELETE|HEAD)\b/i;
829
+ function withSyntheticMethod(ext, pattern) {
830
+ const info = ext.info;
831
+ const input = info?.input;
832
+ if (!input || typeof input.method === "string" && input.method) {
833
+ return ext;
834
+ }
835
+ const verbMatch = pattern.match(HTTP_VERB_RE);
836
+ const method = verbMatch ? verbMatch[1].toUpperCase() : input.body !== void 0 || input.bodyType !== void 0 ? "POST" : "GET";
837
+ return { ...ext, info: { ...info, input: { ...input, method } } };
838
+ }
839
+ function validateBazaarRouteExtensions(routes) {
840
+ const entries = "accepts" in routes ? [["*", routes]] : Object.entries(routes);
841
+ for (const [pattern, config] of entries) {
842
+ const bazaarExt = config.extensions?.["bazaar"];
843
+ if (!bazaarExt) continue;
844
+ if (typeof bazaarExt === "object" && bazaarExt !== null && "info" in bazaarExt && "schema" in bazaarExt) {
845
+ const specResult = validateDiscoveryExtensionSpec(bazaarExt);
846
+ if (!specResult.valid) {
847
+ console.warn(
848
+ `x402: Route "${pattern}" has an invalid bazaar extension: ${specResult.errors?.join(", ")}`
849
+ );
850
+ continue;
851
+ }
852
+ const extForSchema = withSyntheticMethod(bazaarExt, pattern);
853
+ const schemaResult = validateDiscoveryExtension(
854
+ extForSchema
855
+ );
856
+ if (!schemaResult.valid) {
857
+ console.warn(
858
+ `x402: Route "${pattern}" has an invalid bazaar extension: ${schemaResult.errors?.join(", ")}`
859
+ );
860
+ }
861
+ } else {
862
+ console.warn(
863
+ `x402: Route "${pattern}" declares a bazaar extension but it is malformed (expected an object with "info" and "schema" fields)`
864
+ );
865
+ }
866
+ }
867
+ }
868
+
869
+ // src/bazaar/facilitatorClient.ts
870
+ function withBazaar(client) {
871
+ const existingExtensions = client.extensions ?? {};
872
+ const extended = client;
873
+ extended.extensions = {
874
+ ...existingExtensions,
875
+ bazaar: {
876
+ async listResources(params) {
877
+ let headers = {
878
+ "Content-Type": "application/json"
879
+ };
880
+ const authHeaders = await client.createAuthHeaders("bazaar");
881
+ headers = { ...headers, ...authHeaders.headers };
882
+ const queryParams = new URLSearchParams();
883
+ if (params?.type !== void 0) {
884
+ queryParams.set("type", params.type);
885
+ }
886
+ if (params?.payTo !== void 0) {
887
+ queryParams.set("payTo", params.payTo);
888
+ }
889
+ if (params?.scheme !== void 0) {
890
+ queryParams.set("scheme", params.scheme);
891
+ }
892
+ if (params?.network !== void 0) {
893
+ queryParams.set("network", params.network);
894
+ }
895
+ if (params?.extensions !== void 0) {
896
+ queryParams.set("extensions", params.extensions);
897
+ }
898
+ if (params?.limit !== void 0) {
899
+ queryParams.set("limit", params.limit.toString());
900
+ }
901
+ if (params?.offset !== void 0) {
902
+ queryParams.set("offset", params.offset.toString());
903
+ }
904
+ const queryString = queryParams.toString();
905
+ const endpoint = `${client.url}/discovery/resources${queryString ? `?${queryString}` : ""}`;
906
+ const response = await fetch(endpoint, {
907
+ method: "GET",
908
+ headers
909
+ });
910
+ if (!response.ok) {
911
+ const errorText = await response.text().catch(() => response.statusText);
912
+ throw new Error(
913
+ `Facilitator listDiscoveryResources failed (${response.status}): ${errorText}`
914
+ );
915
+ }
916
+ return await response.json();
917
+ },
918
+ async search(params) {
919
+ let headers = {
920
+ "Content-Type": "application/json"
921
+ };
922
+ const authHeaders = await client.createAuthHeaders("bazaar");
923
+ headers = { ...headers, ...authHeaders.headers };
924
+ const queryParams = new URLSearchParams();
925
+ queryParams.set("query", params.query);
926
+ if (params.type !== void 0) {
927
+ queryParams.set("type", params.type);
928
+ }
929
+ if (params.payTo !== void 0) {
930
+ queryParams.set("payTo", params.payTo);
931
+ }
932
+ if (params.scheme !== void 0) {
933
+ queryParams.set("scheme", params.scheme);
934
+ }
935
+ if (params.network !== void 0) {
936
+ queryParams.set("network", params.network);
937
+ }
938
+ if (params.extensions !== void 0) {
939
+ queryParams.set("extensions", params.extensions);
940
+ }
941
+ if (params.limit !== void 0) {
942
+ queryParams.set("limit", params.limit.toString());
943
+ }
944
+ if (params.cursor !== void 0) {
945
+ queryParams.set("cursor", params.cursor);
946
+ }
947
+ const endpoint = `${client.url}/discovery/search?${queryParams.toString()}`;
948
+ const response = await fetch(endpoint, {
949
+ method: "GET",
950
+ headers
951
+ });
952
+ if (!response.ok) {
953
+ const errorText = await response.text().catch(() => response.statusText);
954
+ throw new Error(
955
+ `Facilitator searchDiscoveryResources failed (${response.status}): ${errorText}`
956
+ );
957
+ }
958
+ return await response.json();
959
+ }
960
+ }
961
+ };
962
+ return extended;
963
+ }
964
+
965
+ export {
966
+ isQueryExtensionConfig,
967
+ isBodyExtensionConfig,
968
+ isMcpExtensionConfig,
969
+ BAZAAR,
970
+ declareDiscoveryExtension,
971
+ bazaarResourceServerExtension,
972
+ extractDiscoveryInfoV1,
973
+ isDiscoverableV1,
974
+ extractResourceMetadataV1,
975
+ isValidRouteTemplate,
976
+ validateRouteTemplate,
977
+ isValidServiceName,
978
+ sanitizeTags,
979
+ isValidIconUrl,
980
+ sanitizeResourceServiceMetadata,
981
+ validateDiscoveryExtension,
982
+ validateDiscoveryExtensionSpec,
983
+ extractDiscoveryInfo,
984
+ extractDiscoveryInfoFromExtension,
985
+ validateAndExtract,
986
+ validateBazaarRouteExtensions,
987
+ checkIfBazaarNeeded,
988
+ withBazaar
989
+ };
990
+ //# sourceMappingURL=chunk-4IPDE3NS.mjs.map