@x402scan/mcp 0.0.7 → 0.0.8-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.
@@ -0,0 +1,963 @@
1
+ // src/shared/neverthrow/fs/index.ts
2
+ import { readFile, writeFile, appendFile, chmod } from "fs/promises";
3
+
4
+ // ../../../node_modules/.pnpm/neverthrow@8.2.0/node_modules/neverthrow/dist/index.es.js
5
+ var defaultErrorConfig = {
6
+ withStackTrace: false
7
+ };
8
+ var createNeverThrowError = (message, result, config = defaultErrorConfig) => {
9
+ const data = result.isOk() ? { type: "Ok", value: result.value } : { type: "Err", value: result.error };
10
+ const maybeStack = config.withStackTrace ? new Error().stack : void 0;
11
+ return {
12
+ data,
13
+ message,
14
+ stack: maybeStack
15
+ };
16
+ };
17
+ function __awaiter(thisArg, _arguments, P, generator) {
18
+ function adopt(value) {
19
+ return value instanceof P ? value : new P(function(resolve) {
20
+ resolve(value);
21
+ });
22
+ }
23
+ return new (P || (P = Promise))(function(resolve, reject) {
24
+ function fulfilled(value) {
25
+ try {
26
+ step(generator.next(value));
27
+ } catch (e) {
28
+ reject(e);
29
+ }
30
+ }
31
+ function rejected(value) {
32
+ try {
33
+ step(generator["throw"](value));
34
+ } catch (e) {
35
+ reject(e);
36
+ }
37
+ }
38
+ function step(result) {
39
+ result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
40
+ }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ }
44
+ function __values(o) {
45
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
46
+ if (m) return m.call(o);
47
+ if (o && typeof o.length === "number") return {
48
+ next: function() {
49
+ if (o && i >= o.length) o = void 0;
50
+ return { value: o && o[i++], done: !o };
51
+ }
52
+ };
53
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
54
+ }
55
+ function __await(v) {
56
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
57
+ }
58
+ function __asyncGenerator(thisArg, _arguments, generator) {
59
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
60
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
61
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
62
+ return this;
63
+ }, i;
64
+ function awaitReturn(f) {
65
+ return function(v) {
66
+ return Promise.resolve(v).then(f, reject);
67
+ };
68
+ }
69
+ function verb(n, f) {
70
+ if (g[n]) {
71
+ i[n] = function(v) {
72
+ return new Promise(function(a, b) {
73
+ q.push([n, v, a, b]) > 1 || resume(n, v);
74
+ });
75
+ };
76
+ if (f) i[n] = f(i[n]);
77
+ }
78
+ }
79
+ function resume(n, v) {
80
+ try {
81
+ step(g[n](v));
82
+ } catch (e) {
83
+ settle(q[0][3], e);
84
+ }
85
+ }
86
+ function step(r) {
87
+ r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
88
+ }
89
+ function fulfill(value) {
90
+ resume("next", value);
91
+ }
92
+ function reject(value) {
93
+ resume("throw", value);
94
+ }
95
+ function settle(f, v) {
96
+ if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
97
+ }
98
+ }
99
+ function __asyncDelegator(o) {
100
+ var i, p;
101
+ return i = {}, verb("next"), verb("throw", function(e) {
102
+ throw e;
103
+ }), verb("return"), i[Symbol.iterator] = function() {
104
+ return this;
105
+ }, i;
106
+ function verb(n, f) {
107
+ i[n] = o[n] ? function(v) {
108
+ return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
109
+ } : f;
110
+ }
111
+ }
112
+ function __asyncValues(o) {
113
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
114
+ var m = o[Symbol.asyncIterator], i;
115
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
116
+ return this;
117
+ }, i);
118
+ function verb(n) {
119
+ i[n] = o[n] && function(v) {
120
+ return new Promise(function(resolve, reject) {
121
+ v = o[n](v), settle(resolve, reject, v.done, v.value);
122
+ });
123
+ };
124
+ }
125
+ function settle(resolve, reject, d, v) {
126
+ Promise.resolve(v).then(function(v2) {
127
+ resolve({ value: v2, done: d });
128
+ }, reject);
129
+ }
130
+ }
131
+ var ResultAsync = class _ResultAsync {
132
+ constructor(res) {
133
+ this._promise = res;
134
+ }
135
+ static fromSafePromise(promise) {
136
+ const newPromise = promise.then((value) => new Ok(value));
137
+ return new _ResultAsync(newPromise);
138
+ }
139
+ static fromPromise(promise, errorFn) {
140
+ const newPromise = promise.then((value) => new Ok(value)).catch((e) => new Err(errorFn(e)));
141
+ return new _ResultAsync(newPromise);
142
+ }
143
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
144
+ static fromThrowable(fn, errorFn) {
145
+ return (...args) => {
146
+ return new _ResultAsync((() => __awaiter(this, void 0, void 0, function* () {
147
+ try {
148
+ return new Ok(yield fn(...args));
149
+ } catch (error) {
150
+ return new Err(errorFn ? errorFn(error) : error);
151
+ }
152
+ }))());
153
+ };
154
+ }
155
+ static combine(asyncResultList) {
156
+ return combineResultAsyncList(asyncResultList);
157
+ }
158
+ static combineWithAllErrors(asyncResultList) {
159
+ return combineResultAsyncListWithAllErrors(asyncResultList);
160
+ }
161
+ map(f) {
162
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
163
+ if (res.isErr()) {
164
+ return new Err(res.error);
165
+ }
166
+ return new Ok(yield f(res.value));
167
+ })));
168
+ }
169
+ andThrough(f) {
170
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
171
+ if (res.isErr()) {
172
+ return new Err(res.error);
173
+ }
174
+ const newRes = yield f(res.value);
175
+ if (newRes.isErr()) {
176
+ return new Err(newRes.error);
177
+ }
178
+ return new Ok(res.value);
179
+ })));
180
+ }
181
+ andTee(f) {
182
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
183
+ if (res.isErr()) {
184
+ return new Err(res.error);
185
+ }
186
+ try {
187
+ yield f(res.value);
188
+ } catch (e) {
189
+ }
190
+ return new Ok(res.value);
191
+ })));
192
+ }
193
+ orTee(f) {
194
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
195
+ if (res.isOk()) {
196
+ return new Ok(res.value);
197
+ }
198
+ try {
199
+ yield f(res.error);
200
+ } catch (e) {
201
+ }
202
+ return new Err(res.error);
203
+ })));
204
+ }
205
+ mapErr(f) {
206
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
207
+ if (res.isOk()) {
208
+ return new Ok(res.value);
209
+ }
210
+ return new Err(yield f(res.error));
211
+ })));
212
+ }
213
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
214
+ andThen(f) {
215
+ return new _ResultAsync(this._promise.then((res) => {
216
+ if (res.isErr()) {
217
+ return new Err(res.error);
218
+ }
219
+ const newValue = f(res.value);
220
+ return newValue instanceof _ResultAsync ? newValue._promise : newValue;
221
+ }));
222
+ }
223
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
224
+ orElse(f) {
225
+ return new _ResultAsync(this._promise.then((res) => __awaiter(this, void 0, void 0, function* () {
226
+ if (res.isErr()) {
227
+ return f(res.error);
228
+ }
229
+ return new Ok(res.value);
230
+ })));
231
+ }
232
+ match(ok3, _err) {
233
+ return this._promise.then((res) => res.match(ok3, _err));
234
+ }
235
+ unwrapOr(t) {
236
+ return this._promise.then((res) => res.unwrapOr(t));
237
+ }
238
+ /**
239
+ * @deprecated will be removed in 9.0.0.
240
+ *
241
+ * You can use `safeTry` without this method.
242
+ * @example
243
+ * ```typescript
244
+ * safeTry(async function* () {
245
+ * const okValue = yield* yourResult
246
+ * })
247
+ * ```
248
+ * Emulates Rust's `?` operator in `safeTry`'s body. See also `safeTry`.
249
+ */
250
+ safeUnwrap() {
251
+ return __asyncGenerator(this, arguments, function* safeUnwrap_1() {
252
+ return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(yield __await(this._promise.then((res) => res.safeUnwrap()))))));
253
+ });
254
+ }
255
+ // Makes ResultAsync implement PromiseLike<Result>
256
+ then(successCallback, failureCallback) {
257
+ return this._promise.then(successCallback, failureCallback);
258
+ }
259
+ [Symbol.asyncIterator]() {
260
+ return __asyncGenerator(this, arguments, function* _a() {
261
+ const result = yield __await(this._promise);
262
+ if (result.isErr()) {
263
+ yield yield __await(errAsync(result.error));
264
+ }
265
+ return yield __await(result.value);
266
+ });
267
+ }
268
+ };
269
+ function errAsync(err3) {
270
+ return new ResultAsync(Promise.resolve(new Err(err3)));
271
+ }
272
+ var fromPromise = ResultAsync.fromPromise;
273
+ var fromSafePromise = ResultAsync.fromSafePromise;
274
+ var fromAsyncThrowable = ResultAsync.fromThrowable;
275
+ var combineResultList = (resultList) => {
276
+ let acc = ok([]);
277
+ for (const result of resultList) {
278
+ if (result.isErr()) {
279
+ acc = err(result.error);
280
+ break;
281
+ } else {
282
+ acc.map((list) => list.push(result.value));
283
+ }
284
+ }
285
+ return acc;
286
+ };
287
+ var combineResultAsyncList = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultList);
288
+ var combineResultListWithAllErrors = (resultList) => {
289
+ let acc = ok([]);
290
+ for (const result of resultList) {
291
+ if (result.isErr() && acc.isErr()) {
292
+ acc.error.push(result.error);
293
+ } else if (result.isErr() && acc.isOk()) {
294
+ acc = err([result.error]);
295
+ } else if (result.isOk() && acc.isOk()) {
296
+ acc.value.push(result.value);
297
+ }
298
+ }
299
+ return acc;
300
+ };
301
+ var combineResultAsyncListWithAllErrors = (asyncResultList) => ResultAsync.fromSafePromise(Promise.all(asyncResultList)).andThen(combineResultListWithAllErrors);
302
+ var Result;
303
+ (function(Result2) {
304
+ function fromThrowable2(fn, errorFn) {
305
+ return (...args) => {
306
+ try {
307
+ const result = fn(...args);
308
+ return ok(result);
309
+ } catch (e) {
310
+ return err(errorFn ? errorFn(e) : e);
311
+ }
312
+ };
313
+ }
314
+ Result2.fromThrowable = fromThrowable2;
315
+ function combine(resultList) {
316
+ return combineResultList(resultList);
317
+ }
318
+ Result2.combine = combine;
319
+ function combineWithAllErrors(resultList) {
320
+ return combineResultListWithAllErrors(resultList);
321
+ }
322
+ Result2.combineWithAllErrors = combineWithAllErrors;
323
+ })(Result || (Result = {}));
324
+ function ok(value) {
325
+ return new Ok(value);
326
+ }
327
+ function err(err3) {
328
+ return new Err(err3);
329
+ }
330
+ var Ok = class {
331
+ constructor(value) {
332
+ this.value = value;
333
+ }
334
+ isOk() {
335
+ return true;
336
+ }
337
+ isErr() {
338
+ return !this.isOk();
339
+ }
340
+ map(f) {
341
+ return ok(f(this.value));
342
+ }
343
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
344
+ mapErr(_f) {
345
+ return ok(this.value);
346
+ }
347
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
348
+ andThen(f) {
349
+ return f(this.value);
350
+ }
351
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
352
+ andThrough(f) {
353
+ return f(this.value).map((_value) => this.value);
354
+ }
355
+ andTee(f) {
356
+ try {
357
+ f(this.value);
358
+ } catch (e) {
359
+ }
360
+ return ok(this.value);
361
+ }
362
+ orTee(_f) {
363
+ return ok(this.value);
364
+ }
365
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
366
+ orElse(_f) {
367
+ return ok(this.value);
368
+ }
369
+ asyncAndThen(f) {
370
+ return f(this.value);
371
+ }
372
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
373
+ asyncAndThrough(f) {
374
+ return f(this.value).map(() => this.value);
375
+ }
376
+ asyncMap(f) {
377
+ return ResultAsync.fromSafePromise(f(this.value));
378
+ }
379
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
380
+ unwrapOr(_v) {
381
+ return this.value;
382
+ }
383
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
384
+ match(ok3, _err) {
385
+ return ok3(this.value);
386
+ }
387
+ safeUnwrap() {
388
+ const value = this.value;
389
+ return (function* () {
390
+ return value;
391
+ })();
392
+ }
393
+ _unsafeUnwrap(_) {
394
+ return this.value;
395
+ }
396
+ _unsafeUnwrapErr(config) {
397
+ throw createNeverThrowError("Called `_unsafeUnwrapErr` on an Ok", this, config);
398
+ }
399
+ // eslint-disable-next-line @typescript-eslint/no-this-alias, require-yield
400
+ *[Symbol.iterator]() {
401
+ return this.value;
402
+ }
403
+ };
404
+ var Err = class {
405
+ constructor(error) {
406
+ this.error = error;
407
+ }
408
+ isOk() {
409
+ return false;
410
+ }
411
+ isErr() {
412
+ return !this.isOk();
413
+ }
414
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
415
+ map(_f) {
416
+ return err(this.error);
417
+ }
418
+ mapErr(f) {
419
+ return err(f(this.error));
420
+ }
421
+ andThrough(_f) {
422
+ return err(this.error);
423
+ }
424
+ andTee(_f) {
425
+ return err(this.error);
426
+ }
427
+ orTee(f) {
428
+ try {
429
+ f(this.error);
430
+ } catch (e) {
431
+ }
432
+ return err(this.error);
433
+ }
434
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
435
+ andThen(_f) {
436
+ return err(this.error);
437
+ }
438
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
439
+ orElse(f) {
440
+ return f(this.error);
441
+ }
442
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
443
+ asyncAndThen(_f) {
444
+ return errAsync(this.error);
445
+ }
446
+ asyncAndThrough(_f) {
447
+ return errAsync(this.error);
448
+ }
449
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
450
+ asyncMap(_f) {
451
+ return errAsync(this.error);
452
+ }
453
+ unwrapOr(v) {
454
+ return v;
455
+ }
456
+ match(_ok, err3) {
457
+ return err3(this.error);
458
+ }
459
+ safeUnwrap() {
460
+ const error = this.error;
461
+ return (function* () {
462
+ yield err(error);
463
+ throw new Error("Do not use this generator out of `safeTry`");
464
+ })();
465
+ }
466
+ _unsafeUnwrap(config) {
467
+ throw createNeverThrowError("Called `_unsafeUnwrap` on an Err", this, config);
468
+ }
469
+ _unsafeUnwrapErr(_) {
470
+ return this.error;
471
+ }
472
+ *[Symbol.iterator]() {
473
+ const self = this;
474
+ yield self;
475
+ return self;
476
+ }
477
+ };
478
+ var fromThrowable = Result.fromThrowable;
479
+
480
+ // ../../internal/neverthrow/dist/index.js
481
+ function resultFromPromise(type3, surface, promise, error) {
482
+ return ResultAsync.fromPromise(promise, (e) => ({
483
+ ...error(e),
484
+ type: type3,
485
+ surface
486
+ }));
487
+ }
488
+ function resultFromThrowable(type3, surface, fn, error) {
489
+ return Result.fromThrowable(fn, (e) => ({
490
+ ...error(e),
491
+ type: type3,
492
+ surface
493
+ }))();
494
+ }
495
+ function ok2(data) {
496
+ return ok(data);
497
+ }
498
+ function err2(type3, surface, error) {
499
+ return err({
500
+ ...error,
501
+ type: type3,
502
+ surface
503
+ });
504
+ }
505
+
506
+ // src/shared/neverthrow/fs/index.ts
507
+ var errorType = "fs";
508
+ var fsErr = (surface, error) => err2(errorType, surface, error);
509
+ var fsResultFromPromise = (surface, promise, error) => resultFromPromise(errorType, surface, promise, error);
510
+ var safeReadFile = (surface, path) => fsResultFromPromise(surface, readFile(path, "utf-8"), () => ({
511
+ cause: "file_not_readable",
512
+ message: "Failed to read file"
513
+ }));
514
+ var safeWriteFile = (surface, path, data) => fsResultFromPromise(surface, writeFile(path, data), () => ({
515
+ cause: "file_not_writable",
516
+ message: "Failed to write file"
517
+ }));
518
+ var safeAppendFile = (surface, path, data) => fsResultFromPromise(surface, appendFile(path, data), () => ({
519
+ cause: "file_not_writable",
520
+ message: "Failed to append file"
521
+ }));
522
+ var safeChmod = (surface, path, mode) => fsResultFromPromise(surface, chmod(path, mode), () => ({
523
+ cause: "file_not_chmodable",
524
+ message: "Failed to chmod file"
525
+ }));
526
+
527
+ // src/shared/fs.ts
528
+ import { join } from "path";
529
+ import { homedir } from "os";
530
+ import * as fs from "fs";
531
+ var BASE_DIRECTORY = join(homedir(), ".x402scan-mcp");
532
+ if (!fs.existsSync(BASE_DIRECTORY)) {
533
+ fs.mkdirSync(BASE_DIRECTORY, { recursive: true });
534
+ }
535
+ var configFile = (name, defaultValue) => {
536
+ if (!fs.existsSync(BASE_DIRECTORY)) {
537
+ fs.mkdirSync(BASE_DIRECTORY, { recursive: true });
538
+ }
539
+ const filePath = join(BASE_DIRECTORY, name);
540
+ if (!fs.existsSync(filePath)) {
541
+ fs.writeFileSync(filePath, defaultValue);
542
+ }
543
+ return filePath;
544
+ };
545
+
546
+ // src/shared/log.ts
547
+ var LOG_FILE = configFile("mcp.log", "");
548
+ var DEBUG = process.env.X402_DEBUG === "true";
549
+ function format(args) {
550
+ return args.map(
551
+ (a) => typeof a === "object" && a !== null ? JSON.stringify(a) : String(a)
552
+ ).join(" ");
553
+ }
554
+ function write(level, msg, args) {
555
+ const formatted = args.length ? `${msg} ${format(args)}` : msg;
556
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] [${level}] ${formatted}
557
+ `;
558
+ safeAppendFile("log", LOG_FILE, line);
559
+ if (process.env.X402_DEBUG === "true") {
560
+ console.error(`[x402scan] ${formatted}`);
561
+ }
562
+ }
563
+ var log = {
564
+ info: (msg, ...args) => write("INFO", msg, args),
565
+ error: (msg, ...args) => write("ERROR", msg, args),
566
+ debug: (msg, ...args) => DEBUG && write("DEBUG", msg, args),
567
+ path: LOG_FILE
568
+ };
569
+
570
+ // src/shared/redeem-invite.ts
571
+ import z3 from "zod";
572
+
573
+ // src/shared/neverthrow/parse/index.ts
574
+ import z from "zod";
575
+ var type = "json";
576
+ var parseErr = (surface, error) => err2(type, surface, error);
577
+ var safeParse = (surface, schema, value) => {
578
+ const parseResult = schema.safeParse(value);
579
+ if (!parseResult.success) {
580
+ return parseErr(surface, {
581
+ cause: "invalid_data",
582
+ message: JSON.stringify(z.treeifyError(parseResult.error), null, 2),
583
+ error: parseResult.error
584
+ });
585
+ }
586
+ return ok2(parseResult.data);
587
+ };
588
+
589
+ // src/shared/neverthrow/fetch/index.ts
590
+ var errorType2 = "fetch";
591
+ var fetchErr = (surface, error) => err2(errorType2, surface, error);
592
+ var fetchHttpErr = (surface, response) => fetchErr(surface, {
593
+ cause: "http",
594
+ statusCode: response.status,
595
+ message: response.statusText,
596
+ response
597
+ });
598
+ var safeFetch = (surface, request) => {
599
+ return resultFromPromise(
600
+ errorType2,
601
+ surface,
602
+ fetch(request),
603
+ (error) => ({
604
+ cause: "network",
605
+ message: error instanceof Error ? error.message : "Network error"
606
+ })
607
+ );
608
+ };
609
+ var safeFetchJson = (surface, request, schema) => {
610
+ return safeFetch(surface, request).andThen((response) => {
611
+ if (!response.ok) {
612
+ return fetchHttpErr(surface, response);
613
+ }
614
+ return resultFromPromise(errorType2, surface, response.json(), () => ({
615
+ cause: "parse",
616
+ message: "Could not parse JSON from response",
617
+ statusCode: response.status,
618
+ contentType: response.headers.get("content-type") ?? "Not specified"
619
+ }));
620
+ }).andThen((data) => safeParse(surface, schema, data));
621
+ };
622
+ var safeParseResponse = (surface, response) => {
623
+ return resultFromPromise(
624
+ errorType2,
625
+ surface,
626
+ (async () => {
627
+ const contentType = response.headers.get("content-type") ?? "";
628
+ switch (contentType) {
629
+ case "application/json":
630
+ return {
631
+ type: "json",
632
+ data: await response.json()
633
+ };
634
+ case "image/png":
635
+ case "image/jpeg":
636
+ case "image/gif":
637
+ case "image/webp":
638
+ case "image/svg+xml":
639
+ case "image/tiff":
640
+ case "image/bmp":
641
+ case "image/ico":
642
+ return {
643
+ type: "image",
644
+ mimeType: contentType,
645
+ data: await response.arrayBuffer()
646
+ };
647
+ case "audio/":
648
+ return {
649
+ type: "audio",
650
+ mimeType: contentType,
651
+ data: await response.arrayBuffer()
652
+ };
653
+ case "video/":
654
+ return {
655
+ type: "video",
656
+ mimeType: contentType,
657
+ data: await response.arrayBuffer()
658
+ };
659
+ case "application/pdf":
660
+ return {
661
+ type: "pdf",
662
+ mimeType: contentType,
663
+ data: await response.arrayBuffer()
664
+ };
665
+ case "application/octet-stream":
666
+ return {
667
+ type: "octet-stream",
668
+ mimeType: contentType,
669
+ data: await response.arrayBuffer()
670
+ };
671
+ case "multipart/form-data":
672
+ return { type: "formData", data: await response.formData() };
673
+ case "text/":
674
+ return { type: "text", data: await response.text() };
675
+ default:
676
+ throw new Error(`Unsupported content type: ${contentType}`);
677
+ }
678
+ })(),
679
+ (e) => ({
680
+ cause: "parse",
681
+ message: e instanceof Error ? e.message : "Could not parse response",
682
+ statusCode: response.status,
683
+ contentType: response.headers.get("content-type") ?? "Not specified"
684
+ })
685
+ );
686
+ };
687
+ var isFetchError = (error) => {
688
+ return error.type === errorType2;
689
+ };
690
+
691
+ // src/shared/utils.ts
692
+ import open from "open";
693
+ var getBaseUrl = (dev) => {
694
+ return dev ? "http://localhost:3000" : "https://x402scan.com";
695
+ };
696
+ var getDepositLink = (address, flags) => {
697
+ return `${getBaseUrl(flags.dev)}/mcp/deposit/${address}`;
698
+ };
699
+ var openDepositLink = async (address, flags) => {
700
+ const depositLink = getDepositLink(address, flags);
701
+ await open(depositLink);
702
+ };
703
+
704
+ // src/shared/state.ts
705
+ import z2 from "zod";
706
+ import fs2 from "fs";
707
+ var STATE_FILE = configFile("state.json", "{}");
708
+ var stateSchema = z2.looseObject({
709
+ redeemedCodes: z2.array(z2.string())
710
+ }).partial();
711
+ var getState = () => {
712
+ const result = stateSchema.safeParse(
713
+ JSON.parse(fs2.readFileSync(STATE_FILE, "utf-8"))
714
+ );
715
+ if (!result.success) {
716
+ log.error("Failed to parse state", { error: result.error });
717
+ return {};
718
+ }
719
+ return result.data;
720
+ };
721
+ var setState = (state) => {
722
+ const existing = getState();
723
+ const newState = stateSchema.parse({ ...existing, ...state });
724
+ fs2.writeFileSync(STATE_FILE, JSON.stringify(newState, null, 2));
725
+ };
726
+
727
+ // src/shared/redeem-invite.ts
728
+ var redeemInviteCode = async ({
729
+ code,
730
+ dev,
731
+ address,
732
+ surface
733
+ }) => {
734
+ const state = getState();
735
+ if (state.redeemedCodes?.includes(code)) {
736
+ return err2("user", surface, {
737
+ cause: "conflict",
738
+ message: "This invite code has already been redeemed"
739
+ });
740
+ }
741
+ const result = await safeFetchJson(
742
+ surface,
743
+ new Request(`${getBaseUrl(dev)}/api/invite/redeem`, {
744
+ method: "POST",
745
+ headers: {
746
+ "Content-Type": "application/json"
747
+ },
748
+ body: JSON.stringify({
749
+ code,
750
+ recipientAddr: address
751
+ })
752
+ }),
753
+ z3.object({
754
+ redemptionId: z3.string(),
755
+ txHash: z3.string(),
756
+ amount: z3.coerce.number()
757
+ })
758
+ );
759
+ if (result.isOk()) {
760
+ setState({
761
+ redeemedCodes: [...state.redeemedCodes ?? [], code]
762
+ });
763
+ }
764
+ return result;
765
+ };
766
+
767
+ // src/shared/wallet.ts
768
+ import { existsSync as existsSync2 } from "fs";
769
+ import { getAddress } from "viem";
770
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
771
+ import z4 from "zod";
772
+
773
+ // src/shared/neverthrow/json/index.ts
774
+ var type2 = "json";
775
+ var jsonErr = (surface, error) => {
776
+ return err2(type2, surface, error);
777
+ };
778
+ var safeStringifyJson = (surface, value) => {
779
+ return resultFromThrowable(
780
+ type2,
781
+ surface,
782
+ () => JSON.stringify(value, null, 2),
783
+ () => ({
784
+ cause: "stringify",
785
+ message: "Could not stringify JSON"
786
+ })
787
+ );
788
+ };
789
+ var safeParseJson = (surface, value) => {
790
+ return resultFromThrowable(
791
+ type2,
792
+ surface,
793
+ () => JSON.parse(value),
794
+ (e) => ({
795
+ cause: "parse",
796
+ message: e instanceof Error ? e.message : "Could not parse JSON"
797
+ })
798
+ );
799
+ };
800
+
801
+ // src/shared/wallet.ts
802
+ var WALLET_FILE = configFile("wallet.json", "");
803
+ var storedWalletSchema = z4.object({
804
+ privateKey: z4.string().regex(/^0x[a-fA-F0-9]{64}$/, "Invalid Ethereum private key").transform((privateKey) => privateKey),
805
+ address: z4.string().regex(/^0x[a-fA-F0-9]{40}$/, "Invalid Ethereum address").transform((address) => getAddress(address)),
806
+ createdAt: z4.string()
807
+ });
808
+ var walletSurface = "wallet";
809
+ async function getWallet() {
810
+ if (process.env.X402_PRIVATE_KEY) {
811
+ const account2 = privateKeyToAccount(process.env.X402_PRIVATE_KEY);
812
+ log.info(`Using wallet from env: ${account2.address}`);
813
+ return ok2({ account: account2, isNew: false });
814
+ }
815
+ const readFileResult = await safeReadFile(walletSurface, WALLET_FILE);
816
+ if (!readFileResult.isOk()) {
817
+ const fileExistsResult = existsSync2(WALLET_FILE);
818
+ if (fileExistsResult) {
819
+ return fsErr(walletSurface, {
820
+ cause: "file_not_readable",
821
+ message: `The file exists but is not readable. Fix corrupted state file: ${WALLET_FILE}`
822
+ });
823
+ }
824
+ }
825
+ if (readFileResult.isOk()) {
826
+ const data = readFileResult.value;
827
+ const jsonParseResult = safeParseJson(walletSurface, data);
828
+ if (jsonParseResult.isErr()) {
829
+ return jsonErr(walletSurface, {
830
+ cause: "parse",
831
+ message: `The data in ${WALLET_FILE} is not valid JSON`
832
+ });
833
+ }
834
+ const parseResult = safeParse(
835
+ walletSurface,
836
+ storedWalletSchema,
837
+ jsonParseResult.value
838
+ );
839
+ if (parseResult.isErr()) {
840
+ return parseResult;
841
+ }
842
+ const account2 = privateKeyToAccount(parseResult.value.privateKey);
843
+ log.info(`Loaded wallet: ${account2.address}`);
844
+ return ok2({ account: account2, isNew: false });
845
+ }
846
+ const privateKey = generatePrivateKey();
847
+ const account = privateKeyToAccount(privateKey);
848
+ const stored = {
849
+ privateKey,
850
+ address: account.address,
851
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
852
+ };
853
+ const saveResult = await safeWriteFile(
854
+ walletSurface,
855
+ WALLET_FILE,
856
+ JSON.stringify(stored, null, 2)
857
+ ).andThen(() => safeChmod(walletSurface, WALLET_FILE, 384));
858
+ if (saveResult.isErr()) {
859
+ return saveResult;
860
+ }
861
+ log.info(`Created wallet: ${account.address}`);
862
+ log.info(`Saved to: ${WALLET_FILE}`);
863
+ return ok2({ account, isNew: true });
864
+ }
865
+
866
+ // src/shared/networks.ts
867
+ import {
868
+ base,
869
+ baseSepolia,
870
+ mainnet,
871
+ sepolia,
872
+ optimism,
873
+ arbitrum,
874
+ polygon
875
+ } from "viem/chains";
876
+ var CHAIN_CONFIGS = {
877
+ "eip155:8453": {
878
+ chain: base,
879
+ caip2: "eip155:8453",
880
+ v1Name: "base",
881
+ usdcAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
882
+ },
883
+ "eip155:84532": {
884
+ chain: baseSepolia,
885
+ caip2: "eip155:84532",
886
+ v1Name: "base-sepolia",
887
+ usdcAddress: "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
888
+ },
889
+ "eip155:1": {
890
+ chain: mainnet,
891
+ caip2: "eip155:1",
892
+ v1Name: "ethereum",
893
+ usdcAddress: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
894
+ },
895
+ "eip155:11155111": {
896
+ chain: sepolia,
897
+ caip2: "eip155:11155111",
898
+ v1Name: "ethereum-sepolia",
899
+ usdcAddress: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
900
+ },
901
+ "eip155:10": {
902
+ chain: optimism,
903
+ caip2: "eip155:10",
904
+ v1Name: "optimism",
905
+ usdcAddress: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"
906
+ },
907
+ "eip155:42161": {
908
+ chain: arbitrum,
909
+ caip2: "eip155:42161",
910
+ v1Name: "arbitrum",
911
+ usdcAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"
912
+ },
913
+ "eip155:137": {
914
+ chain: polygon,
915
+ caip2: "eip155:137",
916
+ v1Name: "polygon",
917
+ usdcAddress: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"
918
+ }
919
+ };
920
+ var V1_TO_CAIP2 = {
921
+ base: "eip155:8453",
922
+ "base-sepolia": "eip155:84532",
923
+ ethereum: "eip155:1",
924
+ "ethereum-sepolia": "eip155:11155111",
925
+ optimism: "eip155:10",
926
+ arbitrum: "eip155:42161",
927
+ polygon: "eip155:137"
928
+ };
929
+ var DEFAULT_NETWORK = "eip155:8453";
930
+ function toCaip2(network) {
931
+ if (network.startsWith("eip155:")) return network;
932
+ return V1_TO_CAIP2[network.toLowerCase()] ?? network;
933
+ }
934
+ function getChainConfig(network) {
935
+ return CHAIN_CONFIGS[toCaip2(network)];
936
+ }
937
+ function getChainName(network) {
938
+ return getChainConfig(network)?.chain.name ?? network;
939
+ }
940
+
941
+ export {
942
+ resultFromPromise,
943
+ resultFromThrowable,
944
+ ok2 as ok,
945
+ err2 as err,
946
+ fetchHttpErr,
947
+ safeFetch,
948
+ safeFetchJson,
949
+ safeParseResponse,
950
+ isFetchError,
951
+ safeStringifyJson,
952
+ getBaseUrl,
953
+ getDepositLink,
954
+ openDepositLink,
955
+ safeReadFile,
956
+ safeWriteFile,
957
+ log,
958
+ DEFAULT_NETWORK,
959
+ getChainName,
960
+ redeemInviteCode,
961
+ getWallet
962
+ };
963
+ //# sourceMappingURL=chunk-7BI7Y3ZF.js.map