@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.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.
- package/CHANGELOG.md +29 -0
- package/README.md +1131 -34
- package/dist/cli.js +15 -12
- package/dist/core/credentials.d.ts +21 -0
- package/dist/core/credentials.js +45 -0
- package/dist/core/origins.d.ts +18 -0
- package/dist/core/origins.js +40 -0
- package/dist/core/upload-hosts.d.ts +15 -0
- package/dist/core/upload-hosts.js +43 -0
- package/dist/host/describe.d.ts +10 -0
- package/dist/host/describe.js +38 -0
- package/dist/host/env.d.ts +25 -2
- package/dist/host/env.js +24 -7
- package/dist/host/guarded-fetch.d.ts +36 -9
- package/dist/host/guarded-fetch.js +175 -52
- package/dist/host/index.d.ts +8 -5
- package/dist/host/index.js +12 -1
- package/dist/host/load.js +31 -1
- package/dist/host/server.d.ts +13 -2
- package/dist/host/server.js +15 -2
- package/dist/types.d.ts +96 -5
- package/dist/vendors/adapty.js +1303 -0
- package/dist/vendors/adjust.js +1372 -0
- package/dist/vendors/apollo.js +2499 -0
- package/dist/vendors/apple-appstore.js +2798 -0
- package/dist/vendors/beehiiv.js +1965 -0
- package/dist/vendors/blogger.js +1687 -0
- package/dist/vendors/bluesky.js +850 -127
- package/dist/vendors/brevo.js +2195 -0
- package/dist/vendors/calendarific.js +1116 -0
- package/dist/vendors/devto.js +685 -92
- package/dist/vendors/facebook-pages.js +2185 -0
- package/dist/vendors/firebase.js +1333 -0
- package/dist/vendors/ga4.js +1585 -0
- package/dist/vendors/gmail.js +1962 -0
- package/dist/vendors/google-ads.js +2201 -0
- package/dist/vendors/google-business.js +1621 -0
- package/dist/vendors/google-calendar.js +1936 -0
- package/dist/vendors/google-drive.js +2654 -0
- package/dist/vendors/google-merchant-center.js +1742 -0
- package/dist/vendors/google-play.js +1856 -0
- package/dist/vendors/google-search-console.js +1572 -0
- package/dist/vendors/hashnode.js +1722 -0
- package/dist/vendors/instagram.js +2249 -0
- package/dist/vendors/kaggle.js +2043 -0
- package/dist/vendors/keepa.js +2087 -0
- package/dist/vendors/linkedin.js +1588 -0
- package/dist/vendors/mailchimp.js +2402 -0
- package/dist/vendors/mastodon.js +1836 -0
- package/dist/vendors/meta-ads.js +2375 -0
- package/dist/vendors/notion.js +1950 -0
- package/dist/vendors/pinterest.js +1744 -0
- package/dist/vendors/qiita.js +1552 -0
- package/dist/vendors/reddit.js +1791 -0
- package/dist/vendors/revenuecat.js +1593 -0
- package/dist/vendors/roasit.js +1460 -0
- package/dist/vendors/sendgrid.js +2188 -0
- package/dist/vendors/serper.js +901 -179
- package/dist/vendors/shopify.js +2511 -0
- package/dist/vendors/threads.js +1869 -0
- package/dist/vendors/tiktok.js +2199 -0
- package/dist/vendors/tumblr.js +1793 -0
- package/dist/vendors/twitter.js +1650 -0
- package/dist/vendors/woocommerce.js +2258 -0
- package/dist/vendors/wordpress.js +1904 -0
- package/dist/vendors/youtube.js +2542 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1856 @@
|
|
|
1
|
+
/* google-play connector module (MIT License). Built from src/vendors/google-play; do not edit. */
|
|
2
|
+
"use strict";
|
|
3
|
+
|
|
4
|
+
// src/core/errors.ts
|
|
5
|
+
var ToolFailure = class extends Error {
|
|
6
|
+
details;
|
|
7
|
+
constructor(message, details = {}) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "ToolFailure";
|
|
10
|
+
this.details = details;
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
var OutcomeUnknown = class extends Error {
|
|
14
|
+
constructor(message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = "OutcomeUnknown";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// src/core/accounts.ts
|
|
21
|
+
function allowedAccounts(accounts, key) {
|
|
22
|
+
if (accounts === null) return null;
|
|
23
|
+
const list = accounts?.[key];
|
|
24
|
+
return Array.isArray(list) ? list.map(String) : [];
|
|
25
|
+
}
|
|
26
|
+
function requireAccounts(accounts, key, ids, label = "account") {
|
|
27
|
+
const allowed = allowedAccounts(accounts, key);
|
|
28
|
+
if (allowed === null) return;
|
|
29
|
+
const requested = (Array.isArray(ids) ? ids : [ids]).map(String);
|
|
30
|
+
const refused = requested.filter((id) => !allowed.includes(id));
|
|
31
|
+
if (!refused.length) return;
|
|
32
|
+
throw new ToolFailure(
|
|
33
|
+
`The ${label} ${refused.join(", ")} ${refused.length > 1 ? "are" : "is"} not among the ${label}s chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`) + " Nothing was sent."
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/core/text.ts
|
|
38
|
+
var encoder = new TextEncoder();
|
|
39
|
+
var decoder = new TextDecoder();
|
|
40
|
+
function utf8Bytes(text) {
|
|
41
|
+
return encoder.encode(text);
|
|
42
|
+
}
|
|
43
|
+
function utf8Length(text) {
|
|
44
|
+
return encoder.encode(text).length;
|
|
45
|
+
}
|
|
46
|
+
function utf8Decode(bytes) {
|
|
47
|
+
return decoder.decode(bytes);
|
|
48
|
+
}
|
|
49
|
+
function base64Encode(bytes) {
|
|
50
|
+
let binary = "";
|
|
51
|
+
for (let i = 0; i < bytes.length; i += 32768) {
|
|
52
|
+
binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
|
|
53
|
+
}
|
|
54
|
+
return btoa(binary);
|
|
55
|
+
}
|
|
56
|
+
function base64UrlEncode(bytes) {
|
|
57
|
+
return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
58
|
+
}
|
|
59
|
+
function base64UrlDecode(text) {
|
|
60
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
|
|
61
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
|
|
62
|
+
const binary = atob(padded);
|
|
63
|
+
const bytes = new Uint8Array(binary.length);
|
|
64
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
65
|
+
return bytes;
|
|
66
|
+
}
|
|
67
|
+
function base64Decode(text) {
|
|
68
|
+
const clean = text.replace(/\s+/g, "");
|
|
69
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 === 1) throw new Error("not base64");
|
|
70
|
+
const binary = atob(clean);
|
|
71
|
+
const bytes = new Uint8Array(binary.length);
|
|
72
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
73
|
+
return bytes;
|
|
74
|
+
}
|
|
75
|
+
async function sha256Hex(text) {
|
|
76
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(text)));
|
|
77
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
78
|
+
}
|
|
79
|
+
function truncate(text, max) {
|
|
80
|
+
if (text.length <= max) return text;
|
|
81
|
+
const points = Array.from(text);
|
|
82
|
+
if (points.length <= max) return text;
|
|
83
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
84
|
+
}
|
|
85
|
+
function cleanVendorText(text, max = 300) {
|
|
86
|
+
if (typeof text !== "string") return void 0;
|
|
87
|
+
if (/^\s*</.test(text)) return void 0;
|
|
88
|
+
const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
89
|
+
return line ? truncate(line, max) : void 0;
|
|
90
|
+
}
|
|
91
|
+
function formatNumber(value) {
|
|
92
|
+
return value.toLocaleString("en-US");
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// src/core/output.ts
|
|
96
|
+
var OUTPUT_LIMIT_BYTES = 32 * 1024;
|
|
97
|
+
function jsonSize(value) {
|
|
98
|
+
return utf8Length(JSON.stringify(value) ?? "");
|
|
99
|
+
}
|
|
100
|
+
function cutStrings(value, max) {
|
|
101
|
+
if (typeof value === "string") return truncate(value, max);
|
|
102
|
+
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
103
|
+
if (typeof value === "object" && value !== null) {
|
|
104
|
+
const out = {};
|
|
105
|
+
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
return value;
|
|
109
|
+
}
|
|
110
|
+
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
111
|
+
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
112
|
+
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
113
|
+
const cut = cutStrings(value, max);
|
|
114
|
+
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
115
|
+
}
|
|
116
|
+
return void 0;
|
|
117
|
+
}
|
|
118
|
+
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
119
|
+
const build = (count) => {
|
|
120
|
+
const cut = count < input.items.length;
|
|
121
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
122
|
+
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
123
|
+
if (next) result2["nextCursor"] = next;
|
|
124
|
+
if (cut) result2["truncated"] = true;
|
|
125
|
+
return result2;
|
|
126
|
+
};
|
|
127
|
+
const all = build(input.items.length);
|
|
128
|
+
if (jsonSize(all) <= limit) return all;
|
|
129
|
+
let low = 1;
|
|
130
|
+
let high = input.items.length - 1;
|
|
131
|
+
while (low < high) {
|
|
132
|
+
const middle = Math.ceil((low + high) / 2);
|
|
133
|
+
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
134
|
+
else high = middle - 1;
|
|
135
|
+
}
|
|
136
|
+
const best = build(low);
|
|
137
|
+
if (jsonSize(best) <= limit) return best;
|
|
138
|
+
const shrunk = shrinkToFit(best, limit);
|
|
139
|
+
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
140
|
+
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
141
|
+
}
|
|
142
|
+
function encodeCursor(tool, state) {
|
|
143
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
144
|
+
}
|
|
145
|
+
function decodeCursor(tool, cursor) {
|
|
146
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
147
|
+
try {
|
|
148
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
149
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
150
|
+
return state;
|
|
151
|
+
}
|
|
152
|
+
} catch {
|
|
153
|
+
}
|
|
154
|
+
throw new ToolFailure(
|
|
155
|
+
"The cursor is not valid for this tool. Pass the nextCursor value of the previous result unchanged, or leave cursor out to start from the beginning."
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/core/api-tools.ts
|
|
160
|
+
var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
|
|
161
|
+
var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
|
|
162
|
+
var NOTE_ROOM = 400;
|
|
163
|
+
var MAX_CUT_POINTS = 4e4;
|
|
164
|
+
function isQueryValue(value) {
|
|
165
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
166
|
+
}
|
|
167
|
+
function nothingSent(sentence) {
|
|
168
|
+
return new ToolFailure(`${sentence} Nothing was sent.`);
|
|
169
|
+
}
|
|
170
|
+
function fitReply(reply) {
|
|
171
|
+
if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
|
|
172
|
+
const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
|
|
173
|
+
if (shrunk) {
|
|
174
|
+
return {
|
|
175
|
+
...shrunk.value,
|
|
176
|
+
truncated: true,
|
|
177
|
+
note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
const text = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
|
|
181
|
+
const points = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
|
|
182
|
+
if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
|
|
183
|
+
const cut = (count) => ({
|
|
184
|
+
status: reply["status"],
|
|
185
|
+
...reply["headers"] ? { headers: reply["headers"] } : {},
|
|
186
|
+
truncated: true,
|
|
187
|
+
note: `The reply has ${formatNumber(utf8Length(text))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
|
|
188
|
+
text: points.slice(0, count).join("")
|
|
189
|
+
});
|
|
190
|
+
let low = 0;
|
|
191
|
+
let high = points.length;
|
|
192
|
+
while (low < high) {
|
|
193
|
+
const middle = Math.ceil((low + high) / 2);
|
|
194
|
+
if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
|
|
195
|
+
else high = middle - 1;
|
|
196
|
+
}
|
|
197
|
+
return cut(low);
|
|
198
|
+
}
|
|
199
|
+
function shapeReply(response, headerNames) {
|
|
200
|
+
const reply = { status: response.status };
|
|
201
|
+
const headers = {};
|
|
202
|
+
for (const name2 of headerNames) {
|
|
203
|
+
const value = response.headers.get(name2);
|
|
204
|
+
if (value) headers[name2] = truncate(value, 2e3);
|
|
205
|
+
}
|
|
206
|
+
if (Object.keys(headers).length) reply["headers"] = headers;
|
|
207
|
+
const type = response.headers.get("content-type") ?? "";
|
|
208
|
+
if (type && !TEXT_TYPES.test(type)) {
|
|
209
|
+
reply["contentType"] = truncate(type, 200);
|
|
210
|
+
reply["note"] = "The reply is a binary file and is not shown.";
|
|
211
|
+
return reply;
|
|
212
|
+
}
|
|
213
|
+
if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
|
|
214
|
+
return fitReply(reply);
|
|
215
|
+
}
|
|
216
|
+
function checkAccounts(rule, request, h) {
|
|
217
|
+
const label = rule.label ?? "account";
|
|
218
|
+
const allowed = allowedAccounts(h.ctx.accounts, rule.key);
|
|
219
|
+
if (allowed === null) return;
|
|
220
|
+
const namesNone = nothingSent(
|
|
221
|
+
`This request names none of the ${label}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`)
|
|
222
|
+
);
|
|
223
|
+
if (rule.ids) {
|
|
224
|
+
const ids = rule.ids(request).map(String);
|
|
225
|
+
if (!ids.length) throw namesNone;
|
|
226
|
+
requireAccounts(h.ctx.accounts, rule.key, ids, label);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
|
|
230
|
+
}
|
|
231
|
+
function apiTools(options) {
|
|
232
|
+
const { label, basePath } = options;
|
|
233
|
+
const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
|
|
234
|
+
const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
|
|
235
|
+
const base = basePath?.replace(/\/+$/, "");
|
|
236
|
+
const pathSchema = {
|
|
237
|
+
type: "string",
|
|
238
|
+
minLength: 1,
|
|
239
|
+
maxLength: 2e3,
|
|
240
|
+
pattern: "^(?!.*//)/[^?#]*$",
|
|
241
|
+
description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
|
|
242
|
+
};
|
|
243
|
+
const querySchema = {
|
|
244
|
+
type: "object",
|
|
245
|
+
description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
|
|
246
|
+
};
|
|
247
|
+
const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
|
|
248
|
+
async function run(method, args, h) {
|
|
249
|
+
let origin = h.origins[0];
|
|
250
|
+
if (args.origin !== void 0) {
|
|
251
|
+
let wanted;
|
|
252
|
+
try {
|
|
253
|
+
wanted = new URL(args.origin).origin;
|
|
254
|
+
} catch {
|
|
255
|
+
}
|
|
256
|
+
if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
|
|
257
|
+
origin = wanted;
|
|
258
|
+
}
|
|
259
|
+
const url = new URL(args.path, origin);
|
|
260
|
+
if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
|
|
261
|
+
const path = url.pathname;
|
|
262
|
+
if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
|
|
263
|
+
let segments;
|
|
264
|
+
try {
|
|
265
|
+
segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
|
|
266
|
+
} catch {
|
|
267
|
+
throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
|
|
268
|
+
}
|
|
269
|
+
if (segments[segments.length - 1] === "") segments.pop();
|
|
270
|
+
const query = {};
|
|
271
|
+
const queryLists = {};
|
|
272
|
+
for (const [key, value] of Object.entries(args.query ?? {})) {
|
|
273
|
+
if (value === void 0 || value === null) continue;
|
|
274
|
+
const list = Array.isArray(value) ? value : [value];
|
|
275
|
+
if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
|
|
276
|
+
query[key] = Array.isArray(value) ? list : value;
|
|
277
|
+
queryLists[key] = list.map(String);
|
|
278
|
+
}
|
|
279
|
+
const request = { method, origin, path, query };
|
|
280
|
+
if (method !== "GET") {
|
|
281
|
+
if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
|
|
282
|
+
if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
|
|
283
|
+
if (args.json !== void 0 && !args.content_type) {
|
|
284
|
+
request.json = args.json;
|
|
285
|
+
} else if (args.json !== void 0 || args.body !== void 0) {
|
|
286
|
+
request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
|
|
287
|
+
request.contentType = args.content_type;
|
|
288
|
+
}
|
|
289
|
+
request.write = true;
|
|
290
|
+
}
|
|
291
|
+
const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
|
|
292
|
+
if (options.accounts) checkAccounts(options.accounts, info, h);
|
|
293
|
+
await options.guard?.(info, h);
|
|
294
|
+
const response = options.send ? await options.send(request, h) : await h.api(request);
|
|
295
|
+
return shapeReply(response, headerNames);
|
|
296
|
+
}
|
|
297
|
+
return [
|
|
298
|
+
{
|
|
299
|
+
name: "api_get",
|
|
300
|
+
kind: "read",
|
|
301
|
+
title: `Call the ${label} API (GET)`,
|
|
302
|
+
description: `${options.description} Sends one GET request with the connection's credentials and returns the HTTP status and the reply, JSON or text, cut to fit 32 KB (use the API's own paging and field parameters for long lists). It changes nothing.`,
|
|
303
|
+
inputSchema: {
|
|
304
|
+
type: "object",
|
|
305
|
+
properties: { path: pathSchema, query: querySchema, ...originSchema },
|
|
306
|
+
required: ["path"],
|
|
307
|
+
additionalProperties: false
|
|
308
|
+
},
|
|
309
|
+
run: (args, h) => run("GET", args, h)
|
|
310
|
+
},
|
|
311
|
+
{
|
|
312
|
+
name: "api_request",
|
|
313
|
+
kind: "write",
|
|
314
|
+
check: "api_get",
|
|
315
|
+
title: `Send a request to the ${label} API`,
|
|
316
|
+
description: `${options.description} Sends one ${methods.join(", ")} request with the connection's credentials, with a JSON body (json) or another body (body and content_type), and returns the HTTP status and the reply. It can create, change or delete data. It is never retried: when the outcome is unclear, check with api_get before sending it again.`,
|
|
317
|
+
inputSchema: {
|
|
318
|
+
type: "object",
|
|
319
|
+
properties: {
|
|
320
|
+
method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
|
|
321
|
+
path: pathSchema,
|
|
322
|
+
query: querySchema,
|
|
323
|
+
json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
|
|
324
|
+
body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
|
|
325
|
+
content_type: {
|
|
326
|
+
type: "string",
|
|
327
|
+
pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
|
|
328
|
+
maxLength: 200,
|
|
329
|
+
description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
|
|
330
|
+
},
|
|
331
|
+
...originSchema
|
|
332
|
+
},
|
|
333
|
+
required: ["method", "path"],
|
|
334
|
+
additionalProperties: false
|
|
335
|
+
},
|
|
336
|
+
run: (args, h) => run(args.method, args, h)
|
|
337
|
+
}
|
|
338
|
+
];
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// src/core/credentials.ts
|
|
342
|
+
function requiredAlternatives(module2) {
|
|
343
|
+
return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
|
|
344
|
+
}
|
|
345
|
+
function unmetAlternatives(alternatives, has) {
|
|
346
|
+
const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
|
|
347
|
+
if (lacking.some((list) => list.length === 0)) return [];
|
|
348
|
+
return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
|
|
349
|
+
}
|
|
350
|
+
function andList(items) {
|
|
351
|
+
if (items.length <= 2) return items.join(" and ");
|
|
352
|
+
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
353
|
+
}
|
|
354
|
+
function orList(items) {
|
|
355
|
+
if (items.length <= 1) return items.join("");
|
|
356
|
+
return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// src/core/files.ts
|
|
360
|
+
var ATTACHMENT_URI = "attachment:///";
|
|
361
|
+
var MAX_NAME = 200;
|
|
362
|
+
function fileLimitOf(ctx) {
|
|
363
|
+
const maxBytes = ctx.files?.maxBytes;
|
|
364
|
+
return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
|
|
365
|
+
}
|
|
366
|
+
function fileName(name2) {
|
|
367
|
+
const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
|
|
368
|
+
const points = Array.from(clean);
|
|
369
|
+
if (points.length <= MAX_NAME) return clean || "file";
|
|
370
|
+
const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
|
|
371
|
+
return points.slice(0, MAX_NAME - extension.length).join("") + extension;
|
|
372
|
+
}
|
|
373
|
+
function fileType(mimeType) {
|
|
374
|
+
const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
|
|
375
|
+
return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
|
|
376
|
+
}
|
|
377
|
+
function resourceBlock(file) {
|
|
378
|
+
return {
|
|
379
|
+
type: "resource",
|
|
380
|
+
resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// src/core/http.ts
|
|
385
|
+
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
386
|
+
var USER_AGENT = "agent-connectors";
|
|
387
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
388
|
+
function errorCode(error) {
|
|
389
|
+
const code = error?.code;
|
|
390
|
+
return typeof code === "string" ? code : void 0;
|
|
391
|
+
}
|
|
392
|
+
function describe(error) {
|
|
393
|
+
const name2 = error?.name;
|
|
394
|
+
const code = errorCode(error);
|
|
395
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
396
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
397
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
398
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
399
|
+
}
|
|
400
|
+
function retryAfterSeconds(headers, now = Date.now()) {
|
|
401
|
+
const retryAfter = headers.get("retry-after");
|
|
402
|
+
if (retryAfter) {
|
|
403
|
+
const seconds = Number(retryAfter);
|
|
404
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
405
|
+
const date = Date.parse(retryAfter);
|
|
406
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
407
|
+
}
|
|
408
|
+
const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
|
409
|
+
if (reset) {
|
|
410
|
+
const value = Number(reset);
|
|
411
|
+
if (Number.isFinite(value) && value >= 0) {
|
|
412
|
+
return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
return void 0;
|
|
416
|
+
}
|
|
417
|
+
function vendorCode(data) {
|
|
418
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
419
|
+
for (const key of ["error", "code"]) {
|
|
420
|
+
const value = data[key];
|
|
421
|
+
if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
|
|
422
|
+
}
|
|
423
|
+
return void 0;
|
|
424
|
+
}
|
|
425
|
+
function vendorMessage(data) {
|
|
426
|
+
if (typeof data === "string") return cleanVendorText(data);
|
|
427
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
428
|
+
const record = data;
|
|
429
|
+
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
430
|
+
const value = record[key];
|
|
431
|
+
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
432
|
+
const nested = value?.message;
|
|
433
|
+
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
434
|
+
}
|
|
435
|
+
if (Array.isArray(record["errors"])) {
|
|
436
|
+
const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
437
|
+
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
438
|
+
}
|
|
439
|
+
return void 0;
|
|
440
|
+
}
|
|
441
|
+
var TooLarge = class extends Error {
|
|
442
|
+
constructor(limit) {
|
|
443
|
+
super(`the reply is larger than ${formatNumber(limit)} bytes`);
|
|
444
|
+
this.limit = limit;
|
|
445
|
+
}
|
|
446
|
+
limit;
|
|
447
|
+
};
|
|
448
|
+
async function readCapped(response, maxBytes) {
|
|
449
|
+
const declared = Number(response.headers.get("content-length"));
|
|
450
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
451
|
+
await response.body?.cancel().catch(() => {
|
|
452
|
+
});
|
|
453
|
+
throw new TooLarge(maxBytes);
|
|
454
|
+
}
|
|
455
|
+
if (!response.body) return new Uint8Array(0);
|
|
456
|
+
const reader = response.body.getReader();
|
|
457
|
+
const chunks = [];
|
|
458
|
+
let total = 0;
|
|
459
|
+
for (; ; ) {
|
|
460
|
+
const { done, value } = await reader.read();
|
|
461
|
+
if (done) break;
|
|
462
|
+
total += value.byteLength;
|
|
463
|
+
if (total > maxBytes) {
|
|
464
|
+
await reader.cancel().catch(() => {
|
|
465
|
+
});
|
|
466
|
+
throw new TooLarge(maxBytes);
|
|
467
|
+
}
|
|
468
|
+
chunks.push(value);
|
|
469
|
+
}
|
|
470
|
+
const bytes = new Uint8Array(total);
|
|
471
|
+
let offset = 0;
|
|
472
|
+
for (const chunk of chunks) {
|
|
473
|
+
bytes.set(chunk, offset);
|
|
474
|
+
offset += chunk.byteLength;
|
|
475
|
+
}
|
|
476
|
+
return bytes;
|
|
477
|
+
}
|
|
478
|
+
function parseBody(bytes, contentType) {
|
|
479
|
+
if (bytes.length === 0) return null;
|
|
480
|
+
const text = utf8Decode(bytes);
|
|
481
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
|
|
482
|
+
try {
|
|
483
|
+
return JSON.parse(text);
|
|
484
|
+
} catch {
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
return text;
|
|
488
|
+
}
|
|
489
|
+
function createHttp(env) {
|
|
490
|
+
const { label, ctx } = env;
|
|
491
|
+
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
492
|
+
const checkCredentials = env.credentialLabels.length ? `Check that the ${andList(env.credentialLabels)} ${env.credentialLabels.length > 1 ? "are" : "is"} correct and still active.` : `Check that the ${label} credentials are correct and still active.`;
|
|
493
|
+
function failureFor(status, headers, data, request) {
|
|
494
|
+
const message = vendorMessage(data);
|
|
495
|
+
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
496
|
+
const retryAfter = retryAfterSeconds(headers);
|
|
497
|
+
const code = vendorCode(data);
|
|
498
|
+
const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
499
|
+
const custom = request.errors?.[status];
|
|
500
|
+
const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
|
|
501
|
+
if (status >= 500) {
|
|
502
|
+
if (request.write) {
|
|
503
|
+
return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
|
|
504
|
+
}
|
|
505
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
|
|
506
|
+
}
|
|
507
|
+
if (status === 429) {
|
|
508
|
+
return new ToolFailure(
|
|
509
|
+
`${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
510
|
+
{ status, ...extra }
|
|
511
|
+
);
|
|
512
|
+
}
|
|
513
|
+
if (status === 401) {
|
|
514
|
+
return new ToolFailure(
|
|
515
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
|
|
516
|
+
{ status, ...extra }
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
520
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
521
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
|
|
522
|
+
return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
|
|
523
|
+
}
|
|
524
|
+
async function api(request) {
|
|
525
|
+
const method = request.method ?? "GET";
|
|
526
|
+
if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
|
|
527
|
+
throw new Error(`read-only tool sent ${method}`);
|
|
528
|
+
}
|
|
529
|
+
const origin = request.origin ?? env.origins[0];
|
|
530
|
+
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
531
|
+
const url = new URL(request.path, origin);
|
|
532
|
+
if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
533
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
534
|
+
if (value === void 0 || value === null) continue;
|
|
535
|
+
if (Array.isArray(value)) {
|
|
536
|
+
url.searchParams.delete(key);
|
|
537
|
+
for (const item of value) url.searchParams.append(key, String(item));
|
|
538
|
+
} else {
|
|
539
|
+
url.searchParams.set(key, String(value));
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const headers = {
|
|
543
|
+
accept: "application/json",
|
|
544
|
+
"user-agent": USER_AGENT,
|
|
545
|
+
...request.auth === false ? {} : env.authHeaders(),
|
|
546
|
+
...request.headers
|
|
547
|
+
};
|
|
548
|
+
let body;
|
|
549
|
+
if (request.json !== void 0) {
|
|
550
|
+
body = JSON.stringify(request.json);
|
|
551
|
+
headers["content-type"] = "application/json";
|
|
552
|
+
} else if (request.body) {
|
|
553
|
+
body = request.body;
|
|
554
|
+
headers["content-type"] = request.contentType ?? "application/octet-stream";
|
|
555
|
+
}
|
|
556
|
+
const started = Date.now();
|
|
557
|
+
if (request.write) env.onWriteSent();
|
|
558
|
+
let response;
|
|
559
|
+
try {
|
|
560
|
+
response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
561
|
+
} catch (error) {
|
|
562
|
+
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
563
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
564
|
+
throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
|
|
565
|
+
}
|
|
566
|
+
if (request.write) {
|
|
567
|
+
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
568
|
+
}
|
|
569
|
+
if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
|
|
570
|
+
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
571
|
+
}
|
|
572
|
+
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
573
|
+
let bytes;
|
|
574
|
+
try {
|
|
575
|
+
bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
|
|
576
|
+
} catch (error) {
|
|
577
|
+
if (request.write && (response.ok || response.status >= 500)) {
|
|
578
|
+
throw new OutcomeUnknown(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}), so it is not known whether the change was made.`);
|
|
579
|
+
}
|
|
580
|
+
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
581
|
+
}
|
|
582
|
+
const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
|
|
583
|
+
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
584
|
+
throw failureFor(response.status, response.headers, data, request);
|
|
585
|
+
}
|
|
586
|
+
async function media(rawUrl, options) {
|
|
587
|
+
const { what } = options;
|
|
588
|
+
let url;
|
|
589
|
+
try {
|
|
590
|
+
url = new URL(rawUrl);
|
|
591
|
+
} catch {
|
|
592
|
+
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
593
|
+
}
|
|
594
|
+
if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
595
|
+
const started = Date.now();
|
|
596
|
+
let response;
|
|
597
|
+
try {
|
|
598
|
+
response = await ctx.fetch(url.toString(), {
|
|
599
|
+
method: "GET",
|
|
600
|
+
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
601
|
+
...ctx.signal ? { signal: ctx.signal } : {}
|
|
602
|
+
});
|
|
603
|
+
} catch (error) {
|
|
604
|
+
env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
|
|
605
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
606
|
+
throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
|
|
607
|
+
}
|
|
608
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
609
|
+
}
|
|
610
|
+
env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
611
|
+
if (!response.ok) {
|
|
612
|
+
await response.body?.cancel().catch(() => {
|
|
613
|
+
});
|
|
614
|
+
throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
|
|
615
|
+
}
|
|
616
|
+
try {
|
|
617
|
+
const bytes = await readCapped(response, options.maxBytes);
|
|
618
|
+
return { bytes, contentType: response.headers.get("content-type") };
|
|
619
|
+
} catch (error) {
|
|
620
|
+
if (error instanceof TooLarge) {
|
|
621
|
+
throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
|
|
622
|
+
}
|
|
623
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
return { api, media };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
// src/core/origins.ts
|
|
630
|
+
function parseSiteUrl(value) {
|
|
631
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
632
|
+
if (!text) return { ok: false, problem: "is empty" };
|
|
633
|
+
let url;
|
|
634
|
+
try {
|
|
635
|
+
url = new URL(text.includes("://") ? text : `https://${text}`);
|
|
636
|
+
} catch {
|
|
637
|
+
return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
|
|
638
|
+
}
|
|
639
|
+
if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
|
|
640
|
+
if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
|
|
641
|
+
if (!url.hostname) return { ok: false, problem: "has no host name" };
|
|
642
|
+
return { ok: true, url, origin: url.origin };
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// src/core/schema.ts
|
|
646
|
+
var patterns = /* @__PURE__ */ new Map();
|
|
647
|
+
function patternOf(source) {
|
|
648
|
+
let compiled = patterns.get(source);
|
|
649
|
+
if (!compiled) {
|
|
650
|
+
compiled = new RegExp(source, "u");
|
|
651
|
+
patterns.set(source, compiled);
|
|
652
|
+
}
|
|
653
|
+
return compiled;
|
|
654
|
+
}
|
|
655
|
+
function isPlainObject(value) {
|
|
656
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
657
|
+
}
|
|
658
|
+
function isHttpUrl(value) {
|
|
659
|
+
try {
|
|
660
|
+
const url = new URL(value);
|
|
661
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
662
|
+
} catch {
|
|
663
|
+
return false;
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
function name(path) {
|
|
667
|
+
return `\`${path}\``;
|
|
668
|
+
}
|
|
669
|
+
function child(path, key) {
|
|
670
|
+
return path ? `${path}.${key}` : key;
|
|
671
|
+
}
|
|
672
|
+
function checkValue(schema, value, path, issues) {
|
|
673
|
+
switch (schema.type) {
|
|
674
|
+
case "object":
|
|
675
|
+
checkObject(schema, value, path, issues);
|
|
676
|
+
return;
|
|
677
|
+
case "array": {
|
|
678
|
+
if (!Array.isArray(value)) {
|
|
679
|
+
issues.push(`${name(path)} must be an array`);
|
|
680
|
+
return;
|
|
681
|
+
}
|
|
682
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
683
|
+
issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
|
|
684
|
+
}
|
|
685
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
686
|
+
issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
|
|
687
|
+
}
|
|
688
|
+
if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
|
|
689
|
+
issues.push(`${name(path)} must not repeat an item`);
|
|
690
|
+
}
|
|
691
|
+
if (schema.items) {
|
|
692
|
+
value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
|
|
693
|
+
}
|
|
694
|
+
break;
|
|
695
|
+
}
|
|
696
|
+
case "string": {
|
|
697
|
+
if (typeof value !== "string") {
|
|
698
|
+
issues.push(`${name(path)} must be a string`);
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
const length = Array.from(value).length;
|
|
702
|
+
if (schema.minLength !== void 0 && length < schema.minLength) {
|
|
703
|
+
issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
|
|
704
|
+
}
|
|
705
|
+
if (schema.maxLength !== void 0 && length > schema.maxLength) {
|
|
706
|
+
issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
|
|
707
|
+
}
|
|
708
|
+
if (schema.format === "uri" && !isHttpUrl(value)) {
|
|
709
|
+
issues.push(`${name(path)} must be an absolute http(s) URL`);
|
|
710
|
+
} else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
|
|
711
|
+
issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
|
|
712
|
+
}
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
case "integer":
|
|
716
|
+
case "number": {
|
|
717
|
+
if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
|
|
718
|
+
issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
722
|
+
issues.push(`${name(path)} must be at least ${schema.minimum}`);
|
|
723
|
+
}
|
|
724
|
+
if (schema.maximum !== void 0 && value > schema.maximum) {
|
|
725
|
+
issues.push(`${name(path)} must be at most ${schema.maximum}`);
|
|
726
|
+
}
|
|
727
|
+
break;
|
|
728
|
+
}
|
|
729
|
+
case "boolean":
|
|
730
|
+
if (typeof value !== "boolean") {
|
|
731
|
+
issues.push(`${name(path)} must be true or false`);
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
break;
|
|
735
|
+
default:
|
|
736
|
+
break;
|
|
737
|
+
}
|
|
738
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
739
|
+
issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
function checkObject(schema, value, path, issues) {
|
|
743
|
+
if (!isPlainObject(value)) {
|
|
744
|
+
issues.push(`${path ? name(path) : "the arguments"} must be an object`);
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
const properties = schema.properties ?? {};
|
|
748
|
+
for (const key of schema.required ?? []) {
|
|
749
|
+
if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
|
|
750
|
+
}
|
|
751
|
+
const unknown = [];
|
|
752
|
+
for (const [key, item] of Object.entries(value)) {
|
|
753
|
+
const property = properties[key];
|
|
754
|
+
if (!property) {
|
|
755
|
+
if (schema.additionalProperties === false) unknown.push(key);
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
if (item === void 0 || item === null) continue;
|
|
759
|
+
checkValue(property, item, child(path, key), issues);
|
|
760
|
+
}
|
|
761
|
+
if (unknown.length) {
|
|
762
|
+
const known = Object.keys(properties);
|
|
763
|
+
issues.push(`unknown ${path ? `field${unknown.length > 1 ? "s" : ""} in ${name(path)}` : `argument${unknown.length > 1 ? "s" : ""}`} ${unknown.map((key) => JSON.stringify(key)).join(", ")}` + (known.length ? ` (expected: ${known.join(", ")})` : ""));
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
function copyDefault(value) {
|
|
767
|
+
return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
|
|
768
|
+
}
|
|
769
|
+
function validateArguments(schema, args) {
|
|
770
|
+
const input = args === void 0 || args === null ? {} : args;
|
|
771
|
+
if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
|
|
772
|
+
const value = { ...input };
|
|
773
|
+
if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
|
|
774
|
+
const issues = [];
|
|
775
|
+
checkObject(schema, value, "", issues);
|
|
776
|
+
if (issues.length) return { ok: false, issues };
|
|
777
|
+
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
|
778
|
+
if (value[key] === null) delete value[key];
|
|
779
|
+
if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
|
|
780
|
+
}
|
|
781
|
+
return { ok: true, value };
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// src/core/upload-hosts.ts
|
|
785
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
786
|
+
function uploadHostProblem(entry) {
|
|
787
|
+
if (typeof entry !== "string") return "must be a host name";
|
|
788
|
+
const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
|
|
789
|
+
const labels = name2.split(".");
|
|
790
|
+
if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
|
|
791
|
+
return "must be a lowercase host name like uploads.example.com, or one with a leading dot like .example.com for every host under it";
|
|
792
|
+
}
|
|
793
|
+
if (labels.length < 2) return "needs at least two labels, like example.com";
|
|
794
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
|
|
795
|
+
return void 0;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// src/core/connector.ts
|
|
799
|
+
var ANNOTATIONS = {
|
|
800
|
+
read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
801
|
+
create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
802
|
+
update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
803
|
+
delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
|
|
804
|
+
write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
|
|
805
|
+
};
|
|
806
|
+
var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
|
|
807
|
+
var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
808
|
+
var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
809
|
+
var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
|
810
|
+
var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
|
|
811
|
+
var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
812
|
+
var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
|
|
813
|
+
function deepFreeze(value) {
|
|
814
|
+
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
|
|
815
|
+
Object.freeze(value);
|
|
816
|
+
for (const item of Object.values(value)) deepFreeze(item);
|
|
817
|
+
}
|
|
818
|
+
return value;
|
|
819
|
+
}
|
|
820
|
+
function assertDefinition(def) {
|
|
821
|
+
const problem = (message) => {
|
|
822
|
+
throw new Error(`connector "${def.vendor}": ${message}`);
|
|
823
|
+
};
|
|
824
|
+
if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
|
|
825
|
+
if (!def.label?.trim()) problem("label is required");
|
|
826
|
+
const originFields = def.originFields ?? [];
|
|
827
|
+
if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
|
|
828
|
+
for (const origin of def.origins) {
|
|
829
|
+
let url;
|
|
830
|
+
try {
|
|
831
|
+
url = new URL(origin);
|
|
832
|
+
} catch {
|
|
833
|
+
}
|
|
834
|
+
if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
|
|
835
|
+
}
|
|
836
|
+
for (const name2 of def.credentials) {
|
|
837
|
+
if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
|
|
838
|
+
}
|
|
839
|
+
for (const [index, name2] of originFields.entries()) {
|
|
840
|
+
if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
|
|
841
|
+
if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
|
|
842
|
+
}
|
|
843
|
+
const names = /* @__PURE__ */ new Set();
|
|
844
|
+
for (const tool of def.tools) {
|
|
845
|
+
if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
846
|
+
if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
|
|
847
|
+
names.add(tool.name);
|
|
848
|
+
if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
|
|
849
|
+
if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
|
|
850
|
+
if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
|
|
851
|
+
if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
|
|
852
|
+
problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
for (const tool of def.tools) {
|
|
856
|
+
if (tool.kind === "read") continue;
|
|
857
|
+
const check = def.tools.find((candidate) => candidate.name === tool.check);
|
|
858
|
+
if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
|
|
859
|
+
}
|
|
860
|
+
assertUploadHosts(def, problem);
|
|
861
|
+
assertRequiredCredentials(def, problem);
|
|
862
|
+
assertAccountPickers(def, problem);
|
|
863
|
+
}
|
|
864
|
+
function assertUploadHosts(def, problem) {
|
|
865
|
+
const hosts = def.uploadHosts;
|
|
866
|
+
if (hosts === void 0) return;
|
|
867
|
+
if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
|
|
868
|
+
hosts.forEach((entry, index) => {
|
|
869
|
+
const wrong = uploadHostProblem(entry);
|
|
870
|
+
if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
|
|
871
|
+
if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
function assertRequiredCredentials(def, problem) {
|
|
875
|
+
const required = def.requiredCredentials;
|
|
876
|
+
if (required === void 0) return;
|
|
877
|
+
if (!Array.isArray(required) || !required.length) {
|
|
878
|
+
problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
|
|
879
|
+
}
|
|
880
|
+
required.forEach((list, index) => {
|
|
881
|
+
const which = `requiredCredentials[${index}]`;
|
|
882
|
+
if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
|
|
883
|
+
list.forEach((name2, position) => {
|
|
884
|
+
if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
|
|
885
|
+
if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
|
|
886
|
+
});
|
|
887
|
+
});
|
|
888
|
+
const lists = required;
|
|
889
|
+
lists.forEach((list, index) => {
|
|
890
|
+
const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
|
|
891
|
+
if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
|
|
892
|
+
if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
|
|
893
|
+
problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
|
|
894
|
+
}
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
function isDotPath(value) {
|
|
898
|
+
return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
|
|
899
|
+
}
|
|
900
|
+
function assertAccountPickers(def, problem) {
|
|
901
|
+
const pickers = def.accountPickers;
|
|
902
|
+
if (pickers === void 0) return;
|
|
903
|
+
if (!Array.isArray(pickers)) problem("accountPickers must be a list");
|
|
904
|
+
const keys = /* @__PURE__ */ new Set();
|
|
905
|
+
for (const item of pickers) {
|
|
906
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
|
|
907
|
+
const picker = item;
|
|
908
|
+
const key = picker["key"];
|
|
909
|
+
if (typeof key !== "string" || !PICKER_KEY_PATTERN.test(key)) problem(`account picker ${JSON.stringify(key)}: key must match ^[a-z][a-z0-9_]{0,63}$`);
|
|
910
|
+
if (keys.has(key)) problem(`account picker ${key} is defined twice`);
|
|
911
|
+
keys.add(key);
|
|
912
|
+
const fail = (message) => problem(`account picker ${key}: ${message}`);
|
|
913
|
+
const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
|
|
914
|
+
if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
|
|
915
|
+
const { label, description, multiple, legacyField } = picker;
|
|
916
|
+
if (typeof label !== "string" || !label.trim()) fail("label is required");
|
|
917
|
+
if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
|
|
918
|
+
fail("description, when given, must be a text of 1 to 1024 characters");
|
|
919
|
+
}
|
|
920
|
+
if (typeof multiple !== "boolean") fail("multiple must be true or false");
|
|
921
|
+
const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
|
|
922
|
+
if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
|
|
923
|
+
if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
|
|
924
|
+
for (const field of ["idField", "nameField"]) {
|
|
925
|
+
if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
|
|
926
|
+
}
|
|
927
|
+
if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
|
|
928
|
+
fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
function copyPicker(picker) {
|
|
933
|
+
return {
|
|
934
|
+
key: picker.key,
|
|
935
|
+
label: picker.label,
|
|
936
|
+
...picker.description !== void 0 ? { description: picker.description } : {},
|
|
937
|
+
multiple: picker.multiple,
|
|
938
|
+
tool: picker.tool,
|
|
939
|
+
idField: picker.idField,
|
|
940
|
+
nameField: picker.nameField,
|
|
941
|
+
...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
function result(payload, isError, files = []) {
|
|
945
|
+
return {
|
|
946
|
+
content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
|
|
947
|
+
...isError ? { isError: true } : {}
|
|
948
|
+
};
|
|
949
|
+
}
|
|
950
|
+
function failure(message, details = {}) {
|
|
951
|
+
return result({ error: message, ...details }, true);
|
|
952
|
+
}
|
|
953
|
+
function trimmed(values) {
|
|
954
|
+
const out = {};
|
|
955
|
+
if (typeof values !== "object" || values === null) return out;
|
|
956
|
+
for (const [key, value] of Object.entries(values)) {
|
|
957
|
+
if (value === void 0 || value === null) continue;
|
|
958
|
+
const text = String(value).trim();
|
|
959
|
+
if (text) out[key] = text;
|
|
960
|
+
}
|
|
961
|
+
return out;
|
|
962
|
+
}
|
|
963
|
+
function defineConnector(def) {
|
|
964
|
+
assertDefinition(def);
|
|
965
|
+
const { label } = def;
|
|
966
|
+
const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
|
|
967
|
+
const toolList = def.tools.map((tool) => tool.name).join(", ");
|
|
968
|
+
const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
|
|
969
|
+
const required = requiredAlternatives(def);
|
|
970
|
+
const notConnected = (unmet) => {
|
|
971
|
+
const [first] = unmet;
|
|
972
|
+
if (unmet.length === 1 && first) {
|
|
973
|
+
return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
|
|
974
|
+
}
|
|
975
|
+
return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
|
|
976
|
+
};
|
|
977
|
+
const descriptors = def.tools.map((tool) => ({
|
|
978
|
+
name: tool.name,
|
|
979
|
+
title: tool.title,
|
|
980
|
+
description: tool.description,
|
|
981
|
+
inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
|
|
982
|
+
annotations: { ...ANNOTATIONS[tool.kind] }
|
|
983
|
+
}));
|
|
984
|
+
async function call(toolName, args, ctx) {
|
|
985
|
+
const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
|
|
986
|
+
if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
|
|
987
|
+
if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
|
|
988
|
+
const log = (text) => {
|
|
989
|
+
try {
|
|
990
|
+
ctx.log?.(text);
|
|
991
|
+
} catch {
|
|
992
|
+
}
|
|
993
|
+
};
|
|
994
|
+
const given = trimmed(ctx.credentials);
|
|
995
|
+
const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
|
|
996
|
+
const has = (name2) => Boolean(credentials[name2]);
|
|
997
|
+
const unmet = unmetAlternatives(required, has);
|
|
998
|
+
if (unmet.length) return failure(notConnected(unmet));
|
|
999
|
+
const complete = required.filter((list) => list.every(has));
|
|
1000
|
+
const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
|
|
1001
|
+
const fieldOrigins = /* @__PURE__ */ new Map();
|
|
1002
|
+
for (const name2 of def.originFields ?? []) {
|
|
1003
|
+
if (!given[name2] && !inUse.includes(name2)) continue;
|
|
1004
|
+
const site = parseSiteUrl(given[name2] ?? "");
|
|
1005
|
+
if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
|
|
1006
|
+
fieldOrigins.set(name2, site.origin);
|
|
1007
|
+
}
|
|
1008
|
+
const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
|
|
1009
|
+
const parsed = validateArguments(tool.inputSchema, args);
|
|
1010
|
+
if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
|
|
1011
|
+
const frozenCredentials = Object.freeze({ ...credentials });
|
|
1012
|
+
let writeSent = false;
|
|
1013
|
+
const fileLimit = fileLimitOf(ctx);
|
|
1014
|
+
const files = [];
|
|
1015
|
+
let fileBytes = 0;
|
|
1016
|
+
const http = createHttp({
|
|
1017
|
+
vendor: def.vendor,
|
|
1018
|
+
label,
|
|
1019
|
+
tool: tool.name,
|
|
1020
|
+
readOnly: tool.kind === "read",
|
|
1021
|
+
origins,
|
|
1022
|
+
// A 401 names the credentials in use (for a module that needs none, the ones given).
|
|
1023
|
+
credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
|
|
1024
|
+
ctx,
|
|
1025
|
+
authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
|
|
1026
|
+
log,
|
|
1027
|
+
onWriteSent: () => {
|
|
1028
|
+
writeSent = true;
|
|
1029
|
+
}
|
|
1030
|
+
});
|
|
1031
|
+
const helpers = {
|
|
1032
|
+
tool: tool.name,
|
|
1033
|
+
credentials: frozenCredentials,
|
|
1034
|
+
ctx,
|
|
1035
|
+
origins: Object.freeze([...origins]),
|
|
1036
|
+
originOf: (credential) => {
|
|
1037
|
+
const origin = fieldOrigins.get(credential);
|
|
1038
|
+
if (!origin) throw new Error(`${credential} gives no origin in this call`);
|
|
1039
|
+
return origin;
|
|
1040
|
+
},
|
|
1041
|
+
api: http.api,
|
|
1042
|
+
media: http.media,
|
|
1043
|
+
page: (input) => fitPage(input),
|
|
1044
|
+
cursor: (cursor) => decodeCursor(tool.name, cursor),
|
|
1045
|
+
makeCursor: (state) => encodeCursor(tool.name, state),
|
|
1046
|
+
fileLimit: () => fileLimit,
|
|
1047
|
+
file: ({ name: name2, mimeType, bytes }) => {
|
|
1048
|
+
if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
|
|
1049
|
+
const total = fileBytes + bytes.byteLength;
|
|
1050
|
+
if (total > fileLimit) {
|
|
1051
|
+
throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
|
|
1052
|
+
}
|
|
1053
|
+
fileBytes = total;
|
|
1054
|
+
const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
|
|
1055
|
+
files.push({ ...info, bytes });
|
|
1056
|
+
return { ...info };
|
|
1057
|
+
},
|
|
1058
|
+
log
|
|
1059
|
+
};
|
|
1060
|
+
try {
|
|
1061
|
+
const data = await tool.run(parsed.value, helpers);
|
|
1062
|
+
const fitted = shrinkToFit(data ?? {});
|
|
1063
|
+
if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
|
|
1064
|
+
const payload = fitted.value;
|
|
1065
|
+
return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
|
|
1066
|
+
} catch (error) {
|
|
1067
|
+
if (error instanceof OutcomeUnknown) {
|
|
1068
|
+
return result({
|
|
1069
|
+
outcome: "unknown",
|
|
1070
|
+
check: tool.check,
|
|
1071
|
+
error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
|
|
1072
|
+
}, true);
|
|
1073
|
+
}
|
|
1074
|
+
if (error instanceof ToolFailure) return failure(error.message, error.details);
|
|
1075
|
+
log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
|
|
1076
|
+
if (writeSent) {
|
|
1077
|
+
return result({
|
|
1078
|
+
outcome: "unknown",
|
|
1079
|
+
check: tool.check,
|
|
1080
|
+
error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
|
|
1081
|
+
}, true);
|
|
1082
|
+
}
|
|
1083
|
+
return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
return deepFreeze({
|
|
1087
|
+
vendor: def.vendor,
|
|
1088
|
+
origins: [...def.origins],
|
|
1089
|
+
originFields: [...def.originFields ?? []],
|
|
1090
|
+
uploadHosts: [...def.uploadHosts ?? []],
|
|
1091
|
+
credentials: [...def.credentials],
|
|
1092
|
+
requiredCredentials: required.map((list) => [...list]),
|
|
1093
|
+
accountPickers: (def.accountPickers ?? []).map(copyPicker),
|
|
1094
|
+
tools: descriptors,
|
|
1095
|
+
call
|
|
1096
|
+
});
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
// src/core/jwt.ts
|
|
1100
|
+
var KEY_ALGORITHMS = {
|
|
1101
|
+
RS256: { import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, sign: { name: "RSASSA-PKCS1-v1_5" }, kind: "an RSA" },
|
|
1102
|
+
// WebCrypto returns ECDSA signatures as raw r||s, the form JWS (ES256) needs.
|
|
1103
|
+
ES256: { import: { name: "ECDSA", namedCurve: "P-256" }, sign: { name: "ECDSA", hash: "SHA-256" }, kind: "a P-256 (ES256)" }
|
|
1104
|
+
};
|
|
1105
|
+
function base64UrlJson(value) {
|
|
1106
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify(value)));
|
|
1107
|
+
}
|
|
1108
|
+
function pkcs8Der(pem, keyName) {
|
|
1109
|
+
const text = String(pem).replace(/\\r\\n|\\n/g, "\n").trim();
|
|
1110
|
+
const block = /-----BEGIN ([A-Z0-9 ]+)-----([\s\S]*?)-----END \1-----/.exec(text);
|
|
1111
|
+
const whole = `it must be the whole PEM text, from -----BEGIN PRIVATE KEY----- to -----END PRIVATE KEY-----`;
|
|
1112
|
+
if (!block) throw new ToolFailure(`The ${keyName} could not be read: ${whole}. Nothing was sent.`);
|
|
1113
|
+
const type = block[1];
|
|
1114
|
+
if (type === "ENCRYPTED PRIVATE KEY") throw new ToolFailure(`The ${keyName} is encrypted with a passphrase: use the key without one. Nothing was sent.`);
|
|
1115
|
+
if (type !== "PRIVATE KEY") {
|
|
1116
|
+
throw new ToolFailure(`The ${keyName} is a "${type}" block, not a PKCS#8 "PRIVATE KEY": convert it with openssl pkcs8 -topk8 -nocrypt. Nothing was sent.`);
|
|
1117
|
+
}
|
|
1118
|
+
try {
|
|
1119
|
+
return base64Decode(block[2]);
|
|
1120
|
+
} catch {
|
|
1121
|
+
throw new ToolFailure(`The ${keyName} could not be read: ${whole}. Nothing was sent.`);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
async function signJwt(options) {
|
|
1125
|
+
const keyName = options.keyName ?? "private key";
|
|
1126
|
+
const algorithm = KEY_ALGORITHMS[options.algorithm];
|
|
1127
|
+
if (!algorithm) throw new Error(`unsupported JWT algorithm ${String(options.algorithm)}`);
|
|
1128
|
+
const der = pkcs8Der(options.privateKey, keyName);
|
|
1129
|
+
let key;
|
|
1130
|
+
try {
|
|
1131
|
+
key = await crypto.subtle.importKey("pkcs8", der, algorithm.import, false, ["sign"]);
|
|
1132
|
+
} catch {
|
|
1133
|
+
throw new ToolFailure(`The ${keyName} is not ${algorithm.kind} private key. Nothing was sent.`);
|
|
1134
|
+
}
|
|
1135
|
+
const header = { alg: options.algorithm, typ: "JWT", ...options.header };
|
|
1136
|
+
header.alg = options.algorithm;
|
|
1137
|
+
const signingInput = `${base64UrlJson(header)}.${base64UrlJson(options.payload)}`;
|
|
1138
|
+
const signature = new Uint8Array(await crypto.subtle.sign(algorithm.sign, key, utf8Bytes(signingInput)));
|
|
1139
|
+
return `${signingInput}.${base64UrlEncode(signature)}`;
|
|
1140
|
+
}
|
|
1141
|
+
var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
1142
|
+
var GOOGLE_TOKEN_ORIGIN = "https://oauth2.googleapis.com";
|
|
1143
|
+
var JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
|
|
1144
|
+
var TOKEN_EARLY_MS = 5 * 60 * 1e3;
|
|
1145
|
+
var MAX_CACHED_TOKENS = 64;
|
|
1146
|
+
var SERVICE_ACCOUNT_HELP = 'The service account key is not a Google service account key file: paste the whole JSON file Google Cloud creates for the key (IAM and admin -> Service accounts -> Keys -> Add key -> JSON), with "client_email" and "private_key" in it. Nothing was sent.';
|
|
1147
|
+
var googleTokens = /* @__PURE__ */ new Map();
|
|
1148
|
+
var pendingGoogleTokens = /* @__PURE__ */ new Map();
|
|
1149
|
+
function readServiceAccount(json) {
|
|
1150
|
+
let data;
|
|
1151
|
+
try {
|
|
1152
|
+
data = JSON.parse(json);
|
|
1153
|
+
} catch {
|
|
1154
|
+
throw new ToolFailure(SERVICE_ACCOUNT_HELP);
|
|
1155
|
+
}
|
|
1156
|
+
if (typeof data !== "object" || data === null || typeof data.client_email !== "string" || typeof data.private_key !== "string") {
|
|
1157
|
+
throw new ToolFailure(SERVICE_ACCOUNT_HELP);
|
|
1158
|
+
}
|
|
1159
|
+
if (data.type !== void 0 && data.type !== "service_account") {
|
|
1160
|
+
throw new ToolFailure(`The Google key is a "${String(data.type).slice(0, 40)}" credential, not a service account key. ${SERVICE_ACCOUNT_HELP}`);
|
|
1161
|
+
}
|
|
1162
|
+
return { clientEmail: data.client_email, privateKey: data.private_key, ...typeof data.private_key_id === "string" ? { keyId: data.private_key_id } : {} };
|
|
1163
|
+
}
|
|
1164
|
+
async function exchangeGoogleToken(h, account, options) {
|
|
1165
|
+
const iat = Math.floor(Date.now() / 1e3);
|
|
1166
|
+
const assertion = await signJwt({
|
|
1167
|
+
algorithm: "RS256",
|
|
1168
|
+
privateKey: account.privateKey,
|
|
1169
|
+
header: account.keyId ? { kid: account.keyId } : {},
|
|
1170
|
+
payload: {
|
|
1171
|
+
iss: account.clientEmail,
|
|
1172
|
+
scope: options.scopes.join(" "),
|
|
1173
|
+
aud: GOOGLE_TOKEN_URL,
|
|
1174
|
+
iat,
|
|
1175
|
+
exp: iat + 3600,
|
|
1176
|
+
...options.subject ? { sub: options.subject } : {}
|
|
1177
|
+
},
|
|
1178
|
+
keyName: "service account private key"
|
|
1179
|
+
});
|
|
1180
|
+
const { data } = await h.api({
|
|
1181
|
+
method: "POST",
|
|
1182
|
+
origin: GOOGLE_TOKEN_ORIGIN,
|
|
1183
|
+
path: "/token",
|
|
1184
|
+
body: utf8Bytes(new URLSearchParams({ grant_type: JWT_BEARER, assertion }).toString()),
|
|
1185
|
+
contentType: "application/x-www-form-urlencoded",
|
|
1186
|
+
// The assertion is the credential: no module auth header goes with it.
|
|
1187
|
+
auth: false,
|
|
1188
|
+
// A token exchange changes nothing, so read tools may make it.
|
|
1189
|
+
safe: true,
|
|
1190
|
+
errors: {
|
|
1191
|
+
400: "Google did not accept the service account key",
|
|
1192
|
+
401: "Google did not accept the service account key"
|
|
1193
|
+
}
|
|
1194
|
+
});
|
|
1195
|
+
if (typeof data?.access_token !== "string" || !data.access_token) throw new ToolFailure("Google sent no access token for the service account.");
|
|
1196
|
+
const expiresIn = typeof data.expires_in === "number" && data.expires_in > 0 ? data.expires_in : 3600;
|
|
1197
|
+
return { token: data.access_token, expiresIn };
|
|
1198
|
+
}
|
|
1199
|
+
async function googleServiceAccountToken(h, serviceAccountJson, options) {
|
|
1200
|
+
if (!h.origins.includes(GOOGLE_TOKEN_ORIGIN)) throw new Error(`a module that uses googleServiceAccountToken declares ${GOOGLE_TOKEN_ORIGIN} in its origins`);
|
|
1201
|
+
const account = readServiceAccount(serviceAccountJson);
|
|
1202
|
+
const key = await sha256Hex([account.clientEmail, account.privateKey, options.scopes.join(" "), options.subject ?? ""].join("\n"));
|
|
1203
|
+
const cached = googleTokens.get(key);
|
|
1204
|
+
if (cached && cached.expiresAt > Date.now()) return cached.token;
|
|
1205
|
+
googleTokens.delete(key);
|
|
1206
|
+
const inFlight = pendingGoogleTokens.get(key);
|
|
1207
|
+
if (inFlight) return inFlight;
|
|
1208
|
+
const started = exchangeGoogleToken(h, account, options).then(({ token, expiresIn }) => {
|
|
1209
|
+
const now = Date.now();
|
|
1210
|
+
for (const [other, entry] of googleTokens) if (entry.expiresAt <= now) googleTokens.delete(other);
|
|
1211
|
+
while (googleTokens.size >= MAX_CACHED_TOKENS) {
|
|
1212
|
+
const oldest = googleTokens.keys().next().value;
|
|
1213
|
+
if (oldest === void 0) break;
|
|
1214
|
+
googleTokens.delete(oldest);
|
|
1215
|
+
}
|
|
1216
|
+
googleTokens.set(key, { token, expiresAt: now + Math.min(expiresIn, 3600) * 1e3 - TOKEN_EARLY_MS });
|
|
1217
|
+
return token;
|
|
1218
|
+
}).finally(() => pendingGoogleTokens.delete(key));
|
|
1219
|
+
pendingGoogleTokens.set(key, started);
|
|
1220
|
+
return started;
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
// src/vendors/google-play/catalog.ts
|
|
1224
|
+
function compact(value) {
|
|
1225
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
|
|
1226
|
+
}
|
|
1227
|
+
function isoTime(stamp) {
|
|
1228
|
+
const seconds = Number(stamp?.seconds);
|
|
1229
|
+
return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1e3).toISOString() : void 0;
|
|
1230
|
+
}
|
|
1231
|
+
function cleanText(value) {
|
|
1232
|
+
return typeof value === "string" ? value.replace(/^\t+/, "").trim() : void 0;
|
|
1233
|
+
}
|
|
1234
|
+
function trimReview(review) {
|
|
1235
|
+
const comments = Array.isArray(review?.comments) ? review.comments : [];
|
|
1236
|
+
const user = comments.find((comment) => comment?.userComment)?.userComment;
|
|
1237
|
+
const developer = comments.find((comment) => comment?.developerComment)?.developerComment;
|
|
1238
|
+
return compact({
|
|
1239
|
+
reviewId: review?.reviewId,
|
|
1240
|
+
author: review?.authorName,
|
|
1241
|
+
rating: user?.starRating,
|
|
1242
|
+
text: cleanText(user?.text),
|
|
1243
|
+
originalText: cleanText(user?.originalText),
|
|
1244
|
+
language: user?.reviewerLanguage,
|
|
1245
|
+
modifiedAt: isoTime(user?.lastModified),
|
|
1246
|
+
appVersion: user?.appVersionName,
|
|
1247
|
+
appVersionCode: user?.appVersionCode,
|
|
1248
|
+
device: user?.deviceMetadata?.productName ?? user?.device,
|
|
1249
|
+
androidOsVersion: user?.androidOsVersion,
|
|
1250
|
+
thumbsUp: user?.thumbsUpCount,
|
|
1251
|
+
thumbsDown: user?.thumbsDownCount,
|
|
1252
|
+
replied: Boolean(developer),
|
|
1253
|
+
reply: developer ? compact({ text: cleanText(developer.text), modifiedAt: isoTime(developer.lastModified) }) : void 0
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
function trimListing(listing) {
|
|
1257
|
+
return compact({
|
|
1258
|
+
language: listing?.language,
|
|
1259
|
+
title: listing?.title,
|
|
1260
|
+
shortDescription: listing?.shortDescription,
|
|
1261
|
+
fullDescription: listing?.fullDescription,
|
|
1262
|
+
video: listing?.video
|
|
1263
|
+
});
|
|
1264
|
+
}
|
|
1265
|
+
function money(value) {
|
|
1266
|
+
if (!value || typeof value !== "object" || typeof value.currencyCode !== "string") return void 0;
|
|
1267
|
+
const amount = Number(value.units ?? 0) + Number(value.nanos ?? 0) / 1e9;
|
|
1268
|
+
return Number.isFinite(amount) ? { amount: amount.toFixed(2), currency: value.currencyCode } : void 0;
|
|
1269
|
+
}
|
|
1270
|
+
function regionalPrice(configs, region, priceKey = "price") {
|
|
1271
|
+
const list = Array.isArray(configs) ? configs : [];
|
|
1272
|
+
const config = list.find((item) => item?.regionCode === region) ?? list[0];
|
|
1273
|
+
const price = money(config?.[priceKey]);
|
|
1274
|
+
return price ? { region: config?.regionCode, ...price } : void 0;
|
|
1275
|
+
}
|
|
1276
|
+
function phaseOf(phase, region) {
|
|
1277
|
+
const configs = Array.isArray(phase?.regionalConfigs) ? phase.regionalConfigs : [];
|
|
1278
|
+
const config = configs.find((item) => item?.regionCode === region) ?? configs[0];
|
|
1279
|
+
const free = Boolean(config?.free) || Boolean(phase?.otherRegionsConfig?.free);
|
|
1280
|
+
return compact({
|
|
1281
|
+
duration: phase?.duration,
|
|
1282
|
+
recurrenceCount: phase?.recurrenceCount,
|
|
1283
|
+
free: free ? true : void 0,
|
|
1284
|
+
price: free ? void 0 : money(config?.price),
|
|
1285
|
+
relativeDiscount: free ? void 0 : config?.relativeDiscount
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
1288
|
+
function offersByBasePlan(offers, region) {
|
|
1289
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
1290
|
+
for (const offer of offers) {
|
|
1291
|
+
const key = `${offer?.productId}/${offer?.basePlanId}`;
|
|
1292
|
+
const phases = Array.isArray(offer?.phases) ? offer.phases : [];
|
|
1293
|
+
const trimmed2 = phases.map((phase) => phaseOf(phase, region));
|
|
1294
|
+
const trial = trimmed2.find((phase) => phase["free"] === true);
|
|
1295
|
+
const list = grouped.get(key) ?? [];
|
|
1296
|
+
list.push(compact({
|
|
1297
|
+
offerId: offer?.offerId,
|
|
1298
|
+
state: offer?.state,
|
|
1299
|
+
offerTags: Array.isArray(offer?.offerTags) ? offer.offerTags.map((tag) => tag?.tag).filter(Boolean) : void 0,
|
|
1300
|
+
phases: trimmed2,
|
|
1301
|
+
freeTrial: trial ? trial["duration"] : void 0
|
|
1302
|
+
}));
|
|
1303
|
+
grouped.set(key, list);
|
|
1304
|
+
}
|
|
1305
|
+
return grouped;
|
|
1306
|
+
}
|
|
1307
|
+
function basePlanType(plan) {
|
|
1308
|
+
if (plan?.autoRenewingBasePlanType) return "auto_renewing";
|
|
1309
|
+
if (plan?.prepaidBasePlanType) return "prepaid";
|
|
1310
|
+
if (plan?.installmentsBasePlanType) return "installments";
|
|
1311
|
+
return void 0;
|
|
1312
|
+
}
|
|
1313
|
+
function trimSubscription(subscription, region, offers) {
|
|
1314
|
+
const listings = Array.isArray(subscription?.listings) ? subscription.listings : [];
|
|
1315
|
+
const plans = Array.isArray(subscription?.basePlans) ? subscription.basePlans : [];
|
|
1316
|
+
let hasFreeTrial = false;
|
|
1317
|
+
const basePlans = plans.map((plan) => {
|
|
1318
|
+
const kind = plan?.autoRenewingBasePlanType ?? plan?.prepaidBasePlanType ?? plan?.installmentsBasePlanType;
|
|
1319
|
+
const planOffers = offers?.get(`${subscription?.productId}/${plan?.basePlanId}`);
|
|
1320
|
+
if (plan?.state === "ACTIVE" && planOffers?.some((offer) => offer["state"] === "ACTIVE" && offer["freeTrial"])) hasFreeTrial = true;
|
|
1321
|
+
return compact({
|
|
1322
|
+
basePlanId: plan?.basePlanId,
|
|
1323
|
+
state: plan?.state,
|
|
1324
|
+
type: basePlanType(plan),
|
|
1325
|
+
billingPeriod: kind?.billingPeriodDuration,
|
|
1326
|
+
gracePeriod: plan?.autoRenewingBasePlanType?.gracePeriodDuration,
|
|
1327
|
+
offerTags: Array.isArray(plan?.offerTags) ? plan.offerTags.map((tag) => tag?.tag).filter(Boolean) : void 0,
|
|
1328
|
+
price: regionalPrice(plan?.regionalConfigs, region),
|
|
1329
|
+
regions: Array.isArray(plan?.regionalConfigs) ? plan.regionalConfigs.length : void 0,
|
|
1330
|
+
offers: planOffers
|
|
1331
|
+
});
|
|
1332
|
+
});
|
|
1333
|
+
return compact({
|
|
1334
|
+
productId: subscription?.productId,
|
|
1335
|
+
listings: listings.slice(0, 8).map((listing) => compact({
|
|
1336
|
+
language: listing?.languageCode,
|
|
1337
|
+
title: listing?.title,
|
|
1338
|
+
description: typeof listing?.description === "string" ? truncate(listing.description, 300) : void 0,
|
|
1339
|
+
benefits: Array.isArray(listing?.benefits) ? listing.benefits.slice(0, 4) : void 0
|
|
1340
|
+
})),
|
|
1341
|
+
languages: listings.length > 8 ? listings.length : void 0,
|
|
1342
|
+
basePlans,
|
|
1343
|
+
hasFreeTrial: offers ? hasFreeTrial : void 0
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
function trimInAppProduct(product, region) {
|
|
1347
|
+
const listings = product?.listings && typeof product.listings === "object" ? product.listings : {};
|
|
1348
|
+
const languages = Object.keys(listings);
|
|
1349
|
+
const listing = listings[product?.defaultLanguage] ?? listings[languages[0]];
|
|
1350
|
+
const micros = Number(product?.defaultPrice?.priceMicros);
|
|
1351
|
+
const regional = product?.prices?.[region];
|
|
1352
|
+
const regionalMicros = Number(regional?.priceMicros);
|
|
1353
|
+
return compact({
|
|
1354
|
+
sku: product?.sku,
|
|
1355
|
+
status: product?.status,
|
|
1356
|
+
purchaseType: product?.purchaseType,
|
|
1357
|
+
title: listing?.title,
|
|
1358
|
+
description: typeof listing?.description === "string" ? truncate(listing.description, 300) : void 0,
|
|
1359
|
+
defaultLanguage: product?.defaultLanguage,
|
|
1360
|
+
languages: languages.length,
|
|
1361
|
+
price: Number.isFinite(micros) ? { amount: (micros / 1e6).toFixed(2), currency: product?.defaultPrice?.currency } : void 0,
|
|
1362
|
+
regionPrice: Number.isFinite(regionalMicros) ? { region, amount: (regionalMicros / 1e6).toFixed(2), currency: regional?.currency } : void 0
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
function trimOneTimeProduct(product, region) {
|
|
1366
|
+
const listings = Array.isArray(product?.listings) ? product.listings : [];
|
|
1367
|
+
const options = Array.isArray(product?.purchaseOptions) ? product.purchaseOptions : [];
|
|
1368
|
+
return compact({
|
|
1369
|
+
productId: product?.productId,
|
|
1370
|
+
title: listings[0]?.title,
|
|
1371
|
+
description: typeof listings[0]?.description === "string" ? truncate(listings[0].description, 300) : void 0,
|
|
1372
|
+
languages: listings.length,
|
|
1373
|
+
offerTags: Array.isArray(product?.offerTags) ? product.offerTags.map((tag) => tag?.tag).filter(Boolean) : void 0,
|
|
1374
|
+
purchaseOptions: options.slice(0, 10).map((option) => compact({
|
|
1375
|
+
purchaseOptionId: option?.purchaseOptionId,
|
|
1376
|
+
state: option?.state,
|
|
1377
|
+
type: option?.buyOption ? "buy" : option?.rentOption ? "rent" : void 0,
|
|
1378
|
+
price: regionalPrice(option?.regionalPricingAndAvailabilityConfigs, region)
|
|
1379
|
+
}))
|
|
1380
|
+
});
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
// src/vendors/google-play/service-account.ts
|
|
1384
|
+
var KEY_CREDENTIAL = "serviceaccountjson";
|
|
1385
|
+
function keyFileText(value) {
|
|
1386
|
+
const text = (value ?? "").trim();
|
|
1387
|
+
if (text.startsWith("{")) return text;
|
|
1388
|
+
const raw = text.replace(/^data:[^,]*;base64,/i, "").replace(/-/g, "+").replace(/_/g, "/");
|
|
1389
|
+
try {
|
|
1390
|
+
const decoded = utf8Decode(base64Decode(raw)).trim();
|
|
1391
|
+
if (decoded.startsWith("{")) return decoded;
|
|
1392
|
+
} catch {
|
|
1393
|
+
}
|
|
1394
|
+
return text;
|
|
1395
|
+
}
|
|
1396
|
+
function serviceAccountEmail(h) {
|
|
1397
|
+
try {
|
|
1398
|
+
const data = JSON.parse(keyFileText(h.credentials[KEY_CREDENTIAL]));
|
|
1399
|
+
const email = data?.client_email;
|
|
1400
|
+
return typeof email === "string" && /^[^\s@]+@[^\s@]+$/.test(email) ? email : void 0;
|
|
1401
|
+
} catch {
|
|
1402
|
+
return void 0;
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1405
|
+
function serviceAccountWords(h) {
|
|
1406
|
+
const email = serviceAccountEmail(h);
|
|
1407
|
+
return email ? `the service account ${email}` : "the service account";
|
|
1408
|
+
}
|
|
1409
|
+
async function googleApi(h, scopes, request) {
|
|
1410
|
+
const token = await googleServiceAccountToken(h, keyFileText(h.credentials[KEY_CREDENTIAL]), { scopes });
|
|
1411
|
+
return h.api({ ...request, headers: { ...request.headers, authorization: `Bearer ${token}` } });
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
// src/vendors/google-play/store-page.ts
|
|
1415
|
+
var NAMED = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
|
1416
|
+
function character(code, fallback) {
|
|
1417
|
+
return Number.isInteger(code) && code > 0 && code <= 1114111 && (code < 55296 || code > 57343) ? String.fromCodePoint(code) : fallback;
|
|
1418
|
+
}
|
|
1419
|
+
function decodeEntities(text) {
|
|
1420
|
+
return text.replace(/&(#[xX][0-9a-fA-F]{1,6}|#[0-9]{1,7}|[A-Za-z]{2,6});/g, (whole, name2) => {
|
|
1421
|
+
if (name2[0] === "#") return character(name2[1] === "x" || name2[1] === "X" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10), whole);
|
|
1422
|
+
return NAMED[name2.toLowerCase()] ?? whole;
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
function htmlText(html) {
|
|
1426
|
+
return decodeEntities(html.replace(/<br\s*\/?>/gi, "\n").replace(/<\/(p|div|li)>/gi, "\n").replace(/<[^>]*>/g, "")).replace(/\n{3,}/g, "\n\n").trim();
|
|
1427
|
+
}
|
|
1428
|
+
function numberOf(value) {
|
|
1429
|
+
const number = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
|
|
1430
|
+
return Number.isFinite(number) ? number : void 0;
|
|
1431
|
+
}
|
|
1432
|
+
function parseStorePage(html) {
|
|
1433
|
+
let app;
|
|
1434
|
+
for (const match of html.matchAll(/<script[^>]*type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/g)) {
|
|
1435
|
+
try {
|
|
1436
|
+
const data = JSON.parse(match[1]);
|
|
1437
|
+
const type = data?.["@type"];
|
|
1438
|
+
if (type === "SoftwareApplication" || type === "MobileApplication" || type === "VideoGame") {
|
|
1439
|
+
app = data;
|
|
1440
|
+
break;
|
|
1441
|
+
}
|
|
1442
|
+
} catch {
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
const description = /<div[^>]*\bdata-g-id="description"[^>]*>([\s\S]*?)<\/div>/.exec(html)?.[1];
|
|
1446
|
+
if (!app && description === void 0) return void 0;
|
|
1447
|
+
const offers = Array.isArray(app?.offers) ? app.offers : app?.offers ? [app.offers] : [];
|
|
1448
|
+
const price = numberOf(offers[0]?.price);
|
|
1449
|
+
const rating = numberOf(app?.aggregateRating?.ratingValue);
|
|
1450
|
+
return compact({
|
|
1451
|
+
title: typeof app?.name === "string" ? app.name : void 0,
|
|
1452
|
+
shortDescription: typeof app?.description === "string" ? app.description : void 0,
|
|
1453
|
+
fullDescription: description !== void 0 ? truncate(htmlText(description), 6e3) : void 0,
|
|
1454
|
+
category: app?.applicationCategory,
|
|
1455
|
+
contentRating: app?.contentRating,
|
|
1456
|
+
developer: app?.author?.name,
|
|
1457
|
+
developerWebsite: app?.author?.url,
|
|
1458
|
+
rating: rating !== void 0 ? Math.round(rating * 100) / 100 : void 0,
|
|
1459
|
+
ratingCount: numberOf(app?.aggregateRating?.ratingCount),
|
|
1460
|
+
price: price === void 0 ? void 0 : price === 0 ? "free" : { amount: price.toFixed(2), currency: offers[0]?.priceCurrency },
|
|
1461
|
+
icon: typeof app?.image === "string" ? app.image : void 0
|
|
1462
|
+
});
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// src/vendors/google-play/index.ts
|
|
1466
|
+
var LABEL2 = "Google Play";
|
|
1467
|
+
var PUBLISHER_ORIGIN = "https://androidpublisher.googleapis.com";
|
|
1468
|
+
var REPORTING_ORIGIN = "https://playdeveloperreporting.googleapis.com";
|
|
1469
|
+
var TOKEN_ORIGIN = "https://oauth2.googleapis.com";
|
|
1470
|
+
var SCOPES = ["https://www.googleapis.com/auth/androidpublisher", "https://www.googleapis.com/auth/playdeveloperreporting"];
|
|
1471
|
+
var PICKER = "apps";
|
|
1472
|
+
var MAX_REPLY = 350;
|
|
1473
|
+
var PACKAGE_PATTERN = "^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+$";
|
|
1474
|
+
var STORE_PAGE = "https://play.google.com/store/apps/details";
|
|
1475
|
+
var MAX_STORE_PAGE_BYTES = 8 * 1024 * 1024;
|
|
1476
|
+
var DEFAULT_LANGUAGE = "en-US";
|
|
1477
|
+
var PACKAGE = {
|
|
1478
|
+
type: "string",
|
|
1479
|
+
pattern: PACKAGE_PATTERN,
|
|
1480
|
+
maxLength: 150,
|
|
1481
|
+
description: "The app's package name, e.g. com.example.app. Optional when only one app is chosen for the connection."
|
|
1482
|
+
};
|
|
1483
|
+
var REVIEW_ID = { type: "string", pattern: "^(?!\\.{1,2}$)[A-Za-z0-9:_.\\-]{1,512}$", description: "The review id, e.g. gp:AOqpTOE... from list_reviews." };
|
|
1484
|
+
var LANGUAGE = { type: "string", pattern: "^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$", maxLength: 20, description: "A language code as Play uses it, e.g. en-US, tr-TR or es-419." };
|
|
1485
|
+
var REGION = { type: "string", pattern: "^[A-Z]{2}$", default: "US", description: "The country whose prices to show, e.g. US (default) or TR." };
|
|
1486
|
+
function play(h, request) {
|
|
1487
|
+
const who = serviceAccountWords(h);
|
|
1488
|
+
return googleApi(h, SCOPES, {
|
|
1489
|
+
...request,
|
|
1490
|
+
errors: {
|
|
1491
|
+
401: `Google Play did not accept ${who}: check that it is invited in Play Console -> Users and permissions`,
|
|
1492
|
+
403: `Google Play refused the request: invite ${who} in Play Console -> Users and permissions with access to this app and the permission the action needs (View app information to read, Reply to reviews to reply, Manage store presence for listings and products), and check that the Google Play Android Developer API is enabled for the key's project`,
|
|
1493
|
+
404: "Google Play found no such app or item: check the package name, and that the app is published on Google Play",
|
|
1494
|
+
...request.errors
|
|
1495
|
+
}
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
function packageFor(h, given) {
|
|
1499
|
+
if (given !== void 0) {
|
|
1500
|
+
requireAccounts(h.ctx.accounts, PICKER, given, "app");
|
|
1501
|
+
return given;
|
|
1502
|
+
}
|
|
1503
|
+
const allowed = allowedAccounts(h.ctx.accounts, PICKER);
|
|
1504
|
+
if (allowed?.length === 1) return allowed[0];
|
|
1505
|
+
throw new ToolFailure(
|
|
1506
|
+
allowed?.length ? `Give package_name: one of ${allowed.join(", ")}. Nothing was sent.` : allowed ? "No app is chosen for this Google Play connection yet. Nothing was sent." : "Give package_name, such as com.example.app (list_apps lists the apps). Nothing was sent."
|
|
1507
|
+
);
|
|
1508
|
+
}
|
|
1509
|
+
function appPath(packageName, rest = "") {
|
|
1510
|
+
return `/androidpublisher/v3/applications/${encodeURIComponent(packageName)}${rest}`;
|
|
1511
|
+
}
|
|
1512
|
+
async function searchApps(h, pageToken, pageSize) {
|
|
1513
|
+
const { data } = await play(h, {
|
|
1514
|
+
origin: REPORTING_ORIGIN,
|
|
1515
|
+
path: "/v1beta1/apps:search",
|
|
1516
|
+
query: { pageSize, pageToken },
|
|
1517
|
+
errors: {
|
|
1518
|
+
403: `Google Play did not list the apps: enable the Google Play Developer Reporting API for the key's project and invite ${serviceAccountWords(h)} in Play Console -> Users and permissions`
|
|
1519
|
+
}
|
|
1520
|
+
});
|
|
1521
|
+
return {
|
|
1522
|
+
apps: Array.isArray(data?.apps) ? data.apps : [],
|
|
1523
|
+
...typeof data?.nextPageToken === "string" && data.nextPageToken ? { next: data.nextPageToken } : {}
|
|
1524
|
+
};
|
|
1525
|
+
}
|
|
1526
|
+
function trimApp(app) {
|
|
1527
|
+
const fromName = typeof app?.name === "string" ? app.name.replace(/^apps\//, "") : void 0;
|
|
1528
|
+
return compact({ packageName: app?.packageName ?? fromName, displayName: app?.displayName ?? app?.packageName ?? fromName });
|
|
1529
|
+
}
|
|
1530
|
+
async function storePage(h, packageName, language, region) {
|
|
1531
|
+
const url = `${STORE_PAGE}?id=${encodeURIComponent(packageName)}&hl=${encodeURIComponent(language)}&gl=${encodeURIComponent(region)}`;
|
|
1532
|
+
let html;
|
|
1533
|
+
try {
|
|
1534
|
+
const { bytes } = await h.media(url, { what: "Google Play store page", maxBytes: MAX_STORE_PAGE_BYTES, accept: "text/html" });
|
|
1535
|
+
html = utf8Decode(bytes);
|
|
1536
|
+
} catch (error) {
|
|
1537
|
+
if (error instanceof ToolFailure && /HTTP 404/.test(error.message)) {
|
|
1538
|
+
throw new ToolFailure(`Google Play has no public store page for ${packageName} (HTTP 404): the app is not published yet, or not in the country ${region}.`);
|
|
1539
|
+
}
|
|
1540
|
+
throw error;
|
|
1541
|
+
}
|
|
1542
|
+
const details = parseStorePage(html);
|
|
1543
|
+
if (!details) throw new ToolFailure(`Google Play's store page for ${packageName} could not be read: it carries no app details.`);
|
|
1544
|
+
return details;
|
|
1545
|
+
}
|
|
1546
|
+
function playGuard(request) {
|
|
1547
|
+
if (request.segments[2] === "developers") {
|
|
1548
|
+
throw new ToolFailure("Google Play user and permission management (/androidpublisher/v3/developers/...) is not available here: manage users in Play Console. Nothing was sent.");
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
var connector = defineConnector({
|
|
1552
|
+
vendor: "google-play",
|
|
1553
|
+
label: LABEL2,
|
|
1554
|
+
origins: [PUBLISHER_ORIGIN, REPORTING_ORIGIN, TOKEN_ORIGIN],
|
|
1555
|
+
credentials: [KEY_CREDENTIAL],
|
|
1556
|
+
credentialLabels: { serviceaccountjson: "Google Play service account key" },
|
|
1557
|
+
accountPickers: [
|
|
1558
|
+
{
|
|
1559
|
+
key: PICKER,
|
|
1560
|
+
label: "Google Play apps",
|
|
1561
|
+
description: "The Android apps the agent works on: their reviews, store listings and products.",
|
|
1562
|
+
multiple: true,
|
|
1563
|
+
tool: "list_apps",
|
|
1564
|
+
idField: "packageName",
|
|
1565
|
+
nameField: "displayName",
|
|
1566
|
+
legacyField: "apps"
|
|
1567
|
+
}
|
|
1568
|
+
],
|
|
1569
|
+
tools: [
|
|
1570
|
+
{
|
|
1571
|
+
name: "list_apps",
|
|
1572
|
+
kind: "read",
|
|
1573
|
+
title: "List Google Play apps",
|
|
1574
|
+
description: "Lists the Android apps: the apps chosen for this connection, or, with no choice made, every app the service account can see in Play Console (through the Google Play Developer Reporting API, which must be enabled for the key's project). Each has its package name and display name. Pass nextCursor back as cursor for more.",
|
|
1575
|
+
inputSchema: { type: "object", properties: { cursor: { type: "string", description: "nextCursor from the previous result." } }, additionalProperties: false },
|
|
1576
|
+
async run(args, h) {
|
|
1577
|
+
const allowed = allowedAccounts(h.ctx.accounts, PICKER);
|
|
1578
|
+
const state = h.cursor(args.cursor);
|
|
1579
|
+
if (allowed !== null) {
|
|
1580
|
+
let names = /* @__PURE__ */ new Map();
|
|
1581
|
+
let note;
|
|
1582
|
+
try {
|
|
1583
|
+
const { apps: apps2 } = await searchApps(h, void 0, 1e3);
|
|
1584
|
+
names = new Map(apps2.map((app) => trimApp(app)).map((app) => [String(app["packageName"]), String(app["displayName"])]));
|
|
1585
|
+
} catch (error) {
|
|
1586
|
+
if (!(error instanceof ToolFailure)) throw error;
|
|
1587
|
+
note = `The app names could not be read: ${truncate(error.message, 300)}`;
|
|
1588
|
+
}
|
|
1589
|
+
const offset = typeof state?.["c"] === "number" ? state["c"] : 0;
|
|
1590
|
+
return h.page({
|
|
1591
|
+
key: "apps",
|
|
1592
|
+
items: allowed.slice(offset).map((packageName) => ({ packageName, displayName: names.get(packageName) ?? packageName })),
|
|
1593
|
+
extra: compact({ chosen: true, note }),
|
|
1594
|
+
resumeAt: (index) => h.makeCursor({ c: offset + index })
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1597
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
1598
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1599
|
+
const { apps, next } = await searchApps(h, pageToken, 100);
|
|
1600
|
+
return h.page({
|
|
1601
|
+
key: "apps",
|
|
1602
|
+
items: apps.map(trimApp).slice(skip),
|
|
1603
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index }),
|
|
1604
|
+
...next ? { nextPage: h.makeCursor({ p: next, o: 0 }) } : {}
|
|
1605
|
+
});
|
|
1606
|
+
}
|
|
1607
|
+
},
|
|
1608
|
+
{
|
|
1609
|
+
name: "list_reviews",
|
|
1610
|
+
kind: "read",
|
|
1611
|
+
title: "List Google Play reviews",
|
|
1612
|
+
description: "Lists an app's reviews with text that were written or changed in the last week (all Google Play returns), newest first: id, author, stars, text, language, app version, device, and the developer reply if there is one. unanswered_only leaves out replied reviews. translation_language translates the texts. Google Play allows 200 review reads per hour per app. Pass nextCursor back as cursor for more.",
|
|
1613
|
+
inputSchema: {
|
|
1614
|
+
type: "object",
|
|
1615
|
+
properties: {
|
|
1616
|
+
package_name: PACKAGE,
|
|
1617
|
+
max_results: { type: "integer", minimum: 1, maximum: 100, default: 50, description: "Reviews per page, 1 to 100 (default 50)." },
|
|
1618
|
+
unanswered_only: { type: "boolean", default: false, description: "Only reviews without a developer reply (default false)." },
|
|
1619
|
+
translation_language: { ...LANGUAGE, description: "Translate the review texts into this language, e.g. en." },
|
|
1620
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1621
|
+
},
|
|
1622
|
+
additionalProperties: false
|
|
1623
|
+
},
|
|
1624
|
+
async run(args, h) {
|
|
1625
|
+
const packageName = packageFor(h, args.package_name);
|
|
1626
|
+
const state = h.cursor(args.cursor);
|
|
1627
|
+
const token = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
1628
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1629
|
+
const { data } = await play(h, {
|
|
1630
|
+
path: appPath(packageName, "/reviews"),
|
|
1631
|
+
query: { maxResults: args.max_results, token, translationLanguage: args.translation_language }
|
|
1632
|
+
});
|
|
1633
|
+
const reviews = (Array.isArray(data?.reviews) ? data.reviews : []).map(trimReview).filter((review) => !args.unanswered_only || review["replied"] === false);
|
|
1634
|
+
const next = data?.tokenPagination?.nextPageToken;
|
|
1635
|
+
return h.page({
|
|
1636
|
+
key: "reviews",
|
|
1637
|
+
items: reviews.slice(skip),
|
|
1638
|
+
extra: { packageName },
|
|
1639
|
+
resumeAt: (index) => h.makeCursor({ ...token ? { p: token } : {}, o: skip + index }),
|
|
1640
|
+
...typeof next === "string" && next ? { nextPage: h.makeCursor({ p: next, o: 0 }) } : {}
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
},
|
|
1644
|
+
{
|
|
1645
|
+
name: "get_review",
|
|
1646
|
+
kind: "read",
|
|
1647
|
+
title: "Get a Google Play review",
|
|
1648
|
+
description: "Returns one review of an app by its id, with the developer reply if there is one.",
|
|
1649
|
+
inputSchema: {
|
|
1650
|
+
type: "object",
|
|
1651
|
+
properties: { package_name: PACKAGE, review_id: REVIEW_ID, translation_language: { ...LANGUAGE, description: "Translate the review text into this language." } },
|
|
1652
|
+
required: ["review_id"],
|
|
1653
|
+
additionalProperties: false
|
|
1654
|
+
},
|
|
1655
|
+
async run(args, h) {
|
|
1656
|
+
const packageName = packageFor(h, args.package_name);
|
|
1657
|
+
const { data } = await play(h, { path: appPath(packageName, `/reviews/${args.review_id}`), query: { translationLanguage: args.translation_language } });
|
|
1658
|
+
return { packageName, ...trimReview(data) };
|
|
1659
|
+
}
|
|
1660
|
+
},
|
|
1661
|
+
{
|
|
1662
|
+
name: "reply_to_review",
|
|
1663
|
+
kind: "update",
|
|
1664
|
+
check: "get_review",
|
|
1665
|
+
title: "Reply to a Google Play review",
|
|
1666
|
+
description: `Posts the developer reply to a review, or replaces the earlier reply: plain text up to ${MAX_REPLY} characters. Google Play's policy allows no links, phone numbers or promotions in replies; the reviewer is notified of the first reply only. Returns the reply as saved.`,
|
|
1667
|
+
inputSchema: {
|
|
1668
|
+
type: "object",
|
|
1669
|
+
properties: {
|
|
1670
|
+
package_name: PACKAGE,
|
|
1671
|
+
review_id: REVIEW_ID,
|
|
1672
|
+
reply_text: { type: "string", minLength: 1, maxLength: MAX_REPLY, description: `The reply, up to ${MAX_REPLY} characters.` }
|
|
1673
|
+
},
|
|
1674
|
+
required: ["review_id", "reply_text"],
|
|
1675
|
+
additionalProperties: false
|
|
1676
|
+
},
|
|
1677
|
+
async run(args, h) {
|
|
1678
|
+
const packageName = packageFor(h, args.package_name);
|
|
1679
|
+
const { data } = await play(h, {
|
|
1680
|
+
method: "POST",
|
|
1681
|
+
path: appPath(packageName, `/reviews/${args.review_id}:reply`),
|
|
1682
|
+
json: { replyText: args.reply_text },
|
|
1683
|
+
write: true,
|
|
1684
|
+
errors: { 400: `Google Play did not accept the reply (at most ${MAX_REPLY} characters of plain text)` }
|
|
1685
|
+
});
|
|
1686
|
+
return compact({ packageName, reviewId: args.review_id, replyText: data?.result?.replyText ?? args.reply_text, lastEdited: isoTime(data?.result?.lastEdited) });
|
|
1687
|
+
}
|
|
1688
|
+
},
|
|
1689
|
+
{
|
|
1690
|
+
name: "get_store_listing",
|
|
1691
|
+
kind: "read",
|
|
1692
|
+
title: "Get a Google Play store listing",
|
|
1693
|
+
description: "Returns an app's live store listing as Google Play shows it to people, from its public store page: title, short and full description, category, developer, content rating, star rating, price and icon, in one language (an app without that translation shows its default language). A change made with update_store_listing shows here once Google Play's review has passed. An app that is not published has no store page.",
|
|
1694
|
+
inputSchema: {
|
|
1695
|
+
type: "object",
|
|
1696
|
+
properties: {
|
|
1697
|
+
package_name: PACKAGE,
|
|
1698
|
+
language: { ...LANGUAGE, description: `The language to show the listing in, e.g. tr-TR (default ${DEFAULT_LANGUAGE}).` },
|
|
1699
|
+
region: { ...REGION, description: "The country to show the store page for, which sets the price, e.g. US (default) or TR." }
|
|
1700
|
+
},
|
|
1701
|
+
additionalProperties: false
|
|
1702
|
+
},
|
|
1703
|
+
async run(args, h) {
|
|
1704
|
+
const packageName = packageFor(h, args.package_name);
|
|
1705
|
+
const language = args.language ?? DEFAULT_LANGUAGE;
|
|
1706
|
+
const details = await storePage(h, packageName, language, args.region);
|
|
1707
|
+
return { packageName, language, region: args.region, url: `${STORE_PAGE}?id=${encodeURIComponent(packageName)}`, ...details };
|
|
1708
|
+
}
|
|
1709
|
+
},
|
|
1710
|
+
{
|
|
1711
|
+
name: "update_store_listing",
|
|
1712
|
+
kind: "update",
|
|
1713
|
+
check: "get_store_listing",
|
|
1714
|
+
title: "Update a Google Play store listing",
|
|
1715
|
+
description: "Changes an app's store listing in one language (adding the language if it is new): title (up to 30 characters), short description (80), full description (4000) or promo video. Only the fields given change. It opens an edit, saves the listing and commits the edit; the change goes through Google Play's review before it shows on the store page. Google Play keeps one open edit per account, so this ends any other edit the same service account has open: not while a release made with the same key is in progress. Needs the Manage store presence permission.",
|
|
1716
|
+
inputSchema: {
|
|
1717
|
+
type: "object",
|
|
1718
|
+
properties: {
|
|
1719
|
+
package_name: PACKAGE,
|
|
1720
|
+
language: LANGUAGE,
|
|
1721
|
+
title: { type: "string", minLength: 1, maxLength: 30, description: "The app name on the listing, up to 30 characters." },
|
|
1722
|
+
short_description: { type: "string", minLength: 1, maxLength: 80, description: "Up to 80 characters." },
|
|
1723
|
+
full_description: { type: "string", minLength: 1, maxLength: 4e3, description: "Up to 4000 characters." },
|
|
1724
|
+
video: { type: "string", format: "uri", pattern: "^https://", maxLength: 500, description: "The URL of the promo video, as the listing's promo video field takes it." },
|
|
1725
|
+
changes_not_sent_for_review: {
|
|
1726
|
+
type: "boolean",
|
|
1727
|
+
default: false,
|
|
1728
|
+
description: "true when Google Play answers that the changes cannot be sent for review automatically: they then wait in Play Console until someone sends them."
|
|
1729
|
+
}
|
|
1730
|
+
},
|
|
1731
|
+
required: ["language"],
|
|
1732
|
+
additionalProperties: false
|
|
1733
|
+
},
|
|
1734
|
+
async run(args, h) {
|
|
1735
|
+
const packageName = packageFor(h, args.package_name);
|
|
1736
|
+
const listing = compact({ title: args.title, shortDescription: args.short_description, fullDescription: args.full_description, video: args.video });
|
|
1737
|
+
if (!Object.keys(listing).length) throw new ToolFailure("Give at least one field to change. Nothing was changed.");
|
|
1738
|
+
const { data: edit } = await play(h, { method: "POST", path: appPath(packageName, "/edits"), json: {} });
|
|
1739
|
+
if (typeof edit?.id !== "string" || !edit.id) throw new ToolFailure("Google Play opened no edit for the app. Nothing was changed.");
|
|
1740
|
+
const editPath = appPath(packageName, `/edits/${encodeURIComponent(edit.id)}`);
|
|
1741
|
+
try {
|
|
1742
|
+
const { data: saved } = await play(h, { method: "PATCH", path: `${editPath}/listings/${encodeURIComponent(args.language)}`, json: listing });
|
|
1743
|
+
await play(h, {
|
|
1744
|
+
method: "POST",
|
|
1745
|
+
path: `${editPath}:commit`,
|
|
1746
|
+
query: { changesNotSentForReview: args.changes_not_sent_for_review || void 0 },
|
|
1747
|
+
write: true
|
|
1748
|
+
});
|
|
1749
|
+
return compact({ packageName, committed: true, sentForReview: !args.changes_not_sent_for_review, listing: trimListing(saved) });
|
|
1750
|
+
} catch (error) {
|
|
1751
|
+
if (error instanceof OutcomeUnknown) {
|
|
1752
|
+
throw new OutcomeUnknown(`${error.message} Play Console -> Publishing overview lists a change waiting for review; the store page shows it once the review has passed.`);
|
|
1753
|
+
}
|
|
1754
|
+
await play(h, { method: "DELETE", path: editPath }).catch(() => void 0);
|
|
1755
|
+
throw error;
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
},
|
|
1759
|
+
{
|
|
1760
|
+
name: "list_subscriptions",
|
|
1761
|
+
kind: "read",
|
|
1762
|
+
title: "List Google Play subscriptions",
|
|
1763
|
+
description: "Lists an app's subscriptions: product id, name and description per language, and each base plan with its state, billing period, price in one country and offers (with free trials and intro prices). hasFreeTrial says whether an active offer starts free. Pass nextCursor back as cursor for more.",
|
|
1764
|
+
inputSchema: {
|
|
1765
|
+
type: "object",
|
|
1766
|
+
properties: {
|
|
1767
|
+
package_name: PACKAGE,
|
|
1768
|
+
region: REGION,
|
|
1769
|
+
include_offers: { type: "boolean", default: true, description: "Read the offers too (one more request; default true)." },
|
|
1770
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1771
|
+
},
|
|
1772
|
+
additionalProperties: false
|
|
1773
|
+
},
|
|
1774
|
+
async run(args, h) {
|
|
1775
|
+
const packageName = packageFor(h, args.package_name);
|
|
1776
|
+
const state = h.cursor(args.cursor);
|
|
1777
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
1778
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1779
|
+
const { data } = await play(h, { path: appPath(packageName, "/subscriptions"), query: { pageSize: 100, pageToken } });
|
|
1780
|
+
const subscriptions = Array.isArray(data?.subscriptions) ? data.subscriptions : [];
|
|
1781
|
+
let offers;
|
|
1782
|
+
let note;
|
|
1783
|
+
if (args.include_offers && subscriptions.length) {
|
|
1784
|
+
try {
|
|
1785
|
+
const read = await play(h, { path: appPath(packageName, "/subscriptions/-/basePlans/-/offers"), query: { pageSize: 1e3 } });
|
|
1786
|
+
offers = offersByBasePlan(Array.isArray(read.data?.subscriptionOffers) ? read.data.subscriptionOffers : [], args.region);
|
|
1787
|
+
if (read.data?.nextPageToken) note = "The app has more than 1000 offers: only the first 1000 are shown.";
|
|
1788
|
+
} catch (error) {
|
|
1789
|
+
if (!(error instanceof ToolFailure)) throw error;
|
|
1790
|
+
note = `The offers could not be read: ${truncate(error.message, 300)}`;
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
return h.page({
|
|
1794
|
+
key: "subscriptions",
|
|
1795
|
+
items: subscriptions.map((subscription) => trimSubscription(subscription, args.region, offers)).slice(skip),
|
|
1796
|
+
extra: compact({ packageName, note }),
|
|
1797
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index }),
|
|
1798
|
+
...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0 }) } : {}
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
},
|
|
1802
|
+
{
|
|
1803
|
+
name: "list_in_app_products",
|
|
1804
|
+
kind: "read",
|
|
1805
|
+
title: "List Google Play in-app products",
|
|
1806
|
+
description: "Lists an app's one-time in-app products: sku, status, name and description, default price and the price in one country. catalog one_time_products reads the newer one-time products API instead (purchase options). Pass nextCursor back as cursor for more.",
|
|
1807
|
+
inputSchema: {
|
|
1808
|
+
type: "object",
|
|
1809
|
+
properties: {
|
|
1810
|
+
package_name: PACKAGE,
|
|
1811
|
+
catalog: { type: "string", enum: ["in_app_products", "one_time_products"], default: "in_app_products", description: "in_app_products (default) or one_time_products." },
|
|
1812
|
+
region: REGION,
|
|
1813
|
+
cursor: { type: "string", description: "nextCursor from the previous result." }
|
|
1814
|
+
},
|
|
1815
|
+
additionalProperties: false
|
|
1816
|
+
},
|
|
1817
|
+
async run(args, h) {
|
|
1818
|
+
const packageName = packageFor(h, args.package_name);
|
|
1819
|
+
const state = h.cursor(args.cursor);
|
|
1820
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
1821
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1822
|
+
let items;
|
|
1823
|
+
let next;
|
|
1824
|
+
if (args.catalog === "one_time_products") {
|
|
1825
|
+
const { data } = await play(h, { path: appPath(packageName, "/oneTimeProducts"), query: { pageSize: 100, pageToken } });
|
|
1826
|
+
items = (Array.isArray(data?.oneTimeProducts) ? data.oneTimeProducts : []).map((product) => trimOneTimeProduct(product, args.region));
|
|
1827
|
+
next = data?.nextPageToken;
|
|
1828
|
+
} else {
|
|
1829
|
+
const { data } = await play(h, { path: appPath(packageName, "/inappproducts"), query: { token: pageToken } });
|
|
1830
|
+
items = (Array.isArray(data?.inappproduct) ? data.inappproduct : []).map((product) => trimInAppProduct(product, args.region));
|
|
1831
|
+
next = data?.tokenPagination?.nextPageToken;
|
|
1832
|
+
}
|
|
1833
|
+
return h.page({
|
|
1834
|
+
key: "products",
|
|
1835
|
+
items: items.slice(skip),
|
|
1836
|
+
extra: { packageName, catalog: args.catalog },
|
|
1837
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index }),
|
|
1838
|
+
...typeof next === "string" && next ? { nextPage: h.makeCursor({ p: next, o: 0 }) } : {}
|
|
1839
|
+
});
|
|
1840
|
+
}
|
|
1841
|
+
},
|
|
1842
|
+
...apiTools({
|
|
1843
|
+
label: LABEL2,
|
|
1844
|
+
description: "The Google Play Android Developer API v3 at https://androidpublisher.googleapis.com/androidpublisher/v3, as the service account: paths start with /androidpublisher/v3/applications/{packageName}/, such as .../edits, .../subscriptions/{productId}/basePlans:batchUpdateStates or .../purchases/subscriptionsv2/tokens/{token}, and must name a chosen app. What a call may do follows the service account's permissions in Play Console. Reference: https://developers.google.com/android-publisher/api-ref/rest.",
|
|
1845
|
+
basePath: "/androidpublisher/v3/",
|
|
1846
|
+
accounts: {
|
|
1847
|
+
key: PICKER,
|
|
1848
|
+
label: "app",
|
|
1849
|
+
ids: (request) => request.segments[2] === "applications" && request.segments[3] ? [request.segments[3]] : []
|
|
1850
|
+
},
|
|
1851
|
+
guard: playGuard,
|
|
1852
|
+
send: (request, h) => play(h, request)
|
|
1853
|
+
})
|
|
1854
|
+
]
|
|
1855
|
+
});
|
|
1856
|
+
module.exports = connector;
|