@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,2798 @@
|
|
|
1
|
+
/* apple-appstore connector module (MIT License). Built from src/vendors/apple-appstore; 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(text2) {
|
|
41
|
+
return encoder.encode(text2);
|
|
42
|
+
}
|
|
43
|
+
function utf8Length(text2) {
|
|
44
|
+
return encoder.encode(text2).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(text2) {
|
|
60
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text2)) throw new Error("not base64url");
|
|
61
|
+
const padded = text2.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text2.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(text2) {
|
|
68
|
+
const clean = text2.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
|
+
function truncate(text2, max) {
|
|
76
|
+
if (text2.length <= max) return text2;
|
|
77
|
+
const points = Array.from(text2);
|
|
78
|
+
if (points.length <= max) return text2;
|
|
79
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
80
|
+
}
|
|
81
|
+
function cleanVendorText(text2, max = 300) {
|
|
82
|
+
if (typeof text2 !== "string") return void 0;
|
|
83
|
+
if (/^\s*</.test(text2)) return void 0;
|
|
84
|
+
const line = text2.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
|
|
85
|
+
return line ? truncate(line, max) : void 0;
|
|
86
|
+
}
|
|
87
|
+
function formatNumber(value) {
|
|
88
|
+
return value.toLocaleString("en-US");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/core/output.ts
|
|
92
|
+
var OUTPUT_LIMIT_BYTES = 32 * 1024;
|
|
93
|
+
function jsonSize(value) {
|
|
94
|
+
return utf8Length(JSON.stringify(value) ?? "");
|
|
95
|
+
}
|
|
96
|
+
function cutStrings(value, max) {
|
|
97
|
+
if (typeof value === "string") return truncate(value, max);
|
|
98
|
+
if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
|
|
99
|
+
if (typeof value === "object" && value !== null) {
|
|
100
|
+
const out = {};
|
|
101
|
+
for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
|
|
102
|
+
return out;
|
|
103
|
+
}
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
|
|
107
|
+
if (jsonSize(value) <= limit) return { value, truncated: false };
|
|
108
|
+
for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
|
|
109
|
+
const cut = cutStrings(value, max);
|
|
110
|
+
if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
|
|
111
|
+
}
|
|
112
|
+
return void 0;
|
|
113
|
+
}
|
|
114
|
+
function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
|
|
115
|
+
const build = (count) => {
|
|
116
|
+
const cut = count < input.items.length;
|
|
117
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
|
|
118
|
+
const next = cut ? input.resumeAt(count) : input.nextPage;
|
|
119
|
+
if (next) result2["nextCursor"] = next;
|
|
120
|
+
if (cut) result2["truncated"] = true;
|
|
121
|
+
return result2;
|
|
122
|
+
};
|
|
123
|
+
const all = build(input.items.length);
|
|
124
|
+
if (jsonSize(all) <= limit) return all;
|
|
125
|
+
let low = 1;
|
|
126
|
+
let high = input.items.length - 1;
|
|
127
|
+
while (low < high) {
|
|
128
|
+
const middle = Math.ceil((low + high) / 2);
|
|
129
|
+
if (jsonSize(build(middle)) <= limit) low = middle;
|
|
130
|
+
else high = middle - 1;
|
|
131
|
+
}
|
|
132
|
+
const best = build(low);
|
|
133
|
+
if (jsonSize(best) <= limit) return best;
|
|
134
|
+
const shrunk = shrinkToFit(best, limit);
|
|
135
|
+
if (shrunk) return { ...shrunk.value, truncated: true };
|
|
136
|
+
throw new ToolFailure("The result is too large to return, even one item at a time.");
|
|
137
|
+
}
|
|
138
|
+
function encodeCursor(tool, state) {
|
|
139
|
+
return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
|
|
140
|
+
}
|
|
141
|
+
function decodeCursor(tool, cursor) {
|
|
142
|
+
if (cursor === void 0 || cursor === "") return null;
|
|
143
|
+
try {
|
|
144
|
+
const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
|
|
145
|
+
if (typeof state === "object" && state !== null && state.t === tool) {
|
|
146
|
+
return state;
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
}
|
|
150
|
+
throw new ToolFailure(
|
|
151
|
+
"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."
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// src/core/api-tools.ts
|
|
156
|
+
var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
|
|
157
|
+
var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
|
|
158
|
+
var NOTE_ROOM = 400;
|
|
159
|
+
var MAX_CUT_POINTS = 4e4;
|
|
160
|
+
function isQueryValue(value) {
|
|
161
|
+
return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
162
|
+
}
|
|
163
|
+
function nothingSent(sentence) {
|
|
164
|
+
return new ToolFailure(`${sentence} Nothing was sent.`);
|
|
165
|
+
}
|
|
166
|
+
function fitReply(reply) {
|
|
167
|
+
if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
|
|
168
|
+
const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
|
|
169
|
+
if (shrunk) {
|
|
170
|
+
return {
|
|
171
|
+
...shrunk.value,
|
|
172
|
+
truncated: true,
|
|
173
|
+
note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
const text2 = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
|
|
177
|
+
const points = Array.from(text2.length > MAX_CUT_POINTS ? text2.slice(0, MAX_CUT_POINTS) : text2);
|
|
178
|
+
if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
|
|
179
|
+
const cut = (count) => ({
|
|
180
|
+
status: reply["status"],
|
|
181
|
+
...reply["headers"] ? { headers: reply["headers"] } : {},
|
|
182
|
+
truncated: true,
|
|
183
|
+
note: `The reply has ${formatNumber(utf8Length(text2))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
|
|
184
|
+
text: points.slice(0, count).join("")
|
|
185
|
+
});
|
|
186
|
+
let low = 0;
|
|
187
|
+
let high = points.length;
|
|
188
|
+
while (low < high) {
|
|
189
|
+
const middle = Math.ceil((low + high) / 2);
|
|
190
|
+
if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
|
|
191
|
+
else high = middle - 1;
|
|
192
|
+
}
|
|
193
|
+
return cut(low);
|
|
194
|
+
}
|
|
195
|
+
function shapeReply(response, headerNames) {
|
|
196
|
+
const reply = { status: response.status };
|
|
197
|
+
const headers = {};
|
|
198
|
+
for (const name2 of headerNames) {
|
|
199
|
+
const value = response.headers.get(name2);
|
|
200
|
+
if (value) headers[name2] = truncate(value, 2e3);
|
|
201
|
+
}
|
|
202
|
+
if (Object.keys(headers).length) reply["headers"] = headers;
|
|
203
|
+
const type = response.headers.get("content-type") ?? "";
|
|
204
|
+
if (type && !TEXT_TYPES.test(type)) {
|
|
205
|
+
reply["contentType"] = truncate(type, 200);
|
|
206
|
+
reply["note"] = "The reply is a binary file and is not shown.";
|
|
207
|
+
return reply;
|
|
208
|
+
}
|
|
209
|
+
if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
|
|
210
|
+
return fitReply(reply);
|
|
211
|
+
}
|
|
212
|
+
function checkAccounts(rule, request, h) {
|
|
213
|
+
const label = rule.label ?? "account";
|
|
214
|
+
const allowed = allowedAccounts(h.ctx.accounts, rule.key);
|
|
215
|
+
if (allowed === null) return;
|
|
216
|
+
const namesNone = nothingSent(
|
|
217
|
+
`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.`)
|
|
218
|
+
);
|
|
219
|
+
if (rule.ids) {
|
|
220
|
+
const ids = rule.ids(request).map(String);
|
|
221
|
+
if (!ids.length) throw namesNone;
|
|
222
|
+
requireAccounts(h.ctx.accounts, rule.key, ids, label);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
|
|
226
|
+
}
|
|
227
|
+
function apiTools(options) {
|
|
228
|
+
const { label, basePath } = options;
|
|
229
|
+
const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
|
|
230
|
+
const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
|
|
231
|
+
const base = basePath?.replace(/\/+$/, "");
|
|
232
|
+
const pathSchema = {
|
|
233
|
+
type: "string",
|
|
234
|
+
minLength: 1,
|
|
235
|
+
maxLength: 2e3,
|
|
236
|
+
pattern: "^(?!.*//)/[^?#]*$",
|
|
237
|
+
description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
|
|
238
|
+
};
|
|
239
|
+
const querySchema = {
|
|
240
|
+
type: "object",
|
|
241
|
+
description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
|
|
242
|
+
};
|
|
243
|
+
const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
|
|
244
|
+
async function run(method, args, h) {
|
|
245
|
+
let origin = h.origins[0];
|
|
246
|
+
if (args.origin !== void 0) {
|
|
247
|
+
let wanted;
|
|
248
|
+
try {
|
|
249
|
+
wanted = new URL(args.origin).origin;
|
|
250
|
+
} catch {
|
|
251
|
+
}
|
|
252
|
+
if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
|
|
253
|
+
origin = wanted;
|
|
254
|
+
}
|
|
255
|
+
const url = new URL(args.path, origin);
|
|
256
|
+
if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
|
|
257
|
+
const path = url.pathname;
|
|
258
|
+
if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
|
|
259
|
+
let segments;
|
|
260
|
+
try {
|
|
261
|
+
segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
|
|
262
|
+
} catch {
|
|
263
|
+
throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
|
|
264
|
+
}
|
|
265
|
+
if (segments[segments.length - 1] === "") segments.pop();
|
|
266
|
+
const query = {};
|
|
267
|
+
const queryLists = {};
|
|
268
|
+
for (const [key, value] of Object.entries(args.query ?? {})) {
|
|
269
|
+
if (value === void 0 || value === null) continue;
|
|
270
|
+
const list = Array.isArray(value) ? value : [value];
|
|
271
|
+
if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
|
|
272
|
+
query[key] = Array.isArray(value) ? list : value;
|
|
273
|
+
queryLists[key] = list.map(String);
|
|
274
|
+
}
|
|
275
|
+
const request = { method, origin, path, query };
|
|
276
|
+
if (method !== "GET") {
|
|
277
|
+
if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
|
|
278
|
+
if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
|
|
279
|
+
if (args.json !== void 0 && !args.content_type) {
|
|
280
|
+
request.json = args.json;
|
|
281
|
+
} else if (args.json !== void 0 || args.body !== void 0) {
|
|
282
|
+
request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
|
|
283
|
+
request.contentType = args.content_type;
|
|
284
|
+
}
|
|
285
|
+
request.write = true;
|
|
286
|
+
}
|
|
287
|
+
const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
|
|
288
|
+
if (options.accounts) checkAccounts(options.accounts, info, h);
|
|
289
|
+
await options.guard?.(info, h);
|
|
290
|
+
const response = options.send ? await options.send(request, h) : await h.api(request);
|
|
291
|
+
return shapeReply(response, headerNames);
|
|
292
|
+
}
|
|
293
|
+
return [
|
|
294
|
+
{
|
|
295
|
+
name: "api_get",
|
|
296
|
+
kind: "read",
|
|
297
|
+
title: `Call the ${label} API (GET)`,
|
|
298
|
+
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.`,
|
|
299
|
+
inputSchema: {
|
|
300
|
+
type: "object",
|
|
301
|
+
properties: { path: pathSchema, query: querySchema, ...originSchema },
|
|
302
|
+
required: ["path"],
|
|
303
|
+
additionalProperties: false
|
|
304
|
+
},
|
|
305
|
+
run: (args, h) => run("GET", args, h)
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
name: "api_request",
|
|
309
|
+
kind: "write",
|
|
310
|
+
check: "api_get",
|
|
311
|
+
title: `Send a request to the ${label} API`,
|
|
312
|
+
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.`,
|
|
313
|
+
inputSchema: {
|
|
314
|
+
type: "object",
|
|
315
|
+
properties: {
|
|
316
|
+
method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
|
|
317
|
+
path: pathSchema,
|
|
318
|
+
query: querySchema,
|
|
319
|
+
json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
|
|
320
|
+
body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
|
|
321
|
+
content_type: {
|
|
322
|
+
type: "string",
|
|
323
|
+
pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
|
|
324
|
+
maxLength: 200,
|
|
325
|
+
description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
|
|
326
|
+
},
|
|
327
|
+
...originSchema
|
|
328
|
+
},
|
|
329
|
+
required: ["method", "path"],
|
|
330
|
+
additionalProperties: false
|
|
331
|
+
},
|
|
332
|
+
run: (args, h) => run(args.method, args, h)
|
|
333
|
+
}
|
|
334
|
+
];
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// src/core/credentials.ts
|
|
338
|
+
function requiredAlternatives(module2) {
|
|
339
|
+
return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
|
|
340
|
+
}
|
|
341
|
+
function unmetAlternatives(alternatives, has) {
|
|
342
|
+
const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
|
|
343
|
+
if (lacking.some((list) => list.length === 0)) return [];
|
|
344
|
+
return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
|
|
345
|
+
}
|
|
346
|
+
function andList(items) {
|
|
347
|
+
if (items.length <= 2) return items.join(" and ");
|
|
348
|
+
return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
|
|
349
|
+
}
|
|
350
|
+
function orList(items) {
|
|
351
|
+
if (items.length <= 1) return items.join("");
|
|
352
|
+
return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// src/core/files.ts
|
|
356
|
+
var ATTACHMENT_URI = "attachment:///";
|
|
357
|
+
var MAX_NAME = 200;
|
|
358
|
+
function fileLimitOf(ctx) {
|
|
359
|
+
const maxBytes = ctx.files?.maxBytes;
|
|
360
|
+
return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
|
|
361
|
+
}
|
|
362
|
+
function fileName(name2) {
|
|
363
|
+
const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
|
|
364
|
+
const points = Array.from(clean);
|
|
365
|
+
if (points.length <= MAX_NAME) return clean || "file";
|
|
366
|
+
const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
|
|
367
|
+
return points.slice(0, MAX_NAME - extension.length).join("") + extension;
|
|
368
|
+
}
|
|
369
|
+
function fileType(mimeType) {
|
|
370
|
+
const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
|
|
371
|
+
return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
|
|
372
|
+
}
|
|
373
|
+
function resourceBlock(file) {
|
|
374
|
+
return {
|
|
375
|
+
type: "resource",
|
|
376
|
+
resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// src/core/http.ts
|
|
381
|
+
var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
|
|
382
|
+
var USER_AGENT = "agent-connectors";
|
|
383
|
+
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
|
|
384
|
+
function errorCode(error) {
|
|
385
|
+
const code = error?.code;
|
|
386
|
+
return typeof code === "string" ? code : void 0;
|
|
387
|
+
}
|
|
388
|
+
function describe(error) {
|
|
389
|
+
const name2 = error?.name;
|
|
390
|
+
const code = errorCode(error);
|
|
391
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
392
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
393
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
394
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
395
|
+
}
|
|
396
|
+
function retryAfterSeconds(headers, now = Date.now()) {
|
|
397
|
+
const retryAfter = headers.get("retry-after");
|
|
398
|
+
if (retryAfter) {
|
|
399
|
+
const seconds = Number(retryAfter);
|
|
400
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
|
|
401
|
+
const date = Date.parse(retryAfter);
|
|
402
|
+
if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
|
|
403
|
+
}
|
|
404
|
+
const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
|
|
405
|
+
if (reset) {
|
|
406
|
+
const value = Number(reset);
|
|
407
|
+
if (Number.isFinite(value) && value >= 0) {
|
|
408
|
+
return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return void 0;
|
|
412
|
+
}
|
|
413
|
+
function vendorCode(data) {
|
|
414
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
415
|
+
for (const key of ["error", "code"]) {
|
|
416
|
+
const value = data[key];
|
|
417
|
+
if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
|
|
418
|
+
}
|
|
419
|
+
return void 0;
|
|
420
|
+
}
|
|
421
|
+
function vendorMessage(data) {
|
|
422
|
+
if (typeof data === "string") return cleanVendorText(data);
|
|
423
|
+
if (typeof data !== "object" || data === null) return void 0;
|
|
424
|
+
const record = data;
|
|
425
|
+
for (const key of ["message", "error_description", "error", "detail", "title"]) {
|
|
426
|
+
const value = record[key];
|
|
427
|
+
if (typeof value === "string" && value.trim()) return cleanVendorText(value);
|
|
428
|
+
const nested = value?.message;
|
|
429
|
+
if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
|
|
430
|
+
}
|
|
431
|
+
if (Array.isArray(record["errors"])) {
|
|
432
|
+
const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
|
|
433
|
+
if (messages.length) return cleanVendorText(messages.join("; "));
|
|
434
|
+
}
|
|
435
|
+
return void 0;
|
|
436
|
+
}
|
|
437
|
+
var TooLarge = class extends Error {
|
|
438
|
+
constructor(limit) {
|
|
439
|
+
super(`the reply is larger than ${formatNumber(limit)} bytes`);
|
|
440
|
+
this.limit = limit;
|
|
441
|
+
}
|
|
442
|
+
limit;
|
|
443
|
+
};
|
|
444
|
+
async function readCapped(response, maxBytes) {
|
|
445
|
+
const declared = Number(response.headers.get("content-length"));
|
|
446
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
447
|
+
await response.body?.cancel().catch(() => {
|
|
448
|
+
});
|
|
449
|
+
throw new TooLarge(maxBytes);
|
|
450
|
+
}
|
|
451
|
+
if (!response.body) return new Uint8Array(0);
|
|
452
|
+
const reader = response.body.getReader();
|
|
453
|
+
const chunks = [];
|
|
454
|
+
let total = 0;
|
|
455
|
+
for (; ; ) {
|
|
456
|
+
const { done, value } = await reader.read();
|
|
457
|
+
if (done) break;
|
|
458
|
+
total += value.byteLength;
|
|
459
|
+
if (total > maxBytes) {
|
|
460
|
+
await reader.cancel().catch(() => {
|
|
461
|
+
});
|
|
462
|
+
throw new TooLarge(maxBytes);
|
|
463
|
+
}
|
|
464
|
+
chunks.push(value);
|
|
465
|
+
}
|
|
466
|
+
const bytes = new Uint8Array(total);
|
|
467
|
+
let offset = 0;
|
|
468
|
+
for (const chunk of chunks) {
|
|
469
|
+
bytes.set(chunk, offset);
|
|
470
|
+
offset += chunk.byteLength;
|
|
471
|
+
}
|
|
472
|
+
return bytes;
|
|
473
|
+
}
|
|
474
|
+
function parseBody(bytes, contentType) {
|
|
475
|
+
if (bytes.length === 0) return null;
|
|
476
|
+
const text2 = utf8Decode(bytes);
|
|
477
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text2)) {
|
|
478
|
+
try {
|
|
479
|
+
return JSON.parse(text2);
|
|
480
|
+
} catch {
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
return text2;
|
|
484
|
+
}
|
|
485
|
+
function createHttp(env) {
|
|
486
|
+
const { label, ctx } = env;
|
|
487
|
+
const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
|
|
488
|
+
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.`;
|
|
489
|
+
function failureFor(status, headers, data, request) {
|
|
490
|
+
const message = vendorMessage(data);
|
|
491
|
+
const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
|
|
492
|
+
const retryAfter = retryAfterSeconds(headers);
|
|
493
|
+
const code = vendorCode(data);
|
|
494
|
+
const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
|
|
495
|
+
const custom = request.errors?.[status];
|
|
496
|
+
const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
|
|
497
|
+
if (status >= 500) {
|
|
498
|
+
if (request.write) {
|
|
499
|
+
return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
|
|
500
|
+
}
|
|
501
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
|
|
502
|
+
}
|
|
503
|
+
if (status === 429) {
|
|
504
|
+
return new ToolFailure(
|
|
505
|
+
`${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
|
|
506
|
+
{ status, ...extra }
|
|
507
|
+
);
|
|
508
|
+
}
|
|
509
|
+
if (status === 401) {
|
|
510
|
+
return new ToolFailure(
|
|
511
|
+
withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
|
|
512
|
+
{ status, ...extra }
|
|
513
|
+
);
|
|
514
|
+
}
|
|
515
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
516
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
517
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
|
|
518
|
+
return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
|
|
519
|
+
}
|
|
520
|
+
async function api(request) {
|
|
521
|
+
const method = request.method ?? "GET";
|
|
522
|
+
if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
|
|
523
|
+
throw new Error(`read-only tool sent ${method}`);
|
|
524
|
+
}
|
|
525
|
+
const origin = request.origin ?? env.origins[0];
|
|
526
|
+
if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
|
|
527
|
+
const url = new URL(request.path, origin);
|
|
528
|
+
if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
|
|
529
|
+
for (const [key, value] of Object.entries(request.query ?? {})) {
|
|
530
|
+
if (value === void 0 || value === null) continue;
|
|
531
|
+
if (Array.isArray(value)) {
|
|
532
|
+
url.searchParams.delete(key);
|
|
533
|
+
for (const item of value) url.searchParams.append(key, String(item));
|
|
534
|
+
} else {
|
|
535
|
+
url.searchParams.set(key, String(value));
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
const headers = {
|
|
539
|
+
accept: "application/json",
|
|
540
|
+
"user-agent": USER_AGENT,
|
|
541
|
+
...request.auth === false ? {} : env.authHeaders(),
|
|
542
|
+
...request.headers
|
|
543
|
+
};
|
|
544
|
+
let body;
|
|
545
|
+
if (request.json !== void 0) {
|
|
546
|
+
body = JSON.stringify(request.json);
|
|
547
|
+
headers["content-type"] = "application/json";
|
|
548
|
+
} else if (request.body) {
|
|
549
|
+
body = request.body;
|
|
550
|
+
headers["content-type"] = request.contentType ?? "application/octet-stream";
|
|
551
|
+
}
|
|
552
|
+
const started = Date.now();
|
|
553
|
+
if (request.write) env.onWriteSent();
|
|
554
|
+
let response;
|
|
555
|
+
try {
|
|
556
|
+
response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
|
|
557
|
+
} catch (error) {
|
|
558
|
+
env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
|
|
559
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
560
|
+
throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
|
|
561
|
+
}
|
|
562
|
+
if (request.write) {
|
|
563
|
+
throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
|
|
564
|
+
}
|
|
565
|
+
if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
|
|
566
|
+
throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
|
|
567
|
+
}
|
|
568
|
+
env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
|
|
569
|
+
let bytes;
|
|
570
|
+
try {
|
|
571
|
+
bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
|
|
572
|
+
} catch (error) {
|
|
573
|
+
if (request.write && (response.ok || response.status >= 500)) {
|
|
574
|
+
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.`);
|
|
575
|
+
}
|
|
576
|
+
throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
|
|
577
|
+
}
|
|
578
|
+
const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
|
|
579
|
+
if (response.ok) return { status: response.status, headers: response.headers, data };
|
|
580
|
+
throw failureFor(response.status, response.headers, data, request);
|
|
581
|
+
}
|
|
582
|
+
async function media(rawUrl, options) {
|
|
583
|
+
const { what } = options;
|
|
584
|
+
let url;
|
|
585
|
+
try {
|
|
586
|
+
url = new URL(rawUrl);
|
|
587
|
+
} catch {
|
|
588
|
+
throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
|
|
589
|
+
}
|
|
590
|
+
if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
|
|
591
|
+
const started = Date.now();
|
|
592
|
+
let response;
|
|
593
|
+
try {
|
|
594
|
+
response = await ctx.fetch(url.toString(), {
|
|
595
|
+
method: "GET",
|
|
596
|
+
headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
|
|
597
|
+
...ctx.signal ? { signal: ctx.signal } : {}
|
|
598
|
+
});
|
|
599
|
+
} catch (error) {
|
|
600
|
+
env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
|
|
601
|
+
if (errorCode(error) === "URL_REFUSED") {
|
|
602
|
+
throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
|
|
603
|
+
}
|
|
604
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
605
|
+
}
|
|
606
|
+
env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
607
|
+
if (!response.ok) {
|
|
608
|
+
await response.body?.cancel().catch(() => {
|
|
609
|
+
});
|
|
610
|
+
throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
|
|
611
|
+
}
|
|
612
|
+
try {
|
|
613
|
+
const bytes = await readCapped(response, options.maxBytes);
|
|
614
|
+
return { bytes, contentType: response.headers.get("content-type") };
|
|
615
|
+
} catch (error) {
|
|
616
|
+
if (error instanceof TooLarge) {
|
|
617
|
+
throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
|
|
618
|
+
}
|
|
619
|
+
throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
return { api, media };
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// src/core/origins.ts
|
|
626
|
+
function parseSiteUrl(value) {
|
|
627
|
+
const text2 = typeof value === "string" ? value.trim() : "";
|
|
628
|
+
if (!text2) return { ok: false, problem: "is empty" };
|
|
629
|
+
let url;
|
|
630
|
+
try {
|
|
631
|
+
url = new URL(text2.includes("://") ? text2 : `https://${text2}`);
|
|
632
|
+
} catch {
|
|
633
|
+
return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
|
|
634
|
+
}
|
|
635
|
+
if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
|
|
636
|
+
if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
|
|
637
|
+
if (!url.hostname) return { ok: false, problem: "has no host name" };
|
|
638
|
+
return { ok: true, url, origin: url.origin };
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
// src/core/schema.ts
|
|
642
|
+
var patterns = /* @__PURE__ */ new Map();
|
|
643
|
+
function patternOf(source) {
|
|
644
|
+
let compiled = patterns.get(source);
|
|
645
|
+
if (!compiled) {
|
|
646
|
+
compiled = new RegExp(source, "u");
|
|
647
|
+
patterns.set(source, compiled);
|
|
648
|
+
}
|
|
649
|
+
return compiled;
|
|
650
|
+
}
|
|
651
|
+
function isPlainObject(value) {
|
|
652
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
653
|
+
}
|
|
654
|
+
function isHttpUrl(value) {
|
|
655
|
+
try {
|
|
656
|
+
const url = new URL(value);
|
|
657
|
+
return url.protocol === "https:" || url.protocol === "http:";
|
|
658
|
+
} catch {
|
|
659
|
+
return false;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
function name(path) {
|
|
663
|
+
return `\`${path}\``;
|
|
664
|
+
}
|
|
665
|
+
function child(path, key) {
|
|
666
|
+
return path ? `${path}.${key}` : key;
|
|
667
|
+
}
|
|
668
|
+
function checkValue(schema, value, path, issues) {
|
|
669
|
+
switch (schema.type) {
|
|
670
|
+
case "object":
|
|
671
|
+
checkObject(schema, value, path, issues);
|
|
672
|
+
return;
|
|
673
|
+
case "array": {
|
|
674
|
+
if (!Array.isArray(value)) {
|
|
675
|
+
issues.push(`${name(path)} must be an array`);
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
679
|
+
issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
|
|
680
|
+
}
|
|
681
|
+
if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
|
|
682
|
+
issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
|
|
683
|
+
}
|
|
684
|
+
if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
|
|
685
|
+
issues.push(`${name(path)} must not repeat an item`);
|
|
686
|
+
}
|
|
687
|
+
if (schema.items) {
|
|
688
|
+
value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
|
|
689
|
+
}
|
|
690
|
+
break;
|
|
691
|
+
}
|
|
692
|
+
case "string": {
|
|
693
|
+
if (typeof value !== "string") {
|
|
694
|
+
issues.push(`${name(path)} must be a string`);
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
const length = Array.from(value).length;
|
|
698
|
+
if (schema.minLength !== void 0 && length < schema.minLength) {
|
|
699
|
+
issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
|
|
700
|
+
}
|
|
701
|
+
if (schema.maxLength !== void 0 && length > schema.maxLength) {
|
|
702
|
+
issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
|
|
703
|
+
}
|
|
704
|
+
if (schema.format === "uri" && !isHttpUrl(value)) {
|
|
705
|
+
issues.push(`${name(path)} must be an absolute http(s) URL`);
|
|
706
|
+
} else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
|
|
707
|
+
issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
|
|
708
|
+
}
|
|
709
|
+
break;
|
|
710
|
+
}
|
|
711
|
+
case "integer":
|
|
712
|
+
case "number": {
|
|
713
|
+
if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
|
|
714
|
+
issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
718
|
+
issues.push(`${name(path)} must be at least ${schema.minimum}`);
|
|
719
|
+
}
|
|
720
|
+
if (schema.maximum !== void 0 && value > schema.maximum) {
|
|
721
|
+
issues.push(`${name(path)} must be at most ${schema.maximum}`);
|
|
722
|
+
}
|
|
723
|
+
break;
|
|
724
|
+
}
|
|
725
|
+
case "boolean":
|
|
726
|
+
if (typeof value !== "boolean") {
|
|
727
|
+
issues.push(`${name(path)} must be true or false`);
|
|
728
|
+
return;
|
|
729
|
+
}
|
|
730
|
+
break;
|
|
731
|
+
default:
|
|
732
|
+
break;
|
|
733
|
+
}
|
|
734
|
+
if (schema.enum && !schema.enum.includes(value)) {
|
|
735
|
+
issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
function checkObject(schema, value, path, issues) {
|
|
739
|
+
if (!isPlainObject(value)) {
|
|
740
|
+
issues.push(`${path ? name(path) : "the arguments"} must be an object`);
|
|
741
|
+
return;
|
|
742
|
+
}
|
|
743
|
+
const properties = schema.properties ?? {};
|
|
744
|
+
for (const key of schema.required ?? []) {
|
|
745
|
+
if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
|
|
746
|
+
}
|
|
747
|
+
const unknown = [];
|
|
748
|
+
for (const [key, item] of Object.entries(value)) {
|
|
749
|
+
const property = properties[key];
|
|
750
|
+
if (!property) {
|
|
751
|
+
if (schema.additionalProperties === false) unknown.push(key);
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
if (item === void 0 || item === null) continue;
|
|
755
|
+
checkValue(property, item, child(path, key), issues);
|
|
756
|
+
}
|
|
757
|
+
if (unknown.length) {
|
|
758
|
+
const known = Object.keys(properties);
|
|
759
|
+
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(", ")})` : ""));
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
function copyDefault(value) {
|
|
763
|
+
return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
|
|
764
|
+
}
|
|
765
|
+
function validateArguments(schema, args) {
|
|
766
|
+
const input = args === void 0 || args === null ? {} : args;
|
|
767
|
+
if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
|
|
768
|
+
const value = { ...input };
|
|
769
|
+
if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
|
|
770
|
+
const issues = [];
|
|
771
|
+
checkObject(schema, value, "", issues);
|
|
772
|
+
if (issues.length) return { ok: false, issues };
|
|
773
|
+
for (const [key, property] of Object.entries(schema.properties ?? {})) {
|
|
774
|
+
if (value[key] === null) delete value[key];
|
|
775
|
+
if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
|
|
776
|
+
}
|
|
777
|
+
return { ok: true, value };
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// src/core/upload-hosts.ts
|
|
781
|
+
var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
782
|
+
function uploadHostProblem(entry) {
|
|
783
|
+
if (typeof entry !== "string") return "must be a host name";
|
|
784
|
+
const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
|
|
785
|
+
const labels = name2.split(".");
|
|
786
|
+
if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
|
|
787
|
+
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";
|
|
788
|
+
}
|
|
789
|
+
if (labels.length < 2) return "needs at least two labels, like example.com";
|
|
790
|
+
if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
|
|
791
|
+
return void 0;
|
|
792
|
+
}
|
|
793
|
+
function isUploadHost(hostname, uploadHosts) {
|
|
794
|
+
const name2 = hostname.toLowerCase().replace(/\.$/, "");
|
|
795
|
+
return uploadHosts.some((entry) => entry.startsWith(".") ? name2.length > entry.length && name2.endsWith(entry) : name2 === entry);
|
|
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 text2 = String(value).trim();
|
|
959
|
+
if (text2) out[key] = text2;
|
|
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 = (text2) => {
|
|
989
|
+
try {
|
|
990
|
+
ctx.log?.(text2);
|
|
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 text2 = String(pem).replace(/\\r\\n|\\n/g, "\n").trim();
|
|
1110
|
+
const block = /-----BEGIN ([A-Z0-9 ]+)-----([\s\S]*?)-----END \1-----/.exec(text2);
|
|
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
|
+
async function appStoreConnectToken(key) {
|
|
1142
|
+
const iat = Math.floor(Date.now() / 1e3);
|
|
1143
|
+
return signJwt({
|
|
1144
|
+
algorithm: "ES256",
|
|
1145
|
+
privateKey: key.privateKey,
|
|
1146
|
+
header: { kid: key.keyId },
|
|
1147
|
+
payload: { ...key.issuerId ? { iss: key.issuerId } : { sub: "user" }, iat, exp: iat + 20 * 60, aud: "appstoreconnect-v1" },
|
|
1148
|
+
keyName: "App Store Connect private key"
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
var TOKEN_EARLY_MS = 5 * 60 * 1e3;
|
|
1152
|
+
|
|
1153
|
+
// src/vendors/apple-appstore/client.ts
|
|
1154
|
+
var ORIGIN = "https://api.appstoreconnect.apple.com";
|
|
1155
|
+
var LOOKUP_ORIGIN = "https://itunes.apple.com";
|
|
1156
|
+
var REVIEW_SCAN_PAGES = 5;
|
|
1157
|
+
function privateKeyPem(value) {
|
|
1158
|
+
const text2 = value.replace(/\\r\\n|\\n/g, "\n").trim();
|
|
1159
|
+
if (text2.includes("-----BEGIN")) return text2;
|
|
1160
|
+
const packed = text2.replace(/\s+/g, "");
|
|
1161
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(packed)) return text2;
|
|
1162
|
+
try {
|
|
1163
|
+
const bytes = base64Decode(packed);
|
|
1164
|
+
const decoded = utf8Decode(bytes);
|
|
1165
|
+
if (decoded.includes("-----BEGIN")) return decoded.trim();
|
|
1166
|
+
if (bytes[0] === 48) return `-----BEGIN PRIVATE KEY-----
|
|
1167
|
+
${packed}
|
|
1168
|
+
-----END PRIVATE KEY-----`;
|
|
1169
|
+
} catch {
|
|
1170
|
+
}
|
|
1171
|
+
return text2;
|
|
1172
|
+
}
|
|
1173
|
+
function asc(h) {
|
|
1174
|
+
let token;
|
|
1175
|
+
const authorization = () => {
|
|
1176
|
+
token ??= appStoreConnectToken({
|
|
1177
|
+
issuerId: h.credentials["issuerid"],
|
|
1178
|
+
keyId: h.credentials["keyid"],
|
|
1179
|
+
privateKey: h.credentials["privatekey"]
|
|
1180
|
+
}).then((jwt) => `Bearer ${jwt}`);
|
|
1181
|
+
return token;
|
|
1182
|
+
};
|
|
1183
|
+
const send = async (request) => h.api({
|
|
1184
|
+
...request,
|
|
1185
|
+
origin: ORIGIN,
|
|
1186
|
+
headers: { ...request.headers, authorization: await authorization() }
|
|
1187
|
+
});
|
|
1188
|
+
return {
|
|
1189
|
+
send,
|
|
1190
|
+
async get(path, query, errors) {
|
|
1191
|
+
const { data } = await send({ path, ...query ? { query } : {}, ...errors ? { errors } : {} });
|
|
1192
|
+
return data;
|
|
1193
|
+
}
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
1196
|
+
function nextAppleCursor(data) {
|
|
1197
|
+
const next = data?.links?.next;
|
|
1198
|
+
if (typeof next !== "string") return void 0;
|
|
1199
|
+
try {
|
|
1200
|
+
return new URL(next).searchParams.get("cursor") ?? void 0;
|
|
1201
|
+
} catch {
|
|
1202
|
+
return void 0;
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
function includedMap(data, type) {
|
|
1206
|
+
const map = /* @__PURE__ */ new Map();
|
|
1207
|
+
for (const item of Array.isArray(data?.included) ? data.included : []) {
|
|
1208
|
+
if (item?.type === type && typeof item.id === "string") map.set(item.id, item);
|
|
1209
|
+
}
|
|
1210
|
+
return map;
|
|
1211
|
+
}
|
|
1212
|
+
function compact(value) {
|
|
1213
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
|
|
1214
|
+
}
|
|
1215
|
+
function text(value, max) {
|
|
1216
|
+
return typeof value === "string" && value.trim() ? truncate(value, max) : void 0;
|
|
1217
|
+
}
|
|
1218
|
+
async function applePage(h, api, options) {
|
|
1219
|
+
const state = h.cursor(options.cursor);
|
|
1220
|
+
const appleCursor = typeof state?.["c"] === "string" ? state["c"] : void 0;
|
|
1221
|
+
const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1222
|
+
const data = await api.get(options.path, { ...options.query, ...appleCursor ? { cursor: appleCursor } : {} });
|
|
1223
|
+
const items = (Array.isArray(data?.data) ? data.data : []).map((item) => options.map(item, data)).slice(skip);
|
|
1224
|
+
if (options.enrich) await options.enrich(items);
|
|
1225
|
+
const next = nextAppleCursor(data);
|
|
1226
|
+
return h.page({
|
|
1227
|
+
key: options.key,
|
|
1228
|
+
items,
|
|
1229
|
+
...options.extra ? { extra: options.extra(data) } : {},
|
|
1230
|
+
resumeAt: (index) => h.makeCursor({ ...appleCursor ? { c: appleCursor } : {}, o: skip + index }),
|
|
1231
|
+
...next ? { nextPage: h.makeCursor({ c: next, o: 0 }) } : {}
|
|
1232
|
+
});
|
|
1233
|
+
}
|
|
1234
|
+
function locked(h) {
|
|
1235
|
+
return h.ctx.accounts !== null;
|
|
1236
|
+
}
|
|
1237
|
+
function sleep(ms, signal) {
|
|
1238
|
+
return new Promise((resolve, reject) => {
|
|
1239
|
+
if (signal?.aborted) {
|
|
1240
|
+
reject(new ToolFailure("The call was cancelled while waiting for App Store Connect."));
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
const stop = () => {
|
|
1244
|
+
clearTimeout(timer);
|
|
1245
|
+
reject(new ToolFailure("The call was cancelled while waiting for App Store Connect."));
|
|
1246
|
+
};
|
|
1247
|
+
const timer = setTimeout(() => {
|
|
1248
|
+
signal?.removeEventListener("abort", stop);
|
|
1249
|
+
resolve();
|
|
1250
|
+
}, ms);
|
|
1251
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
async function appEventOf(api, appId, eventId, fields = "referenceName") {
|
|
1255
|
+
const data = await api.get(`/v1/apps/${appId}/appEvents`, { "filter[id]": eventId, "fields[appEvents]": fields, limit: 1 });
|
|
1256
|
+
const event = (Array.isArray(data?.data) ? data.data : []).find((item) => item?.id === eventId);
|
|
1257
|
+
if (!event) throw new ToolFailure(`App ${appId} has no in-app event ${eventId}. Use list_app_events to find the event's id. Nothing was sent.`);
|
|
1258
|
+
return event;
|
|
1259
|
+
}
|
|
1260
|
+
async function assertEventInApp(api, appId, eventId) {
|
|
1261
|
+
await appEventOf(api, appId, eventId);
|
|
1262
|
+
}
|
|
1263
|
+
async function eventLocalizationMedia(api, localizationId) {
|
|
1264
|
+
const data = await api.get(
|
|
1265
|
+
`/v1/appEventLocalizations/${encodeURIComponent(localizationId)}`,
|
|
1266
|
+
{
|
|
1267
|
+
include: "appEvent,appEventScreenshots,appEventVideoClips,placements",
|
|
1268
|
+
"fields[appEventLocalizations]": "locale,appEvent,appEventScreenshots,appEventVideoClips,placements",
|
|
1269
|
+
"fields[appEventScreenshots]": "fileName,fileSize,appEventAssetType,assetDeliveryState,imageAsset",
|
|
1270
|
+
"fields[appEventVideoClips]": "fileName,fileSize,appEventAssetType,assetDeliveryState,videoDeliveryState",
|
|
1271
|
+
"fields[appAssetLibraryPlacements]": "placementType,mediaType,state",
|
|
1272
|
+
"limit[appEventScreenshots]": 10,
|
|
1273
|
+
"limit[appEventVideoClips]": 10,
|
|
1274
|
+
"limit[placements]": 10
|
|
1275
|
+
},
|
|
1276
|
+
{ 404: "App Store Connect has no in-app event localization with that id" }
|
|
1277
|
+
);
|
|
1278
|
+
const eventId = data?.data?.relationships?.appEvent?.data?.id;
|
|
1279
|
+
if (typeof eventId !== "string" || !eventId) throw new ToolFailure("App Store Connect did not say which event the localization belongs to. Nothing was sent.");
|
|
1280
|
+
const related = (name2, type) => {
|
|
1281
|
+
const included = includedMap(data, type);
|
|
1282
|
+
const refs = Array.isArray(data?.data?.relationships?.[name2]?.data) ? data.data.relationships[name2].data : [];
|
|
1283
|
+
return refs.map((ref) => included.get(ref?.id) ?? { type, id: ref?.id }).filter((item) => typeof item?.id === "string");
|
|
1284
|
+
};
|
|
1285
|
+
return {
|
|
1286
|
+
id: localizationId,
|
|
1287
|
+
eventId,
|
|
1288
|
+
locale: data?.data?.attributes?.locale,
|
|
1289
|
+
images: related("appEventScreenshots", "appEventScreenshots"),
|
|
1290
|
+
videos: related("appEventVideoClips", "appEventVideoClips"),
|
|
1291
|
+
placements: related("placements", "appAssetLibraryPlacements")
|
|
1292
|
+
};
|
|
1293
|
+
}
|
|
1294
|
+
function deliveryNotes(list) {
|
|
1295
|
+
if (!Array.isArray(list) || !list.length) return void 0;
|
|
1296
|
+
return list.slice(0, 10).map((item) => text([item?.code, item?.description].filter(Boolean).join(": "), 300)).filter((item) => Boolean(item));
|
|
1297
|
+
}
|
|
1298
|
+
function trimEventImage(item) {
|
|
1299
|
+
const a = item?.attributes ?? {};
|
|
1300
|
+
const asset = a.imageAsset ?? {};
|
|
1301
|
+
return compact({
|
|
1302
|
+
id: item?.id,
|
|
1303
|
+
assetType: a.appEventAssetType,
|
|
1304
|
+
fileName: a.fileName,
|
|
1305
|
+
fileSize: a.fileSize,
|
|
1306
|
+
state: a.assetDeliveryState?.state,
|
|
1307
|
+
errors: deliveryNotes(a.assetDeliveryState?.errors),
|
|
1308
|
+
warnings: deliveryNotes(a.assetDeliveryState?.warnings),
|
|
1309
|
+
width: asset.width,
|
|
1310
|
+
height: asset.height,
|
|
1311
|
+
templateUrl: text(asset.templateUrl, 1e3)
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
function trimEventVideo(item) {
|
|
1315
|
+
const a = item?.attributes ?? {};
|
|
1316
|
+
return compact({
|
|
1317
|
+
id: item?.id,
|
|
1318
|
+
assetType: a.appEventAssetType,
|
|
1319
|
+
fileName: a.fileName,
|
|
1320
|
+
fileSize: a.fileSize,
|
|
1321
|
+
state: a.assetDeliveryState?.state,
|
|
1322
|
+
videoState: a.videoDeliveryState?.state
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
function trimPlacement(item) {
|
|
1326
|
+
const a = item?.attributes ?? {};
|
|
1327
|
+
return compact({ id: item?.id, placementType: a.placementType, mediaType: a.mediaType, state: a.state });
|
|
1328
|
+
}
|
|
1329
|
+
async function eventOfLocalization(api, localizationId) {
|
|
1330
|
+
const data = await api.get(
|
|
1331
|
+
`/v1/appEventLocalizations/${encodeURIComponent(localizationId)}`,
|
|
1332
|
+
{ include: "appEvent", "fields[appEventLocalizations]": "locale,appEvent" },
|
|
1333
|
+
{ 404: "App Store Connect has no in-app event localization with that id" }
|
|
1334
|
+
);
|
|
1335
|
+
const eventId = data?.data?.relationships?.appEvent?.data?.id;
|
|
1336
|
+
if (typeof eventId !== "string" || !eventId) throw new ToolFailure("App Store Connect did not say which event the localization belongs to. Nothing was sent.");
|
|
1337
|
+
return eventId;
|
|
1338
|
+
}
|
|
1339
|
+
async function assertReviewInApp(api, appId, reviewId) {
|
|
1340
|
+
let cursor;
|
|
1341
|
+
for (let page = 0; page < REVIEW_SCAN_PAGES; page++) {
|
|
1342
|
+
const data = await api.get(`/v1/apps/${appId}/customerReviews`, {
|
|
1343
|
+
sort: "-createdDate",
|
|
1344
|
+
limit: 200,
|
|
1345
|
+
"fields[customerReviews]": "createdDate",
|
|
1346
|
+
...cursor ? { cursor } : {}
|
|
1347
|
+
});
|
|
1348
|
+
if ((Array.isArray(data?.data) ? data.data : []).some((review) => review?.id === reviewId)) return;
|
|
1349
|
+
cursor = nextAppleCursor(data);
|
|
1350
|
+
if (!cursor) break;
|
|
1351
|
+
}
|
|
1352
|
+
throw new ToolFailure(
|
|
1353
|
+
`The review ${reviewId} is not among the newest ${REVIEW_SCAN_PAGES * 200} reviews of app ${appId}. Use list_reviews for that app to find the review's id. Nothing was sent.`
|
|
1354
|
+
);
|
|
1355
|
+
}
|
|
1356
|
+
function trimApp(item) {
|
|
1357
|
+
const a = item?.attributes ?? {};
|
|
1358
|
+
return compact({ id: item?.id, name: a.name, bundleId: a.bundleId, sku: a.sku, primaryLocale: a.primaryLocale });
|
|
1359
|
+
}
|
|
1360
|
+
function trimResponse(item) {
|
|
1361
|
+
const a = item?.attributes ?? {};
|
|
1362
|
+
return compact({ id: item?.id, body: text(a.responseBody, 6e3), state: a.state, lastModifiedDate: a.lastModifiedDate });
|
|
1363
|
+
}
|
|
1364
|
+
function trimReview(item, responses) {
|
|
1365
|
+
const a = item?.attributes ?? {};
|
|
1366
|
+
const responseId = item?.relationships?.response?.data?.id;
|
|
1367
|
+
const response = typeof responseId === "string" ? responses.get(responseId) : void 0;
|
|
1368
|
+
return compact({
|
|
1369
|
+
id: item?.id,
|
|
1370
|
+
rating: a.rating,
|
|
1371
|
+
title: text(a.title, 300),
|
|
1372
|
+
body: text(a.body, 6e3),
|
|
1373
|
+
reviewer: text(a.reviewerNickname, 100),
|
|
1374
|
+
territory: a.territory,
|
|
1375
|
+
createdDate: a.createdDate,
|
|
1376
|
+
responded: Boolean(response),
|
|
1377
|
+
response: response ? trimResponse(response) : void 0
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
function trimSchedule(schedule) {
|
|
1381
|
+
return compact({
|
|
1382
|
+
territories: Array.isArray(schedule?.territories) ? schedule.territories.map(String) : void 0,
|
|
1383
|
+
publishStart: schedule?.publishStart,
|
|
1384
|
+
eventStart: schedule?.eventStart,
|
|
1385
|
+
eventEnd: schedule?.eventEnd
|
|
1386
|
+
});
|
|
1387
|
+
}
|
|
1388
|
+
function trimEventLocalization(item) {
|
|
1389
|
+
const a = item?.attributes ?? {};
|
|
1390
|
+
return compact({ id: item?.id, locale: a.locale, name: a.name, shortDescription: a.shortDescription, longDescription: a.longDescription });
|
|
1391
|
+
}
|
|
1392
|
+
function trimEvent(item, localizations) {
|
|
1393
|
+
const a = item?.attributes ?? {};
|
|
1394
|
+
const ids = (Array.isArray(item?.relationships?.localizations?.data) ? item.relationships.localizations.data : []).map((ref) => ref?.id).filter((id) => typeof id === "string");
|
|
1395
|
+
return compact({
|
|
1396
|
+
id: item?.id,
|
|
1397
|
+
referenceName: a.referenceName,
|
|
1398
|
+
badge: a.badge,
|
|
1399
|
+
state: a.eventState,
|
|
1400
|
+
priority: a.priority,
|
|
1401
|
+
purpose: a.purpose,
|
|
1402
|
+
purchaseRequirement: a.purchaseRequirement,
|
|
1403
|
+
deepLink: a.deepLink,
|
|
1404
|
+
primaryLocale: a.primaryLocale,
|
|
1405
|
+
territorySchedules: Array.isArray(a.territorySchedules) ? a.territorySchedules.map(trimSchedule) : void 0,
|
|
1406
|
+
localizations: localizations ? ids.map((id) => localizations.get(id)).filter(Boolean).map(trimEventLocalization) : void 0
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
// src/vendors/apple-appstore/media.ts
|
|
1411
|
+
var EVENT_ASSET_TYPES = ["EVENT_CARD", "EVENT_DETAILS_PAGE"];
|
|
1412
|
+
var MAX_IMAGE_BYTES = 25 * 1024 * 1024;
|
|
1413
|
+
var POLL_MS = 3e3;
|
|
1414
|
+
var POLL_FOR_MS = 45e3;
|
|
1415
|
+
var UPLOAD_HOSTS = [".blobstore.apple.com", "northamerica-1.object-storage.apple.com"];
|
|
1416
|
+
var UPLOAD_SERVERS = UPLOAD_HOSTS.map((host) => host.startsWith(".") ? `*${host}` : host).join(" or ");
|
|
1417
|
+
var HEADER_NAME = /^[A-Za-z0-9-]{1,100}$/;
|
|
1418
|
+
var SPECS = {
|
|
1419
|
+
EVENT_CARD: { name: "event card", min: [1920, 1080], max: [3840, 2160], ratio: [16, 9], orientation: "landscape" },
|
|
1420
|
+
EVENT_DETAILS_PAGE: { name: "event details page", min: [1080, 1920], max: [2160, 3840], ratio: [9, 16], orientation: "portrait" }
|
|
1421
|
+
};
|
|
1422
|
+
function u32(bytes, at) {
|
|
1423
|
+
return (bytes[at] ?? 0) * 16777216 + ((bytes[at + 1] ?? 0) << 16 | (bytes[at + 2] ?? 0) << 8 | (bytes[at + 3] ?? 0));
|
|
1424
|
+
}
|
|
1425
|
+
function u16(bytes, at) {
|
|
1426
|
+
return (bytes[at] ?? 0) << 8 | (bytes[at + 1] ?? 0);
|
|
1427
|
+
}
|
|
1428
|
+
var PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10];
|
|
1429
|
+
var isStartOfFrame = (marker) => marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204;
|
|
1430
|
+
function imageInfo(bytes) {
|
|
1431
|
+
if (bytes.length >= 24 && PNG_SIGNATURE.every((value, index) => bytes[index] === value)) {
|
|
1432
|
+
if (bytes[12] !== 73 || bytes[13] !== 72 || bytes[14] !== 68 || bytes[15] !== 82) return void 0;
|
|
1433
|
+
return { format: "png", width: u32(bytes, 16), height: u32(bytes, 20) };
|
|
1434
|
+
}
|
|
1435
|
+
if (bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 216) {
|
|
1436
|
+
let at = 2;
|
|
1437
|
+
while (at + 4 <= bytes.length) {
|
|
1438
|
+
if (bytes[at] !== 255) return void 0;
|
|
1439
|
+
const marker = bytes[at + 1];
|
|
1440
|
+
if (marker === 255) {
|
|
1441
|
+
at += 1;
|
|
1442
|
+
continue;
|
|
1443
|
+
}
|
|
1444
|
+
if (marker === 1 || marker >= 208 && marker <= 216) {
|
|
1445
|
+
at += 2;
|
|
1446
|
+
continue;
|
|
1447
|
+
}
|
|
1448
|
+
if (marker === 217 || marker === 218) return void 0;
|
|
1449
|
+
const length = u16(bytes, at + 2);
|
|
1450
|
+
if (length < 2) return void 0;
|
|
1451
|
+
if (isStartOfFrame(marker)) {
|
|
1452
|
+
if (at + 9 > bytes.length) return void 0;
|
|
1453
|
+
return { format: "jpeg", width: u16(bytes, at + 7), height: u16(bytes, at + 5) };
|
|
1454
|
+
}
|
|
1455
|
+
at += 2 + length;
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
return void 0;
|
|
1459
|
+
}
|
|
1460
|
+
function checkEventImage(info, assetType) {
|
|
1461
|
+
const spec = SPECS[assetType];
|
|
1462
|
+
const [minWidth, minHeight] = spec.min;
|
|
1463
|
+
const [maxWidth, maxHeight] = spec.max;
|
|
1464
|
+
const [ratioWidth, ratioHeight] = spec.ratio;
|
|
1465
|
+
const needs = `The ${spec.name} image must be a ${spec.orientation} JPEG or PNG with a ${ratioWidth}:${ratioHeight} aspect ratio, from ${minWidth}x${minHeight} to ${maxWidth}x${maxHeight} pixels`;
|
|
1466
|
+
if (!info) throw new ToolFailure(`The file at image_url is not a JPEG or PNG image. ${needs}. Nothing was changed.`);
|
|
1467
|
+
const { width, height } = info;
|
|
1468
|
+
if (width * ratioHeight !== height * ratioWidth || width < minWidth || height < minHeight || width > maxWidth || height > maxHeight) {
|
|
1469
|
+
throw new ToolFailure(`The image is ${width}x${height} pixels. ${needs}, such as ${minWidth}x${minHeight}: crop or resize it first. Nothing was changed.`);
|
|
1470
|
+
}
|
|
1471
|
+
return info;
|
|
1472
|
+
}
|
|
1473
|
+
var RESERVE_ERRORS = {
|
|
1474
|
+
403: "The App Store Connect key's role cannot manage in-app events (it needs Admin, App Manager or Marketing)",
|
|
1475
|
+
409: "App Store Connect refused the image: the localization may already have one of this kind, or the event can no longer be changed in its state",
|
|
1476
|
+
422: "App Store Connect refused the image: a value is invalid"
|
|
1477
|
+
};
|
|
1478
|
+
var COMMIT_ERRORS = {
|
|
1479
|
+
409: "App Store Connect refused to finish the upload: the bytes it received do not match the image, or the reservation has expired"
|
|
1480
|
+
};
|
|
1481
|
+
var UploadProblem = class extends Error {
|
|
1482
|
+
constructor(message) {
|
|
1483
|
+
super(message);
|
|
1484
|
+
this.name = "UploadProblem";
|
|
1485
|
+
}
|
|
1486
|
+
};
|
|
1487
|
+
function describe2(error) {
|
|
1488
|
+
const code = error?.code;
|
|
1489
|
+
const name2 = error?.name;
|
|
1490
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
1491
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
1492
|
+
return "a network error";
|
|
1493
|
+
}
|
|
1494
|
+
async function uploadParts(h, operations, bytes) {
|
|
1495
|
+
if (!Array.isArray(operations) || !operations.length) throw new UploadProblem("App Store Connect returned no upload address for the image.");
|
|
1496
|
+
const parts = operations.map((operation, index) => {
|
|
1497
|
+
const which = `part ${index + 1} of ${operations.length}`;
|
|
1498
|
+
const offset = operation?.offset;
|
|
1499
|
+
const length = operation?.length;
|
|
1500
|
+
if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length <= 0 || offset + length > bytes.length) {
|
|
1501
|
+
throw new UploadProblem(`App Store Connect asked for ${which} at a place the image does not have.`);
|
|
1502
|
+
}
|
|
1503
|
+
if (String(operation?.method ?? "PUT").toUpperCase() !== "PUT") throw new UploadProblem(`App Store Connect asked to upload ${which} with a method other than PUT.`);
|
|
1504
|
+
let url;
|
|
1505
|
+
try {
|
|
1506
|
+
url = new URL(String(operation?.url));
|
|
1507
|
+
} catch {
|
|
1508
|
+
}
|
|
1509
|
+
if (!url || url.protocol !== "https:" || !isUploadHost(url.hostname, UPLOAD_HOSTS) || url.username || url.password) {
|
|
1510
|
+
throw new UploadProblem(`App Store Connect returned an upload address for ${which} that is not an https address on its upload servers (${UPLOAD_SERVERS}).`);
|
|
1511
|
+
}
|
|
1512
|
+
const headers = {};
|
|
1513
|
+
for (const header of Array.isArray(operation?.requestHeaders) ? operation.requestHeaders : []) {
|
|
1514
|
+
if (typeof header?.name === "string" && HEADER_NAME.test(header.name) && typeof header?.value === "string") headers[header.name] = header.value;
|
|
1515
|
+
}
|
|
1516
|
+
return { which, url: url.toString(), headers, offset, length };
|
|
1517
|
+
});
|
|
1518
|
+
for (const part of parts) {
|
|
1519
|
+
const started = Date.now();
|
|
1520
|
+
let response;
|
|
1521
|
+
try {
|
|
1522
|
+
response = await h.ctx.fetch(part.url, {
|
|
1523
|
+
method: "PUT",
|
|
1524
|
+
headers: part.headers,
|
|
1525
|
+
body: bytes.slice(part.offset, part.offset + part.length),
|
|
1526
|
+
...h.ctx.signal ? { signal: h.ctx.signal } : {}
|
|
1527
|
+
});
|
|
1528
|
+
} catch (error) {
|
|
1529
|
+
h.log(`apple-appstore ${h.tool} PUT failed ${Date.now() - started}ms`);
|
|
1530
|
+
if (error?.code === "URL_REFUSED") {
|
|
1531
|
+
const reason = cleanVendorText(error?.message, 200);
|
|
1532
|
+
throw new UploadProblem(`The host running this connector refused to send ${part.which} to App Store Connect's upload server${reason ? ` (${reason})` : ""}, so the image was not sent.`);
|
|
1533
|
+
}
|
|
1534
|
+
throw new UploadProblem(`The upload of ${part.which} to App Store Connect's upload server failed (${describe2(error)}).`);
|
|
1535
|
+
}
|
|
1536
|
+
h.log(`apple-appstore ${h.tool} PUT ${response.status} ${Date.now() - started}ms`);
|
|
1537
|
+
await response.body?.cancel().catch(() => {
|
|
1538
|
+
});
|
|
1539
|
+
if (!response.ok) throw new UploadProblem(`App Store Connect's upload server answered HTTP ${response.status} for ${part.which}.`);
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
async function removeReservation(api, id) {
|
|
1543
|
+
try {
|
|
1544
|
+
await api.send({ method: "DELETE", path: `/v1/appEventScreenshots/${encodeURIComponent(id)}` });
|
|
1545
|
+
return `The reserved image ${id} was removed again, so nothing was left behind.`;
|
|
1546
|
+
} catch {
|
|
1547
|
+
return `The reserved image ${id} could not be removed: delete it with delete_app_event_image before trying again.`;
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
var IN_APP_STORE_CONNECT = "Or add the image in App Store Connect (Apps > the app > In-App Events > the event, in its locale).";
|
|
1551
|
+
async function waitProcessed(h, api, id) {
|
|
1552
|
+
const until = Date.now() + POLL_FOR_MS;
|
|
1553
|
+
for (; ; ) {
|
|
1554
|
+
const reply = await api.get(`/v1/appEventScreenshots/${encodeURIComponent(id)}`, {
|
|
1555
|
+
"fields[appEventScreenshots]": "fileName,fileSize,appEventAssetType,assetDeliveryState,imageAsset"
|
|
1556
|
+
});
|
|
1557
|
+
const state = reply?.data?.attributes?.assetDeliveryState?.state;
|
|
1558
|
+
if (state === "COMPLETE" || state === "FAILED" || Date.now() + POLL_MS > until) return reply?.data;
|
|
1559
|
+
await sleep(POLL_MS, h.ctx.signal);
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
async function uploadEventImage(h, api, args) {
|
|
1563
|
+
const { localizationId, assetType, bytes, info } = args;
|
|
1564
|
+
const fileName2 = `${assetType === "EVENT_CARD" ? "event-card" : "event-details-page"}.${info.format === "png" ? "png" : "jpg"}`;
|
|
1565
|
+
const { data } = await api.send({
|
|
1566
|
+
method: "POST",
|
|
1567
|
+
path: "/v1/appEventScreenshots",
|
|
1568
|
+
json: {
|
|
1569
|
+
data: {
|
|
1570
|
+
type: "appEventScreenshots",
|
|
1571
|
+
attributes: { fileName: fileName2, fileSize: bytes.length, appEventAssetType: assetType },
|
|
1572
|
+
relationships: { appEventLocalization: { data: { type: "appEventLocalizations", id: localizationId } } }
|
|
1573
|
+
}
|
|
1574
|
+
},
|
|
1575
|
+
write: true,
|
|
1576
|
+
errors: RESERVE_ERRORS
|
|
1577
|
+
});
|
|
1578
|
+
const id = data?.data?.id;
|
|
1579
|
+
if (typeof id !== "string" || !id) throw new OutcomeUnknown("App Store Connect answered without the id of the reserved image, so it is not known whether one was reserved.");
|
|
1580
|
+
try {
|
|
1581
|
+
await uploadParts(h, data?.data?.attributes?.uploadOperations, bytes);
|
|
1582
|
+
} catch (error) {
|
|
1583
|
+
if (!(error instanceof UploadProblem)) throw error;
|
|
1584
|
+
throw new ToolFailure(`${error.message} ${await removeReservation(api, id)} ${IN_APP_STORE_CONNECT}`);
|
|
1585
|
+
}
|
|
1586
|
+
try {
|
|
1587
|
+
await api.send({
|
|
1588
|
+
method: "PATCH",
|
|
1589
|
+
path: `/v1/appEventScreenshots/${encodeURIComponent(id)}`,
|
|
1590
|
+
json: { data: { type: "appEventScreenshots", id, attributes: { uploaded: true } } },
|
|
1591
|
+
write: true,
|
|
1592
|
+
errors: COMMIT_ERRORS
|
|
1593
|
+
});
|
|
1594
|
+
} catch (error) {
|
|
1595
|
+
if (!(error instanceof ToolFailure)) throw error;
|
|
1596
|
+
throw new ToolFailure(`${error.message.replace(/ Nothing was changed\./, "")} ${await removeReservation(api, id)} ${IN_APP_STORE_CONNECT}`, error.details);
|
|
1597
|
+
}
|
|
1598
|
+
let image;
|
|
1599
|
+
try {
|
|
1600
|
+
image = await waitProcessed(h, api, id);
|
|
1601
|
+
} catch (error) {
|
|
1602
|
+
if (!(error instanceof ToolFailure)) throw error;
|
|
1603
|
+
return compact({
|
|
1604
|
+
localizationId,
|
|
1605
|
+
image: { id, assetType, fileName: fileName2, fileSize: bytes.length, state: "UPLOAD_COMPLETE" },
|
|
1606
|
+
note: `The image was uploaded, but its processing could not be followed (${error.message.replace(/ Nothing was changed\./, "").replace(/[.!?]+$/u, "")}). Check it with list_app_event_images.`
|
|
1607
|
+
});
|
|
1608
|
+
}
|
|
1609
|
+
const trimmed2 = trimEventImage(image ?? { id });
|
|
1610
|
+
if (trimmed2["state"] === "FAILED") {
|
|
1611
|
+
const reasons = Array.isArray(trimmed2["errors"]) && trimmed2["errors"].length ? `: ${trimmed2["errors"].map((reason) => reason.replace(/[.!?]+$/u, "")).join("; ")}` : "";
|
|
1612
|
+
throw new ToolFailure(`App Store Connect could not process the image${reasons}. ${await removeReservation(api, id)}`);
|
|
1613
|
+
}
|
|
1614
|
+
return compact({
|
|
1615
|
+
localizationId,
|
|
1616
|
+
image: trimmed2,
|
|
1617
|
+
note: trimmed2["state"] === "COMPLETE" ? void 0 : "App Store Connect is still processing the image (it can take a few minutes): check it with list_app_event_images."
|
|
1618
|
+
});
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
// src/vendors/apple-appstore/metadata.ts
|
|
1622
|
+
var LIVE_STATES = /* @__PURE__ */ new Set(["READY_FOR_SALE", "READY_FOR_DISTRIBUTION"]);
|
|
1623
|
+
function trimAppInfo(item, localizations, locale) {
|
|
1624
|
+
const a = item?.attributes ?? {};
|
|
1625
|
+
const refs = Array.isArray(item?.relationships?.appInfoLocalizations?.data) ? item.relationships.appInfoLocalizations.data : [];
|
|
1626
|
+
const all = refs.map((ref) => localizations.get(ref?.id)).filter(Boolean);
|
|
1627
|
+
const chosen = all.find((loc) => loc?.attributes?.locale === locale) ?? all[0];
|
|
1628
|
+
const l = chosen?.attributes ?? {};
|
|
1629
|
+
return compact({
|
|
1630
|
+
id: item?.id,
|
|
1631
|
+
state: a.state ?? a.appStoreState,
|
|
1632
|
+
ageRating: a.appStoreAgeRating,
|
|
1633
|
+
primaryCategory: item?.relationships?.primaryCategory?.data?.id,
|
|
1634
|
+
secondaryCategory: item?.relationships?.secondaryCategory?.data?.id,
|
|
1635
|
+
locale: l.locale,
|
|
1636
|
+
name: l.name,
|
|
1637
|
+
subtitle: l.subtitle,
|
|
1638
|
+
privacyPolicyUrl: l.privacyPolicyUrl,
|
|
1639
|
+
locales: all.map((loc) => loc?.attributes?.locale).filter(Boolean)
|
|
1640
|
+
});
|
|
1641
|
+
}
|
|
1642
|
+
function trimVersion(item) {
|
|
1643
|
+
const a = item?.attributes ?? {};
|
|
1644
|
+
return compact({
|
|
1645
|
+
id: item?.id,
|
|
1646
|
+
platform: a.platform,
|
|
1647
|
+
versionString: a.versionString,
|
|
1648
|
+
state: a.appVersionState ?? a.appStoreState,
|
|
1649
|
+
releaseType: a.releaseType,
|
|
1650
|
+
createdDate: a.createdDate
|
|
1651
|
+
});
|
|
1652
|
+
}
|
|
1653
|
+
function trimListing(result2, country) {
|
|
1654
|
+
return compact({
|
|
1655
|
+
country,
|
|
1656
|
+
available: true,
|
|
1657
|
+
url: result2?.trackViewUrl,
|
|
1658
|
+
name: result2?.trackName,
|
|
1659
|
+
seller: result2?.sellerName,
|
|
1660
|
+
price: result2?.price,
|
|
1661
|
+
formattedPrice: result2?.formattedPrice,
|
|
1662
|
+
currency: result2?.currency,
|
|
1663
|
+
primaryGenre: result2?.primaryGenreName,
|
|
1664
|
+
genres: Array.isArray(result2?.genres) ? result2.genres : void 0,
|
|
1665
|
+
averageUserRating: result2?.averageUserRating,
|
|
1666
|
+
userRatingCount: result2?.userRatingCount,
|
|
1667
|
+
contentAdvisoryRating: result2?.contentAdvisoryRating,
|
|
1668
|
+
version: result2?.version,
|
|
1669
|
+
currentVersionReleaseDate: result2?.currentVersionReleaseDate,
|
|
1670
|
+
releaseNotes: text(result2?.releaseNotes, 2e3),
|
|
1671
|
+
description: text(result2?.description, 4e3),
|
|
1672
|
+
minimumOsVersion: result2?.minimumOsVersion,
|
|
1673
|
+
languages: Array.isArray(result2?.languageCodesISO2A) ? result2.languageCodesISO2A : void 0,
|
|
1674
|
+
fileSizeBytes: result2?.fileSizeBytes
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
async function storeListing(h, appId, country) {
|
|
1678
|
+
try {
|
|
1679
|
+
const { data } = await h.api({ origin: LOOKUP_ORIGIN, path: "/lookup", query: { id: appId, country }, auth: false });
|
|
1680
|
+
const result2 = Array.isArray(data?.results) ? data.results.find((item) => String(item?.trackId) === appId) ?? data.results[0] : void 0;
|
|
1681
|
+
if (!result2) return { country, available: false, note: `The app is not on the App Store in this country (${country.toUpperCase()}), or not released yet.` };
|
|
1682
|
+
return trimListing(result2, country);
|
|
1683
|
+
} catch (error) {
|
|
1684
|
+
if (error instanceof ToolFailure) return { country, error: error.message };
|
|
1685
|
+
throw error;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
async function appMetadata(h, api, args) {
|
|
1689
|
+
const appId = args.app_id;
|
|
1690
|
+
const app = await api.get(`/v1/apps/${appId}`, {
|
|
1691
|
+
"fields[apps]": "name,bundleId,sku,primaryLocale,contentRightsDeclaration,isOrEverWasMadeForKids"
|
|
1692
|
+
}, { 404: `App Store Connect has no app ${appId} that this key can see` });
|
|
1693
|
+
const a = app?.data?.attributes ?? {};
|
|
1694
|
+
const locale = args.locale ?? (typeof a.primaryLocale === "string" ? a.primaryLocale : "en-US");
|
|
1695
|
+
const infos = await api.get(`/v1/apps/${appId}/appInfos`, {
|
|
1696
|
+
include: "appInfoLocalizations,primaryCategory,secondaryCategory",
|
|
1697
|
+
"fields[appInfos]": "appStoreState,state,appStoreAgeRating,appInfoLocalizations,primaryCategory,secondaryCategory",
|
|
1698
|
+
"fields[appInfoLocalizations]": "locale,name,subtitle,privacyPolicyUrl",
|
|
1699
|
+
"limit[appInfoLocalizations]": 50,
|
|
1700
|
+
limit: 5
|
|
1701
|
+
});
|
|
1702
|
+
const infoLocalizations = includedMap(infos, "appInfoLocalizations");
|
|
1703
|
+
const appInfos = (Array.isArray(infos?.data) ? infos.data : []).map((item) => trimAppInfo(item, infoLocalizations, locale));
|
|
1704
|
+
const versionsReply = await api.get(`/v1/apps/${appId}/appStoreVersions`, {
|
|
1705
|
+
"fields[appStoreVersions]": "platform,versionString,appStoreState,appVersionState,releaseType,createdDate",
|
|
1706
|
+
limit: 5
|
|
1707
|
+
});
|
|
1708
|
+
const versionItems = Array.isArray(versionsReply?.data) ? versionsReply.data : [];
|
|
1709
|
+
const versions = versionItems.map(trimVersion);
|
|
1710
|
+
const shown = versionItems.find((item) => LIVE_STATES.has(item?.attributes?.appVersionState) || LIVE_STATES.has(item?.attributes?.appStoreState)) ?? versionItems[0];
|
|
1711
|
+
let versionLocalization;
|
|
1712
|
+
if (shown?.id) {
|
|
1713
|
+
const localizations = await api.get(`/v1/appStoreVersions/${encodeURIComponent(shown.id)}/appStoreVersionLocalizations`, {
|
|
1714
|
+
"filter[locale]": locale,
|
|
1715
|
+
"fields[appStoreVersionLocalizations]": "locale,description,keywords,promotionalText,whatsNew,marketingUrl,supportUrl",
|
|
1716
|
+
limit: 1
|
|
1717
|
+
});
|
|
1718
|
+
const l = (Array.isArray(localizations?.data) ? localizations.data[0] : void 0)?.attributes;
|
|
1719
|
+
versionLocalization = l ? compact({
|
|
1720
|
+
versionId: shown.id,
|
|
1721
|
+
versionString: shown.attributes?.versionString,
|
|
1722
|
+
locale: l.locale,
|
|
1723
|
+
description: text(l.description, 4e3),
|
|
1724
|
+
keywords: l.keywords,
|
|
1725
|
+
promotionalText: l.promotionalText,
|
|
1726
|
+
whatsNew: text(l.whatsNew, 4e3),
|
|
1727
|
+
marketingUrl: l.marketingUrl,
|
|
1728
|
+
supportUrl: l.supportUrl
|
|
1729
|
+
}) : { versionId: shown.id, locale, note: `The version has no ${locale} localization.` };
|
|
1730
|
+
}
|
|
1731
|
+
return compact({
|
|
1732
|
+
app: compact({
|
|
1733
|
+
id: app?.data?.id ?? appId,
|
|
1734
|
+
name: a.name,
|
|
1735
|
+
bundleId: a.bundleId,
|
|
1736
|
+
sku: a.sku,
|
|
1737
|
+
primaryLocale: a.primaryLocale,
|
|
1738
|
+
contentRightsDeclaration: a.contentRightsDeclaration,
|
|
1739
|
+
madeForKids: a.isOrEverWasMadeForKids
|
|
1740
|
+
}),
|
|
1741
|
+
appInfos,
|
|
1742
|
+
versions,
|
|
1743
|
+
versionLocalization,
|
|
1744
|
+
storeListing: args.include_store_listing ? await storeListing(h, appId, args.country) : void 0
|
|
1745
|
+
});
|
|
1746
|
+
}
|
|
1747
|
+
function summarizeOffers(refs, offers) {
|
|
1748
|
+
const groups = /* @__PURE__ */ new Map();
|
|
1749
|
+
for (const ref of refs) {
|
|
1750
|
+
const offer = offers.get(ref?.id);
|
|
1751
|
+
const o = offer?.attributes ?? {};
|
|
1752
|
+
const key = [o.offerMode, o.duration, o.numberOfPeriods].join("|");
|
|
1753
|
+
const group = groups.get(key) ?? { ...compact({ offerMode: o.offerMode, duration: o.duration, numberOfPeriods: o.numberOfPeriods }), territories: 0 };
|
|
1754
|
+
group.territories += 1;
|
|
1755
|
+
groups.set(key, group);
|
|
1756
|
+
}
|
|
1757
|
+
return [...groups.values()];
|
|
1758
|
+
}
|
|
1759
|
+
async function priceList(api, path, query) {
|
|
1760
|
+
try {
|
|
1761
|
+
return await api.get(path, query);
|
|
1762
|
+
} catch (error) {
|
|
1763
|
+
if (error instanceof ToolFailure && error.details.status === 404) return void 0;
|
|
1764
|
+
throw error;
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
function currentAndScheduled(rows) {
|
|
1768
|
+
const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
1769
|
+
const started = rows.filter((row) => (typeof row.startDate !== "string" || row.startDate <= today) && (typeof row.endDate !== "string" || row.endDate > today)).sort((a, b) => String(b.startDate ?? "").localeCompare(String(a.startDate ?? "")));
|
|
1770
|
+
const later = rows.filter((row) => typeof row.startDate === "string" && row.startDate > today);
|
|
1771
|
+
if (!started.length && !later.length) return void 0;
|
|
1772
|
+
return compact({ ...started[0] ?? {}, scheduled: later.length ? later : void 0 });
|
|
1773
|
+
}
|
|
1774
|
+
async function subscriptionPrice(api, subscriptionId, territory) {
|
|
1775
|
+
const reply = await priceList(api, `/v1/subscriptions/${encodeURIComponent(subscriptionId)}/prices`, {
|
|
1776
|
+
"filter[territory]": territory,
|
|
1777
|
+
include: "subscriptionPricePoint,territory",
|
|
1778
|
+
"fields[subscriptionPrices]": "startDate,planType,subscriptionPricePoint,territory",
|
|
1779
|
+
"fields[subscriptionPricePoints]": "customerPrice,proceeds",
|
|
1780
|
+
"fields[territories]": "currency",
|
|
1781
|
+
limit: 20
|
|
1782
|
+
});
|
|
1783
|
+
if (!reply) return void 0;
|
|
1784
|
+
const points = includedMap(reply, "subscriptionPricePoints");
|
|
1785
|
+
const territories = includedMap(reply, "territories");
|
|
1786
|
+
const rows = (Array.isArray(reply?.data) ? reply.data : []).map((item) => {
|
|
1787
|
+
const point = points.get(item?.relationships?.subscriptionPricePoint?.data?.id);
|
|
1788
|
+
const place = territories.get(item?.relationships?.territory?.data?.id);
|
|
1789
|
+
return compact({
|
|
1790
|
+
customerPrice: point?.attributes?.customerPrice,
|
|
1791
|
+
proceeds: point?.attributes?.proceeds,
|
|
1792
|
+
currency: place?.attributes?.currency,
|
|
1793
|
+
territory: item?.relationships?.territory?.data?.id ?? territory,
|
|
1794
|
+
planType: item?.attributes?.planType,
|
|
1795
|
+
startDate: item?.attributes?.startDate ?? void 0
|
|
1796
|
+
});
|
|
1797
|
+
});
|
|
1798
|
+
const monthly = rows.filter((row) => row["planType"] === "MONTHLY");
|
|
1799
|
+
const price = currentAndScheduled(rows.filter((row) => row["planType"] !== "MONTHLY"));
|
|
1800
|
+
const monthlyPrice = monthly.length ? currentAndScheduled(monthly) : void 0;
|
|
1801
|
+
if (!price && !monthlyPrice) return void 0;
|
|
1802
|
+
return compact({ ...price ?? {}, monthlyPlan: monthlyPrice });
|
|
1803
|
+
}
|
|
1804
|
+
async function purchasePrice(api, purchaseId, territory) {
|
|
1805
|
+
for (const kind of ["manualPrices", "automaticPrices"]) {
|
|
1806
|
+
const reply = await priceList(api, `/v1/inAppPurchasePriceSchedules/${encodeURIComponent(purchaseId)}/${kind}`, {
|
|
1807
|
+
"filter[territory]": territory,
|
|
1808
|
+
include: "inAppPurchasePricePoint,territory",
|
|
1809
|
+
"fields[inAppPurchasePrices]": "startDate,endDate,inAppPurchasePricePoint,territory",
|
|
1810
|
+
"fields[inAppPurchasePricePoints]": "customerPrice,proceeds",
|
|
1811
|
+
"fields[territories]": "currency",
|
|
1812
|
+
limit: 20
|
|
1813
|
+
});
|
|
1814
|
+
if (!reply) return void 0;
|
|
1815
|
+
const points = includedMap(reply, "inAppPurchasePricePoints");
|
|
1816
|
+
const territories = includedMap(reply, "territories");
|
|
1817
|
+
const rows = (Array.isArray(reply?.data) ? reply.data : []).map((item) => {
|
|
1818
|
+
const point = points.get(item?.relationships?.inAppPurchasePricePoint?.data?.id);
|
|
1819
|
+
const place = territories.get(item?.relationships?.territory?.data?.id);
|
|
1820
|
+
return compact({
|
|
1821
|
+
customerPrice: point?.attributes?.customerPrice,
|
|
1822
|
+
proceeds: point?.attributes?.proceeds,
|
|
1823
|
+
currency: place?.attributes?.currency,
|
|
1824
|
+
territory: item?.relationships?.territory?.data?.id ?? territory,
|
|
1825
|
+
startDate: item?.attributes?.startDate ?? void 0,
|
|
1826
|
+
endDate: item?.attributes?.endDate ?? void 0
|
|
1827
|
+
});
|
|
1828
|
+
});
|
|
1829
|
+
const price = currentAndScheduled(rows);
|
|
1830
|
+
if (price) return compact({ ...price, automatic: kind === "automaticPrices" ? true : void 0 });
|
|
1831
|
+
}
|
|
1832
|
+
return void 0;
|
|
1833
|
+
}
|
|
1834
|
+
var GROUP_PAGE = 50;
|
|
1835
|
+
var GROUPS_SHOWN = 50;
|
|
1836
|
+
async function subscriptions(h, api, args) {
|
|
1837
|
+
const appId = args.app_id;
|
|
1838
|
+
const territory = args.include_prices ? args.price_territory : void 0;
|
|
1839
|
+
const groupsReply = await api.get(`/v1/apps/${appId}/subscriptionGroups`, { "fields[subscriptionGroups]": "referenceName", limit: 200 });
|
|
1840
|
+
const allGroups = (Array.isArray(groupsReply?.data) ? groupsReply.data : []).filter((group) => typeof group?.id === "string").map((group) => ({ id: group.id, referenceName: group?.attributes?.referenceName }));
|
|
1841
|
+
const moreGroups = Boolean(nextAppleCursor(groupsReply));
|
|
1842
|
+
const groups = args.group_id ? allGroups.filter((group) => group.id === args.group_id) : allGroups;
|
|
1843
|
+
if (args.group_id && !groups.length) {
|
|
1844
|
+
throw new ToolFailure(`App ${appId} has no subscription group ${args.group_id}${moreGroups ? " among its first 200" : ""}. list_subscriptions without group_id names its groups.`);
|
|
1845
|
+
}
|
|
1846
|
+
const state = h.cursor(args.cursor);
|
|
1847
|
+
let g = typeof state?.["g"] === "number" ? state["g"] : 0;
|
|
1848
|
+
let c = typeof state?.["c"] === "string" ? state["c"] : void 0;
|
|
1849
|
+
let o = typeof state?.["o"] === "number" ? state["o"] : 0;
|
|
1850
|
+
const items = [];
|
|
1851
|
+
const positions = [];
|
|
1852
|
+
let next;
|
|
1853
|
+
let freeTrial = false;
|
|
1854
|
+
while (g < groups.length) {
|
|
1855
|
+
const group = groups[g];
|
|
1856
|
+
const reply = await api.get(`/v1/subscriptionGroups/${encodeURIComponent(group.id)}/subscriptions`, {
|
|
1857
|
+
"fields[subscriptions]": "name,productId,subscriptionPeriod,state,groupLevel,familySharable,introductoryOffers",
|
|
1858
|
+
include: "introductoryOffers",
|
|
1859
|
+
"fields[subscriptionIntroductoryOffers]": "duration,offerMode,numberOfPeriods",
|
|
1860
|
+
"limit[introductoryOffers]": 50,
|
|
1861
|
+
limit: GROUP_PAGE,
|
|
1862
|
+
...c ? { cursor: c } : {}
|
|
1863
|
+
});
|
|
1864
|
+
const offers = includedMap(reply, "subscriptionIntroductoryOffers");
|
|
1865
|
+
const page = Array.isArray(reply?.data) ? reply.data : [];
|
|
1866
|
+
const appleNext = nextAppleCursor(reply);
|
|
1867
|
+
let index = o;
|
|
1868
|
+
for (; index < page.length && items.length < args.limit; index++) {
|
|
1869
|
+
const item = page[index];
|
|
1870
|
+
const s = item?.attributes ?? {};
|
|
1871
|
+
const refs = Array.isArray(item?.relationships?.introductoryOffers?.data) ? item.relationships.introductoryOffers.data : [];
|
|
1872
|
+
const introductoryOffers = summarizeOffers(refs, offers);
|
|
1873
|
+
if (introductoryOffers.some((offer) => offer["offerMode"] === "FREE_TRIAL")) freeTrial = true;
|
|
1874
|
+
positions.push({ g, ...c ? { c } : {}, o: index });
|
|
1875
|
+
items.push(compact({
|
|
1876
|
+
groupId: group.id,
|
|
1877
|
+
id: item?.id,
|
|
1878
|
+
name: s.name,
|
|
1879
|
+
productId: s.productId,
|
|
1880
|
+
period: s.subscriptionPeriod,
|
|
1881
|
+
state: s.state,
|
|
1882
|
+
groupLevel: s.groupLevel,
|
|
1883
|
+
familySharable: s.familySharable,
|
|
1884
|
+
price: territory && typeof item?.id === "string" ? await subscriptionPrice(api, item.id, territory) : void 0,
|
|
1885
|
+
introductoryOffers
|
|
1886
|
+
}));
|
|
1887
|
+
}
|
|
1888
|
+
if (items.length >= args.limit) {
|
|
1889
|
+
if (index < page.length) next = { g, ...c ? { c } : {}, o: index };
|
|
1890
|
+
else if (appleNext) next = { g, c: appleNext, o: 0 };
|
|
1891
|
+
else if (g + 1 < groups.length) next = { g: g + 1, o: 0 };
|
|
1892
|
+
break;
|
|
1893
|
+
}
|
|
1894
|
+
if (appleNext) {
|
|
1895
|
+
c = appleNext;
|
|
1896
|
+
} else {
|
|
1897
|
+
g += 1;
|
|
1898
|
+
c = void 0;
|
|
1899
|
+
}
|
|
1900
|
+
o = 0;
|
|
1901
|
+
}
|
|
1902
|
+
const notes = [
|
|
1903
|
+
moreGroups && !args.group_id ? "The app has more than 200 subscription groups; the first 200 are read." : void 0,
|
|
1904
|
+
groups.length > GROUPS_SHOWN ? `The first ${GROUPS_SHOWN} of ${groups.length} groups are named in groups.` : void 0,
|
|
1905
|
+
next ? "hasFreeTrial covers the subscriptions on this page: pass nextCursor back as cursor for the rest." : void 0
|
|
1906
|
+
].filter(Boolean);
|
|
1907
|
+
return h.page({
|
|
1908
|
+
key: "subscriptions",
|
|
1909
|
+
items,
|
|
1910
|
+
extra: compact({
|
|
1911
|
+
appId,
|
|
1912
|
+
priceTerritory: territory,
|
|
1913
|
+
hasFreeTrial: freeTrial,
|
|
1914
|
+
groups: groups.slice(0, GROUPS_SHOWN).map((group) => compact({ id: group.id, referenceName: group.referenceName })),
|
|
1915
|
+
note: notes.length ? notes.join(" ") : void 0
|
|
1916
|
+
}),
|
|
1917
|
+
resumeAt: (index) => h.makeCursor(positions[index] ?? { g: groups.length, o: 0 }),
|
|
1918
|
+
...next ? { nextPage: h.makeCursor(next) } : {}
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// src/vendors/apple-appstore/review.ts
|
|
1923
|
+
var PLATFORMS = ["IOS", "MAC_OS", "TV_OS", "VISION_OS"];
|
|
1924
|
+
var SUBMITTABLE = /* @__PURE__ */ new Set(["DRAFT", "READY_FOR_REVIEW", "REJECTED"]);
|
|
1925
|
+
var MAX_OPEN = 3;
|
|
1926
|
+
var CREATE_ERRORS = {
|
|
1927
|
+
403: "The App Store Connect key's role cannot send items to App Review (it needs Admin, App Manager or Marketing)",
|
|
1928
|
+
409: "App Store Connect refused to start a review submission: the app may already have one waiting for or in review on this platform. Send the event once that review is done, or add it in App Store Connect"
|
|
1929
|
+
};
|
|
1930
|
+
var ITEM_ERRORS = {
|
|
1931
|
+
403: "The App Store Connect key's role cannot send items to App Review (it needs Admin, App Manager or Marketing)",
|
|
1932
|
+
409: "App Store Connect refused to add the event: an event needs its texts and both images (event card and event details page) in its locales, and must not be in another submission",
|
|
1933
|
+
422: "App Store Connect refused to add the event"
|
|
1934
|
+
};
|
|
1935
|
+
var SUBMIT_ERRORS = {
|
|
1936
|
+
403: "The App Store Connect key's role cannot send items to App Review (it needs Admin, App Manager or Marketing)",
|
|
1937
|
+
409: "App Store Connect refused to send the submission: an item in it is not complete, or the submission can no longer be sent"
|
|
1938
|
+
};
|
|
1939
|
+
async function contentOf(api, submissionId, eventId) {
|
|
1940
|
+
const data = await api.get(`/v1/reviewSubmissions/${encodeURIComponent(submissionId)}/items`, {
|
|
1941
|
+
include: "appEvent,appStoreVersion",
|
|
1942
|
+
"fields[reviewSubmissionItems]": "state,appEvent,appStoreVersion",
|
|
1943
|
+
"fields[appEvents]": "referenceName",
|
|
1944
|
+
"fields[appStoreVersions]": "versionString,platform",
|
|
1945
|
+
limit: 50
|
|
1946
|
+
});
|
|
1947
|
+
const events = includedMap(data, "appEvents");
|
|
1948
|
+
const versions = includedMap(data, "appStoreVersions");
|
|
1949
|
+
let hasEvent = false;
|
|
1950
|
+
const others = [];
|
|
1951
|
+
for (const item of Array.isArray(data?.data) ? data.data : []) {
|
|
1952
|
+
if (item?.attributes?.state === "REMOVED") continue;
|
|
1953
|
+
const eventRef = item?.relationships?.appEvent?.data?.id;
|
|
1954
|
+
const versionRef = item?.relationships?.appStoreVersion?.data?.id;
|
|
1955
|
+
if (eventRef === eventId) hasEvent = true;
|
|
1956
|
+
else if (typeof eventRef === "string") others.push(`the in-app event ${truncate(String(events.get(eventRef)?.attributes?.referenceName ?? eventRef), 80)}`);
|
|
1957
|
+
else if (typeof versionRef === "string") others.push(`app version ${truncate(String(versions.get(versionRef)?.attributes?.versionString ?? versionRef), 40)}`);
|
|
1958
|
+
else others.push("an item that is not an in-app event");
|
|
1959
|
+
}
|
|
1960
|
+
return { hasEvent, others };
|
|
1961
|
+
}
|
|
1962
|
+
function after(error, sentence) {
|
|
1963
|
+
if (error instanceof ToolFailure) throw new ToolFailure(`${error.message.replace(/ Nothing was changed\./, "")} ${sentence}`, error.details);
|
|
1964
|
+
throw error;
|
|
1965
|
+
}
|
|
1966
|
+
async function submitEventForReview(api, args) {
|
|
1967
|
+
const { app_id: appId, event_id: eventId, platform } = args;
|
|
1968
|
+
const event = await appEventOf(api, appId, eventId, "referenceName,eventState");
|
|
1969
|
+
const state = event?.attributes?.eventState;
|
|
1970
|
+
if (typeof state === "string" && !SUBMITTABLE.has(state)) {
|
|
1971
|
+
throw new ToolFailure(`The in-app event ${eventId} is ${state}: only a draft, a rejected event or one ready for review can be sent to App Review. Nothing was sent.`);
|
|
1972
|
+
}
|
|
1973
|
+
const open = await api.get("/v1/reviewSubmissions", {
|
|
1974
|
+
"filter[app]": appId,
|
|
1975
|
+
"filter[platform]": platform,
|
|
1976
|
+
"filter[state]": "READY_FOR_REVIEW,UNRESOLVED_ISSUES",
|
|
1977
|
+
"fields[reviewSubmissions]": "platform,state",
|
|
1978
|
+
limit: 10
|
|
1979
|
+
});
|
|
1980
|
+
const submissions = (Array.isArray(open?.data) ? open.data : []).filter((item) => typeof item?.id === "string").slice(0, MAX_OPEN);
|
|
1981
|
+
let target;
|
|
1982
|
+
let draft;
|
|
1983
|
+
for (const submission of submissions) {
|
|
1984
|
+
const content = await contentOf(api, submission.id, eventId);
|
|
1985
|
+
if (content.hasEvent) {
|
|
1986
|
+
target = { id: submission.id, content };
|
|
1987
|
+
break;
|
|
1988
|
+
}
|
|
1989
|
+
if (!draft && submission?.attributes?.state === "READY_FOR_REVIEW") draft = { id: submission.id, content };
|
|
1990
|
+
}
|
|
1991
|
+
target ??= draft;
|
|
1992
|
+
if (target?.content.others.length) {
|
|
1993
|
+
throw new ToolFailure(
|
|
1994
|
+
`App ${appId} has an open review submission (${target.id}) that also holds ${target.content.others.slice(0, 5).join(", ")}${target.content.others.length > 5 ? ` and ${target.content.others.length - 5} more` : ""}: sending it would send those to App Review too. Send the event in App Store Connect, or take the other items out of that submission first. Nothing was sent.`
|
|
1995
|
+
);
|
|
1996
|
+
}
|
|
1997
|
+
let submissionId = target?.id;
|
|
1998
|
+
const created = !submissionId;
|
|
1999
|
+
if (!submissionId) {
|
|
2000
|
+
const { data } = await api.send({
|
|
2001
|
+
method: "POST",
|
|
2002
|
+
path: "/v1/reviewSubmissions",
|
|
2003
|
+
json: { data: { type: "reviewSubmissions", attributes: { platform }, relationships: { app: { data: { type: "apps", id: appId } } } } },
|
|
2004
|
+
write: true,
|
|
2005
|
+
errors: CREATE_ERRORS
|
|
2006
|
+
});
|
|
2007
|
+
submissionId = data?.data?.id;
|
|
2008
|
+
if (typeof submissionId !== "string" || !submissionId) {
|
|
2009
|
+
throw new ToolFailure("App Store Connect started a review submission but did not say its id. Check the app's review submissions in App Store Connect before trying again.");
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
if (!target?.content.hasEvent) {
|
|
2013
|
+
try {
|
|
2014
|
+
await api.send({
|
|
2015
|
+
method: "POST",
|
|
2016
|
+
path: "/v1/reviewSubmissionItems",
|
|
2017
|
+
json: {
|
|
2018
|
+
data: {
|
|
2019
|
+
type: "reviewSubmissionItems",
|
|
2020
|
+
relationships: {
|
|
2021
|
+
reviewSubmission: { data: { type: "reviewSubmissions", id: submissionId } },
|
|
2022
|
+
appEvent: { data: { type: "appEvents", id: eventId } }
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
},
|
|
2026
|
+
write: true,
|
|
2027
|
+
errors: ITEM_ERRORS
|
|
2028
|
+
});
|
|
2029
|
+
} catch (error) {
|
|
2030
|
+
after(error, created ? `The review submission ${submissionId} started for it stays open and empty; the next call reuses it.` : `The open review submission ${submissionId} was not changed.`);
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
let reply;
|
|
2034
|
+
try {
|
|
2035
|
+
({ data: reply } = await api.send({
|
|
2036
|
+
method: "PATCH",
|
|
2037
|
+
path: `/v1/reviewSubmissions/${encodeURIComponent(submissionId)}`,
|
|
2038
|
+
json: { data: { type: "reviewSubmissions", id: submissionId, attributes: { submitted: true } } },
|
|
2039
|
+
write: true,
|
|
2040
|
+
errors: SUBMIT_ERRORS
|
|
2041
|
+
}));
|
|
2042
|
+
} catch (error) {
|
|
2043
|
+
after(error, `The event is in review submission ${submissionId}, which was not sent: fix what App Store Connect names, then call submit_app_event_for_review again, or send it in App Store Connect.`);
|
|
2044
|
+
}
|
|
2045
|
+
const attributes = reply?.data?.attributes ?? {};
|
|
2046
|
+
return compact({
|
|
2047
|
+
appId,
|
|
2048
|
+
eventId,
|
|
2049
|
+
referenceName: event?.attributes?.referenceName,
|
|
2050
|
+
submission: compact({ id: submissionId, platform: attributes.platform ?? platform, state: attributes.state, submittedDate: attributes.submittedDate }),
|
|
2051
|
+
reusedSubmission: created ? void 0 : true,
|
|
2052
|
+
note: "App Review usually answers within a day or two; list_app_events shows the event's state."
|
|
2053
|
+
});
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
// src/vendors/apple-appstore/index.ts
|
|
2057
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
2058
|
+
var BADGES = ["LIVE_EVENT", "PREMIERE", "CHALLENGE", "COMPETITION", "NEW_SEASON", "MAJOR_UPDATE", "SPECIAL_EVENT"];
|
|
2059
|
+
var PURPOSES = ["APPROPRIATE_FOR_ALL_USERS", "ATTRACT_NEW_USERS", "KEEP_ACTIVE_USERS_INFORMED", "BRING_BACK_LAPSED_USERS"];
|
|
2060
|
+
var PURCHASE_REQUIREMENTS = ["NO_COST_ASSOCIATED", "IN_APP_PURCHASE"];
|
|
2061
|
+
var EVENT_STATES = ["DRAFT", "READY_FOR_REVIEW", "WAITING_FOR_REVIEW", "IN_REVIEW", "REJECTED", "ACCEPTED", "APPROVED", "PUBLISHED", "PAST", "ARCHIVED"];
|
|
2062
|
+
var EVENT_FIELDS = "referenceName,badge,eventState,deepLink,purchaseRequirement,primaryLocale,priority,purpose,territorySchedules,localizations";
|
|
2063
|
+
var EVENT_LOCALIZATION_FIELDS = "locale,name,shortDescription,longDescription";
|
|
2064
|
+
var APP_ID = {
|
|
2065
|
+
type: "string",
|
|
2066
|
+
pattern: "^[0-9]{1,20}$",
|
|
2067
|
+
description: "The app's Apple ID, the number in its App Store URL (apps.apple.com/app/id1234567890), from list_apps."
|
|
2068
|
+
};
|
|
2069
|
+
var RESOURCE_ID = { type: "string", pattern: "^[A-Za-z0-9_-]{1,128}$" };
|
|
2070
|
+
var CURSOR = { type: "string", description: "nextCursor from the previous result, with the same other arguments." };
|
|
2071
|
+
var PRICE_TERRITORY = { type: "string", pattern: "^[A-Z]{3}$", default: "USA", description: "The territory of the prices, an ISO alpha-3 code (default USA)." };
|
|
2072
|
+
var MAX_PRICED_PURCHASES = 20;
|
|
2073
|
+
var DATE_TIME = {
|
|
2074
|
+
type: "string",
|
|
2075
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,3})?)?(Z|[+-]\\d{2}:\\d{2})$"
|
|
2076
|
+
};
|
|
2077
|
+
var LOCALE = { type: "string", pattern: "^[a-z]{2,3}(-[A-Za-z0-9]{2,8}){0,2}$" };
|
|
2078
|
+
var DEEP_LINK = {
|
|
2079
|
+
type: "string",
|
|
2080
|
+
pattern: "^[A-Za-z][A-Za-z0-9+.-]*:\\S+$",
|
|
2081
|
+
maxLength: 1e3,
|
|
2082
|
+
description: "A universal link or custom URL that opens the event in the app, e.g. https://example.com/events/spring or myapp://events/spring."
|
|
2083
|
+
};
|
|
2084
|
+
var SCHEDULE = {
|
|
2085
|
+
type: "object",
|
|
2086
|
+
properties: {
|
|
2087
|
+
territories: {
|
|
2088
|
+
type: "array",
|
|
2089
|
+
items: { type: "string", pattern: "^[A-Z]{3}$" },
|
|
2090
|
+
minItems: 1,
|
|
2091
|
+
maxItems: 200,
|
|
2092
|
+
uniqueItems: true,
|
|
2093
|
+
description: 'ISO 3166-1 alpha-3 territory codes, e.g. ["USA", "GBR", "TUR"].'
|
|
2094
|
+
},
|
|
2095
|
+
publish_start: { ...DATE_TIME, description: "When the event appears on the App Store, at most 14 days before event_start, e.g. 2026-12-20T00:00:00Z." },
|
|
2096
|
+
event_start: { ...DATE_TIME, description: "When the event starts." },
|
|
2097
|
+
event_end: { ...DATE_TIME, description: "When the event ends: 15 minutes to 31 days after event_start." }
|
|
2098
|
+
},
|
|
2099
|
+
required: ["territories", "publish_start", "event_start", "event_end"],
|
|
2100
|
+
additionalProperties: false
|
|
2101
|
+
};
|
|
2102
|
+
function checkSchedules(schedules) {
|
|
2103
|
+
schedules.forEach((schedule, index) => {
|
|
2104
|
+
const which = `territory_schedules[${index}]`;
|
|
2105
|
+
const publish = Date.parse(schedule.publish_start);
|
|
2106
|
+
const start = Date.parse(schedule.event_start);
|
|
2107
|
+
const end = Date.parse(schedule.event_end);
|
|
2108
|
+
const fail = (problem) => {
|
|
2109
|
+
throw new ToolFailure(`${which}: ${problem}. Nothing was changed.`);
|
|
2110
|
+
};
|
|
2111
|
+
if ([publish, start, end].some(Number.isNaN)) fail("a date is not a valid date and time");
|
|
2112
|
+
if (publish > start) fail("publish_start must not be after event_start");
|
|
2113
|
+
if (start - publish > 14 * DAY_MS) fail("the App Store shows an event at most 14 days before it starts, so publish_start must be within 14 days of event_start");
|
|
2114
|
+
if (end - start < 15 * 60 * 1e3) fail("an event lasts at least 15 minutes, so event_end must be at least 15 minutes after event_start");
|
|
2115
|
+
if (end - start > 31 * DAY_MS) fail("an event lasts at most 31 days, so event_end must be within 31 days of event_start");
|
|
2116
|
+
});
|
|
2117
|
+
}
|
|
2118
|
+
function eventAttributes(args) {
|
|
2119
|
+
const attributes = {};
|
|
2120
|
+
if (args.reference_name !== void 0) attributes["referenceName"] = args.reference_name;
|
|
2121
|
+
if (args.badge !== void 0) attributes["badge"] = args.badge;
|
|
2122
|
+
if (args.purchase_requirement !== void 0) attributes["purchaseRequirement"] = args.purchase_requirement;
|
|
2123
|
+
if (args.priority !== void 0) attributes["priority"] = args.priority;
|
|
2124
|
+
if (args.purpose !== void 0) attributes["purpose"] = args.purpose;
|
|
2125
|
+
if (args.deep_link !== void 0) attributes["deepLink"] = args.deep_link;
|
|
2126
|
+
if (args.primary_locale !== void 0) attributes["primaryLocale"] = args.primary_locale;
|
|
2127
|
+
if (args.territory_schedules !== void 0) {
|
|
2128
|
+
checkSchedules(args.territory_schedules);
|
|
2129
|
+
attributes["territorySchedules"] = args.territory_schedules.map((schedule) => ({
|
|
2130
|
+
territories: schedule.territories,
|
|
2131
|
+
publishStart: schedule.publish_start,
|
|
2132
|
+
eventStart: schedule.event_start,
|
|
2133
|
+
eventEnd: schedule.event_end
|
|
2134
|
+
}));
|
|
2135
|
+
}
|
|
2136
|
+
return attributes;
|
|
2137
|
+
}
|
|
2138
|
+
var EVENT_WRITE_ERRORS = {
|
|
2139
|
+
403: "The App Store Connect key's role cannot manage in-app events (it needs Admin, App Manager or Marketing)",
|
|
2140
|
+
409: "App Store Connect refused the event: a value is invalid, the reference name is already used, or the event can no longer be changed in its state",
|
|
2141
|
+
422: "App Store Connect refused the event: a value is invalid"
|
|
2142
|
+
};
|
|
2143
|
+
var LOCALIZATION_WRITE_ERRORS = {
|
|
2144
|
+
403: "The App Store Connect key's role cannot manage in-app events (it needs Admin, App Manager or Marketing)",
|
|
2145
|
+
409: "App Store Connect refused the localization: a text is too long or not allowed, the locale already has a localization (change it with update_app_event_localization), or the event can no longer be changed",
|
|
2146
|
+
422: "App Store Connect refused the localization: a value is invalid"
|
|
2147
|
+
};
|
|
2148
|
+
var REVIEW_WRITE_ERRORS = {
|
|
2149
|
+
403: "The App Store Connect key's role cannot answer reviews (it needs Admin, App Manager or Customer Support)",
|
|
2150
|
+
404: "App Store Connect found no such review or response",
|
|
2151
|
+
409: "App Store Connect refused the response: the text is not allowed or too long"
|
|
2152
|
+
};
|
|
2153
|
+
var EVENT_EDIT_FIELDS = {
|
|
2154
|
+
badge: { type: "string", enum: BADGES, description: "The badge on the event card: LIVE_EVENT, PREMIERE, CHALLENGE, COMPETITION, NEW_SEASON, MAJOR_UPDATE or SPECIAL_EVENT (holidays)." },
|
|
2155
|
+
purchase_requirement: {
|
|
2156
|
+
type: "string",
|
|
2157
|
+
enum: PURCHASE_REQUIREMENTS,
|
|
2158
|
+
description: "NO_COST_ASSOCIATED, or IN_APP_PURCHASE when taking part needs an in-app purchase or a subscription."
|
|
2159
|
+
},
|
|
2160
|
+
priority: { type: "string", enum: ["HIGH", "NORMAL"], description: "HIGH puts the event first on the product page; NORMAL otherwise." },
|
|
2161
|
+
purpose: {
|
|
2162
|
+
type: "string",
|
|
2163
|
+
enum: PURPOSES,
|
|
2164
|
+
description: "Who the event is for: APPROPRIATE_FOR_ALL_USERS, ATTRACT_NEW_USERS, KEEP_ACTIVE_USERS_INFORMED or BRING_BACK_LAPSED_USERS."
|
|
2165
|
+
},
|
|
2166
|
+
deep_link: DEEP_LINK,
|
|
2167
|
+
primary_locale: { ...LOCALE, description: "The event's primary locale, e.g. en-US." },
|
|
2168
|
+
territory_schedules: {
|
|
2169
|
+
type: "array",
|
|
2170
|
+
items: SCHEDULE,
|
|
2171
|
+
minItems: 1,
|
|
2172
|
+
maxItems: 20,
|
|
2173
|
+
description: "When and where the event runs: territories with publish_start, event_start and event_end each."
|
|
2174
|
+
}
|
|
2175
|
+
};
|
|
2176
|
+
function requireApp(h, appId) {
|
|
2177
|
+
requireAccounts(h.ctx.accounts, "apps", appId, "app");
|
|
2178
|
+
}
|
|
2179
|
+
function requestApps(request) {
|
|
2180
|
+
const [, collection, id] = request.segments;
|
|
2181
|
+
if (collection === "apps" && id) return [id];
|
|
2182
|
+
if (request.segments.length !== 2) return [];
|
|
2183
|
+
if (request.method === "POST") {
|
|
2184
|
+
const relationships = request.json?.["data"]?.relationships;
|
|
2185
|
+
if (typeof relationships !== "object" || relationships === null || Object.keys(relationships).join() !== "app") return [];
|
|
2186
|
+
const app = relationships.app?.data?.id;
|
|
2187
|
+
return typeof app === "string" || typeof app === "number" ? [String(app)] : [];
|
|
2188
|
+
}
|
|
2189
|
+
if (request.method === "GET") return (request.query["filter[app]"] ?? []).flatMap((value) => value.split(",")).filter(Boolean);
|
|
2190
|
+
return [];
|
|
2191
|
+
}
|
|
2192
|
+
var connector = defineConnector({
|
|
2193
|
+
vendor: "apple-appstore",
|
|
2194
|
+
label: "App Store Connect",
|
|
2195
|
+
origins: [ORIGIN, LOOKUP_ORIGIN],
|
|
2196
|
+
// Event image parts go to the pre-signed addresses App Store Connect returns, on these hosts.
|
|
2197
|
+
uploadHosts: UPLOAD_HOSTS,
|
|
2198
|
+
credentials: ["keyid", "issuerid", "privatekey"],
|
|
2199
|
+
credentialLabels: {
|
|
2200
|
+
keyid: "App Store Connect key ID",
|
|
2201
|
+
issuerid: "App Store Connect issuer ID",
|
|
2202
|
+
privatekey: "App Store Connect private key"
|
|
2203
|
+
},
|
|
2204
|
+
normalizeCredentials: (credentials) => ({
|
|
2205
|
+
...credentials,
|
|
2206
|
+
...credentials["privatekey"] ? { privatekey: privateKeyPem(credentials["privatekey"]) } : {}
|
|
2207
|
+
}),
|
|
2208
|
+
accountPickers: [
|
|
2209
|
+
{
|
|
2210
|
+
key: "apps",
|
|
2211
|
+
label: "App Store apps",
|
|
2212
|
+
description: "The apps the agent may read and manage in App Store Connect.",
|
|
2213
|
+
multiple: true,
|
|
2214
|
+
tool: "list_apps",
|
|
2215
|
+
idField: "id",
|
|
2216
|
+
nameField: "name",
|
|
2217
|
+
legacyField: "apps"
|
|
2218
|
+
}
|
|
2219
|
+
],
|
|
2220
|
+
tools: [
|
|
2221
|
+
{
|
|
2222
|
+
name: "list_apps",
|
|
2223
|
+
kind: "read",
|
|
2224
|
+
title: "List App Store Connect apps",
|
|
2225
|
+
description: "Lists the apps the App Store Connect key can see, by name: the Apple ID (id), name, bundle ID, SKU and primary locale of each. When the connection is limited to chosen apps, those are marked selected: true, and only they can be used. Pass nextCursor back as cursor for more.",
|
|
2226
|
+
inputSchema: {
|
|
2227
|
+
type: "object",
|
|
2228
|
+
properties: {
|
|
2229
|
+
limit: { type: "integer", minimum: 1, maximum: 200, default: 100, description: "Apps per page, 1 to 200 (default 100)." },
|
|
2230
|
+
cursor: CURSOR
|
|
2231
|
+
},
|
|
2232
|
+
additionalProperties: false
|
|
2233
|
+
},
|
|
2234
|
+
async run(args, h) {
|
|
2235
|
+
const chosen = allowedAccounts(h.ctx.accounts, "apps");
|
|
2236
|
+
return applePage(h, asc(h), {
|
|
2237
|
+
key: "apps",
|
|
2238
|
+
path: "/v1/apps",
|
|
2239
|
+
query: { "fields[apps]": "name,bundleId,sku,primaryLocale", sort: "name", limit: args.limit },
|
|
2240
|
+
...args.cursor ? { cursor: args.cursor } : {},
|
|
2241
|
+
map: (item) => compact({ ...trimApp(item), selected: chosen?.includes(String(item?.id)) ? true : void 0 }),
|
|
2242
|
+
...chosen?.length === 0 ? { extra: () => ({ note: "No app is chosen for this connection yet, so every tool that names an app is refused until apps from this list are chosen for it." }) } : {}
|
|
2243
|
+
});
|
|
2244
|
+
}
|
|
2245
|
+
},
|
|
2246
|
+
{
|
|
2247
|
+
name: "get_app_metadata",
|
|
2248
|
+
kind: "read",
|
|
2249
|
+
title: "Get App Store app details",
|
|
2250
|
+
description: "What an app is: its App Store Connect record (name, bundle ID, primary locale), app info (subtitle, categories, age rating, privacy URL) for one locale, its latest versions, the description, keywords, promotional text and what's new of the live version (or the newest), and, from the public App Store listing of one country, its price, genre, rating, rating count and live description. Up to five requests.",
|
|
2251
|
+
inputSchema: {
|
|
2252
|
+
type: "object",
|
|
2253
|
+
properties: {
|
|
2254
|
+
app_id: APP_ID,
|
|
2255
|
+
locale: { ...LOCALE, description: "The locale of the texts, e.g. en-US or tr. Default: the app's primary locale." },
|
|
2256
|
+
country: { type: "string", pattern: "^[a-z]{2}$", default: "us", description: "The App Store country of the public listing, two lower-case letters (default us)." },
|
|
2257
|
+
include_store_listing: { type: "boolean", default: true, description: "false skips the public App Store listing." }
|
|
2258
|
+
},
|
|
2259
|
+
required: ["app_id"],
|
|
2260
|
+
additionalProperties: false
|
|
2261
|
+
},
|
|
2262
|
+
async run(args, h) {
|
|
2263
|
+
requireApp(h, args.app_id);
|
|
2264
|
+
return appMetadata(h, asc(h), args);
|
|
2265
|
+
}
|
|
2266
|
+
},
|
|
2267
|
+
{
|
|
2268
|
+
name: "list_subscriptions",
|
|
2269
|
+
kind: "read",
|
|
2270
|
+
title: "List App Store subscriptions",
|
|
2271
|
+
description: "An app's auto-renewable subscriptions, group by group: group, name, product ID, period, state and level of each, its current price in one territory (customer price, proceeds, currency, any price change already scheduled, and a monthly plan's price where there is one), its introductory offers (free trial, pay as you go or pay up front, with the duration and the number of territories), and whether a subscription on the page has a free trial. groups names the app's subscription groups. One request per subscription for its price. Pass nextCursor back as cursor for more.",
|
|
2272
|
+
inputSchema: {
|
|
2273
|
+
type: "object",
|
|
2274
|
+
properties: {
|
|
2275
|
+
app_id: APP_ID,
|
|
2276
|
+
group_id: { ...RESOURCE_ID, description: "Only this subscription group, from groups in an earlier result." },
|
|
2277
|
+
price_territory: PRICE_TERRITORY,
|
|
2278
|
+
include_prices: { type: "boolean", default: true, description: "false skips the prices (one request less per subscription)." },
|
|
2279
|
+
limit: { type: "integer", minimum: 1, maximum: 50, default: 20, description: "Subscriptions per page, 1 to 50 (default 20)." },
|
|
2280
|
+
cursor: CURSOR
|
|
2281
|
+
},
|
|
2282
|
+
required: ["app_id"],
|
|
2283
|
+
additionalProperties: false
|
|
2284
|
+
},
|
|
2285
|
+
async run(args, h) {
|
|
2286
|
+
requireApp(h, args.app_id);
|
|
2287
|
+
return subscriptions(h, asc(h), args);
|
|
2288
|
+
}
|
|
2289
|
+
},
|
|
2290
|
+
{
|
|
2291
|
+
name: "list_in_app_purchases",
|
|
2292
|
+
kind: "read",
|
|
2293
|
+
title: "List App Store in-app purchases",
|
|
2294
|
+
description: `An app's in-app purchases (consumable, non-consumable and non-renewing subscriptions): name, product ID, type, state and family sharing, and the current price of each in one territory (customer price, proceeds, currency, any price change already scheduled; automatic true when App Store Connect derived it from the base territory). With prices, at most ${MAX_PRICED_PURCHASES} a page, one or two requests each. Auto-renewable subscriptions are in list_subscriptions. Pass nextCursor back as cursor for more.`,
|
|
2295
|
+
inputSchema: {
|
|
2296
|
+
type: "object",
|
|
2297
|
+
properties: {
|
|
2298
|
+
app_id: APP_ID,
|
|
2299
|
+
type: { type: "string", enum: ["CONSUMABLE", "NON_CONSUMABLE", "NON_RENEWING_SUBSCRIPTION"], description: "Only this type." },
|
|
2300
|
+
price_territory: PRICE_TERRITORY,
|
|
2301
|
+
include_prices: { type: "boolean", default: true, description: "false skips the prices: then up to 200 a page." },
|
|
2302
|
+
limit: { type: "integer", minimum: 1, maximum: 200, default: 100, description: `Items per page, 1 to 200 (default 100; at most ${MAX_PRICED_PURCHASES} with prices).` },
|
|
2303
|
+
cursor: CURSOR
|
|
2304
|
+
},
|
|
2305
|
+
required: ["app_id"],
|
|
2306
|
+
additionalProperties: false
|
|
2307
|
+
},
|
|
2308
|
+
async run(args, h) {
|
|
2309
|
+
requireApp(h, args.app_id);
|
|
2310
|
+
const api = asc(h);
|
|
2311
|
+
return applePage(h, api, {
|
|
2312
|
+
key: "inAppPurchases",
|
|
2313
|
+
path: `/v1/apps/${args.app_id}/inAppPurchasesV2`,
|
|
2314
|
+
query: {
|
|
2315
|
+
"fields[inAppPurchases]": "name,productId,inAppPurchaseType,state,familySharable",
|
|
2316
|
+
"filter[inAppPurchaseType]": args.type,
|
|
2317
|
+
limit: args.include_prices ? Math.min(args.limit, MAX_PRICED_PURCHASES) : args.limit
|
|
2318
|
+
},
|
|
2319
|
+
...args.cursor ? { cursor: args.cursor } : {},
|
|
2320
|
+
map: (item) => compact({
|
|
2321
|
+
id: item?.id,
|
|
2322
|
+
name: item?.attributes?.name,
|
|
2323
|
+
productId: item?.attributes?.productId,
|
|
2324
|
+
type: item?.attributes?.inAppPurchaseType,
|
|
2325
|
+
state: item?.attributes?.state,
|
|
2326
|
+
familySharable: item?.attributes?.familySharable
|
|
2327
|
+
}),
|
|
2328
|
+
...args.include_prices ? {
|
|
2329
|
+
async enrich(items) {
|
|
2330
|
+
for (const item of items) {
|
|
2331
|
+
const price = typeof item["id"] === "string" ? await purchasePrice(api, item["id"], args.price_territory) : void 0;
|
|
2332
|
+
if (price) item["price"] = price;
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
} : {},
|
|
2336
|
+
extra: () => compact({ appId: args.app_id, priceTerritory: args.include_prices ? args.price_territory : void 0 })
|
|
2337
|
+
});
|
|
2338
|
+
}
|
|
2339
|
+
},
|
|
2340
|
+
{
|
|
2341
|
+
name: "list_reviews",
|
|
2342
|
+
kind: "read",
|
|
2343
|
+
title: "List App Store customer reviews",
|
|
2344
|
+
description: "An app's customer reviews, newest first by default: rating, title, text, reviewer nickname, territory and date, and the developer response if there is one (its text and whether it is published yet). Filter by rating, territory, or whether a response is published. Pass nextCursor back as cursor for more.",
|
|
2345
|
+
inputSchema: {
|
|
2346
|
+
type: "object",
|
|
2347
|
+
properties: {
|
|
2348
|
+
app_id: APP_ID,
|
|
2349
|
+
sort: { type: "string", enum: ["-createdDate", "createdDate", "-rating", "rating"], default: "-createdDate", description: "Order: -createdDate (newest first, default), createdDate, -rating or rating." },
|
|
2350
|
+
ratings: {
|
|
2351
|
+
type: "array",
|
|
2352
|
+
items: { type: "integer", minimum: 1, maximum: 5 },
|
|
2353
|
+
minItems: 1,
|
|
2354
|
+
maxItems: 5,
|
|
2355
|
+
uniqueItems: true,
|
|
2356
|
+
description: "Only these star ratings, e.g. [1, 2]."
|
|
2357
|
+
},
|
|
2358
|
+
territory: { type: "string", pattern: "^[A-Z]{3}$", description: "Only reviews from this territory, an ISO alpha-3 code such as USA." },
|
|
2359
|
+
has_published_response: {
|
|
2360
|
+
type: "boolean",
|
|
2361
|
+
description: "false: only reviews without a published response (to answer); true: only answered ones. Leave out for all."
|
|
2362
|
+
},
|
|
2363
|
+
limit: { type: "integer", minimum: 1, maximum: 200, default: 20, description: "Reviews per page, 1 to 200 (default 20)." },
|
|
2364
|
+
cursor: CURSOR
|
|
2365
|
+
},
|
|
2366
|
+
required: ["app_id"],
|
|
2367
|
+
additionalProperties: false
|
|
2368
|
+
},
|
|
2369
|
+
async run(args, h) {
|
|
2370
|
+
requireApp(h, args.app_id);
|
|
2371
|
+
return applePage(h, asc(h), {
|
|
2372
|
+
key: "reviews",
|
|
2373
|
+
path: `/v1/apps/${args.app_id}/customerReviews`,
|
|
2374
|
+
query: {
|
|
2375
|
+
sort: args.sort,
|
|
2376
|
+
limit: args.limit,
|
|
2377
|
+
include: "response",
|
|
2378
|
+
"fields[customerReviews]": "rating,title,body,reviewerNickname,createdDate,territory,response",
|
|
2379
|
+
"fields[customerReviewResponses]": "responseBody,lastModifiedDate,state",
|
|
2380
|
+
"filter[rating]": args.ratings?.join(","),
|
|
2381
|
+
"filter[territory]": args.territory,
|
|
2382
|
+
"exists[publishedResponse]": args.has_published_response
|
|
2383
|
+
},
|
|
2384
|
+
...args.cursor ? { cursor: args.cursor } : {},
|
|
2385
|
+
map: (item, data) => trimReview(item, includedMap(data, "customerReviewResponses")),
|
|
2386
|
+
extra: () => ({ appId: args.app_id })
|
|
2387
|
+
});
|
|
2388
|
+
}
|
|
2389
|
+
},
|
|
2390
|
+
{
|
|
2391
|
+
name: "respond_to_review",
|
|
2392
|
+
kind: "update",
|
|
2393
|
+
check: "list_reviews",
|
|
2394
|
+
title: "Respond to an App Store review",
|
|
2395
|
+
description: "Publishes the developer response to a customer review, replacing the earlier response if there is one. It shows on the App Store after Apple publishes it (state PENDING_PUBLISH until then). Up to 5,970 characters; a few personal sentences are best. Never sent twice.",
|
|
2396
|
+
inputSchema: {
|
|
2397
|
+
type: "object",
|
|
2398
|
+
properties: {
|
|
2399
|
+
app_id: APP_ID,
|
|
2400
|
+
review_id: { ...RESOURCE_ID, description: "The review id, from list_reviews." },
|
|
2401
|
+
response_body: { type: "string", minLength: 1, maxLength: 5970, description: "The response text." }
|
|
2402
|
+
},
|
|
2403
|
+
required: ["app_id", "review_id", "response_body"],
|
|
2404
|
+
additionalProperties: false
|
|
2405
|
+
},
|
|
2406
|
+
async run(args, h) {
|
|
2407
|
+
requireApp(h, args.app_id);
|
|
2408
|
+
const api = asc(h);
|
|
2409
|
+
if (locked(h)) await assertReviewInApp(api, args.app_id, args.review_id);
|
|
2410
|
+
const { data } = await api.send({
|
|
2411
|
+
method: "POST",
|
|
2412
|
+
path: "/v1/customerReviewResponses",
|
|
2413
|
+
json: {
|
|
2414
|
+
data: {
|
|
2415
|
+
type: "customerReviewResponses",
|
|
2416
|
+
attributes: { responseBody: args.response_body },
|
|
2417
|
+
relationships: { review: { data: { type: "customerReviews", id: args.review_id } } }
|
|
2418
|
+
}
|
|
2419
|
+
},
|
|
2420
|
+
write: true,
|
|
2421
|
+
errors: REVIEW_WRITE_ERRORS
|
|
2422
|
+
});
|
|
2423
|
+
return compact({ reviewId: args.review_id, ...trimResponse(data?.data) });
|
|
2424
|
+
}
|
|
2425
|
+
},
|
|
2426
|
+
{
|
|
2427
|
+
name: "delete_review_response",
|
|
2428
|
+
kind: "delete",
|
|
2429
|
+
check: "list_reviews",
|
|
2430
|
+
title: "Delete an App Store review response",
|
|
2431
|
+
description: "Deletes the developer response to a customer review; it leaves the App Store after a while. The response id is in list_reviews (response.id).",
|
|
2432
|
+
inputSchema: {
|
|
2433
|
+
type: "object",
|
|
2434
|
+
properties: {
|
|
2435
|
+
app_id: APP_ID,
|
|
2436
|
+
response_id: { ...RESOURCE_ID, description: "The response id, from list_reviews (response.id)." }
|
|
2437
|
+
},
|
|
2438
|
+
required: ["app_id", "response_id"],
|
|
2439
|
+
additionalProperties: false
|
|
2440
|
+
},
|
|
2441
|
+
async run(args, h) {
|
|
2442
|
+
requireApp(h, args.app_id);
|
|
2443
|
+
const api = asc(h);
|
|
2444
|
+
if (locked(h)) {
|
|
2445
|
+
const reply = await api.get(
|
|
2446
|
+
`/v1/customerReviewResponses/${encodeURIComponent(args.response_id)}`,
|
|
2447
|
+
{ include: "review", "fields[customerReviewResponses]": "review" },
|
|
2448
|
+
{ 404: "App Store Connect has no review response with that id" }
|
|
2449
|
+
);
|
|
2450
|
+
const reviewId = reply?.data?.relationships?.review?.data?.id;
|
|
2451
|
+
if (typeof reviewId !== "string") throw new ToolFailure("App Store Connect did not say which review the response belongs to. Nothing was sent.");
|
|
2452
|
+
await assertReviewInApp(api, args.app_id, reviewId);
|
|
2453
|
+
}
|
|
2454
|
+
await api.send({ method: "DELETE", path: `/v1/customerReviewResponses/${encodeURIComponent(args.response_id)}`, write: true, errors: REVIEW_WRITE_ERRORS });
|
|
2455
|
+
return { deleted: true, id: args.response_id };
|
|
2456
|
+
}
|
|
2457
|
+
},
|
|
2458
|
+
{
|
|
2459
|
+
name: "list_app_events",
|
|
2460
|
+
kind: "read",
|
|
2461
|
+
title: "List App Store in-app events",
|
|
2462
|
+
description: "An app's in-app events with their state, badge, priority, purpose, purchase requirement, deep link, territory schedules and localizations (name, short and long description per locale), plus how many are in each state. Apple allows 10 published, 15 approved and 50 draft events at a time. Pass nextCursor back as cursor for more.",
|
|
2463
|
+
inputSchema: {
|
|
2464
|
+
type: "object",
|
|
2465
|
+
properties: {
|
|
2466
|
+
app_id: APP_ID,
|
|
2467
|
+
states: { type: "array", items: { type: "string", enum: EVENT_STATES }, minItems: 1, uniqueItems: true, description: 'Only events in these states, e.g. ["DRAFT", "PUBLISHED"].' },
|
|
2468
|
+
limit: { type: "integer", minimum: 1, maximum: 200, default: 50, description: "Events per page, 1 to 200 (default 50)." },
|
|
2469
|
+
cursor: CURSOR
|
|
2470
|
+
},
|
|
2471
|
+
required: ["app_id"],
|
|
2472
|
+
additionalProperties: false
|
|
2473
|
+
},
|
|
2474
|
+
async run(args, h) {
|
|
2475
|
+
requireApp(h, args.app_id);
|
|
2476
|
+
return applePage(h, asc(h), {
|
|
2477
|
+
key: "events",
|
|
2478
|
+
path: `/v1/apps/${args.app_id}/appEvents`,
|
|
2479
|
+
query: {
|
|
2480
|
+
"fields[appEvents]": EVENT_FIELDS,
|
|
2481
|
+
include: "localizations",
|
|
2482
|
+
"fields[appEventLocalizations]": EVENT_LOCALIZATION_FIELDS,
|
|
2483
|
+
"limit[localizations]": 50,
|
|
2484
|
+
"filter[eventState]": args.states?.join(","),
|
|
2485
|
+
limit: args.limit
|
|
2486
|
+
},
|
|
2487
|
+
...args.cursor ? { cursor: args.cursor } : {},
|
|
2488
|
+
map: (item, data) => trimEvent(item, includedMap(data, "appEventLocalizations")),
|
|
2489
|
+
extra: (data) => {
|
|
2490
|
+
const counts = {};
|
|
2491
|
+
for (const item of Array.isArray(data?.data) ? data.data : []) {
|
|
2492
|
+
const state = String(item?.attributes?.eventState ?? "UNKNOWN");
|
|
2493
|
+
counts[state] = (counts[state] ?? 0) + 1;
|
|
2494
|
+
}
|
|
2495
|
+
return { appId: args.app_id, countsOnThisPage: counts };
|
|
2496
|
+
}
|
|
2497
|
+
});
|
|
2498
|
+
}
|
|
2499
|
+
},
|
|
2500
|
+
{
|
|
2501
|
+
name: "create_app_event",
|
|
2502
|
+
kind: "create",
|
|
2503
|
+
check: "list_app_events",
|
|
2504
|
+
title: "Create an App Store in-app event",
|
|
2505
|
+
description: "Creates an in-app event as a draft (nothing is shown until it passes App Review). Add its texts with create_app_event_localization. Rules checked first: publish_start at most 14 days before event_start, events last 15 minutes to 31 days. Apple refuses a reference name the app already uses. Never sent twice: check list_app_events after an unclear outcome.",
|
|
2506
|
+
inputSchema: {
|
|
2507
|
+
type: "object",
|
|
2508
|
+
properties: {
|
|
2509
|
+
app_id: APP_ID,
|
|
2510
|
+
reference_name: { type: "string", minLength: 1, maxLength: 64, description: "An internal name, unique for the app, shown only in App Store Connect, e.g. lunar-new-year-2027." },
|
|
2511
|
+
...EVENT_EDIT_FIELDS
|
|
2512
|
+
},
|
|
2513
|
+
required: ["app_id", "reference_name", "badge", "purchase_requirement", "priority", "purpose", "territory_schedules"],
|
|
2514
|
+
additionalProperties: false
|
|
2515
|
+
},
|
|
2516
|
+
async run(args, h) {
|
|
2517
|
+
requireApp(h, args.app_id);
|
|
2518
|
+
const attributes = eventAttributes(args);
|
|
2519
|
+
const { data } = await asc(h).send({
|
|
2520
|
+
method: "POST",
|
|
2521
|
+
path: "/v1/appEvents",
|
|
2522
|
+
json: { data: { type: "appEvents", attributes, relationships: { app: { data: { type: "apps", id: args.app_id } } } } },
|
|
2523
|
+
write: true,
|
|
2524
|
+
errors: EVENT_WRITE_ERRORS
|
|
2525
|
+
});
|
|
2526
|
+
return { appId: args.app_id, event: trimEvent(data?.data) };
|
|
2527
|
+
}
|
|
2528
|
+
},
|
|
2529
|
+
{
|
|
2530
|
+
name: "update_app_event",
|
|
2531
|
+
kind: "update",
|
|
2532
|
+
check: "list_app_events",
|
|
2533
|
+
title: "Change an App Store in-app event",
|
|
2534
|
+
description: "Changes an in-app event's reference name, badge, purchase requirement, priority, purpose, deep link, primary locale or territory schedules: only the fields given change, and territory_schedules replaces all schedules. Apple allows changes only in some states (a draft always).",
|
|
2535
|
+
inputSchema: {
|
|
2536
|
+
type: "object",
|
|
2537
|
+
properties: {
|
|
2538
|
+
app_id: APP_ID,
|
|
2539
|
+
event_id: { ...RESOURCE_ID, description: "The event id, from list_app_events." },
|
|
2540
|
+
reference_name: { type: "string", minLength: 1, maxLength: 64, description: "A new internal name." },
|
|
2541
|
+
...EVENT_EDIT_FIELDS
|
|
2542
|
+
},
|
|
2543
|
+
required: ["app_id", "event_id"],
|
|
2544
|
+
additionalProperties: false
|
|
2545
|
+
},
|
|
2546
|
+
async run(args, h) {
|
|
2547
|
+
requireApp(h, args.app_id);
|
|
2548
|
+
const attributes = eventAttributes(args);
|
|
2549
|
+
if (!Object.keys(attributes).length) throw new ToolFailure("Nothing to change: give at least one field besides app_id and event_id. Nothing was changed.");
|
|
2550
|
+
const api = asc(h);
|
|
2551
|
+
if (locked(h)) await assertEventInApp(api, args.app_id, args.event_id);
|
|
2552
|
+
const { data } = await api.send({
|
|
2553
|
+
method: "PATCH",
|
|
2554
|
+
path: `/v1/appEvents/${encodeURIComponent(args.event_id)}`,
|
|
2555
|
+
json: { data: { type: "appEvents", id: args.event_id, attributes } },
|
|
2556
|
+
write: true,
|
|
2557
|
+
errors: { ...EVENT_WRITE_ERRORS, 404: "App Store Connect has no in-app event with that id" }
|
|
2558
|
+
});
|
|
2559
|
+
return { appId: args.app_id, event: trimEvent(data?.data) };
|
|
2560
|
+
}
|
|
2561
|
+
},
|
|
2562
|
+
{
|
|
2563
|
+
name: "delete_app_event",
|
|
2564
|
+
kind: "delete",
|
|
2565
|
+
check: "list_app_events",
|
|
2566
|
+
title: "Delete an App Store in-app event",
|
|
2567
|
+
description: "Deletes an in-app event with its localizations and images. Apple refuses this for an event in review or on the App Store; archive those in App Store Connect.",
|
|
2568
|
+
inputSchema: {
|
|
2569
|
+
type: "object",
|
|
2570
|
+
properties: {
|
|
2571
|
+
app_id: APP_ID,
|
|
2572
|
+
event_id: { ...RESOURCE_ID, description: "The event id, from list_app_events." }
|
|
2573
|
+
},
|
|
2574
|
+
required: ["app_id", "event_id"],
|
|
2575
|
+
additionalProperties: false
|
|
2576
|
+
},
|
|
2577
|
+
async run(args, h) {
|
|
2578
|
+
requireApp(h, args.app_id);
|
|
2579
|
+
const api = asc(h);
|
|
2580
|
+
if (locked(h)) await assertEventInApp(api, args.app_id, args.event_id);
|
|
2581
|
+
await api.send({
|
|
2582
|
+
method: "DELETE",
|
|
2583
|
+
path: `/v1/appEvents/${encodeURIComponent(args.event_id)}`,
|
|
2584
|
+
write: true,
|
|
2585
|
+
errors: { ...EVENT_WRITE_ERRORS, 404: "App Store Connect has no in-app event with that id" }
|
|
2586
|
+
});
|
|
2587
|
+
return { deleted: true, appId: args.app_id, eventId: args.event_id };
|
|
2588
|
+
}
|
|
2589
|
+
},
|
|
2590
|
+
{
|
|
2591
|
+
name: "create_app_event_localization",
|
|
2592
|
+
kind: "create",
|
|
2593
|
+
check: "list_app_events",
|
|
2594
|
+
title: "Add texts to an App Store in-app event",
|
|
2595
|
+
description: "Adds an in-app event's texts in one locale: the name (30 characters, title case), short description (50, sentence case, on the event card) and long description (120, on the detail page). No prices, no ALL CAPS, no unverifiable claims. A locale that already has texts (Apple adds the primary locale itself) is changed with update_app_event_localization instead.",
|
|
2596
|
+
inputSchema: {
|
|
2597
|
+
type: "object",
|
|
2598
|
+
properties: {
|
|
2599
|
+
app_id: APP_ID,
|
|
2600
|
+
event_id: { ...RESOURCE_ID, description: "The event id, from list_app_events or create_app_event." },
|
|
2601
|
+
locale: { ...LOCALE, description: "The locale, e.g. en-US, zh-Hans, tr." },
|
|
2602
|
+
name: { type: "string", minLength: 1, maxLength: 30, description: "The event name, up to 30 characters." },
|
|
2603
|
+
short_description: { type: "string", minLength: 1, maxLength: 50, description: "Up to 50 characters, shown on the event card." },
|
|
2604
|
+
long_description: { type: "string", minLength: 1, maxLength: 120, description: "Up to 120 characters, shown on the event page." }
|
|
2605
|
+
},
|
|
2606
|
+
required: ["app_id", "event_id", "locale", "name", "short_description", "long_description"],
|
|
2607
|
+
additionalProperties: false
|
|
2608
|
+
},
|
|
2609
|
+
async run(args, h) {
|
|
2610
|
+
requireApp(h, args.app_id);
|
|
2611
|
+
const api = asc(h);
|
|
2612
|
+
if (locked(h)) await assertEventInApp(api, args.app_id, args.event_id);
|
|
2613
|
+
const { data } = await api.send({
|
|
2614
|
+
method: "POST",
|
|
2615
|
+
path: "/v1/appEventLocalizations",
|
|
2616
|
+
json: {
|
|
2617
|
+
data: {
|
|
2618
|
+
type: "appEventLocalizations",
|
|
2619
|
+
attributes: { locale: args.locale, name: args.name, shortDescription: args.short_description, longDescription: args.long_description },
|
|
2620
|
+
relationships: { appEvent: { data: { type: "appEvents", id: args.event_id } } }
|
|
2621
|
+
}
|
|
2622
|
+
},
|
|
2623
|
+
write: true,
|
|
2624
|
+
errors: LOCALIZATION_WRITE_ERRORS
|
|
2625
|
+
});
|
|
2626
|
+
return { appId: args.app_id, eventId: args.event_id, localization: trimEventLocalization(data?.data) };
|
|
2627
|
+
}
|
|
2628
|
+
},
|
|
2629
|
+
{
|
|
2630
|
+
name: "update_app_event_localization",
|
|
2631
|
+
kind: "update",
|
|
2632
|
+
check: "list_app_events",
|
|
2633
|
+
title: "Change the texts of an App Store in-app event",
|
|
2634
|
+
description: "Changes an in-app event's name (30 characters), short description (50) or long description (120) in one locale: only the texts given change. The localization id is in list_app_events.",
|
|
2635
|
+
inputSchema: {
|
|
2636
|
+
type: "object",
|
|
2637
|
+
properties: {
|
|
2638
|
+
app_id: APP_ID,
|
|
2639
|
+
localization_id: { ...RESOURCE_ID, description: "The localization id, from list_app_events (localizations[].id)." },
|
|
2640
|
+
name: { type: "string", minLength: 1, maxLength: 30, description: "The event name, up to 30 characters." },
|
|
2641
|
+
short_description: { type: "string", minLength: 1, maxLength: 50, description: "Up to 50 characters." },
|
|
2642
|
+
long_description: { type: "string", minLength: 1, maxLength: 120, description: "Up to 120 characters." }
|
|
2643
|
+
},
|
|
2644
|
+
required: ["app_id", "localization_id"],
|
|
2645
|
+
additionalProperties: false
|
|
2646
|
+
},
|
|
2647
|
+
async run(args, h) {
|
|
2648
|
+
requireApp(h, args.app_id);
|
|
2649
|
+
const attributes = compact({ name: args.name, shortDescription: args.short_description, longDescription: args.long_description });
|
|
2650
|
+
if (!Object.keys(attributes).length) throw new ToolFailure("Nothing to change: give name, short_description or long_description. Nothing was changed.");
|
|
2651
|
+
const api = asc(h);
|
|
2652
|
+
if (locked(h)) await assertEventInApp(api, args.app_id, await eventOfLocalization(api, args.localization_id));
|
|
2653
|
+
const { data } = await api.send({
|
|
2654
|
+
method: "PATCH",
|
|
2655
|
+
path: `/v1/appEventLocalizations/${encodeURIComponent(args.localization_id)}`,
|
|
2656
|
+
json: { data: { type: "appEventLocalizations", id: args.localization_id, attributes } },
|
|
2657
|
+
write: true,
|
|
2658
|
+
errors: { ...LOCALIZATION_WRITE_ERRORS, 404: "App Store Connect has no in-app event localization with that id" }
|
|
2659
|
+
});
|
|
2660
|
+
return { appId: args.app_id, localization: trimEventLocalization(data?.data) };
|
|
2661
|
+
}
|
|
2662
|
+
},
|
|
2663
|
+
{
|
|
2664
|
+
name: "list_app_event_images",
|
|
2665
|
+
kind: "read",
|
|
2666
|
+
title: "List the images of an App Store in-app event",
|
|
2667
|
+
description: "What one in-app event localization shows: its images (event card and event details page) with their processing state (COMPLETE when ready, FAILED with Apple's reasons), size and image URL template, its videos, and any asset library placements. The localization id is in list_app_events (localizations[].id).",
|
|
2668
|
+
inputSchema: {
|
|
2669
|
+
type: "object",
|
|
2670
|
+
properties: {
|
|
2671
|
+
app_id: APP_ID,
|
|
2672
|
+
localization_id: { ...RESOURCE_ID, description: "The localization id, from list_app_events (localizations[].id)." }
|
|
2673
|
+
},
|
|
2674
|
+
required: ["app_id", "localization_id"],
|
|
2675
|
+
additionalProperties: false
|
|
2676
|
+
},
|
|
2677
|
+
async run(args, h) {
|
|
2678
|
+
requireApp(h, args.app_id);
|
|
2679
|
+
const api = asc(h);
|
|
2680
|
+
const localization = await eventLocalizationMedia(api, args.localization_id);
|
|
2681
|
+
if (locked(h)) await assertEventInApp(api, args.app_id, localization.eventId);
|
|
2682
|
+
return compact({
|
|
2683
|
+
appId: args.app_id,
|
|
2684
|
+
eventId: localization.eventId,
|
|
2685
|
+
localizationId: localization.id,
|
|
2686
|
+
locale: localization.locale,
|
|
2687
|
+
images: localization.images.map(trimEventImage),
|
|
2688
|
+
videos: localization.videos.length ? localization.videos.map(trimEventVideo) : void 0,
|
|
2689
|
+
placements: localization.placements.length ? localization.placements.map(trimPlacement) : void 0
|
|
2690
|
+
});
|
|
2691
|
+
}
|
|
2692
|
+
},
|
|
2693
|
+
{
|
|
2694
|
+
name: "upload_app_event_image",
|
|
2695
|
+
kind: "create",
|
|
2696
|
+
check: "list_app_event_images",
|
|
2697
|
+
title: "Add an image to an App Store in-app event",
|
|
2698
|
+
description: "Adds an in-app event's image in one locale from a public https URL: the event card (EVENT_CARD, landscape 16:9, 1920x1080 to 3840x2160) or the event details page (EVENT_DETAILS_PAGE, portrait 9:16, 1080x1920 to 2160x3840), JPEG or PNG, checked first. No text, logos, borders or gradients in it. It reserves the image, uploads it to Apple's upload server, commits it and waits up to 45 seconds for processing; a kind the localization already has: delete_app_event_image first. An upload that fails removes the reservation again, so nothing is left behind. submit_app_event_for_review sends the event once it has both images.",
|
|
2699
|
+
inputSchema: {
|
|
2700
|
+
type: "object",
|
|
2701
|
+
properties: {
|
|
2702
|
+
app_id: APP_ID,
|
|
2703
|
+
localization_id: { ...RESOURCE_ID, description: "The localization id, from list_app_events (localizations[].id)." },
|
|
2704
|
+
asset_type: { type: "string", enum: [...EVENT_ASSET_TYPES], description: "EVENT_CARD (the card in Today, Search and the product page) or EVENT_DETAILS_PAGE." },
|
|
2705
|
+
image_url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A public https URL of the JPEG or PNG image." }
|
|
2706
|
+
},
|
|
2707
|
+
required: ["app_id", "localization_id", "asset_type", "image_url"],
|
|
2708
|
+
additionalProperties: false
|
|
2709
|
+
},
|
|
2710
|
+
async run(args, h) {
|
|
2711
|
+
requireApp(h, args.app_id);
|
|
2712
|
+
const api = asc(h);
|
|
2713
|
+
const localization = await eventLocalizationMedia(api, args.localization_id);
|
|
2714
|
+
if (locked(h)) await assertEventInApp(api, args.app_id, localization.eventId);
|
|
2715
|
+
const existing = localization.images.find((image) => image?.attributes?.appEventAssetType === args.asset_type);
|
|
2716
|
+
if (existing) {
|
|
2717
|
+
throw new ToolFailure(
|
|
2718
|
+
`The localization already has an ${args.asset_type} image (${existing.id}, state ${existing.attributes?.assetDeliveryState?.state ?? "unknown"}). Delete it with delete_app_event_image first to replace it. Nothing was changed.`
|
|
2719
|
+
);
|
|
2720
|
+
}
|
|
2721
|
+
const { bytes } = await h.media(args.image_url, { what: "image", maxBytes: MAX_IMAGE_BYTES, accept: "image/png,image/jpeg" });
|
|
2722
|
+
const info = checkEventImage(imageInfo(bytes), args.asset_type);
|
|
2723
|
+
const result2 = await uploadEventImage(h, api, { localizationId: localization.id, assetType: args.asset_type, bytes, info });
|
|
2724
|
+
return { appId: args.app_id, eventId: localization.eventId, ...result2 };
|
|
2725
|
+
}
|
|
2726
|
+
},
|
|
2727
|
+
{
|
|
2728
|
+
name: "delete_app_event_image",
|
|
2729
|
+
kind: "delete",
|
|
2730
|
+
check: "list_app_event_images",
|
|
2731
|
+
title: "Delete an image of an App Store in-app event",
|
|
2732
|
+
description: "Deletes one image of an in-app event localization, such as one to replace or one whose processing FAILED. The image id is in list_app_event_images (images[].id). Apple refuses this for an event in review or on the App Store.",
|
|
2733
|
+
inputSchema: {
|
|
2734
|
+
type: "object",
|
|
2735
|
+
properties: {
|
|
2736
|
+
app_id: APP_ID,
|
|
2737
|
+
image_id: { ...RESOURCE_ID, description: "The image id, from list_app_event_images (images[].id)." }
|
|
2738
|
+
},
|
|
2739
|
+
required: ["app_id", "image_id"],
|
|
2740
|
+
additionalProperties: false
|
|
2741
|
+
},
|
|
2742
|
+
async run(args, h) {
|
|
2743
|
+
requireApp(h, args.app_id);
|
|
2744
|
+
const api = asc(h);
|
|
2745
|
+
if (locked(h)) {
|
|
2746
|
+
const reply = await api.get(
|
|
2747
|
+
`/v1/appEventScreenshots/${encodeURIComponent(args.image_id)}`,
|
|
2748
|
+
{ include: "appEventLocalization", "fields[appEventScreenshots]": "appEventAssetType,appEventLocalization" },
|
|
2749
|
+
{ 404: "App Store Connect has no in-app event image with that id" }
|
|
2750
|
+
);
|
|
2751
|
+
const localizationId = reply?.data?.relationships?.appEventLocalization?.data?.id;
|
|
2752
|
+
if (typeof localizationId !== "string") throw new ToolFailure("App Store Connect did not say which event localization the image belongs to. Nothing was sent.");
|
|
2753
|
+
await assertEventInApp(api, args.app_id, await eventOfLocalization(api, localizationId));
|
|
2754
|
+
}
|
|
2755
|
+
await api.send({
|
|
2756
|
+
method: "DELETE",
|
|
2757
|
+
path: `/v1/appEventScreenshots/${encodeURIComponent(args.image_id)}`,
|
|
2758
|
+
write: true,
|
|
2759
|
+
errors: { ...EVENT_WRITE_ERRORS, 404: "App Store Connect has no in-app event image with that id" }
|
|
2760
|
+
});
|
|
2761
|
+
return { deleted: true, appId: args.app_id, imageId: args.image_id };
|
|
2762
|
+
}
|
|
2763
|
+
},
|
|
2764
|
+
{
|
|
2765
|
+
name: "submit_app_event_for_review",
|
|
2766
|
+
kind: "create",
|
|
2767
|
+
check: "list_app_events",
|
|
2768
|
+
title: "Send an App Store in-app event to App Review",
|
|
2769
|
+
description: "Sends an in-app event to App Review, as App Store Connect's Add for Review does: the event needs its texts and both images first (upload_app_event_image adds them, list_app_event_images shows them). It reuses the app's open review submission when that holds nothing else (or already holds the event), else starts one, adds the event and sends it. An open submission holding other items (an app version, another event) is left alone and the tool says what it holds. Only a draft, a rejected event or one ready for review can be sent. Never sent twice: check list_app_events after an unclear outcome.",
|
|
2770
|
+
inputSchema: {
|
|
2771
|
+
type: "object",
|
|
2772
|
+
properties: {
|
|
2773
|
+
app_id: APP_ID,
|
|
2774
|
+
event_id: { ...RESOURCE_ID, description: "The event id, from list_app_events." },
|
|
2775
|
+
platform: { type: "string", enum: PLATFORMS, default: "IOS", description: "The platform of the review submission: IOS (default), MAC_OS, TV_OS or VISION_OS." }
|
|
2776
|
+
},
|
|
2777
|
+
required: ["app_id", "event_id"],
|
|
2778
|
+
additionalProperties: false
|
|
2779
|
+
},
|
|
2780
|
+
async run(args, h) {
|
|
2781
|
+
requireApp(h, args.app_id);
|
|
2782
|
+
return submitEventForReview(asc(h), args);
|
|
2783
|
+
}
|
|
2784
|
+
},
|
|
2785
|
+
// The rest of the App Store Connect API: app versions and their texts,
|
|
2786
|
+
// app info, prices, analytics report requests and more.
|
|
2787
|
+
...apiTools({
|
|
2788
|
+
label: "App Store Connect",
|
|
2789
|
+
description: 'The App Store Connect API at https://api.appstoreconnect.apple.com, with a token signed from the connected key: paths start with /v1/ (some with /v2/ or /v3/), such as /v1/apps/1234567890/appStoreVersions or /v1/apps/1234567890/appInfos, and JSON:API bodies ({"data": {"type": ..., "attributes": ...}}). Under an account lock a request must name a chosen app: in the path (/v1/apps/<id>/...), in relationships.app of a POST that names nothing else, or in filter[app]; a resource read or changed by its own id, such as /v1/appStoreVersions/<id>, is refused then. Reference: https://developer.apple.com/documentation/appstoreconnectapi.',
|
|
2790
|
+
accounts: { key: "apps", label: "app", ids: requestApps },
|
|
2791
|
+
guard(request) {
|
|
2792
|
+
if (!/^\/v[1-9]\//.test(request.path)) throw new ToolFailure("The path must start with /v1/, /v2/ or /v3/. Nothing was sent.");
|
|
2793
|
+
},
|
|
2794
|
+
send: (request, h) => asc(h).send(request)
|
|
2795
|
+
})
|
|
2796
|
+
]
|
|
2797
|
+
});
|
|
2798
|
+
module.exports = connector;
|