openany-cli-dev 0.0.0-stage → 0.1.1

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 (80) hide show
  1. package/README.md +472 -2
  2. package/bin/openany.js +3 -0
  3. package/package.json +27 -4
  4. package/skills/openany/SKILL.md +353 -0
  5. package/skills/openany/SKILL.zh-CN.md +496 -0
  6. package/skills/openany-provider/SKILL.md +26 -0
  7. package/skills/openany-provider/SKILL.zh-CN.md +26 -0
  8. package/skills/openany-provider/references/apis.md +60 -0
  9. package/skills/openany-provider/references/apis.zh-CN.md +55 -0
  10. package/skills/openany-provider/references/application.md +49 -0
  11. package/skills/openany-provider/references/application.zh-CN.md +51 -0
  12. package/skills/openany-provider/references/auth.md +3 -0
  13. package/skills/openany-provider/references/auth.zh-CN.md +3 -0
  14. package/skills/openany-provider/references/connections.md +36 -0
  15. package/skills/openany-provider/references/connections.zh-CN.md +36 -0
  16. package/skills/openany-provider/references/imports.md +57 -0
  17. package/skills/openany-provider/references/imports.zh-CN.md +57 -0
  18. package/skills/openany-provider/references/listing.md +29 -0
  19. package/skills/openany-provider/references/listing.zh-CN.md +11 -0
  20. package/skills/openany-provider/references/login.md +57 -0
  21. package/skills/openany-provider/references/login.zh-CN.md +57 -0
  22. package/skills/openany-provider/references/model-import.md +11 -0
  23. package/skills/openany-provider/references/model-import.zh-CN.md +11 -0
  24. package/skills/openany-provider/references/models.md +107 -0
  25. package/skills/openany-provider/references/models.zh-CN.md +68 -0
  26. package/skills/openany-provider/references/publishing.md +40 -0
  27. package/skills/openany-provider/references/publishing.zh-CN.md +40 -0
  28. package/skills/openany-provider/references/reviews.md +22 -0
  29. package/skills/openany-provider/references/reviews.zh-CN.md +20 -0
  30. package/skills/openany-provider/templates/api-metadata.json +27 -0
  31. package/skills/openany-provider/templates/bindings.json +1 -0
  32. package/skills/openany-provider/templates/models-v2.json +545 -0
  33. package/skills/openany-provider/templates/models.json +10 -0
  34. package/skills/openany-provider/templates/provider-agent-api-template.json +697 -0
  35. package/skills/openany-provider/templates/seller-agent-api-import-template.json +822 -0
  36. package/skills/openany-provider/templates/seller-registration.json +26 -0
  37. package/src/auth-recovery.js +179 -0
  38. package/src/auth.js +1001 -0
  39. package/src/catalog.js +306 -0
  40. package/src/cli.js +605 -0
  41. package/src/config.js +260 -0
  42. package/src/errors.js +53 -0
  43. package/src/http.js +238 -0
  44. package/src/model-curl.js +359 -0
  45. package/src/model-materials.js +58 -0
  46. package/src/model-request.js +402 -0
  47. package/src/model-validation.js +56 -0
  48. package/src/models.js +188 -0
  49. package/src/native/config-acl.ps1 +34 -0
  50. package/src/native/connection-macos.js +109 -0
  51. package/src/native/connection-windows.ps1 +98 -0
  52. package/src/native/setup-macos.js +72 -0
  53. package/src/native/setup-windows.ps1 +83 -0
  54. package/src/native-prompt.js +85 -0
  55. package/src/payment-signing.js +362 -0
  56. package/src/prompt.js +69 -0
  57. package/src/provider-api-import-v2.js +72 -0
  58. package/src/provider-apis.js +3 -0
  59. package/src/provider-client.js +153 -0
  60. package/src/provider-connections.js +152 -0
  61. package/src/provider-import-format.js +289 -0
  62. package/src/provider-imports.js +402 -0
  63. package/src/provider-json.js +49 -0
  64. package/src/provider-model-import-v2.js +61 -0
  65. package/src/provider-models.js +253 -0
  66. package/src/provider-profile.js +65 -0
  67. package/src/provider-reviews.js +61 -0
  68. package/src/provider-state.js +176 -0
  69. package/src/provider.js +75 -0
  70. package/src/setup.js +201 -0
  71. package/src/tasks.js +53 -0
  72. package/src/topups.js +845 -0
  73. package/src/vendor/provider-apply/market-taxonomy.mjs +22 -0
  74. package/src/vendor/provider-apply/provenance.json +8 -0
  75. package/src/vendor/provider-apply/registration.mjs +151 -0
  76. package/src/vendor/provider-import/api-categories.json +29 -0
  77. package/src/vendor/provider-import/api-fields.json +33 -0
  78. package/src/vendor/provider-import/model-fields.json +44 -0
  79. package/src/wallet.js +213 -0
  80. package/src/windows-permissions.js +22 -0
@@ -0,0 +1,362 @@
1
+ import { randomBytes, createPublicKey, verify } from "node:crypto";
2
+ import { verifyTypedData } from "ethers";
3
+ import {
4
+ ComputeBudgetProgram,
5
+ PublicKey,
6
+ TransactionInstruction,
7
+ TransactionMessage,
8
+ VersionedTransaction,
9
+ } from "@solana/web3.js";
10
+ import { CLIError } from "./errors.js";
11
+ import { isEVM, sameWallet, normalizeWallet } from "./wallet.js";
12
+ export const BASE_NETWORK = "eip155:8453";
13
+ export const SOLANA_NETWORK = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
14
+ const BASE_USDC = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
15
+ const SOLANA_USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
16
+ const fail = () => {
17
+ throw new CLIError(
18
+ "PAYMENT_INVALID",
19
+ "The order, amount, recipient, network or signing payload does not match the authorization; no payment was made.",
20
+ );
21
+ };
22
+ export function integer(value) {
23
+ if (typeof value === "number" && !Number.isSafeInteger(value)) return fail();
24
+ if (!/^(0|[1-9][0-9]*)$/.test(String(value))) return fail();
25
+ return BigInt(value);
26
+ }
27
+ function validateOrder(
28
+ order,
29
+ { identity, network, walletAddress, now = Date.now(), signingOrigin },
30
+ ) {
31
+ try {
32
+ const required = order.paymentRequired;
33
+ const candidates = required?.accepts?.filter((r) => r.network === network);
34
+ if (
35
+ required?.x402Version !== 2 ||
36
+ candidates?.length !== 1 ||
37
+ !["wallet", "email"].includes(identity)
38
+ )
39
+ return fail();
40
+ const r = candidates[0],
41
+ q = order.quote;
42
+ const path =
43
+ identity === "wallet"
44
+ ? "/api/v1/agent-topups"
45
+ : `/api/v1/key-market/x402/topups/${order.orderId}/pay`;
46
+ if (
47
+ required.resource?.url !== signingOrigin + path ||
48
+ order.paymentStatus !== "created" ||
49
+ order.creditStatus !== "uncredited" ||
50
+ !sameWallet(order.walletAddress, walletAddress) ||
51
+ !Number.isFinite(Date.parse(order.paymentExpiresAt)) ||
52
+ Date.parse(order.paymentExpiresAt) <= now + 10000 ||
53
+ r.scheme !== "exact" ||
54
+ !Number.isSafeInteger(r.maxTimeoutSeconds) ||
55
+ r.maxTimeoutSeconds <= 10
56
+ )
57
+ return fail();
58
+ if (
59
+ integer(q.inputAmountMicroUsd) <= 0n ||
60
+ integer(q.creditAmountMicroUsd) <= 0n ||
61
+ integer(q.payAmountMicroUsd) !==
62
+ integer(q.creditAmountMicroUsd) + integer(q.feeAmountMicroUsd)
63
+ )
64
+ return fail();
65
+ if (identity === "email") {
66
+ if (
67
+ order.network !== network ||
68
+ required.accepts.length !== 1 ||
69
+ r.amount !== String(q.payAmountMicroUsd)
70
+ )
71
+ return fail();
72
+ if (network === BASE_NETWORK) {
73
+ if (
74
+ r.asset.toLowerCase() !== BASE_USDC ||
75
+ r.extra?.name !== "USD Coin" ||
76
+ r.extra.version !== "2"
77
+ )
78
+ return fail();
79
+ } else if (network === SOLANA_NETWORK) {
80
+ if (
81
+ r.asset !== SOLANA_USDC ||
82
+ r.extra?.feePayer === walletAddress ||
83
+ r.extra?.memo !== `customer-x402:${order.orderId}`
84
+ )
85
+ return fail();
86
+ new PublicKey(r.payTo);
87
+ new PublicKey(r.extra.feePayer);
88
+ } else return fail();
89
+ } else {
90
+ if (!/^eip155:[1-9][0-9]*$/.test(network)) return fail();
91
+ const options = order.availableNetworks?.filter(
92
+ (o) => o.network === network,
93
+ );
94
+ if (options?.length !== 1) return fail();
95
+ const option = options[0];
96
+ if (
97
+ !Number.isSafeInteger(option.assetDecimals) ||
98
+ option.assetDecimals < 0 ||
99
+ option.assetDecimals > 18
100
+ )
101
+ return fail();
102
+ const scaled =
103
+ integer(q.payAmountMicroUsd) * 10n ** BigInt(option.assetDecimals);
104
+ if (scaled % 1000000n !== 0n || String(scaled / 1000000n) !== r.amount)
105
+ return fail();
106
+ if (
107
+ option.scheme !== r.scheme ||
108
+ option.asset.toLowerCase() !== r.asset.toLowerCase() ||
109
+ option.amountAtomic !== r.amount ||
110
+ option.payTo.toLowerCase() !== r.payTo.toLowerCase() ||
111
+ option.maxTimeoutSeconds !== r.maxTimeoutSeconds ||
112
+ option.assetEip712Name !== r.extra?.name ||
113
+ option.assetEip712Version !== r.extra?.version ||
114
+ option.assetTransferMethod !== r.extra?.assetTransferMethod ||
115
+ option.paymentFlow !== r.extra?.paymentFlow
116
+ )
117
+ return fail();
118
+ }
119
+ if (network.startsWith("eip155:")) {
120
+ if (
121
+ !isEVM(walletAddress) ||
122
+ !isEVM(r.asset) ||
123
+ !isEVM(r.payTo) ||
124
+ !normalizeWallet(r.payTo) ||
125
+ r.extra?.assetTransferMethod !== "eip3009" ||
126
+ r.extra?.paymentFlow !== "upfront" ||
127
+ !r.extra.name ||
128
+ !r.extra.version
129
+ )
130
+ return fail();
131
+ }
132
+ return r;
133
+ } catch (error) {
134
+ if (error instanceof CLIError && error.code === "PAYMENT_INVALID")
135
+ throw error;
136
+ return fail();
137
+ }
138
+ }
139
+ const TOKEN = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
140
+ const ATA = new PublicKey("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
141
+ const MEMO = new PublicKey("MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr");
142
+ const equal = (a, b) => Buffer.from(a).equals(Buffer.from(b));
143
+ const empty = (bytes) => bytes.every((b) => b === 0);
144
+ function validateSolana(transaction, order, r) {
145
+ try {
146
+ const tx = VersionedTransaction.deserialize(
147
+ Buffer.from(transaction, "base64"),
148
+ );
149
+ const owner = new PublicKey(order.walletAddress),
150
+ mint = new PublicKey(r.asset),
151
+ recipient = new PublicKey(r.payTo);
152
+ const tokenAccount = (key) =>
153
+ PublicKey.findProgramAddressSync(
154
+ [key.toBuffer(), TOKEN.toBuffer(), mint.toBuffer()],
155
+ ATA,
156
+ )[0];
157
+ const data = Buffer.alloc(10);
158
+ data[0] = 12;
159
+ data.writeBigUInt64LE(BigInt(r.amount), 1);
160
+ data[9] = 6;
161
+ const expected = new TransactionMessage({
162
+ payerKey: new PublicKey(r.extra.feePayer),
163
+ recentBlockhash: tx.message.recentBlockhash,
164
+ instructions: [
165
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 20000 }),
166
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1 }),
167
+ new TransactionInstruction({
168
+ programId: TOKEN,
169
+ data,
170
+ keys: [
171
+ { pubkey: tokenAccount(owner), isSigner: false, isWritable: true },
172
+ { pubkey: mint, isSigner: false, isWritable: false },
173
+ {
174
+ pubkey: tokenAccount(recipient),
175
+ isSigner: false,
176
+ isWritable: true,
177
+ },
178
+ { pubkey: owner, isSigner: true, isWritable: false },
179
+ ],
180
+ }),
181
+ new TransactionInstruction({
182
+ programId: MEMO,
183
+ keys: [],
184
+ data: Buffer.from(r.extra.memo, "utf8"),
185
+ }),
186
+ ],
187
+ }).compileToV0Message();
188
+ const decoded = tx.message;
189
+ const matches =
190
+ decoded.version === 0 &&
191
+ decoded.addressTableLookups.length === 0 &&
192
+ decoded.staticAccountKeys.length === expected.staticAccountKeys.length &&
193
+ new Set(decoded.staticAccountKeys.map((k) => k.toBase58())).size ===
194
+ decoded.staticAccountKeys.length &&
195
+ decoded.staticAccountKeys.every((key, i) => {
196
+ const j = expected.staticAccountKeys.findIndex((other) =>
197
+ other.equals(key),
198
+ );
199
+ return (
200
+ j >= 0 &&
201
+ decoded.isAccountSigner(i) === expected.isAccountSigner(j) &&
202
+ decoded.isAccountWritable(i) === expected.isAccountWritable(j)
203
+ );
204
+ });
205
+ if (
206
+ !matches ||
207
+ !equal(
208
+ TransactionMessage.decompile(decoded).compileToV0Message().serialize(),
209
+ expected.serialize(),
210
+ ) ||
211
+ tx.signatures.length !== 2 ||
212
+ !tx.signatures.every(empty) ||
213
+ !decoded.staticAccountKeys[0].equals(new PublicKey(r.extra.feePayer)) ||
214
+ !decoded.staticAccountKeys[1].equals(owner)
215
+ )
216
+ return fail();
217
+ return tx;
218
+ } catch {
219
+ return fail();
220
+ }
221
+ }
222
+ export function preparePayment(order, context, unsignedTransaction) {
223
+ const now = context.now ?? Date.now();
224
+ const r = validateOrder(order, { ...context, now });
225
+ const common = {
226
+ resource: order.paymentRequired.resource,
227
+ accepted: r,
228
+ walletAddress: order.walletAddress,
229
+ expiresAt: order.paymentExpiresAt,
230
+ preparedAt: now,
231
+ };
232
+ if (r.network === SOLANA_NETWORK) {
233
+ if (!unsignedTransaction) return fail();
234
+ validateSolana(unsignedTransaction, order, r);
235
+ return { ...common, kind: "solana", transaction: unsignedTransaction };
236
+ }
237
+ const types = {
238
+ TransferWithAuthorization: [
239
+ { name: "from", type: "address" },
240
+ { name: "to", type: "address" },
241
+ { name: "value", type: "uint256" },
242
+ { name: "validAfter", type: "uint256" },
243
+ { name: "validBefore", type: "uint256" },
244
+ { name: "nonce", type: "bytes32" },
245
+ ],
246
+ };
247
+ return {
248
+ ...common,
249
+ kind: "evm",
250
+ domain: {
251
+ name: r.extra.name,
252
+ version: r.extra.version,
253
+ chainId: r.network.slice(7),
254
+ verifyingContract: r.asset,
255
+ },
256
+ types,
257
+ message: {
258
+ from: order.walletAddress,
259
+ to: r.payTo,
260
+ value: r.amount,
261
+ validAfter: "0",
262
+ validBefore: String(
263
+ Math.min(
264
+ Math.floor(Date.parse(order.paymentExpiresAt) / 1000),
265
+ Math.floor(now / 1000) + r.maxTimeoutSeconds - 10,
266
+ ),
267
+ ),
268
+ nonce: "0x" + randomBytes(32).toString("hex"),
269
+ },
270
+ };
271
+ }
272
+ export async function completePayment(
273
+ prepared,
274
+ { signer, signature, transaction } = {},
275
+ now = Date.now(),
276
+ ) {
277
+ let payload;
278
+ if (Date.parse(prepared.expiresAt) <= now + 10000)
279
+ throw new CLIError("PAYMENT_EXPIRED", "The order signing window has closed; query the original order.");
280
+ if (signer && !sameWallet(signer.address, prepared.walletAddress))
281
+ throw new CLIError("WALLET_MISMATCH", "The signing wallet does not match the order payer.");
282
+ if (prepared.kind === "evm") {
283
+ if (Number(prepared.message.validBefore) * 1000 <= now + 10000)
284
+ throw new CLIError("PAYMENT_EXPIRED", "The payment authorization has expired; query the original order.");
285
+ signature ||= await signer?.signTypedData(
286
+ prepared.domain,
287
+ prepared.types,
288
+ prepared.message,
289
+ );
290
+ try {
291
+ if (
292
+ !/^0x[0-9a-f]{130}$/i.test(signature) ||
293
+ !sameWallet(
294
+ verifyTypedData(
295
+ prepared.domain,
296
+ prepared.types,
297
+ prepared.message,
298
+ signature,
299
+ ),
300
+ prepared.walletAddress,
301
+ )
302
+ )
303
+ throw new Error();
304
+ } catch {
305
+ throw new CLIError(
306
+ "SIGNATURE_INVALID",
307
+ "The payment signature does not match the prepared payload or payment wallet.",
308
+ );
309
+ }
310
+ payload = { signature, authorization: prepared.message };
311
+ } else {
312
+ if (now - prepared.preparedAt > 60000)
313
+ throw new CLIError(
314
+ "PAYMENT_EXPIRED",
315
+ "The Solana transaction was prepared more than 60 seconds ago; prepare the original unsubmitted order again.",
316
+ );
317
+ const original = VersionedTransaction.deserialize(
318
+ Buffer.from(prepared.transaction, "base64"),
319
+ );
320
+ if (!transaction && signer)
321
+ transaction = Buffer.from(
322
+ await signer.signTransaction(
323
+ Buffer.from(prepared.transaction, "base64"),
324
+ ),
325
+ ).toString("base64");
326
+ try {
327
+ const tx = VersionedTransaction.deserialize(
328
+ Buffer.from(transaction, "base64"),
329
+ );
330
+ const publicKey = createPublicKey({
331
+ key: Buffer.concat([
332
+ Buffer.from("302a300506032b6570032100", "hex"),
333
+ new PublicKey(prepared.walletAddress).toBuffer(),
334
+ ]),
335
+ type: "spki",
336
+ format: "der",
337
+ });
338
+ if (
339
+ !equal(tx.message.serialize(), original.message.serialize()) ||
340
+ tx.signatures.length !== 2 ||
341
+ !empty(tx.signatures[0]) ||
342
+ !verify(null, tx.message.serialize(), publicKey, tx.signatures[1])
343
+ )
344
+ throw new Error();
345
+ payload = { transaction: Buffer.from(tx.serialize()).toString("base64") };
346
+ } catch {
347
+ throw new CLIError(
348
+ "SIGNATURE_INVALID",
349
+ "The Solana transaction was modified, lacks a valid signature or contains extra signatures.",
350
+ );
351
+ }
352
+ }
353
+ return Buffer.from(
354
+ JSON.stringify({
355
+ x402Version: 2,
356
+ resource: prepared.resource,
357
+ accepted: prepared.accepted,
358
+ payload,
359
+ }),
360
+ "utf8",
361
+ ).toString("base64");
362
+ }
package/src/prompt.js ADDED
@@ -0,0 +1,69 @@
1
+ import { emitKeypressEvents } from "node:readline";
2
+ import { CLIError } from "./errors.js";
3
+
4
+ // Read one terminal line without ever echoing hidden input, including on errors.
5
+ export async function terminalInput(
6
+ stdin, stderr, label, { hidden = false } = {},
7
+ ) {
8
+ if (!stdin.isTTY || typeof stdin.setRawMode !== "function")
9
+ throw new CLIError("INPUT_REQUIRED", "Run openany-dev setup in an interactive terminal.");
10
+ if (stdin.destroyed || stdin.readableEnded)
11
+ throw new CLIError("CANCELLED", "Input ended; configuration was not saved.");
12
+ emitKeypressEvents(stdin);
13
+ return new Promise((resolve, reject) => {
14
+ const wasRaw = Boolean(stdin.isRaw);
15
+ let text = "";
16
+ let finished = false;
17
+ function finish(error) {
18
+ if (finished) return;
19
+ finished = true;
20
+ stdin.off("keypress", onKey);
21
+ stdin.off("end", onEnd);
22
+ stdin.off("close", onEnd);
23
+ stdin.off("error", onError);
24
+ try {
25
+ stdin.setRawMode(wasRaw);
26
+ stdin.pause();
27
+ stderr.write("\n");
28
+ } catch (cleanupError) {
29
+ error ||= cleanupError;
30
+ }
31
+ if (error) reject(error);
32
+ else resolve(text.trim());
33
+ }
34
+ function onEnd() {
35
+ finish(new CLIError("CANCELLED", "Input ended; configuration was not saved."));
36
+ }
37
+ function onError() {
38
+ finish(new CLIError("INPUT_FAILED", "Terminal input failed; configuration was not saved."));
39
+ }
40
+ function onKey(value, key = {}) {
41
+ if (key.ctrl && ["c", "d"].includes(key.name)) return onEnd();
42
+ if (key.name === "return" || key.name === "enter") return finish();
43
+ if (key.name === "backspace") {
44
+ if (text) {
45
+ text = Array.from(text).slice(0, -1).join("");
46
+ if (!hidden) stderr.write("\b \b");
47
+ }
48
+ return;
49
+ }
50
+ if (key.ctrl || key.meta || !value || /[\x00-\x1f\x7f-\x9f]/.test(value))
51
+ return;
52
+ if (text.length + value.length > 65536)
53
+ return finish(new CLIError("INVALID_INPUT", "Input is too long; configuration was not saved."));
54
+ text += value;
55
+ if (!hidden) stderr.write(value);
56
+ }
57
+ stdin.on("keypress", onKey);
58
+ stdin.once("end", onEnd);
59
+ stdin.once("close", onEnd);
60
+ stdin.once("error", onError);
61
+ try {
62
+ stdin.setRawMode(true);
63
+ stdin.resume();
64
+ stderr.write(`${label}: `);
65
+ } catch (error) {
66
+ finish(error);
67
+ }
68
+ });
69
+ }
@@ -0,0 +1,72 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { CLIError } from "./errors.js";
3
+ import { checkConfiguration } from "./provider-models.js";
4
+
5
+ const fields = JSON.parse(readFileSync(new URL("./vendor/provider-import/api-fields.json", import.meta.url), "utf8"));
6
+ const categoryIds = new Set(JSON.parse(readFileSync(new URL("./vendor/provider-import/api-categories.json", import.meta.url), "utf8")));
7
+ const maxPathLength = 2048;
8
+ export const maxApiItemIdLength = "DELETE ".length + maxPathLength;
9
+ export const apiImportVersion = "provider-agent-api-v2";
10
+ const object = value => value && typeof value === "object" && !Array.isArray(value);
11
+
12
+ function rename(value, names, path) {
13
+ if (!object(value)) throw new CLIError("IMPORT_FORMAT", `${path} must be an object`);
14
+ const result = { ...value };
15
+ for (const [external, internal] of Object.entries(names)) {
16
+ if (Object.hasOwn(value, internal))
17
+ throw new CLIError("IMPORT_FORMAT", `${path}: use ${external} instead of ${internal}`);
18
+ if (Object.hasOwn(value, external)) {
19
+ result[internal] = value[external];
20
+ delete result[external];
21
+ }
22
+ }
23
+ return result;
24
+ }
25
+
26
+ export function validateApiImportCategories(categories, path) {
27
+ if (categories === undefined) return;
28
+ if (!Array.isArray(categories) || categories.length > 16 || new Set(categories).size !== categories.length ||
29
+ categories.some(id => !categoryIds.has(id)))
30
+ throw new CLIError("IMPORT_FORMAT", `${path}.categories: select up to 16 unique system category IDs`);
31
+ }
32
+
33
+ export function apiImportV2(document) {
34
+ if (!object(document) || document.schemaVersion !== apiImportVersion ||
35
+ !Array.isArray(document.apis) || document.apis.length < 1 || document.apis.length > 100 ||
36
+ Object.keys(document).some(key => !["schemaVersion", "description", "apis", "templateGuide", "fieldGuide"].includes(key)) ||
37
+ (Object.hasOwn(document, "description") && typeof document.description !== "string") ||
38
+ ["templateGuide", "fieldGuide"].some(key => Object.hasOwn(document, key) && !object(document[key])))
39
+ throw new CLIError("IMPORT_FORMAT", `Use ${apiImportVersion} with 1–100 APIs and optional guide objects`);
40
+
41
+ const seen = new Set();
42
+ return document.apis.map((entry, index) => {
43
+ const path = `apis[${index}]`;
44
+ const api = rename(entry, fields.api, path);
45
+ checkConfiguration(api);
46
+ validateApiImportCategories(api.categories, path);
47
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(api.method) ||
48
+ typeof api.pathTemplate !== "string" || !api.pathTemplate.startsWith("/") || api.pathTemplate.length > maxPathLength)
49
+ throw new CLIError("IMPORT_FORMAT", `${path} requires a supported httpMethod and publicPath`);
50
+ if (Object.hasOwn(api, "upstreamKeyId"))
51
+ throw new CLIError("IMPORT_FORMAT", `${path}: select the connection through bindings`);
52
+ api.upstreamPathTemplate = api.pathTemplate;
53
+ if (Object.hasOwn(api, "config")) {
54
+ api.config = rename(api.config, fields.config, `${path}.config`);
55
+ if (!Object.hasOwn(api.config, "charge_condition")) api.config.charge_condition = null;
56
+ if (Object.hasOwn(api.config, "billing")) {
57
+ api.config.billing = rename(api.config.billing, fields.billing, `${path}.config.billing`);
58
+ const billing = api.config.billing;
59
+ const resource = api.catalogType && api.catalogType !== "api";
60
+ if (billing.mode === "usage" && (resource || !Object.hasOwn(billing, "usage_pointer")))
61
+ billing.usage_pointer = "/usage/count";
62
+ }
63
+ if (Array.isArray(api.config.samples))
64
+ api.config.samples = api.config.samples.map((sample, i) =>
65
+ rename(sample, fields.sample, `${path}.config.requestResponseExamples[${i}]`));
66
+ }
67
+ const itemId = `${api.method} ${api.pathTemplate}`;
68
+ if (seen.has(itemId)) throw new CLIError("DUPLICATE_ITEM", "Duplicate API method and path", { itemId });
69
+ seen.add(itemId);
70
+ return { itemId, source: { method: api.method, path: api.pathTemplate, schemaVersion: apiImportVersion }, configuration: api };
71
+ });
72
+ }
@@ -0,0 +1,3 @@
1
+ import { runResource } from "./provider-models.js";
2
+ export const runApis = (action, client, ctx) =>
3
+ runResource("api", action, client, ctx);
@@ -0,0 +1,153 @@
1
+ import { AuthService } from "./auth.js";
2
+ import { CLIError, requireValue } from "./errors.js";
3
+ import { unwrap } from "./http.js";
4
+ import {
5
+ digest,
6
+ uuid,
7
+ reserve,
8
+ updateOperation,
9
+ receipt,
10
+ uncertain,
11
+ CONTRACT_VERSION,
12
+ } from "./provider-state.js";
13
+ export class ProviderClient {
14
+ static async connect(ctx) {
15
+ const client = new ProviderClient();
16
+ client.ctx = ctx;
17
+ client.auth = new AuthService(ctx);
18
+ client.identity = await client.auth.accountCredential({
19
+ email: ctx.options.email,
20
+ });
21
+ client.generation = digest(client.identity.token);
22
+ client.application = ctx.options.application;
23
+ return client;
24
+ }
25
+ async credential() {
26
+ const current = await this.auth.accountCredential({
27
+ email: this.identity.email,
28
+ userId: this.identity.userId,
29
+ });
30
+ if (digest(current.token) !== this.generation)
31
+ throw new CLIError(
32
+ "SESSION_CHANGED",
33
+ "Account session changed during this task; resume explicitly",
34
+ );
35
+ return current;
36
+ }
37
+ path(suffix, global = false) {
38
+ if (global) return "/api/v1/providers/manage/applications" + suffix;
39
+ if (!this.application)
40
+ throw new CLIError(
41
+ "APPLICATION_REQUIRED",
42
+ "Select a supplier explicitly with --application; use seller applications list",
43
+ );
44
+ return `/api/v1/providers/manage/applications/${uuid(this.application, "application")}${suffix}`;
45
+ }
46
+ async request(suffix, options = {}, global = false) {
47
+ return this.requestPath(this.path(suffix, global), options);
48
+ }
49
+ async requestPath(path, options = {}) {
50
+ const credential = await this.credential();
51
+ const result = unwrap(
52
+ await this.ctx.http.backend(path, {
53
+ ...options,
54
+ credential,
55
+ }),
56
+ );
57
+ await this.credential();
58
+ return result;
59
+ }
60
+ async capabilities(type) {
61
+ const c = await this.request("/capabilities");
62
+ if (!c || c.contractVersion !== CONTRACT_VERSION)
63
+ throw new CLIError(
64
+ "CONTRACT_UNSUPPORTED",
65
+ "Provider review contract is unavailable",
66
+ );
67
+ if (type && !c.resources?.[type]?.enabled)
68
+ throw new CLIError(
69
+ "RESOURCE_UNAVAILABLE",
70
+ "Resource type is unavailable",
71
+ { resourceType: type, reasons: c.unavailableReasons || [] },
72
+ );
73
+ return c;
74
+ }
75
+ async write(
76
+ suffix,
77
+ method,
78
+ json,
79
+ operation,
80
+ { global = false, verification = false, recover = false, registration = false, validate, selectResult = value => value } = {},
81
+ ) {
82
+ requireValue(operation, "--operation");
83
+ await this.credential();
84
+ const app = this.application;
85
+ const path = registration
86
+ ? "/api/v1/provider/account/registrations"
87
+ : this.path(suffix, global);
88
+ if (validate) {
89
+ const previous = (await this.ctx.store.read()).provider?.operations?.[operation];
90
+ if (!previous || previous.state === "ready" || previous.state === "failed") await validate();
91
+ }
92
+ const state = await reserve(
93
+ this.ctx.store,
94
+ { userId: this.identity.userId, application: global || registration ? null : app },
95
+ operation,
96
+ { path, method, json },
97
+ );
98
+ if (state.state === "completed") return state.result;
99
+ const replayable =
100
+ method === "POST" && !registration && !verification && !["/withdraw", "/publish", "/unpublish"].some(end => suffix.endsWith(end));
101
+ if (
102
+ state.state === "sending" &&
103
+ !(replayable && (recover || this.ctx.options.resume))
104
+ )
105
+ throw new CLIError(
106
+ "OPERATION_UNCERTAIN",
107
+ "Another request may still be running; inspect the resource before recovering",
108
+ { operation },
109
+ );
110
+ if (state.state === "unknown" && !replayable)
111
+ throw new CLIError(
112
+ "OPERATION_UNCERTAIN",
113
+ "Query the saved resource or verification; do not repeat an uncertain update or upstream test",
114
+ { operation, resourceId: state.resourceId },
115
+ );
116
+ await updateOperation(this.ctx.store, operation, { state: "sending" });
117
+ try {
118
+ const result = selectResult(await this.requestPath(
119
+ path,
120
+ { method, json, ...(!registration ? { headers: { "Idempotency-Key": state.key } } : {}) },
121
+ ));
122
+ if (app !== this.application)
123
+ throw new CLIError(
124
+ "SESSION_CHANGED",
125
+ "Supplier changed during the operation",
126
+ );
127
+ await updateOperation(this.ctx.store, operation, {
128
+ state: "completed",
129
+ result: receipt(result),
130
+ });
131
+ return result;
132
+ } catch (error) {
133
+ if (uncertain(error) && method === "PUT") {
134
+ try {
135
+ error.details = {
136
+ ...error.details,
137
+ current: receipt(await this.request(suffix)),
138
+ };
139
+ } catch (readError) {
140
+ error.details = {
141
+ ...error.details,
142
+ readErrorCode: readError.code || "READ_FAILED",
143
+ };
144
+ }
145
+ }
146
+ await updateOperation(this.ctx.store, operation, {
147
+ state: uncertain(error) ? "unknown" : "failed",
148
+ errorCode: error.code || "INTERNAL_ERROR",
149
+ });
150
+ throw error;
151
+ }
152
+ }
153
+ }