@x402-lens/cli 0.0.0-stage → 0.2.4
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.
- package/LICENSE +21 -0
- package/README.md +57 -3
- package/dist/index.js +1345 -0
- package/dist/index.js.map +1 -0
- package/package.json +41 -6
package/dist/index.js
ADDED
|
@@ -0,0 +1,1345 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/commands/add.ts
|
|
4
|
+
import { readFile, writeFile } from "fs/promises";
|
|
5
|
+
import { basename } from "path";
|
|
6
|
+
var AddError = class extends Error {
|
|
7
|
+
constructor(message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "AddError";
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
var IMPORT_LINE = 'import { paymentLens } from "@x402-lens/express";';
|
|
13
|
+
var LENS_DECLARATION = "const lens = paymentLens();";
|
|
14
|
+
var MOUNT_LINE = "app.use(lens.middleware);";
|
|
15
|
+
async function addProtection(options) {
|
|
16
|
+
const { file, route } = options;
|
|
17
|
+
const price = assertAddPrice(options.price);
|
|
18
|
+
if (basename(file).match(/\.(ts|js|mjs|cjs)$/) === null) {
|
|
19
|
+
throw new AddError(
|
|
20
|
+
`${file} is not a JavaScript or TypeScript file. This command edits source files, not compiled output.`
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
const original = await readFile(file, "utf8");
|
|
24
|
+
const parsed = parseRoute(route);
|
|
25
|
+
const hasLens = original.includes("paymentLens(");
|
|
26
|
+
const hasRouteEntry = hasRouteEntryFor(original, parsed);
|
|
27
|
+
if (hasLens && hasRouteEntry) {
|
|
28
|
+
return {
|
|
29
|
+
changed: false,
|
|
30
|
+
diff: "",
|
|
31
|
+
text: `${file} already charges for ${parsed.method} ${parsed.path}. Nothing to do.`,
|
|
32
|
+
exitCode: 0
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
const framework = detectFramework(original);
|
|
36
|
+
if (framework !== "express") {
|
|
37
|
+
throw new AddError(
|
|
38
|
+
`${file} does not look like an Express app (${framework}). The add command only supports Express; use paymentLens() from @x402-lens/express manually for anything else.`
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
const routePattern = findRouteDeclaration(original, parsed);
|
|
42
|
+
if (!routePattern) {
|
|
43
|
+
throw new AddError(
|
|
44
|
+
`Could not find a route declaration for ${tsStringLiteral(`${parsed.method} ${parsed.path}`)} in ${file}. The add command recognises app.get("/path", ...) and router.post("/path", ...) forms written on one line. Add the middleware manually:
|
|
45
|
+
|
|
46
|
+
const lens = paymentLens({ routes: { ${routeMapEntry(parsed, price)} } });
|
|
47
|
+
app.use(lens.middleware);
|
|
48
|
+
`
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
const updated = hasLens ? withRouteEntry(original, file, parsed, price) : applyEdits(original, parsed, price, routePattern);
|
|
52
|
+
const diff = unifiedDiff(file, original, updated);
|
|
53
|
+
if (!options.write) {
|
|
54
|
+
return {
|
|
55
|
+
changed: true,
|
|
56
|
+
diff,
|
|
57
|
+
text: [
|
|
58
|
+
`Dry run \u2014 ${file} would change as follows.`,
|
|
59
|
+
"",
|
|
60
|
+
diff,
|
|
61
|
+
"",
|
|
62
|
+
"Re-run with --write to apply. Set X402_FACILITATOR_URL, X402_NETWORK, and X402_PAY_TO first; paymentLens() refuses to guess them."
|
|
63
|
+
].join("\n"),
|
|
64
|
+
exitCode: 0
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
await writeFile(file, updated, "utf8");
|
|
68
|
+
return {
|
|
69
|
+
changed: true,
|
|
70
|
+
diff,
|
|
71
|
+
text: `Updated ${file}.
|
|
72
|
+
|
|
73
|
+
${diff}
|
|
74
|
+
|
|
75
|
+
Next: set X402_FACILITATOR_URL, X402_NETWORK, and X402_PAY_TO, then restart. Run \`x402-lens doctor\` to verify the configuration.`,
|
|
76
|
+
exitCode: 0
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function parseRoute(route) {
|
|
80
|
+
const trimmed = route.trim();
|
|
81
|
+
const spaceIndex = trimmed.indexOf(" ");
|
|
82
|
+
if (spaceIndex === -1) {
|
|
83
|
+
return { method: "GET", path: trimmed };
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
method: trimmed.slice(0, spaceIndex).toUpperCase(),
|
|
87
|
+
path: trimmed.slice(spaceIndex + 1).trim()
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
function routeKey(route) {
|
|
91
|
+
return `${route.method} ${route.path}`;
|
|
92
|
+
}
|
|
93
|
+
function tsStringLiteral(value) {
|
|
94
|
+
return JSON.stringify(value);
|
|
95
|
+
}
|
|
96
|
+
function routeMapEntry(route, price) {
|
|
97
|
+
return `${tsStringLiteral(routeKey(route))}: ${tsStringLiteral(price)}`;
|
|
98
|
+
}
|
|
99
|
+
function assertAddPrice(price) {
|
|
100
|
+
const trimmed = price.trim();
|
|
101
|
+
if (trimmed.length === 0) {
|
|
102
|
+
throw new AddError('price is empty. Use a decimal such as "0.001".');
|
|
103
|
+
}
|
|
104
|
+
return trimmed;
|
|
105
|
+
}
|
|
106
|
+
function matchBrace(source, open) {
|
|
107
|
+
let depth = 0;
|
|
108
|
+
for (let index = open; index < source.length; index += 1) {
|
|
109
|
+
const char = source[index];
|
|
110
|
+
const next = source[index + 1];
|
|
111
|
+
if (char === "/" && next === "/") {
|
|
112
|
+
const newline = source.indexOf("\n", index);
|
|
113
|
+
if (newline === -1) return -1;
|
|
114
|
+
index = newline;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (char === "/" && next === "*") {
|
|
118
|
+
const end = source.indexOf("*/", index + 2);
|
|
119
|
+
if (end === -1) return -1;
|
|
120
|
+
index = end + 1;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
124
|
+
index = skipString(source, index);
|
|
125
|
+
if (index === -1) return -1;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (char === "{") depth += 1;
|
|
129
|
+
else if (char === "}") {
|
|
130
|
+
depth -= 1;
|
|
131
|
+
if (depth === 0) return index;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
return -1;
|
|
135
|
+
}
|
|
136
|
+
function skipString(source, open) {
|
|
137
|
+
const quote = source[open];
|
|
138
|
+
for (let index = open + 1; index < source.length; index += 1) {
|
|
139
|
+
const char = source[index];
|
|
140
|
+
if (char === "\\") {
|
|
141
|
+
index += 1;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (char === quote) return index;
|
|
145
|
+
}
|
|
146
|
+
return -1;
|
|
147
|
+
}
|
|
148
|
+
function findLensCall(source) {
|
|
149
|
+
const pattern = /\bpaymentLens(?:Async)?\s*\(/;
|
|
150
|
+
const match = pattern.exec(source);
|
|
151
|
+
if (!match) return void 0;
|
|
152
|
+
const open = source.indexOf("(", match.index);
|
|
153
|
+
const close = matchParen(source, open);
|
|
154
|
+
if (close === -1) return void 0;
|
|
155
|
+
return { open, close };
|
|
156
|
+
}
|
|
157
|
+
function matchParen(source, open) {
|
|
158
|
+
let depth = 0;
|
|
159
|
+
for (let index = open; index < source.length; index += 1) {
|
|
160
|
+
const char = source[index];
|
|
161
|
+
const next = source[index + 1];
|
|
162
|
+
if (char === "/" && next === "/") {
|
|
163
|
+
const newline = source.indexOf("\n", index);
|
|
164
|
+
if (newline === -1) return -1;
|
|
165
|
+
index = newline;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (char === "/" && next === "*") {
|
|
169
|
+
const end = source.indexOf("*/", index + 2);
|
|
170
|
+
if (end === -1) return -1;
|
|
171
|
+
index = end + 1;
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
175
|
+
index = skipString(source, index);
|
|
176
|
+
if (index === -1) return -1;
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (char === "(") depth += 1;
|
|
180
|
+
else if (char === ")") {
|
|
181
|
+
depth -= 1;
|
|
182
|
+
if (depth === 0) return index;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return -1;
|
|
186
|
+
}
|
|
187
|
+
function findRoutesObject(source) {
|
|
188
|
+
const call = findLensCall(source);
|
|
189
|
+
const scope = call ?? { open: 0, close: source.length - 1 };
|
|
190
|
+
const inner = source.slice(scope.open, scope.close + 1);
|
|
191
|
+
const pattern = /\broutes\s*:\s*\{/;
|
|
192
|
+
const match = pattern.exec(inner);
|
|
193
|
+
if (!match) return void 0;
|
|
194
|
+
const open = scope.open + match.index + match[0].length - 1;
|
|
195
|
+
const close = matchBrace(source, open);
|
|
196
|
+
if (close === -1) return void 0;
|
|
197
|
+
return { open, close };
|
|
198
|
+
}
|
|
199
|
+
function hasRouteEntryFor(source, route) {
|
|
200
|
+
const key = escapeRegExp(routeKey(route));
|
|
201
|
+
const quotedKey = new RegExp(`["'\`]${key}["'\`]\\s*:`);
|
|
202
|
+
const routes = findRoutesObject(source);
|
|
203
|
+
if (routes) return quotedKey.test(source.slice(routes.open, routes.close + 1));
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
function withRouteEntry(source, file, route, price) {
|
|
207
|
+
if (/\broutes\s*:\s*\[/.test(source)) {
|
|
208
|
+
throw new AddError(
|
|
209
|
+
`${file} passes routes as an array, which x402-lens add does not rewrite. Add the entry by hand:
|
|
210
|
+
|
|
211
|
+
{ route: ${tsStringLiteral(routeKey(route))}, price: ${tsStringLiteral(price)} }
|
|
212
|
+
`
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
const routes = findRoutesObject(source);
|
|
216
|
+
if (!routes) {
|
|
217
|
+
throw new AddError(
|
|
218
|
+
`paymentLens is already called, but its routes map could not be found, so x402-lens add will not guess where to put ${routeKey(route)}. Add it by hand:
|
|
219
|
+
|
|
220
|
+
routes: { ${routeMapEntry(route, price)} }
|
|
221
|
+
`
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
const entry = routeMapEntry(route, price);
|
|
225
|
+
const inner = source.slice(routes.open + 1, routes.close);
|
|
226
|
+
const trailing = inner.match(/\s*$/)?.[0] ?? "";
|
|
227
|
+
const insertAt = routes.close - trailing.length;
|
|
228
|
+
const lastEntry = source.slice(routes.open + 1, insertAt);
|
|
229
|
+
if (lastEntry.trim().length === 0) {
|
|
230
|
+
return `${source.slice(0, routes.open + 1)} ${entry} ${source.slice(routes.close)}`;
|
|
231
|
+
}
|
|
232
|
+
const entryEnd = routes.open + 1 + lastEntry.length;
|
|
233
|
+
const lineStart = source.lastIndexOf("\n", entryEnd - 1) + 1;
|
|
234
|
+
const indent = source.slice(lineStart, entryEnd).match(/^[ \t]*/)?.[0] ?? "";
|
|
235
|
+
const spacer = trailing.includes("\n") ? "\n" : " ";
|
|
236
|
+
const trailingComma = lastEntry.trimEnd().endsWith(",");
|
|
237
|
+
const inserted = trailingComma ? `${entry},` : entry;
|
|
238
|
+
const separator = trailingComma ? "" : ",";
|
|
239
|
+
return `${source.slice(0, insertAt)}${separator}${spacer}${indent}${inserted}${source.slice(insertAt)}`;
|
|
240
|
+
}
|
|
241
|
+
function detectFramework(source) {
|
|
242
|
+
if (/from\s+["']express["']|require\(\s*["']express["']\s*\)/.test(source)) return "express";
|
|
243
|
+
if (/from\s+["']fastify["']|require\(\s*["']fastify["']\s*\)/.test(source)) return "fastify";
|
|
244
|
+
if (/from\s+["']hono["']/.test(source)) return "hono";
|
|
245
|
+
if (/from\s+fastapi\s+import|import\s+fastapi/.test(source)) return "fastapi";
|
|
246
|
+
return "unknown";
|
|
247
|
+
}
|
|
248
|
+
function findRouteDeclaration(source, route) {
|
|
249
|
+
const method = route.method.toLowerCase();
|
|
250
|
+
const escapedPath = escapeRegExp(route.path);
|
|
251
|
+
const pattern = new RegExp(
|
|
252
|
+
`\\b(?:app|router|server)\\.${method}\\(\\s*(["'\`])${escapedPath}\\1\\s*,`
|
|
253
|
+
);
|
|
254
|
+
const match = pattern.exec(source);
|
|
255
|
+
if (!match) return void 0;
|
|
256
|
+
return {
|
|
257
|
+
routeStart: match.index,
|
|
258
|
+
matched: match[0]
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
function applyEdits(source, route, price, routeMatch) {
|
|
262
|
+
let updated = source;
|
|
263
|
+
if (!updated.includes("paymentLens(")) {
|
|
264
|
+
const before = `${updated.slice(0, routeMatch.routeStart).replace(/(?:[ \t]*\r?\n)+$/, "")}
|
|
265
|
+
|
|
266
|
+
`;
|
|
267
|
+
const body = `${LENS_DECLARATION.replace(
|
|
268
|
+
"paymentLens()",
|
|
269
|
+
`paymentLens({ routes: { ${routeMapEntry(route, price)} } })`
|
|
270
|
+
)}
|
|
271
|
+
${MOUNT_LINE}
|
|
272
|
+
|
|
273
|
+
`;
|
|
274
|
+
updated = `${before}${body}${updated.slice(routeMatch.routeStart)}`;
|
|
275
|
+
}
|
|
276
|
+
if (!updated.includes("@x402-lens/express")) {
|
|
277
|
+
const lastImport = findLastImportEnd(updated);
|
|
278
|
+
if (lastImport === -1) {
|
|
279
|
+
updated = `${IMPORT_LINE}
|
|
280
|
+
${updated}`;
|
|
281
|
+
} else {
|
|
282
|
+
updated = `${updated.slice(0, lastImport)}
|
|
283
|
+
${IMPORT_LINE}${updated.slice(lastImport)}`;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return updated;
|
|
287
|
+
}
|
|
288
|
+
function findLastImportEnd(source) {
|
|
289
|
+
const lines = source.split("\n");
|
|
290
|
+
let offset = 0;
|
|
291
|
+
let lastEnd = -1;
|
|
292
|
+
for (const line of lines) {
|
|
293
|
+
const trimmed = line.trim();
|
|
294
|
+
const isImportStart = trimmed.startsWith("import ");
|
|
295
|
+
const isImportContinuation = lastEnd !== -1 && trimmed.length > 0 && !trimmed.startsWith("//");
|
|
296
|
+
if (isImportStart) {
|
|
297
|
+
if (/from\s+["'][^"']+["'];?$/.test(trimmed) || /^import\s+["'][^"']+["'];?$/.test(trimmed)) {
|
|
298
|
+
lastEnd = offset + line.length;
|
|
299
|
+
} else {
|
|
300
|
+
lastEnd = -2;
|
|
301
|
+
}
|
|
302
|
+
} else if (lastEnd === -2 && isImportContinuation && trimmed.endsWith(";")) {
|
|
303
|
+
lastEnd = offset + line.length;
|
|
304
|
+
}
|
|
305
|
+
offset += line.length + 1;
|
|
306
|
+
}
|
|
307
|
+
return lastEnd > 0 ? lastEnd : -1;
|
|
308
|
+
}
|
|
309
|
+
function escapeRegExp(value) {
|
|
310
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
311
|
+
}
|
|
312
|
+
function unifiedDiff(file, before, after) {
|
|
313
|
+
const beforeLines = before.split("\n");
|
|
314
|
+
const afterLines = after.split("\n");
|
|
315
|
+
const operations = diffLines(beforeLines, afterLines);
|
|
316
|
+
const changedIndices = operations.map((op, index) => op.type === "equal" ? -1 : index).filter((index) => index !== -1);
|
|
317
|
+
if (changedIndices.length === 0) return "";
|
|
318
|
+
const firstChanged = Math.max(0, (changedIndices[0] ?? 0) - 3);
|
|
319
|
+
const lastChanged = Math.min(operations.length - 1, (changedIndices.at(-1) ?? 0) + 3);
|
|
320
|
+
const header = [`--- a/${file}`, `+++ b/${file}`];
|
|
321
|
+
let beforeCount = 0;
|
|
322
|
+
let afterCount = 0;
|
|
323
|
+
for (let index = firstChanged; index <= lastChanged; index += 1) {
|
|
324
|
+
const op = operations[index];
|
|
325
|
+
if (!op) continue;
|
|
326
|
+
if (op.type !== "insert") beforeCount += 1;
|
|
327
|
+
if (op.type !== "delete") afterCount += 1;
|
|
328
|
+
}
|
|
329
|
+
const body = [`@@ -${firstChanged + 1},${beforeCount} +${firstChanged + 1},${afterCount} @@`];
|
|
330
|
+
for (let index = firstChanged; index <= lastChanged; index += 1) {
|
|
331
|
+
const op = operations[index];
|
|
332
|
+
if (!op) continue;
|
|
333
|
+
if (op.type === "equal") body.push(` ${op.line}`);
|
|
334
|
+
else if (op.type === "delete") body.push(`-${op.line}`);
|
|
335
|
+
else body.push(`+${op.line}`);
|
|
336
|
+
}
|
|
337
|
+
return [...header, ...body].join("\n");
|
|
338
|
+
}
|
|
339
|
+
function diffLines(before, after) {
|
|
340
|
+
const rows = before.length + 1;
|
|
341
|
+
const cols = after.length + 1;
|
|
342
|
+
const table = Array.from({ length: rows }, () => new Array(cols).fill(0));
|
|
343
|
+
for (let i2 = before.length - 1; i2 >= 0; i2 -= 1) {
|
|
344
|
+
for (let j2 = after.length - 1; j2 >= 0; j2 -= 1) {
|
|
345
|
+
const row = table[i2];
|
|
346
|
+
const nextRow = table[i2 + 1];
|
|
347
|
+
if (!row || !nextRow) continue;
|
|
348
|
+
row[j2] = before[i2] === after[j2] ? (nextRow[j2 + 1] ?? 0) + 1 : Math.max(nextRow[j2] ?? 0, row[j2 + 1] ?? 0);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
const operations = [];
|
|
352
|
+
let i = 0;
|
|
353
|
+
let j = 0;
|
|
354
|
+
while (i < before.length && j < after.length) {
|
|
355
|
+
if (before[i] === after[j]) {
|
|
356
|
+
operations.push({ type: "equal", line: before[i] });
|
|
357
|
+
i += 1;
|
|
358
|
+
j += 1;
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
const nextRow = table[i + 1];
|
|
362
|
+
const row = table[i];
|
|
363
|
+
if (!nextRow || !row) break;
|
|
364
|
+
if ((nextRow[j] ?? 0) >= (row[j + 1] ?? 0)) {
|
|
365
|
+
operations.push({ type: "delete", line: before[i] });
|
|
366
|
+
i += 1;
|
|
367
|
+
} else {
|
|
368
|
+
operations.push({ type: "insert", line: after[j] });
|
|
369
|
+
j += 1;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
while (i < before.length) {
|
|
373
|
+
operations.push({ type: "delete", line: before[i] });
|
|
374
|
+
i += 1;
|
|
375
|
+
}
|
|
376
|
+
while (j < after.length) {
|
|
377
|
+
operations.push({ type: "insert", line: after[j] });
|
|
378
|
+
j += 1;
|
|
379
|
+
}
|
|
380
|
+
return operations;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// src/commands/explain.ts
|
|
384
|
+
import {
|
|
385
|
+
diagnose,
|
|
386
|
+
formatFindings
|
|
387
|
+
} from "@x402-lens/core";
|
|
388
|
+
|
|
389
|
+
// src/input.ts
|
|
390
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
391
|
+
var InputError = class extends Error {
|
|
392
|
+
constructor(message) {
|
|
393
|
+
super(message);
|
|
394
|
+
this.name = "InputError";
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
async function readJsonArgument(raw, label) {
|
|
398
|
+
const source = raw.startsWith("@") ? await readFile2(raw.slice(1), "utf8") : raw;
|
|
399
|
+
return parseJsonOrBase64(source, label);
|
|
400
|
+
}
|
|
401
|
+
function parseJsonOrBase64(source, label) {
|
|
402
|
+
const trimmed = source.trim();
|
|
403
|
+
if (trimmed.length === 0) {
|
|
404
|
+
throw new InputError(`${label} is empty.`);
|
|
405
|
+
}
|
|
406
|
+
const asJson = tryParseJson(trimmed);
|
|
407
|
+
if (asJson !== void 0) return asJson;
|
|
408
|
+
const decoded = tryDecodeBase64(trimmed);
|
|
409
|
+
if (decoded !== void 0) {
|
|
410
|
+
const fromBase64 = tryParseJson(decoded);
|
|
411
|
+
if (fromBase64 !== void 0) return fromBase64;
|
|
412
|
+
throw new InputError(
|
|
413
|
+
`${label} decodes from base64 but the result is not JSON. Got: ${decoded.slice(0, 120)}`
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
throw new InputError(
|
|
417
|
+
`${label} is neither JSON nor base64-encoded JSON. Pass the header value verbatim, or JSON, or @file.`
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
function tryParseJson(value) {
|
|
421
|
+
const first = value[0];
|
|
422
|
+
if (first !== "{" && first !== "[" && first !== '"') return void 0;
|
|
423
|
+
try {
|
|
424
|
+
return JSON.parse(value);
|
|
425
|
+
} catch {
|
|
426
|
+
return void 0;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
function tryDecodeBase64(value) {
|
|
430
|
+
const normalised = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
431
|
+
const padded = normalised.padEnd(
|
|
432
|
+
normalised.length + (4 - normalised.length % 4) % 4,
|
|
433
|
+
"="
|
|
434
|
+
);
|
|
435
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(padded)) return void 0;
|
|
436
|
+
try {
|
|
437
|
+
const decoded = Buffer.from(padded, "base64").toString("utf8");
|
|
438
|
+
return decoded.includes("\uFFFD") ? void 0 : decoded;
|
|
439
|
+
} catch {
|
|
440
|
+
return void 0;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// src/commands/explain.ts
|
|
445
|
+
async function explainPayment(input) {
|
|
446
|
+
const paymentRequired = input.challenge ? await readJsonArgument(input.challenge, "--challenge") : void 0;
|
|
447
|
+
const paymentPayload = input.payment ? await readJsonArgument(input.payment, "--payment") : void 0;
|
|
448
|
+
const verifyResponse = input.verify ? await readJsonArgument(input.verify, "--verify") : void 0;
|
|
449
|
+
const settleResponse = input.settle ? await readJsonArgument(input.settle, "--settle") : void 0;
|
|
450
|
+
if (!paymentRequired && !paymentPayload && !verifyResponse && !settleResponse) {
|
|
451
|
+
return {
|
|
452
|
+
text: [
|
|
453
|
+
"Nothing to explain.",
|
|
454
|
+
"",
|
|
455
|
+
"Pass at least one of:",
|
|
456
|
+
" --challenge <PAYMENT-REQUIRED|@file> the 402 terms",
|
|
457
|
+
" --payment <PAYMENT-SIGNATURE|@file> what the client sent",
|
|
458
|
+
" --verify <json|@file> facilitator /verify response",
|
|
459
|
+
" --settle <json|@file> facilitator /settle response"
|
|
460
|
+
].join("\n"),
|
|
461
|
+
exitCode: 2,
|
|
462
|
+
findingCount: 0,
|
|
463
|
+
findings: []
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
const findings = diagnose({
|
|
467
|
+
...paymentRequired ? { paymentRequired } : {},
|
|
468
|
+
...paymentPayload ? { paymentPayload } : {},
|
|
469
|
+
...verifyResponse ? { verifyResponse } : {},
|
|
470
|
+
...settleResponse ? { settleResponse } : {}
|
|
471
|
+
});
|
|
472
|
+
const header = [
|
|
473
|
+
"x402-lens explain",
|
|
474
|
+
` challenge: ${paymentRequired ? "yes" : "no"}`,
|
|
475
|
+
` payment: ${paymentPayload ? "yes" : "no"}`,
|
|
476
|
+
` verify: ${verifyResponse ? verifyResponse.isValid ? "valid" : "invalid" : "no"}`,
|
|
477
|
+
` settle: ${settleResponse ? settleResponse.success ? "settled" : "failed" : "no"}`
|
|
478
|
+
].join("\n");
|
|
479
|
+
const hasError = findings.some((finding) => finding.severity === "error");
|
|
480
|
+
return {
|
|
481
|
+
text: `${header}
|
|
482
|
+
|
|
483
|
+
${formatFindings(findings)}`,
|
|
484
|
+
exitCode: hasError ? 1 : 0,
|
|
485
|
+
findingCount: findings.length,
|
|
486
|
+
findings
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// src/commands/doctor.ts
|
|
491
|
+
import {
|
|
492
|
+
ConfigError,
|
|
493
|
+
WELL_KNOWN_NETWORKS,
|
|
494
|
+
describeNetwork,
|
|
495
|
+
isCaip2,
|
|
496
|
+
loadConfig,
|
|
497
|
+
suggestCaip2
|
|
498
|
+
} from "@x402-lens/core";
|
|
499
|
+
async function runDoctor(options = {}) {
|
|
500
|
+
const checks = [];
|
|
501
|
+
let config;
|
|
502
|
+
let configError;
|
|
503
|
+
try {
|
|
504
|
+
config = options.config ?? await loadConfig({
|
|
505
|
+
readConfigFile: true,
|
|
506
|
+
...options.cwd !== void 0 ? { cwd: options.cwd } : {}
|
|
507
|
+
});
|
|
508
|
+
checks.push({
|
|
509
|
+
name: "config",
|
|
510
|
+
ok: true,
|
|
511
|
+
detail: `facilitator ${config.facilitatorUrl}, network ${config.networks.length > 1 ? config.networks.map(describeNetwork).join(", ") : describeNetwork(config.network)}, ${config.routes.length} route(s)`
|
|
512
|
+
});
|
|
513
|
+
checks.push(checkFacilitatorHeadersOk(config));
|
|
514
|
+
} catch (error) {
|
|
515
|
+
configError = error;
|
|
516
|
+
if (isFacilitatorHeadersConfigError(configError)) {
|
|
517
|
+
checks.push({
|
|
518
|
+
name: "facilitatorHeaders",
|
|
519
|
+
ok: false,
|
|
520
|
+
detail: configError.message
|
|
521
|
+
});
|
|
522
|
+
return finish(checks);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
const facilitatorUrl = (options.facilitatorUrl ?? config?.facilitatorUrl ?? "").replace(/\/+$/, "");
|
|
526
|
+
const networks = options.networks ?? (options.network ? [options.network] : config?.networks ?? []);
|
|
527
|
+
const network = networks[0] ?? "";
|
|
528
|
+
if (!config) {
|
|
529
|
+
if (!facilitatorUrl || !network) {
|
|
530
|
+
checks.push({
|
|
531
|
+
name: "config",
|
|
532
|
+
ok: false,
|
|
533
|
+
detail: configError?.message ?? "Configuration could not be loaded."
|
|
534
|
+
});
|
|
535
|
+
return finish(checks);
|
|
536
|
+
}
|
|
537
|
+
checks.push({
|
|
538
|
+
name: "config",
|
|
539
|
+
ok: true,
|
|
540
|
+
detail: "Probing with facilitator and network overrides. Full configuration (payTo, routes) was not loaded, so it was not checked."
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
if (!isCaip2(network)) {
|
|
544
|
+
const suggestion = suggestCaip2(network);
|
|
545
|
+
checks.push({
|
|
546
|
+
name: "network format",
|
|
547
|
+
ok: false,
|
|
548
|
+
detail: `"${network}" is not CAIP-2.${suggestion ? ` Use "${suggestion}".` : ""}`
|
|
549
|
+
});
|
|
550
|
+
return finish(checks);
|
|
551
|
+
}
|
|
552
|
+
checks.push({
|
|
553
|
+
name: "network format",
|
|
554
|
+
ok: true,
|
|
555
|
+
detail: describeNetwork(network)
|
|
556
|
+
});
|
|
557
|
+
if (config) {
|
|
558
|
+
for (const net of networks.length > 0 ? networks : config.networks) {
|
|
559
|
+
const address = config.payToByNetwork[net] ?? config.payTo;
|
|
560
|
+
checks.push(checkPayToShape(address, net));
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
let supported;
|
|
564
|
+
try {
|
|
565
|
+
const authHeaders = config?.facilitatorHeaders?.supported ?? {};
|
|
566
|
+
const response = await fetch(`${facilitatorUrl}/supported`, {
|
|
567
|
+
headers: {
|
|
568
|
+
Accept: "application/json",
|
|
569
|
+
"User-Agent": "x402-lens/0.2",
|
|
570
|
+
...authHeaders
|
|
571
|
+
},
|
|
572
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 15e3)
|
|
573
|
+
});
|
|
574
|
+
if (!response.ok) {
|
|
575
|
+
checks.push({
|
|
576
|
+
name: "facilitator reachable",
|
|
577
|
+
ok: false,
|
|
578
|
+
detail: `GET ${facilitatorUrl}/supported returned HTTP ${response.status}.`
|
|
579
|
+
});
|
|
580
|
+
return finish(checks);
|
|
581
|
+
}
|
|
582
|
+
supported = await response.json();
|
|
583
|
+
checks.push({
|
|
584
|
+
name: "facilitator reachable",
|
|
585
|
+
ok: true,
|
|
586
|
+
detail: `${facilitatorUrl}/supported responded with ${String(supported.kinds?.length ?? 0)} kind(s).`
|
|
587
|
+
});
|
|
588
|
+
} catch (error) {
|
|
589
|
+
checks.push({
|
|
590
|
+
name: "facilitator reachable",
|
|
591
|
+
ok: false,
|
|
592
|
+
detail: `Could not reach ${facilitatorUrl}/supported: ${error.message}. Check the URL, the network path, and any proxy in between.`
|
|
593
|
+
});
|
|
594
|
+
return finish(checks);
|
|
595
|
+
}
|
|
596
|
+
const kinds = supported.kinds ?? [];
|
|
597
|
+
const matching = kinds.filter(
|
|
598
|
+
(kind) => kind.network === network && kind.x402Version === 2
|
|
599
|
+
);
|
|
600
|
+
if (matching.length === 0) {
|
|
601
|
+
const v1Only = kinds.some((kind) => kind.network === network && kind.x402Version === 1);
|
|
602
|
+
const available = Array.from(
|
|
603
|
+
new Set(kinds.filter((kind) => kind.x402Version === 2).map((kind) => kind.network ?? ""))
|
|
604
|
+
).filter(Boolean);
|
|
605
|
+
checks.push({
|
|
606
|
+
name: "network supported",
|
|
607
|
+
ok: false,
|
|
608
|
+
detail: v1Only ? `The facilitator lists ${network} for x402Version 1 only. This middleware speaks v2, so payments will be rejected.` : `The facilitator does not list ${network} with x402Version 2. It supports: ${available.join(", ") || "nothing"}.`
|
|
609
|
+
});
|
|
610
|
+
} else {
|
|
611
|
+
checks.push({
|
|
612
|
+
name: "network supported",
|
|
613
|
+
ok: true,
|
|
614
|
+
detail: `${network} is available for scheme(s): ${matching.map((kind) => kind.scheme ?? "?").join(", ")}.`
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
const missing = networks.filter(
|
|
618
|
+
(candidate) => !kinds.some((kind) => kind.network === candidate && kind.x402Version === 2)
|
|
619
|
+
);
|
|
620
|
+
if (networks.length > 1) {
|
|
621
|
+
checks.push(
|
|
622
|
+
missing.length === 0 ? {
|
|
623
|
+
name: "all networks supported",
|
|
624
|
+
ok: true,
|
|
625
|
+
detail: `All ${networks.length} configured networks are listed for x402Version 2: ${networks.join(", ")}.`
|
|
626
|
+
} : {
|
|
627
|
+
name: "all networks supported",
|
|
628
|
+
ok: false,
|
|
629
|
+
detail: `These configured networks are not listed for x402Version 2: ${missing.join(
|
|
630
|
+
", "
|
|
631
|
+
)}. The SDK treats this as a fatal startup error and exits the process, so the server will not start. Remove them from networks, or use a facilitator that supports them.`
|
|
632
|
+
}
|
|
633
|
+
);
|
|
634
|
+
}
|
|
635
|
+
const requiredSchemes = Array.from(
|
|
636
|
+
new Set(
|
|
637
|
+
(config?.routes ?? []).map((route) => route.scheme ?? "exact")
|
|
638
|
+
)
|
|
639
|
+
);
|
|
640
|
+
const schemesToCheck = requiredSchemes.length > 0 ? requiredSchemes : ["exact"];
|
|
641
|
+
const networksForSchemes = networks.length > 0 ? networks : [network];
|
|
642
|
+
for (const scheme of schemesToCheck) {
|
|
643
|
+
const missingSchemeNetworks = networksForSchemes.filter(
|
|
644
|
+
(candidate) => !kinds.some(
|
|
645
|
+
(kind) => kind.network === candidate && kind.x402Version === 2 && kind.scheme === scheme
|
|
646
|
+
)
|
|
647
|
+
);
|
|
648
|
+
const schemeOk = missingSchemeNetworks.length === 0;
|
|
649
|
+
checks.push({
|
|
650
|
+
name: `${scheme} scheme`,
|
|
651
|
+
ok: schemeOk,
|
|
652
|
+
detail: schemeOk ? networksForSchemes.length > 1 ? `The facilitator supports the ${scheme} scheme on all configured networks.` : `The facilitator supports the ${scheme} scheme on this network.` : `Configured routes use the ${scheme} scheme, which is not listed for: ${missingSchemeNetworks.join(", ")}.`
|
|
653
|
+
});
|
|
654
|
+
}
|
|
655
|
+
if (WELL_KNOWN_NETWORKS[network]) {
|
|
656
|
+
checks.push({
|
|
657
|
+
name: "known network",
|
|
658
|
+
ok: true,
|
|
659
|
+
detail: `${describeNetwork(network)} \u2014 widely deployed, safe for production.`
|
|
660
|
+
});
|
|
661
|
+
} else {
|
|
662
|
+
checks.push({
|
|
663
|
+
name: "known network",
|
|
664
|
+
ok: true,
|
|
665
|
+
detail: `${network} is not in the built-in list. That is fine if you intended it; verify token and facilitator support yourself.`
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
return finish(checks);
|
|
669
|
+
}
|
|
670
|
+
function isFacilitatorHeadersConfigError(error) {
|
|
671
|
+
return error instanceof ConfigError && error.field === "facilitatorHeaders";
|
|
672
|
+
}
|
|
673
|
+
function checkFacilitatorHeadersOk(config) {
|
|
674
|
+
if (!config.facilitatorHeaders) {
|
|
675
|
+
return {
|
|
676
|
+
name: "facilitatorHeaders",
|
|
677
|
+
ok: true,
|
|
678
|
+
detail: "No facilitatorHeaders set (public facilitator or X402_FACILITATOR_TOKEN unset)."
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
return {
|
|
682
|
+
name: "facilitatorHeaders",
|
|
683
|
+
ok: true,
|
|
684
|
+
detail: "facilitatorHeaders use the per-path shape (verify/settle/supported), not a flat object."
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
function checkPayToShape(payTo, network) {
|
|
688
|
+
const namespace = network.slice(0, network.indexOf(":"));
|
|
689
|
+
if (namespace === "eip155") {
|
|
690
|
+
const ok = /^0x[0-9a-fA-F]{40}$/.test(payTo);
|
|
691
|
+
return {
|
|
692
|
+
name: "payTo address",
|
|
693
|
+
ok,
|
|
694
|
+
detail: ok ? `${payTo} looks like an EVM address.` : `"${payTo}" is not a 0x-prefixed 20-byte address, which ${describeNetwork(network)} requires.`
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
if (namespace === "solana") {
|
|
698
|
+
const ok = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(payTo);
|
|
699
|
+
return {
|
|
700
|
+
name: "payTo address",
|
|
701
|
+
ok,
|
|
702
|
+
detail: ok ? `${payTo} looks like a base58 Solana address.` : `"${payTo}" is not a base58 public key, which ${describeNetwork(network)} requires.`
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
return {
|
|
706
|
+
name: "payTo address",
|
|
707
|
+
ok: payTo.length > 0,
|
|
708
|
+
detail: `No format check available for namespace "${namespace}". Confirm the address format with the network's tooling.`
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
function finish(checks) {
|
|
712
|
+
const failed = checks.filter((check) => !check.ok);
|
|
713
|
+
const lines = checks.map((check) => `${check.ok ? "ok " : "FAIL"} ${check.name}: ${check.detail}`);
|
|
714
|
+
const summary = failed.length === 0 ? "\nAll checks passed." : `
|
|
715
|
+
${failed.length} check(s) failed. Fix the FAIL lines above; every one of them prevents real payments.`;
|
|
716
|
+
return {
|
|
717
|
+
checks,
|
|
718
|
+
exitCode: failed.length === 0 ? 0 : 1,
|
|
719
|
+
text: [...lines, summary].join("\n")
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
// src/commands/inspect.ts
|
|
724
|
+
import {
|
|
725
|
+
checkCors,
|
|
726
|
+
describeNetwork as describeNetwork2,
|
|
727
|
+
diagnose as diagnose2,
|
|
728
|
+
formatFindings as formatFindings2,
|
|
729
|
+
validatePaymentRequired
|
|
730
|
+
} from "@x402-lens/core";
|
|
731
|
+
import { decodePaymentRequiredHeader } from "@x402/core/http";
|
|
732
|
+
async function inspectEndpoint(options) {
|
|
733
|
+
const method = options.method ?? "GET";
|
|
734
|
+
const response = await fetch(options.url, {
|
|
735
|
+
method,
|
|
736
|
+
headers: {
|
|
737
|
+
Accept: "application/json",
|
|
738
|
+
"User-Agent": "x402-lens/0.2",
|
|
739
|
+
...options.headers
|
|
740
|
+
},
|
|
741
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 15e3),
|
|
742
|
+
// Do not follow redirects away from a 402 paywall.
|
|
743
|
+
redirect: "manual"
|
|
744
|
+
});
|
|
745
|
+
const headerValue = response.headers.get("payment-required");
|
|
746
|
+
let paymentRequired;
|
|
747
|
+
let decodedFromBody = false;
|
|
748
|
+
let headerPresent = false;
|
|
749
|
+
if (headerValue) {
|
|
750
|
+
headerPresent = true;
|
|
751
|
+
try {
|
|
752
|
+
paymentRequired = decodePaymentRequiredHeader(headerValue);
|
|
753
|
+
} catch {
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
if (!paymentRequired) {
|
|
757
|
+
const text = await response.text().catch(() => "");
|
|
758
|
+
const fromBody = extractChallengeFromBody(text);
|
|
759
|
+
if (fromBody) {
|
|
760
|
+
paymentRequired = fromBody;
|
|
761
|
+
decodedFromBody = true;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
const headerRecord = {};
|
|
765
|
+
response.headers.forEach((value, key) => {
|
|
766
|
+
headerRecord[key.toLowerCase()] = value;
|
|
767
|
+
});
|
|
768
|
+
const cors = checkCors(headerRecord);
|
|
769
|
+
const conformance = paymentRequired ? validatePaymentRequired(paymentRequired) : [];
|
|
770
|
+
const findingsList = paymentRequired ? diagnose2({ paymentRequired }) : [];
|
|
771
|
+
const lines = [];
|
|
772
|
+
lines.push(`${method} ${options.url} \u2192 HTTP ${response.status}`);
|
|
773
|
+
if (!paymentRequired) {
|
|
774
|
+
lines.push("");
|
|
775
|
+
if (response.status >= 300 && response.status < 400) {
|
|
776
|
+
const location = response.headers.get("location") ?? "(no Location header)";
|
|
777
|
+
lines.push(
|
|
778
|
+
`Redirected (HTTP ${response.status}) to ${location}. inspect does not follow redirects, so a reverse proxy can hide a 402 paywall behind a 3xx.`
|
|
779
|
+
);
|
|
780
|
+
lines.push(
|
|
781
|
+
"Point inspect at the final paywall URL, or stop the redirect for this path."
|
|
782
|
+
);
|
|
783
|
+
} else {
|
|
784
|
+
lines.push(
|
|
785
|
+
"No x402 challenge found. Expected a PAYMENT-REQUIRED header (base64 PaymentRequired) on a 402 response."
|
|
786
|
+
);
|
|
787
|
+
lines.push(
|
|
788
|
+
"If this route is unprotected, you will see its normal response instead. If it is protected, check that paymentMiddleware is mounted before the route."
|
|
789
|
+
);
|
|
790
|
+
}
|
|
791
|
+
} else {
|
|
792
|
+
lines.push(
|
|
793
|
+
headerPresent ? "Challenge: PAYMENT-REQUIRED header" : "Challenge: response body (no PAYMENT-REQUIRED header)"
|
|
794
|
+
);
|
|
795
|
+
lines.push(describeChallenge(paymentRequired));
|
|
796
|
+
}
|
|
797
|
+
if (conformance.length > 0) {
|
|
798
|
+
lines.push("");
|
|
799
|
+
lines.push("Schema conformance:");
|
|
800
|
+
for (const issue of conformance) {
|
|
801
|
+
lines.push(` [error] ${issue.field}: ${issue.problem}`);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
if (cors.issues.length > 0) {
|
|
805
|
+
lines.push("");
|
|
806
|
+
lines.push("Browser (CORS):");
|
|
807
|
+
for (const issue of cors.issues) {
|
|
808
|
+
lines.push(` [error] ${issue.field}: ${issue.problem}`);
|
|
809
|
+
}
|
|
810
|
+
} else if (paymentRequired) {
|
|
811
|
+
lines.push("");
|
|
812
|
+
lines.push("Browser (CORS): PAYMENT-REQUIRED, PAYMENT-RESPONSE exposed; PAYMENT-SIGNATURE allowed.");
|
|
813
|
+
}
|
|
814
|
+
if (findingsList.length > 0) {
|
|
815
|
+
lines.push("");
|
|
816
|
+
lines.push(formatFindings2(findingsList));
|
|
817
|
+
}
|
|
818
|
+
const failed = !paymentRequired || conformance.length > 0 || cors.issues.length > 0;
|
|
819
|
+
return {
|
|
820
|
+
status: response.status,
|
|
821
|
+
...paymentRequired ? { paymentRequired } : {},
|
|
822
|
+
headerPresent,
|
|
823
|
+
decodedFromBody,
|
|
824
|
+
conformance,
|
|
825
|
+
cors,
|
|
826
|
+
findings: lines.join("\n"),
|
|
827
|
+
exitCode: failed ? 1 : 0
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
function describeChallenge(paymentRequired) {
|
|
831
|
+
const lines = [`x402Version: ${String(paymentRequired.x402Version)}`];
|
|
832
|
+
if (paymentRequired.resource?.url) {
|
|
833
|
+
lines.push(`resource: ${paymentRequired.resource.url}`);
|
|
834
|
+
}
|
|
835
|
+
if (paymentRequired.error) {
|
|
836
|
+
lines.push(`error: ${paymentRequired.error}`);
|
|
837
|
+
}
|
|
838
|
+
const accepts = paymentRequired.accepts ?? [];
|
|
839
|
+
lines.push(`accepts: ${accepts.length}`);
|
|
840
|
+
accepts.forEach((entry, index) => {
|
|
841
|
+
lines.push(
|
|
842
|
+
` [${index}] ${entry.scheme} on ${describeNetwork2(entry.network)}`,
|
|
843
|
+
` amount: ${entry.amount} (atomic units)`,
|
|
844
|
+
` asset: ${entry.asset}`,
|
|
845
|
+
` payTo: ${entry.payTo}`,
|
|
846
|
+
` timeout: ${String(entry.maxTimeoutSeconds)}s`
|
|
847
|
+
);
|
|
848
|
+
});
|
|
849
|
+
if (accepts.length > 1) {
|
|
850
|
+
const amounts = new Set(accepts.map((entry) => entry.amount));
|
|
851
|
+
const assets = new Set(accepts.map((entry) => entry.asset));
|
|
852
|
+
lines.push(
|
|
853
|
+
` note: ${accepts.length} payment options \u2014 one per network. ${amounts.size === 1 ? "Amounts match across networks." : `Amounts differ by token decimals (${Array.from(amounts).join(", ")}).`}`
|
|
854
|
+
);
|
|
855
|
+
if (assets.size === 1) {
|
|
856
|
+
lines.push(
|
|
857
|
+
` note: Every option uses the same asset, which is only valid if that token exists on all of them.`
|
|
858
|
+
);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
return lines.join("\n");
|
|
862
|
+
}
|
|
863
|
+
function extractChallengeFromBody(text) {
|
|
864
|
+
if (!text) return void 0;
|
|
865
|
+
try {
|
|
866
|
+
const parsed = JSON.parse(text);
|
|
867
|
+
if (parsed && typeof parsed === "object" && parsed.x402Version === 2 && Array.isArray(parsed.accepts)) {
|
|
868
|
+
return parsed;
|
|
869
|
+
}
|
|
870
|
+
} catch {
|
|
871
|
+
return void 0;
|
|
872
|
+
}
|
|
873
|
+
return void 0;
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// src/commands/reconcile.ts
|
|
877
|
+
import { describeNetwork as describeNetwork3, isCaip2 as isCaip22, suggestCaip2 as suggestCaip22 } from "@x402-lens/core";
|
|
878
|
+
var DEFAULT_RPC = {
|
|
879
|
+
"eip155:1": "https://ethereum.publicnode.com",
|
|
880
|
+
"eip155:8453": "https://mainnet.base.org",
|
|
881
|
+
"eip155:84532": "https://sepolia.base.org",
|
|
882
|
+
"eip155:11155111": "https://ethereum-sepolia.publicnode.com",
|
|
883
|
+
"solana:5eykt4Usfv8P8NJdTREpY1vzqKqZKvdp": "https://api.mainnet-beta.solana.com",
|
|
884
|
+
"solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1": "https://api.devnet.solana.com"
|
|
885
|
+
};
|
|
886
|
+
async function reconcileTransaction(options) {
|
|
887
|
+
const tx = options.tx.trim();
|
|
888
|
+
if (!tx) {
|
|
889
|
+
return report({
|
|
890
|
+
status: "unknown",
|
|
891
|
+
network: options.network ?? "",
|
|
892
|
+
tx: "",
|
|
893
|
+
rpcUrl: "",
|
|
894
|
+
detail: "No transaction hash was provided.",
|
|
895
|
+
exitCode: 2
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
const network = options.network ?? "eip155:84532";
|
|
899
|
+
if (!isCaip22(network)) {
|
|
900
|
+
const suggestion = suggestCaip22(network);
|
|
901
|
+
return report({
|
|
902
|
+
status: "unknown",
|
|
903
|
+
network,
|
|
904
|
+
tx,
|
|
905
|
+
rpcUrl: "",
|
|
906
|
+
detail: suggestion ? `"${network}" is not CAIP-2. Use "${suggestion}".` : `"${network}" is not a CAIP-2 network id.`,
|
|
907
|
+
exitCode: 2
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
const rpcUrl = options.rpcUrl ?? DEFAULT_RPC[network];
|
|
911
|
+
if (!rpcUrl) {
|
|
912
|
+
return report({
|
|
913
|
+
status: "unknown",
|
|
914
|
+
network,
|
|
915
|
+
tx,
|
|
916
|
+
rpcUrl: "",
|
|
917
|
+
detail: `No default RPC for ${describeNetwork3(network)}. Pass --rpc <url>.`,
|
|
918
|
+
exitCode: 2
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
922
|
+
const timeoutMs = options.timeoutMs ?? 15e3;
|
|
923
|
+
const namespace = network.slice(0, network.indexOf(":"));
|
|
924
|
+
try {
|
|
925
|
+
if (namespace === "eip155") {
|
|
926
|
+
return await reconcileEvm({ tx, network, rpcUrl, fetchImpl, timeoutMs });
|
|
927
|
+
}
|
|
928
|
+
if (namespace === "solana") {
|
|
929
|
+
return await reconcileSolana({ tx, network, rpcUrl, fetchImpl, timeoutMs });
|
|
930
|
+
}
|
|
931
|
+
return report({
|
|
932
|
+
status: "unknown",
|
|
933
|
+
network,
|
|
934
|
+
tx,
|
|
935
|
+
rpcUrl,
|
|
936
|
+
detail: `Namespace "${namespace}" is not supported by reconcile. Use eip155:* or solana:*.`,
|
|
937
|
+
exitCode: 2
|
|
938
|
+
});
|
|
939
|
+
} catch (error) {
|
|
940
|
+
return report({
|
|
941
|
+
status: "unknown",
|
|
942
|
+
network,
|
|
943
|
+
tx,
|
|
944
|
+
rpcUrl,
|
|
945
|
+
detail: `RPC call failed: ${error.message}`,
|
|
946
|
+
exitCode: 1
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
async function reconcileEvm(input) {
|
|
951
|
+
const receipt = await rpc(input, "eth_getTransactionReceipt", [input.tx]);
|
|
952
|
+
if (receipt === null) {
|
|
953
|
+
const pending = await rpc(input, "eth_getTransactionByHash", [input.tx]);
|
|
954
|
+
if (pending && pending.hash) {
|
|
955
|
+
return report({
|
|
956
|
+
status: "pending",
|
|
957
|
+
network: input.network,
|
|
958
|
+
tx: input.tx,
|
|
959
|
+
rpcUrl: input.rpcUrl,
|
|
960
|
+
detail: "Transaction is in the mempool or not yet mined. Do not retry the payment.",
|
|
961
|
+
exitCode: 1
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
return report({
|
|
965
|
+
status: "not_found",
|
|
966
|
+
network: input.network,
|
|
967
|
+
tx: input.tx,
|
|
968
|
+
rpcUrl: input.rpcUrl,
|
|
969
|
+
detail: "No transaction with this hash on this network. The settle may never have broadcast.",
|
|
970
|
+
exitCode: 1
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
const statusHex = receipt.status ?? "0x0";
|
|
974
|
+
const confirmed = statusHex === "0x1" || statusHex === "1";
|
|
975
|
+
const block = receipt.blockNumber ? String(Number.parseInt(receipt.blockNumber, 16)) : void 0;
|
|
976
|
+
if (confirmed) {
|
|
977
|
+
return report({
|
|
978
|
+
status: "confirmed",
|
|
979
|
+
network: input.network,
|
|
980
|
+
tx: input.tx,
|
|
981
|
+
rpcUrl: input.rpcUrl,
|
|
982
|
+
...block ? { block } : {},
|
|
983
|
+
detail: `Receipt status success${block ? ` in block ${block}` : ""}. Settlement landed; do not charge the buyer again.`,
|
|
984
|
+
exitCode: 0
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
return report({
|
|
988
|
+
status: "failed",
|
|
989
|
+
network: input.network,
|
|
990
|
+
tx: input.tx,
|
|
991
|
+
rpcUrl: input.rpcUrl,
|
|
992
|
+
...block ? { block } : {},
|
|
993
|
+
detail: `Receipt status failed${block ? ` in block ${block}` : ""}. Funds did not move; a fresh payment is safe after investigation.`,
|
|
994
|
+
exitCode: 1
|
|
995
|
+
});
|
|
996
|
+
}
|
|
997
|
+
async function reconcileSolana(input) {
|
|
998
|
+
const value = await rpc(input, "getTransaction", [
|
|
999
|
+
input.tx,
|
|
1000
|
+
{ encoding: "json", maxSupportedTransactionVersion: 0 }
|
|
1001
|
+
]);
|
|
1002
|
+
if (value === null) {
|
|
1003
|
+
return report({
|
|
1004
|
+
status: "not_found",
|
|
1005
|
+
network: input.network,
|
|
1006
|
+
tx: input.tx,
|
|
1007
|
+
rpcUrl: input.rpcUrl,
|
|
1008
|
+
detail: "Signature not found on this cluster. It may still be propagating, or it never landed.",
|
|
1009
|
+
exitCode: 1
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
const err = value.meta?.err;
|
|
1013
|
+
const slot = value.slot !== void 0 ? String(value.slot) : void 0;
|
|
1014
|
+
if (err == null) {
|
|
1015
|
+
return report({
|
|
1016
|
+
status: "confirmed",
|
|
1017
|
+
network: input.network,
|
|
1018
|
+
tx: input.tx,
|
|
1019
|
+
rpcUrl: input.rpcUrl,
|
|
1020
|
+
...slot ? { block: slot } : {},
|
|
1021
|
+
detail: `Transaction confirmed${slot ? ` at slot ${slot}` : ""}. Settlement landed; do not charge the buyer again.`,
|
|
1022
|
+
exitCode: 0
|
|
1023
|
+
});
|
|
1024
|
+
}
|
|
1025
|
+
return report({
|
|
1026
|
+
status: "failed",
|
|
1027
|
+
network: input.network,
|
|
1028
|
+
tx: input.tx,
|
|
1029
|
+
rpcUrl: input.rpcUrl,
|
|
1030
|
+
...slot ? { block: slot } : {},
|
|
1031
|
+
detail: `Transaction failed on chain${slot ? ` at slot ${slot}` : ""}: ${JSON.stringify(err)}.`,
|
|
1032
|
+
exitCode: 1
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
async function rpc(input, method, params) {
|
|
1036
|
+
const controller = new AbortController();
|
|
1037
|
+
const timer = setTimeout(() => controller.abort(), input.timeoutMs);
|
|
1038
|
+
try {
|
|
1039
|
+
const response = await input.fetchImpl(input.rpcUrl, {
|
|
1040
|
+
method: "POST",
|
|
1041
|
+
headers: { "content-type": "application/json" },
|
|
1042
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
|
|
1043
|
+
signal: controller.signal
|
|
1044
|
+
});
|
|
1045
|
+
if (!response.ok) {
|
|
1046
|
+
throw new Error(`HTTP ${response.status}`);
|
|
1047
|
+
}
|
|
1048
|
+
const body = await response.json();
|
|
1049
|
+
if (body.error) {
|
|
1050
|
+
throw new Error(body.error.message ?? "RPC error");
|
|
1051
|
+
}
|
|
1052
|
+
return body.result;
|
|
1053
|
+
} finally {
|
|
1054
|
+
clearTimeout(timer);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
function report(result) {
|
|
1058
|
+
const lines = [
|
|
1059
|
+
`tx: ${result.tx || "(none)"}`,
|
|
1060
|
+
`network: ${result.network ? describeNetwork3(result.network) : "(none)"}`,
|
|
1061
|
+
`rpc: ${result.rpcUrl || "(none)"}`,
|
|
1062
|
+
`status: ${result.status}`,
|
|
1063
|
+
...result.block ? [`block: ${result.block}`] : [],
|
|
1064
|
+
"",
|
|
1065
|
+
result.detail
|
|
1066
|
+
];
|
|
1067
|
+
return { ...result, text: lines.join("\n") };
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
// src/args.ts
|
|
1071
|
+
function parseArgs(argv) {
|
|
1072
|
+
const flags = {};
|
|
1073
|
+
const positionals = [];
|
|
1074
|
+
let command;
|
|
1075
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
1076
|
+
const token = argv[index];
|
|
1077
|
+
if (token === void 0) continue;
|
|
1078
|
+
if (token.startsWith("--")) {
|
|
1079
|
+
const withoutDashes = token.slice(2);
|
|
1080
|
+
if (withoutDashes.length === 0) continue;
|
|
1081
|
+
const equalsIndex = withoutDashes.indexOf("=");
|
|
1082
|
+
if (equalsIndex !== -1) {
|
|
1083
|
+
flags[withoutDashes.slice(0, equalsIndex)] = withoutDashes.slice(equalsIndex + 1);
|
|
1084
|
+
continue;
|
|
1085
|
+
}
|
|
1086
|
+
const next = argv[index + 1];
|
|
1087
|
+
if (next !== void 0 && !next.startsWith("--")) {
|
|
1088
|
+
flags[withoutDashes] = next;
|
|
1089
|
+
index += 1;
|
|
1090
|
+
} else {
|
|
1091
|
+
flags[withoutDashes] = true;
|
|
1092
|
+
}
|
|
1093
|
+
continue;
|
|
1094
|
+
}
|
|
1095
|
+
if (token.startsWith("-") && token.length > 1) {
|
|
1096
|
+
flags[token.slice(1)] = true;
|
|
1097
|
+
continue;
|
|
1098
|
+
}
|
|
1099
|
+
if (command === void 0) {
|
|
1100
|
+
command = token;
|
|
1101
|
+
continue;
|
|
1102
|
+
}
|
|
1103
|
+
positionals.push(token);
|
|
1104
|
+
}
|
|
1105
|
+
return { command, positionals, flags };
|
|
1106
|
+
}
|
|
1107
|
+
function flagValue(args, name) {
|
|
1108
|
+
const value = args.flags[name];
|
|
1109
|
+
return typeof value === "string" ? value : void 0;
|
|
1110
|
+
}
|
|
1111
|
+
function flagEnabled(args, name) {
|
|
1112
|
+
return args.flags[name] !== void 0;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
// src/index.ts
|
|
1116
|
+
var USAGE = `x402-lens \u2014 explain and verify x402 v2 payments
|
|
1117
|
+
|
|
1118
|
+
Usage:
|
|
1119
|
+
x402-lens inspect <url> [--method GET] [--header "K: V"] [--timeout 15000] [--json]
|
|
1120
|
+
Fetch an endpoint unpaid, decode PAYMENT-REQUIRED, and report schema
|
|
1121
|
+
conformance and CORS readiness for browser buyers.
|
|
1122
|
+
|
|
1123
|
+
x402-lens explain [--challenge <b64|json|@file>] [--payment <...>]
|
|
1124
|
+
[--verify <...>] [--settle <...>] [--json]
|
|
1125
|
+
Diagnose a failed exchange: what is wrong, and what to change.
|
|
1126
|
+
|
|
1127
|
+
x402-lens doctor [--facilitator <url>] [--network <caip2>] [--networks <a,b>] [--json]
|
|
1128
|
+
Verify that configuration can actually accept payments, including that
|
|
1129
|
+
the facilitator supports every configured network with x402Version 2.
|
|
1130
|
+
|
|
1131
|
+
x402-lens reconcile --tx <hash> [--network <caip2>] [--rpc <url>] [--json]
|
|
1132
|
+
Check whether a settlement transaction confirmed on chain. Use this
|
|
1133
|
+
after settlement_pending \u2014 never retry a payment until you know.
|
|
1134
|
+
|
|
1135
|
+
x402-lens add "<METHOD> <path>" --file <path> --price <amount> [--write]
|
|
1136
|
+
Add x402 protection to an existing Express route. Prints a diff unless
|
|
1137
|
+
--write is passed.
|
|
1138
|
+
|
|
1139
|
+
Options:
|
|
1140
|
+
--json Machine-readable JSON on stdout (inspect / explain / doctor / reconcile)
|
|
1141
|
+
--help, -h Show this help.
|
|
1142
|
+
|
|
1143
|
+
Exit codes:
|
|
1144
|
+
0 success
|
|
1145
|
+
1 a check failed or a finding is an error
|
|
1146
|
+
2 bad usage
|
|
1147
|
+
`;
|
|
1148
|
+
async function main(argv) {
|
|
1149
|
+
const args = parseArgs(argv);
|
|
1150
|
+
const asJson = flagEnabled(args, "json");
|
|
1151
|
+
if (flagEnabled(args, "help") || flagEnabled(args, "h") || args.command === void 0) {
|
|
1152
|
+
process.stdout.write(USAGE);
|
|
1153
|
+
return args.command === void 0 && !flagEnabled(args, "help") && !flagEnabled(args, "h") ? 2 : 0;
|
|
1154
|
+
}
|
|
1155
|
+
try {
|
|
1156
|
+
switch (args.command) {
|
|
1157
|
+
case "inspect": {
|
|
1158
|
+
const url = args.positionals[0];
|
|
1159
|
+
if (!url) {
|
|
1160
|
+
process.stderr.write("inspect requires a URL.\n\n" + USAGE);
|
|
1161
|
+
return 2;
|
|
1162
|
+
}
|
|
1163
|
+
const result = await inspectEndpoint({
|
|
1164
|
+
url,
|
|
1165
|
+
...flagValue(args, "method") ? { method: flagValue(args, "method") } : {},
|
|
1166
|
+
...flagValue(args, "header") ? { headers: parseHeaderFlags(argv) } : {},
|
|
1167
|
+
...flagValue(args, "timeout") ? { timeoutMs: Number.parseInt(flagValue(args, "timeout"), 10) } : {}
|
|
1168
|
+
});
|
|
1169
|
+
if (asJson) {
|
|
1170
|
+
process.stdout.write(
|
|
1171
|
+
`${JSON.stringify(
|
|
1172
|
+
{
|
|
1173
|
+
status: result.status,
|
|
1174
|
+
headerPresent: result.headerPresent,
|
|
1175
|
+
decodedFromBody: result.decodedFromBody,
|
|
1176
|
+
paymentRequired: result.paymentRequired ?? null,
|
|
1177
|
+
conformance: result.conformance,
|
|
1178
|
+
cors: result.cors,
|
|
1179
|
+
exitCode: result.exitCode
|
|
1180
|
+
},
|
|
1181
|
+
null,
|
|
1182
|
+
2
|
|
1183
|
+
)}
|
|
1184
|
+
`
|
|
1185
|
+
);
|
|
1186
|
+
} else {
|
|
1187
|
+
process.stdout.write(`${result.findings}
|
|
1188
|
+
`);
|
|
1189
|
+
}
|
|
1190
|
+
return result.exitCode;
|
|
1191
|
+
}
|
|
1192
|
+
case "explain": {
|
|
1193
|
+
const result = await explainPayment({
|
|
1194
|
+
...flagValue(args, "challenge") ? { challenge: flagValue(args, "challenge") } : {},
|
|
1195
|
+
...flagValue(args, "payment") ? { payment: flagValue(args, "payment") } : {},
|
|
1196
|
+
...flagValue(args, "verify") ? { verify: flagValue(args, "verify") } : {},
|
|
1197
|
+
...flagValue(args, "settle") ? { settle: flagValue(args, "settle") } : {}
|
|
1198
|
+
});
|
|
1199
|
+
if (asJson) {
|
|
1200
|
+
process.stdout.write(
|
|
1201
|
+
`${JSON.stringify(
|
|
1202
|
+
{
|
|
1203
|
+
findings: result.findings,
|
|
1204
|
+
findingCount: result.findingCount,
|
|
1205
|
+
exitCode: result.exitCode
|
|
1206
|
+
},
|
|
1207
|
+
null,
|
|
1208
|
+
2
|
|
1209
|
+
)}
|
|
1210
|
+
`
|
|
1211
|
+
);
|
|
1212
|
+
} else {
|
|
1213
|
+
process.stdout.write(`${result.text}
|
|
1214
|
+
`);
|
|
1215
|
+
}
|
|
1216
|
+
return result.exitCode;
|
|
1217
|
+
}
|
|
1218
|
+
case "doctor": {
|
|
1219
|
+
const networksFlag = flagValue(args, "networks");
|
|
1220
|
+
const result = await runDoctor({
|
|
1221
|
+
...flagValue(args, "facilitator") ? { facilitatorUrl: flagValue(args, "facilitator") } : {},
|
|
1222
|
+
...flagValue(args, "network") ? { network: flagValue(args, "network") } : {},
|
|
1223
|
+
...networksFlag ? {
|
|
1224
|
+
networks: networksFlag.split(",").map((part) => part.trim()).filter(Boolean)
|
|
1225
|
+
} : {}
|
|
1226
|
+
});
|
|
1227
|
+
if (asJson) {
|
|
1228
|
+
process.stdout.write(
|
|
1229
|
+
`${JSON.stringify(
|
|
1230
|
+
{
|
|
1231
|
+
checks: result.checks,
|
|
1232
|
+
exitCode: result.exitCode
|
|
1233
|
+
},
|
|
1234
|
+
null,
|
|
1235
|
+
2
|
|
1236
|
+
)}
|
|
1237
|
+
`
|
|
1238
|
+
);
|
|
1239
|
+
} else {
|
|
1240
|
+
process.stdout.write(`${result.text}
|
|
1241
|
+
`);
|
|
1242
|
+
}
|
|
1243
|
+
return result.exitCode;
|
|
1244
|
+
}
|
|
1245
|
+
case "add": {
|
|
1246
|
+
const route = args.positionals[0];
|
|
1247
|
+
const file = flagValue(args, "file");
|
|
1248
|
+
const price = flagValue(args, "price");
|
|
1249
|
+
if (!route || !file || !price) {
|
|
1250
|
+
process.stderr.write(
|
|
1251
|
+
'add requires a route, --file, and --price. Example:\n x402-lens add "GET /weather" --file src/server.ts --price 0.001\n'
|
|
1252
|
+
);
|
|
1253
|
+
return 2;
|
|
1254
|
+
}
|
|
1255
|
+
const result = await addProtection({
|
|
1256
|
+
file,
|
|
1257
|
+
route,
|
|
1258
|
+
price,
|
|
1259
|
+
write: flagEnabled(args, "write")
|
|
1260
|
+
});
|
|
1261
|
+
process.stdout.write(`${result.text}
|
|
1262
|
+
`);
|
|
1263
|
+
return result.exitCode;
|
|
1264
|
+
}
|
|
1265
|
+
case "reconcile": {
|
|
1266
|
+
const tx = flagValue(args, "tx") ?? args.positionals[0];
|
|
1267
|
+
if (!tx) {
|
|
1268
|
+
process.stderr.write(
|
|
1269
|
+
"reconcile requires --tx <hash>. Example:\n x402-lens reconcile --tx 0xabc\u2026 --network eip155:84532\n"
|
|
1270
|
+
);
|
|
1271
|
+
return 2;
|
|
1272
|
+
}
|
|
1273
|
+
const result = await reconcileTransaction({
|
|
1274
|
+
tx,
|
|
1275
|
+
...flagValue(args, "network") ? { network: flagValue(args, "network") } : {},
|
|
1276
|
+
...flagValue(args, "rpc") ? { rpcUrl: flagValue(args, "rpc") } : {},
|
|
1277
|
+
...flagValue(args, "timeout") ? { timeoutMs: Number.parseInt(flagValue(args, "timeout"), 10) } : {}
|
|
1278
|
+
});
|
|
1279
|
+
if (asJson) {
|
|
1280
|
+
process.stdout.write(
|
|
1281
|
+
`${JSON.stringify(
|
|
1282
|
+
{
|
|
1283
|
+
status: result.status,
|
|
1284
|
+
network: result.network,
|
|
1285
|
+
tx: result.tx,
|
|
1286
|
+
rpcUrl: result.rpcUrl,
|
|
1287
|
+
block: result.block ?? null,
|
|
1288
|
+
detail: result.detail,
|
|
1289
|
+
exitCode: result.exitCode
|
|
1290
|
+
},
|
|
1291
|
+
null,
|
|
1292
|
+
2
|
|
1293
|
+
)}
|
|
1294
|
+
`
|
|
1295
|
+
);
|
|
1296
|
+
} else {
|
|
1297
|
+
process.stdout.write(`${result.text}
|
|
1298
|
+
`);
|
|
1299
|
+
}
|
|
1300
|
+
return result.exitCode;
|
|
1301
|
+
}
|
|
1302
|
+
default:
|
|
1303
|
+
process.stderr.write(`Unknown command "${args.command}".
|
|
1304
|
+
|
|
1305
|
+
${USAGE}`);
|
|
1306
|
+
return 2;
|
|
1307
|
+
}
|
|
1308
|
+
} catch (error) {
|
|
1309
|
+
if (error instanceof InputError || error instanceof AddError) {
|
|
1310
|
+
process.stderr.write(`${error.message}
|
|
1311
|
+
`);
|
|
1312
|
+
return 2;
|
|
1313
|
+
}
|
|
1314
|
+
process.stderr.write(`${error.message}
|
|
1315
|
+
`);
|
|
1316
|
+
return 1;
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
function parseHeaderFlags(argv) {
|
|
1320
|
+
const headers = {};
|
|
1321
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
1322
|
+
if (argv[index] !== "--header") continue;
|
|
1323
|
+
const value = argv[index + 1];
|
|
1324
|
+
if (!value) continue;
|
|
1325
|
+
const separator = value.indexOf(":");
|
|
1326
|
+
if (separator === -1) continue;
|
|
1327
|
+
headers[value.slice(0, separator).trim()] = value.slice(separator + 1).trim();
|
|
1328
|
+
index += 1;
|
|
1329
|
+
}
|
|
1330
|
+
return headers;
|
|
1331
|
+
}
|
|
1332
|
+
var isDirectRun = process.argv[1] !== void 0 && (process.argv[1].endsWith("x402-lens") || process.argv[1].endsWith("index.js"));
|
|
1333
|
+
if (isDirectRun) {
|
|
1334
|
+
main(process.argv.slice(2)).then((code) => {
|
|
1335
|
+
process.exitCode = code;
|
|
1336
|
+
}).catch((error) => {
|
|
1337
|
+
process.stderr.write(`Unexpected error: ${error.message}
|
|
1338
|
+
`);
|
|
1339
|
+
process.exitCode = 1;
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
export {
|
|
1343
|
+
main
|
|
1344
|
+
};
|
|
1345
|
+
//# sourceMappingURL=index.js.map
|