@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1185 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +12 -1
@@ -0,0 +1,1333 @@
1
+ /* firebase connector module (MIT License). Built from src/vendors/firebase; 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/text.ts
21
+ var encoder = new TextEncoder();
22
+ var decoder = new TextDecoder();
23
+ function utf8Bytes(text2) {
24
+ return encoder.encode(text2);
25
+ }
26
+ function utf8Length(text2) {
27
+ return encoder.encode(text2).length;
28
+ }
29
+ function utf8Decode(bytes) {
30
+ return decoder.decode(bytes);
31
+ }
32
+ function base64Encode(bytes) {
33
+ let binary = "";
34
+ for (let i = 0; i < bytes.length; i += 32768) {
35
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
36
+ }
37
+ return btoa(binary);
38
+ }
39
+ function base64UrlEncode(bytes) {
40
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
41
+ }
42
+ function base64UrlDecode(text2) {
43
+ if (!/^[A-Za-z0-9_-]*$/.test(text2)) throw new Error("not base64url");
44
+ const padded = text2.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text2.length + 3) % 4);
45
+ const binary = atob(padded);
46
+ const bytes = new Uint8Array(binary.length);
47
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
48
+ return bytes;
49
+ }
50
+ function base64Decode(text2) {
51
+ const clean = text2.replace(/\s+/g, "");
52
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 === 1) throw new Error("not base64");
53
+ const binary = atob(clean);
54
+ const bytes = new Uint8Array(binary.length);
55
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
56
+ return bytes;
57
+ }
58
+ async function sha256Hex(text2) {
59
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(text2)));
60
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
61
+ }
62
+ function truncate(text2, max) {
63
+ if (text2.length <= max) return text2;
64
+ const points = Array.from(text2);
65
+ if (points.length <= max) return text2;
66
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
67
+ }
68
+ function cleanVendorText(text2, max = 300) {
69
+ if (typeof text2 !== "string") return void 0;
70
+ if (/^\s*</.test(text2)) return void 0;
71
+ const line = text2.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
72
+ return line ? truncate(line, max) : void 0;
73
+ }
74
+ function formatNumber(value) {
75
+ return value.toLocaleString("en-US");
76
+ }
77
+
78
+ // src/core/output.ts
79
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
80
+ function jsonSize(value) {
81
+ return utf8Length(JSON.stringify(value) ?? "");
82
+ }
83
+ function cutStrings(value, max) {
84
+ if (typeof value === "string") return truncate(value, max);
85
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
86
+ if (typeof value === "object" && value !== null) {
87
+ const out = {};
88
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
89
+ return out;
90
+ }
91
+ return value;
92
+ }
93
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
94
+ if (jsonSize(value) <= limit) return { value, truncated: false };
95
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
96
+ const cut = cutStrings(value, max);
97
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
98
+ }
99
+ return void 0;
100
+ }
101
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
102
+ const build = (count) => {
103
+ const cut = count < input.items.length;
104
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
105
+ const next = cut ? input.resumeAt(count) : input.nextPage;
106
+ if (next) result2["nextCursor"] = next;
107
+ if (cut) result2["truncated"] = true;
108
+ return result2;
109
+ };
110
+ const all = build(input.items.length);
111
+ if (jsonSize(all) <= limit) return all;
112
+ let low = 1;
113
+ let high = input.items.length - 1;
114
+ while (low < high) {
115
+ const middle = Math.ceil((low + high) / 2);
116
+ if (jsonSize(build(middle)) <= limit) low = middle;
117
+ else high = middle - 1;
118
+ }
119
+ const best = build(low);
120
+ if (jsonSize(best) <= limit) return best;
121
+ const shrunk = shrinkToFit(best, limit);
122
+ if (shrunk) return { ...shrunk.value, truncated: true };
123
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
124
+ }
125
+ function encodeCursor(tool, state) {
126
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
127
+ }
128
+ function decodeCursor(tool, cursor) {
129
+ if (cursor === void 0 || cursor === "") return null;
130
+ try {
131
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
132
+ if (typeof state === "object" && state !== null && state.t === tool) {
133
+ return state;
134
+ }
135
+ } catch {
136
+ }
137
+ throw new ToolFailure(
138
+ "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."
139
+ );
140
+ }
141
+
142
+ // src/core/credentials.ts
143
+ function requiredAlternatives(module2) {
144
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
145
+ }
146
+ function unmetAlternatives(alternatives, has) {
147
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
148
+ if (lacking.some((list) => list.length === 0)) return [];
149
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
150
+ }
151
+ function andList(items) {
152
+ if (items.length <= 2) return items.join(" and ");
153
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
154
+ }
155
+ function orList(items) {
156
+ if (items.length <= 1) return items.join("");
157
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
158
+ }
159
+
160
+ // src/core/files.ts
161
+ var ATTACHMENT_URI = "attachment:///";
162
+ var MAX_NAME = 200;
163
+ function fileLimitOf(ctx) {
164
+ const maxBytes = ctx.files?.maxBytes;
165
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
166
+ }
167
+ function fileName(name2) {
168
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
169
+ const points = Array.from(clean);
170
+ if (points.length <= MAX_NAME) return clean || "file";
171
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
172
+ return points.slice(0, MAX_NAME - extension.length).join("") + extension;
173
+ }
174
+ function fileType(mimeType) {
175
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
176
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
177
+ }
178
+ function resourceBlock(file) {
179
+ return {
180
+ type: "resource",
181
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
182
+ };
183
+ }
184
+
185
+ // src/core/http.ts
186
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
187
+ var USER_AGENT = "agent-connectors";
188
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
189
+ function errorCode(error) {
190
+ const code = error?.code;
191
+ return typeof code === "string" ? code : void 0;
192
+ }
193
+ function describe(error) {
194
+ const name2 = error?.name;
195
+ const code = errorCode(error);
196
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
197
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
198
+ if (code === "TOO_LARGE") return "the reply was too large";
199
+ return cleanVendorText(error?.message, 200) ?? "a network error";
200
+ }
201
+ function retryAfterSeconds(headers, now = Date.now()) {
202
+ const retryAfter = headers.get("retry-after");
203
+ if (retryAfter) {
204
+ const seconds = Number(retryAfter);
205
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
206
+ const date = Date.parse(retryAfter);
207
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
208
+ }
209
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
210
+ if (reset) {
211
+ const value = Number(reset);
212
+ if (Number.isFinite(value) && value >= 0) {
213
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
214
+ }
215
+ }
216
+ return void 0;
217
+ }
218
+ function vendorCode(data) {
219
+ if (typeof data !== "object" || data === null) return void 0;
220
+ for (const key of ["error", "code"]) {
221
+ const value = data[key];
222
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
223
+ }
224
+ return void 0;
225
+ }
226
+ function vendorMessage(data) {
227
+ if (typeof data === "string") return cleanVendorText(data);
228
+ if (typeof data !== "object" || data === null) return void 0;
229
+ const record = data;
230
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
231
+ const value = record[key];
232
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
233
+ const nested = value?.message;
234
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
235
+ }
236
+ if (Array.isArray(record["errors"])) {
237
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
238
+ if (messages.length) return cleanVendorText(messages.join("; "));
239
+ }
240
+ return void 0;
241
+ }
242
+ var TooLarge = class extends Error {
243
+ constructor(limit) {
244
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
245
+ this.limit = limit;
246
+ }
247
+ limit;
248
+ };
249
+ async function readCapped(response, maxBytes) {
250
+ const declared = Number(response.headers.get("content-length"));
251
+ if (Number.isFinite(declared) && declared > maxBytes) {
252
+ await response.body?.cancel().catch(() => {
253
+ });
254
+ throw new TooLarge(maxBytes);
255
+ }
256
+ if (!response.body) return new Uint8Array(0);
257
+ const reader = response.body.getReader();
258
+ const chunks = [];
259
+ let total = 0;
260
+ for (; ; ) {
261
+ const { done, value } = await reader.read();
262
+ if (done) break;
263
+ total += value.byteLength;
264
+ if (total > maxBytes) {
265
+ await reader.cancel().catch(() => {
266
+ });
267
+ throw new TooLarge(maxBytes);
268
+ }
269
+ chunks.push(value);
270
+ }
271
+ const bytes = new Uint8Array(total);
272
+ let offset = 0;
273
+ for (const chunk of chunks) {
274
+ bytes.set(chunk, offset);
275
+ offset += chunk.byteLength;
276
+ }
277
+ return bytes;
278
+ }
279
+ function parseBody(bytes, contentType) {
280
+ if (bytes.length === 0) return null;
281
+ const text2 = utf8Decode(bytes);
282
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text2)) {
283
+ try {
284
+ return JSON.parse(text2);
285
+ } catch {
286
+ }
287
+ }
288
+ return text2;
289
+ }
290
+ function createHttp(env) {
291
+ const { label, ctx } = env;
292
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
293
+ 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.`;
294
+ function failureFor(status, headers, data, request) {
295
+ const message = vendorMessage(data);
296
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
297
+ const retryAfter = retryAfterSeconds(headers);
298
+ const code = vendorCode(data);
299
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
300
+ const custom = request.errors?.[status];
301
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
302
+ if (status >= 500) {
303
+ if (request.write) {
304
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
305
+ }
306
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
307
+ }
308
+ if (status === 429) {
309
+ return new ToolFailure(
310
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
311
+ { status, ...extra }
312
+ );
313
+ }
314
+ if (status === 401) {
315
+ return new ToolFailure(
316
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
317
+ { status, ...extra }
318
+ );
319
+ }
320
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
321
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
322
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
323
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
324
+ }
325
+ async function api(request) {
326
+ const method = request.method ?? "GET";
327
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
328
+ throw new Error(`read-only tool sent ${method}`);
329
+ }
330
+ const origin = request.origin ?? env.origins[0];
331
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
332
+ const url = new URL(request.path, origin);
333
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
334
+ for (const [key, value] of Object.entries(request.query ?? {})) {
335
+ if (value === void 0 || value === null) continue;
336
+ if (Array.isArray(value)) {
337
+ url.searchParams.delete(key);
338
+ for (const item of value) url.searchParams.append(key, String(item));
339
+ } else {
340
+ url.searchParams.set(key, String(value));
341
+ }
342
+ }
343
+ const headers = {
344
+ accept: "application/json",
345
+ "user-agent": USER_AGENT,
346
+ ...request.auth === false ? {} : env.authHeaders(),
347
+ ...request.headers
348
+ };
349
+ let body;
350
+ if (request.json !== void 0) {
351
+ body = JSON.stringify(request.json);
352
+ headers["content-type"] = "application/json";
353
+ } else if (request.body) {
354
+ body = request.body;
355
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
356
+ }
357
+ const started = Date.now();
358
+ if (request.write) env.onWriteSent();
359
+ let response;
360
+ try {
361
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
362
+ } catch (error) {
363
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
364
+ if (errorCode(error) === "URL_REFUSED") {
365
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
366
+ }
367
+ if (request.write) {
368
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
369
+ }
370
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
371
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
372
+ }
373
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
374
+ let bytes;
375
+ try {
376
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
377
+ } catch (error) {
378
+ if (request.write && (response.ok || response.status >= 500)) {
379
+ 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.`);
380
+ }
381
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
382
+ }
383
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
384
+ if (response.ok) return { status: response.status, headers: response.headers, data };
385
+ throw failureFor(response.status, response.headers, data, request);
386
+ }
387
+ async function media(rawUrl, options) {
388
+ const { what } = options;
389
+ let url;
390
+ try {
391
+ url = new URL(rawUrl);
392
+ } catch {
393
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
394
+ }
395
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
396
+ const started = Date.now();
397
+ let response;
398
+ try {
399
+ response = await ctx.fetch(url.toString(), {
400
+ method: "GET",
401
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
402
+ ...ctx.signal ? { signal: ctx.signal } : {}
403
+ });
404
+ } catch (error) {
405
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
406
+ if (errorCode(error) === "URL_REFUSED") {
407
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
408
+ }
409
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
410
+ }
411
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
412
+ if (!response.ok) {
413
+ await response.body?.cancel().catch(() => {
414
+ });
415
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
416
+ }
417
+ try {
418
+ const bytes = await readCapped(response, options.maxBytes);
419
+ return { bytes, contentType: response.headers.get("content-type") };
420
+ } catch (error) {
421
+ if (error instanceof TooLarge) {
422
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
423
+ }
424
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
425
+ }
426
+ }
427
+ return { api, media };
428
+ }
429
+
430
+ // src/core/origins.ts
431
+ function parseSiteUrl(value) {
432
+ const text2 = typeof value === "string" ? value.trim() : "";
433
+ if (!text2) return { ok: false, problem: "is empty" };
434
+ let url;
435
+ try {
436
+ url = new URL(text2.includes("://") ? text2 : `https://${text2}`);
437
+ } catch {
438
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
439
+ }
440
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
441
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
442
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
443
+ return { ok: true, url, origin: url.origin };
444
+ }
445
+
446
+ // src/core/schema.ts
447
+ var patterns = /* @__PURE__ */ new Map();
448
+ function patternOf(source) {
449
+ let compiled = patterns.get(source);
450
+ if (!compiled) {
451
+ compiled = new RegExp(source, "u");
452
+ patterns.set(source, compiled);
453
+ }
454
+ return compiled;
455
+ }
456
+ function isPlainObject(value) {
457
+ return typeof value === "object" && value !== null && !Array.isArray(value);
458
+ }
459
+ function isHttpUrl(value) {
460
+ try {
461
+ const url = new URL(value);
462
+ return url.protocol === "https:" || url.protocol === "http:";
463
+ } catch {
464
+ return false;
465
+ }
466
+ }
467
+ function name(path) {
468
+ return `\`${path}\``;
469
+ }
470
+ function child(path, key) {
471
+ return path ? `${path}.${key}` : key;
472
+ }
473
+ function checkValue(schema, value, path, issues) {
474
+ switch (schema.type) {
475
+ case "object":
476
+ checkObject(schema, value, path, issues);
477
+ return;
478
+ case "array": {
479
+ if (!Array.isArray(value)) {
480
+ issues.push(`${name(path)} must be an array`);
481
+ return;
482
+ }
483
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
484
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
485
+ }
486
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
487
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
488
+ }
489
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
490
+ issues.push(`${name(path)} must not repeat an item`);
491
+ }
492
+ if (schema.items) {
493
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
494
+ }
495
+ break;
496
+ }
497
+ case "string": {
498
+ if (typeof value !== "string") {
499
+ issues.push(`${name(path)} must be a string`);
500
+ return;
501
+ }
502
+ const length = Array.from(value).length;
503
+ if (schema.minLength !== void 0 && length < schema.minLength) {
504
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
505
+ }
506
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
507
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
508
+ }
509
+ if (schema.format === "uri" && !isHttpUrl(value)) {
510
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
511
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
512
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
513
+ }
514
+ break;
515
+ }
516
+ case "integer":
517
+ case "number": {
518
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
519
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
520
+ return;
521
+ }
522
+ if (schema.minimum !== void 0 && value < schema.minimum) {
523
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
524
+ }
525
+ if (schema.maximum !== void 0 && value > schema.maximum) {
526
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
527
+ }
528
+ break;
529
+ }
530
+ case "boolean":
531
+ if (typeof value !== "boolean") {
532
+ issues.push(`${name(path)} must be true or false`);
533
+ return;
534
+ }
535
+ break;
536
+ default:
537
+ break;
538
+ }
539
+ if (schema.enum && !schema.enum.includes(value)) {
540
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
541
+ }
542
+ }
543
+ function checkObject(schema, value, path, issues) {
544
+ if (!isPlainObject(value)) {
545
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
546
+ return;
547
+ }
548
+ const properties = schema.properties ?? {};
549
+ for (const key of schema.required ?? []) {
550
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
551
+ }
552
+ const unknown = [];
553
+ for (const [key, item] of Object.entries(value)) {
554
+ const property = properties[key];
555
+ if (!property) {
556
+ if (schema.additionalProperties === false) unknown.push(key);
557
+ continue;
558
+ }
559
+ if (item === void 0 || item === null) continue;
560
+ checkValue(property, item, child(path, key), issues);
561
+ }
562
+ if (unknown.length) {
563
+ const known = Object.keys(properties);
564
+ 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(", ")})` : ""));
565
+ }
566
+ }
567
+ function copyDefault(value) {
568
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
569
+ }
570
+ function validateArguments(schema, args) {
571
+ const input = args === void 0 || args === null ? {} : args;
572
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
573
+ const value = { ...input };
574
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
575
+ const issues = [];
576
+ checkObject(schema, value, "", issues);
577
+ if (issues.length) return { ok: false, issues };
578
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
579
+ if (value[key] === null) delete value[key];
580
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
581
+ }
582
+ return { ok: true, value };
583
+ }
584
+
585
+ // src/core/upload-hosts.ts
586
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
587
+ function uploadHostProblem(entry) {
588
+ if (typeof entry !== "string") return "must be a host name";
589
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
590
+ const labels = name2.split(".");
591
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
592
+ 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";
593
+ }
594
+ if (labels.length < 2) return "needs at least two labels, like example.com";
595
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
596
+ return void 0;
597
+ }
598
+
599
+ // src/core/connector.ts
600
+ var ANNOTATIONS = {
601
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
602
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
603
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
604
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
605
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
606
+ };
607
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
608
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
609
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
610
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
611
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
612
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
613
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
614
+ function deepFreeze(value) {
615
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
616
+ Object.freeze(value);
617
+ for (const item of Object.values(value)) deepFreeze(item);
618
+ }
619
+ return value;
620
+ }
621
+ function assertDefinition(def) {
622
+ const problem = (message) => {
623
+ throw new Error(`connector "${def.vendor}": ${message}`);
624
+ };
625
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
626
+ if (!def.label?.trim()) problem("label is required");
627
+ const originFields = def.originFields ?? [];
628
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
629
+ for (const origin of def.origins) {
630
+ let url;
631
+ try {
632
+ url = new URL(origin);
633
+ } catch {
634
+ }
635
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
636
+ }
637
+ for (const name2 of def.credentials) {
638
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
639
+ }
640
+ for (const [index, name2] of originFields.entries()) {
641
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
642
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
643
+ }
644
+ const names = /* @__PURE__ */ new Set();
645
+ for (const tool of def.tools) {
646
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
647
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
648
+ names.add(tool.name);
649
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
650
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
651
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
652
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
653
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
654
+ }
655
+ }
656
+ for (const tool of def.tools) {
657
+ if (tool.kind === "read") continue;
658
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
659
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
660
+ }
661
+ assertUploadHosts(def, problem);
662
+ assertRequiredCredentials(def, problem);
663
+ assertAccountPickers(def, problem);
664
+ }
665
+ function assertUploadHosts(def, problem) {
666
+ const hosts = def.uploadHosts;
667
+ if (hosts === void 0) return;
668
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
669
+ hosts.forEach((entry, index) => {
670
+ const wrong = uploadHostProblem(entry);
671
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
672
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
673
+ });
674
+ }
675
+ function assertRequiredCredentials(def, problem) {
676
+ const required = def.requiredCredentials;
677
+ if (required === void 0) return;
678
+ if (!Array.isArray(required) || !required.length) {
679
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
680
+ }
681
+ required.forEach((list, index) => {
682
+ const which = `requiredCredentials[${index}]`;
683
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
684
+ list.forEach((name2, position) => {
685
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
686
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
687
+ });
688
+ });
689
+ const lists = required;
690
+ lists.forEach((list, index) => {
691
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
692
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
693
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
694
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
695
+ }
696
+ });
697
+ }
698
+ function isDotPath(value) {
699
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
700
+ }
701
+ function assertAccountPickers(def, problem) {
702
+ const pickers = def.accountPickers;
703
+ if (pickers === void 0) return;
704
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
705
+ const keys = /* @__PURE__ */ new Set();
706
+ for (const item of pickers) {
707
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
708
+ const picker = item;
709
+ const key = picker["key"];
710
+ 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}$`);
711
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
712
+ keys.add(key);
713
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
714
+ const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
715
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
716
+ const { label, description, multiple, legacyField } = picker;
717
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
718
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
719
+ fail("description, when given, must be a text of 1 to 1024 characters");
720
+ }
721
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
722
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
723
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
724
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
725
+ for (const field of ["idField", "nameField"]) {
726
+ if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
727
+ }
728
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
729
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
730
+ }
731
+ }
732
+ }
733
+ function copyPicker(picker) {
734
+ return {
735
+ key: picker.key,
736
+ label: picker.label,
737
+ ...picker.description !== void 0 ? { description: picker.description } : {},
738
+ multiple: picker.multiple,
739
+ tool: picker.tool,
740
+ idField: picker.idField,
741
+ nameField: picker.nameField,
742
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
743
+ };
744
+ }
745
+ function result(payload, isError, files = []) {
746
+ return {
747
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
748
+ ...isError ? { isError: true } : {}
749
+ };
750
+ }
751
+ function failure(message, details = {}) {
752
+ return result({ error: message, ...details }, true);
753
+ }
754
+ function trimmed(values) {
755
+ const out = {};
756
+ if (typeof values !== "object" || values === null) return out;
757
+ for (const [key, value] of Object.entries(values)) {
758
+ if (value === void 0 || value === null) continue;
759
+ const text2 = String(value).trim();
760
+ if (text2) out[key] = text2;
761
+ }
762
+ return out;
763
+ }
764
+ function defineConnector(def) {
765
+ assertDefinition(def);
766
+ const { label } = def;
767
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
768
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
769
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
770
+ const required = requiredAlternatives(def);
771
+ const notConnected = (unmet) => {
772
+ const [first] = unmet;
773
+ if (unmet.length === 1 && first) {
774
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
775
+ }
776
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
777
+ };
778
+ const descriptors = def.tools.map((tool) => ({
779
+ name: tool.name,
780
+ title: tool.title,
781
+ description: tool.description,
782
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
783
+ annotations: { ...ANNOTATIONS[tool.kind] }
784
+ }));
785
+ async function call(toolName, args, ctx) {
786
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
787
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
788
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
789
+ const log = (text2) => {
790
+ try {
791
+ ctx.log?.(text2);
792
+ } catch {
793
+ }
794
+ };
795
+ const given = trimmed(ctx.credentials);
796
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
797
+ const has = (name2) => Boolean(credentials[name2]);
798
+ const unmet = unmetAlternatives(required, has);
799
+ if (unmet.length) return failure(notConnected(unmet));
800
+ const complete = required.filter((list) => list.every(has));
801
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
802
+ const fieldOrigins = /* @__PURE__ */ new Map();
803
+ for (const name2 of def.originFields ?? []) {
804
+ if (!given[name2] && !inUse.includes(name2)) continue;
805
+ const site = parseSiteUrl(given[name2] ?? "");
806
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
807
+ fieldOrigins.set(name2, site.origin);
808
+ }
809
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
810
+ const parsed = validateArguments(tool.inputSchema, args);
811
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
812
+ const frozenCredentials = Object.freeze({ ...credentials });
813
+ let writeSent = false;
814
+ const fileLimit = fileLimitOf(ctx);
815
+ const files = [];
816
+ let fileBytes = 0;
817
+ const http = createHttp({
818
+ vendor: def.vendor,
819
+ label,
820
+ tool: tool.name,
821
+ readOnly: tool.kind === "read",
822
+ origins,
823
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
824
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
825
+ ctx,
826
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
827
+ log,
828
+ onWriteSent: () => {
829
+ writeSent = true;
830
+ }
831
+ });
832
+ const helpers = {
833
+ tool: tool.name,
834
+ credentials: frozenCredentials,
835
+ ctx,
836
+ origins: Object.freeze([...origins]),
837
+ originOf: (credential) => {
838
+ const origin = fieldOrigins.get(credential);
839
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
840
+ return origin;
841
+ },
842
+ api: http.api,
843
+ media: http.media,
844
+ page: (input) => fitPage(input),
845
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
846
+ makeCursor: (state) => encodeCursor(tool.name, state),
847
+ fileLimit: () => fileLimit,
848
+ file: ({ name: name2, mimeType, bytes }) => {
849
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
850
+ const total = fileBytes + bytes.byteLength;
851
+ if (total > fileLimit) {
852
+ 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.`);
853
+ }
854
+ fileBytes = total;
855
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
856
+ files.push({ ...info, bytes });
857
+ return { ...info };
858
+ },
859
+ log
860
+ };
861
+ try {
862
+ const data = await tool.run(parsed.value, helpers);
863
+ const fitted = shrinkToFit(data ?? {});
864
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
865
+ const payload = fitted.value;
866
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
867
+ } catch (error) {
868
+ if (error instanceof OutcomeUnknown) {
869
+ return result({
870
+ outcome: "unknown",
871
+ check: tool.check,
872
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
873
+ }, true);
874
+ }
875
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
876
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
877
+ if (writeSent) {
878
+ return result({
879
+ outcome: "unknown",
880
+ check: tool.check,
881
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
882
+ }, true);
883
+ }
884
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
885
+ }
886
+ }
887
+ return deepFreeze({
888
+ vendor: def.vendor,
889
+ origins: [...def.origins],
890
+ originFields: [...def.originFields ?? []],
891
+ uploadHosts: [...def.uploadHosts ?? []],
892
+ credentials: [...def.credentials],
893
+ requiredCredentials: required.map((list) => [...list]),
894
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
895
+ tools: descriptors,
896
+ call
897
+ });
898
+ }
899
+
900
+ // src/core/jwt.ts
901
+ var KEY_ALGORITHMS = {
902
+ RS256: { import: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, sign: { name: "RSASSA-PKCS1-v1_5" }, kind: "an RSA" },
903
+ // WebCrypto returns ECDSA signatures as raw r||s, the form JWS (ES256) needs.
904
+ ES256: { import: { name: "ECDSA", namedCurve: "P-256" }, sign: { name: "ECDSA", hash: "SHA-256" }, kind: "a P-256 (ES256)" }
905
+ };
906
+ function base64UrlJson(value) {
907
+ return base64UrlEncode(utf8Bytes(JSON.stringify(value)));
908
+ }
909
+ function pkcs8Der(pem, keyName) {
910
+ const text2 = String(pem).replace(/\\r\\n|\\n/g, "\n").trim();
911
+ const block = /-----BEGIN ([A-Z0-9 ]+)-----([\s\S]*?)-----END \1-----/.exec(text2);
912
+ const whole = `it must be the whole PEM text, from -----BEGIN PRIVATE KEY----- to -----END PRIVATE KEY-----`;
913
+ if (!block) throw new ToolFailure(`The ${keyName} could not be read: ${whole}. Nothing was sent.`);
914
+ const type = block[1];
915
+ if (type === "ENCRYPTED PRIVATE KEY") throw new ToolFailure(`The ${keyName} is encrypted with a passphrase: use the key without one. Nothing was sent.`);
916
+ if (type !== "PRIVATE KEY") {
917
+ 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.`);
918
+ }
919
+ try {
920
+ return base64Decode(block[2]);
921
+ } catch {
922
+ throw new ToolFailure(`The ${keyName} could not be read: ${whole}. Nothing was sent.`);
923
+ }
924
+ }
925
+ async function signJwt(options) {
926
+ const keyName = options.keyName ?? "private key";
927
+ const algorithm = KEY_ALGORITHMS[options.algorithm];
928
+ if (!algorithm) throw new Error(`unsupported JWT algorithm ${String(options.algorithm)}`);
929
+ const der = pkcs8Der(options.privateKey, keyName);
930
+ let key;
931
+ try {
932
+ key = await crypto.subtle.importKey("pkcs8", der, algorithm.import, false, ["sign"]);
933
+ } catch {
934
+ throw new ToolFailure(`The ${keyName} is not ${algorithm.kind} private key. Nothing was sent.`);
935
+ }
936
+ const header = { alg: options.algorithm, typ: "JWT", ...options.header };
937
+ header.alg = options.algorithm;
938
+ const signingInput = `${base64UrlJson(header)}.${base64UrlJson(options.payload)}`;
939
+ const signature = new Uint8Array(await crypto.subtle.sign(algorithm.sign, key, utf8Bytes(signingInput)));
940
+ return `${signingInput}.${base64UrlEncode(signature)}`;
941
+ }
942
+ var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
943
+ var GOOGLE_TOKEN_ORIGIN = "https://oauth2.googleapis.com";
944
+ var JWT_BEARER = "urn:ietf:params:oauth:grant-type:jwt-bearer";
945
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
946
+ var MAX_CACHED_TOKENS = 64;
947
+ var SERVICE_ACCOUNT_HELP = 'The service account key is not a Google service account key file: paste the whole JSON file Google Cloud creates for the key (IAM and admin -> Service accounts -> Keys -> Add key -> JSON), with "client_email" and "private_key" in it. Nothing was sent.';
948
+ var googleTokens = /* @__PURE__ */ new Map();
949
+ var pendingGoogleTokens = /* @__PURE__ */ new Map();
950
+ function readServiceAccount(json) {
951
+ let data;
952
+ try {
953
+ data = JSON.parse(json);
954
+ } catch {
955
+ throw new ToolFailure(SERVICE_ACCOUNT_HELP);
956
+ }
957
+ if (typeof data !== "object" || data === null || typeof data.client_email !== "string" || typeof data.private_key !== "string") {
958
+ throw new ToolFailure(SERVICE_ACCOUNT_HELP);
959
+ }
960
+ if (data.type !== void 0 && data.type !== "service_account") {
961
+ throw new ToolFailure(`The Google key is a "${String(data.type).slice(0, 40)}" credential, not a service account key. ${SERVICE_ACCOUNT_HELP}`);
962
+ }
963
+ return { clientEmail: data.client_email, privateKey: data.private_key, ...typeof data.private_key_id === "string" ? { keyId: data.private_key_id } : {} };
964
+ }
965
+ async function exchangeGoogleToken(h, account, options) {
966
+ const iat = Math.floor(Date.now() / 1e3);
967
+ const assertion = await signJwt({
968
+ algorithm: "RS256",
969
+ privateKey: account.privateKey,
970
+ header: account.keyId ? { kid: account.keyId } : {},
971
+ payload: {
972
+ iss: account.clientEmail,
973
+ scope: options.scopes.join(" "),
974
+ aud: GOOGLE_TOKEN_URL,
975
+ iat,
976
+ exp: iat + 3600,
977
+ ...options.subject ? { sub: options.subject } : {}
978
+ },
979
+ keyName: "service account private key"
980
+ });
981
+ const { data } = await h.api({
982
+ method: "POST",
983
+ origin: GOOGLE_TOKEN_ORIGIN,
984
+ path: "/token",
985
+ body: utf8Bytes(new URLSearchParams({ grant_type: JWT_BEARER, assertion }).toString()),
986
+ contentType: "application/x-www-form-urlencoded",
987
+ // The assertion is the credential: no module auth header goes with it.
988
+ auth: false,
989
+ // A token exchange changes nothing, so read tools may make it.
990
+ safe: true,
991
+ errors: {
992
+ 400: "Google did not accept the service account key",
993
+ 401: "Google did not accept the service account key"
994
+ }
995
+ });
996
+ if (typeof data?.access_token !== "string" || !data.access_token) throw new ToolFailure("Google sent no access token for the service account.");
997
+ const expiresIn = typeof data.expires_in === "number" && data.expires_in > 0 ? data.expires_in : 3600;
998
+ return { token: data.access_token, expiresIn };
999
+ }
1000
+ async function googleServiceAccountToken(h, serviceAccountJson, options) {
1001
+ if (!h.origins.includes(GOOGLE_TOKEN_ORIGIN)) throw new Error(`a module that uses googleServiceAccountToken declares ${GOOGLE_TOKEN_ORIGIN} in its origins`);
1002
+ const account = readServiceAccount(serviceAccountJson);
1003
+ const key = await sha256Hex([account.clientEmail, account.privateKey, options.scopes.join(" "), options.subject ?? ""].join("\n"));
1004
+ const cached = googleTokens.get(key);
1005
+ if (cached && cached.expiresAt > Date.now()) return cached.token;
1006
+ googleTokens.delete(key);
1007
+ const inFlight = pendingGoogleTokens.get(key);
1008
+ if (inFlight) return inFlight;
1009
+ const started = exchangeGoogleToken(h, account, options).then(({ token, expiresIn }) => {
1010
+ const now = Date.now();
1011
+ for (const [other, entry] of googleTokens) if (entry.expiresAt <= now) googleTokens.delete(other);
1012
+ while (googleTokens.size >= MAX_CACHED_TOKENS) {
1013
+ const oldest = googleTokens.keys().next().value;
1014
+ if (oldest === void 0) break;
1015
+ googleTokens.delete(oldest);
1016
+ }
1017
+ googleTokens.set(key, { token, expiresAt: now + Math.min(expiresIn, 3600) * 1e3 - TOKEN_EARLY_MS });
1018
+ return token;
1019
+ }).finally(() => pendingGoogleTokens.delete(key));
1020
+ pendingGoogleTokens.set(key, started);
1021
+ return started;
1022
+ }
1023
+
1024
+ // src/vendors/firebase/projects.ts
1025
+ var MAX_PROJECTS = 25;
1026
+ var HELP = 'Give the service account key file of a Firebase project (Firebase console -> Project settings -> Service accounts -> Generate new private key), or a JSON list of projects such as [{"appname": "My App", "serviceaccountjson": {...the key file...}, "topics": [{"topickey": "locale_en", "topicdesc": "English speakers"}]}].';
1027
+ function isRecord(value) {
1028
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1029
+ }
1030
+ function jsonOf(value) {
1031
+ if (isRecord(value) || Array.isArray(value)) return value;
1032
+ if (typeof value !== "string") return void 0;
1033
+ const text2 = value.trim();
1034
+ for (const candidate of [text2, () => utf8Decode(base64Decode(text2.replace(/^data:[^,]*;base64,/i, "").replace(/-/g, "+").replace(/_/g, "/"))).trim()]) {
1035
+ try {
1036
+ const source = typeof candidate === "string" ? candidate : candidate();
1037
+ if (source.startsWith("{") || source.startsWith("[")) return JSON.parse(source);
1038
+ } catch {
1039
+ }
1040
+ }
1041
+ return void 0;
1042
+ }
1043
+ function firstOf(record, names) {
1044
+ for (const name2 of names) if (record[name2] !== void 0 && record[name2] !== null && record[name2] !== "") return record[name2];
1045
+ return void 0;
1046
+ }
1047
+ function text(value) {
1048
+ return typeof value === "string" && value.trim() ? value.trim() : typeof value === "number" ? String(value) : void 0;
1049
+ }
1050
+ function readApps(value) {
1051
+ const list = Array.isArray(value) ? value : [];
1052
+ const apps = [];
1053
+ for (const item of list) {
1054
+ if (!isRecord(item)) continue;
1055
+ const id = text(firstOf(item, ["id", "appId", "appid", "packageName", "packagename", "bundleId", "bundleid"]));
1056
+ if (!id) continue;
1057
+ const platform = text(item["platform"])?.toLowerCase();
1058
+ apps.push({ ...platform ? { platform } : {}, id });
1059
+ }
1060
+ return apps.slice(0, 50);
1061
+ }
1062
+ function readTopics(value) {
1063
+ const topics = [];
1064
+ const add = (topic, description) => {
1065
+ if (topic) topics.push({ topic: topic.replace(/^\/topics\//, ""), ...description ? { description: truncate(description, 300) } : {} });
1066
+ };
1067
+ if (Array.isArray(value)) {
1068
+ for (const item of value) {
1069
+ if (typeof item === "string") add(text(item), void 0);
1070
+ else if (isRecord(item)) add(text(firstOf(item, ["topickey", "topicKey", "key", "topic", "name"])), text(firstOf(item, ["topicdesc", "topicDesc", "description", "desc"])));
1071
+ }
1072
+ } else if (isRecord(value)) {
1073
+ for (const [topic, description] of Object.entries(value)) add(text(topic), text(description));
1074
+ }
1075
+ return topics.slice(0, 200);
1076
+ }
1077
+ function readProject(entry, position, total) {
1078
+ const which = total > 1 ? `Firebase project ${position + 1} of the accounts list` : "The Firebase project";
1079
+ if (!isRecord(entry)) throw new ToolFailure(`${which} is not an object. ${HELP} Nothing was sent.`);
1080
+ const key = entry["type"] === "service_account" || typeof entry["private_key"] === "string" ? entry : jsonOf(firstOf(entry, ["serviceaccountjson", "serviceAccountJson", "serviceAccountJsonBase64", "service_account_json", "serviceaccount", "serviceAccount", "key"]));
1081
+ if (!isRecord(key) || typeof key["private_key"] !== "string" || typeof key["client_email"] !== "string") {
1082
+ throw new ToolFailure(`${which} has no usable service account key (a key file with client_email and private_key). ${HELP} Nothing was sent.`);
1083
+ }
1084
+ const projectId = text(key["project_id"]) ?? text(firstOf(entry, ["projectid", "projectId", "project_id"]));
1085
+ if (!projectId || !/^[a-z][a-z0-9.:-]{3,100}$/.test(projectId)) {
1086
+ throw new ToolFailure(`${which} has no valid project id: the key file's project_id is missing. ${HELP} Nothing was sent.`);
1087
+ }
1088
+ return {
1089
+ projectId,
1090
+ appName: text(firstOf(entry, ["appname", "appName", "name"])) ?? projectId,
1091
+ keyText: JSON.stringify(key),
1092
+ clientEmail: key["client_email"],
1093
+ apps: readApps(entry["apps"]),
1094
+ topics: readTopics(entry["topics"])
1095
+ };
1096
+ }
1097
+ function readProjects(value) {
1098
+ const parsed = jsonOf(value);
1099
+ let entries;
1100
+ if (Array.isArray(parsed)) entries = parsed;
1101
+ else if (isRecord(parsed) && Array.isArray(parsed["accounts"])) entries = parsed["accounts"];
1102
+ else if (isRecord(parsed)) entries = [parsed];
1103
+ else throw new ToolFailure(`The Firebase accounts value could not be read as JSON. ${HELP} Nothing was sent.`);
1104
+ if (!entries.length) throw new ToolFailure(`The Firebase accounts list is empty. ${HELP} Nothing was sent.`);
1105
+ if (entries.length > MAX_PROJECTS) throw new ToolFailure(`The Firebase accounts list has ${entries.length} projects; at most ${MAX_PROJECTS} are supported. Nothing was sent.`);
1106
+ return entries.map((entry, index) => readProject(entry, index, entries.length));
1107
+ }
1108
+ function describe2(project) {
1109
+ return project.appName === project.projectId ? project.projectId : `${project.projectId} (${project.appName})`;
1110
+ }
1111
+ function projectFor(projects2, given) {
1112
+ const names = projects2.map(describe2).join(", ");
1113
+ if (given === void 0) {
1114
+ if (projects2.length === 1) return projects2[0];
1115
+ throw new ToolFailure(`Several Firebase projects are connected: give project, one of ${names}. Nothing was sent.`);
1116
+ }
1117
+ const wanted = given.trim().toLowerCase();
1118
+ const match = projects2.find((project) => project.projectId.toLowerCase() === wanted) ?? projects2.find((project) => project.appName.toLowerCase() === wanted) ?? projects2.find((project) => project.apps.some((app) => app.id.toLowerCase() === wanted));
1119
+ if (!match) throw new ToolFailure(`No connected Firebase project matches "${truncate(given, 100)}": use one of ${names}. Nothing was sent.`);
1120
+ return match;
1121
+ }
1122
+
1123
+ // src/vendors/firebase/index.ts
1124
+ var LABEL2 = "Firebase";
1125
+ var FCM_ORIGIN = "https://fcm.googleapis.com";
1126
+ var TOKEN_ORIGIN = "https://oauth2.googleapis.com";
1127
+ var SCOPES = ["https://www.googleapis.com/auth/firebase.messaging"];
1128
+ var MAX_DATA_BYTES = 4e3;
1129
+ var CHECK_TOPIC = "connection-check";
1130
+ function compact(value) {
1131
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
1132
+ }
1133
+ function isRecord2(value) {
1134
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1135
+ }
1136
+ function merge(base, extra) {
1137
+ if (!extra) return base;
1138
+ const out = { ...base };
1139
+ for (const [key, value] of Object.entries(extra)) {
1140
+ if (["__proto__", "prototype", "constructor"].includes(key)) continue;
1141
+ const current = out[key];
1142
+ out[key] = isRecord2(current) && isRecord2(value) ? merge(current, value) : value;
1143
+ }
1144
+ return out;
1145
+ }
1146
+ function projects(h) {
1147
+ return readProjects(h.credentials["accounts"]);
1148
+ }
1149
+ async function send(h, project, body, mode) {
1150
+ const token = await googleServiceAccountToken(h, project.keyText, { scopes: SCOPES });
1151
+ return h.api({
1152
+ method: "POST",
1153
+ path: `/v1/projects/${encodeURIComponent(project.projectId)}/messages:send`,
1154
+ headers: { authorization: `Bearer ${token}` },
1155
+ json: mode.validateOnly ? { validate_only: true, ...body } : body,
1156
+ ...mode.validateOnly ? { safe: true } : { write: true },
1157
+ errors: {
1158
+ 400: "Firebase did not accept the message",
1159
+ 401: `Firebase did not accept the service account of the project ${project.projectId}`,
1160
+ 403: `Firebase refused the service account ${project.clientEmail}: give it the Firebase Cloud Messaging API Admin role in the project ${project.projectId} and check that the Firebase Cloud Messaging API is enabled`,
1161
+ 404: "Firebase found no such device token or project; a token that is not registered any more belongs to an app that was uninstalled or whose token expired, so stop sending to it"
1162
+ }
1163
+ });
1164
+ }
1165
+ var MESSAGE_PROPERTIES = {
1166
+ project: { type: "string", minLength: 1, maxLength: 200, description: "The project to send from: its project id, app name or one of its app ids. Optional when one project is connected." },
1167
+ topic: { type: "string", pattern: "^(/topics/)?[A-Za-z0-9\\-_.~%]{1,900}$", description: "A topic the app subscribes its users to, e.g. locale_en (list_projects shows the configured ones)." },
1168
+ condition: {
1169
+ type: "string",
1170
+ minLength: 1,
1171
+ maxLength: 1e3,
1172
+ description: `Topics combined, e.g. "'tier_paid' in topics && 'locale_tr' in topics": up to 5 topics with &&, || and !, each name in single quotes.`
1173
+ },
1174
+ token: { type: "string", minLength: 20, maxLength: 4096, description: "One device's registration token, e.g. for a test push." },
1175
+ title: { type: "string", minLength: 1, maxLength: 1e3, description: "The notification title (about 65 characters show before it is cut)." },
1176
+ body: { type: "string", minLength: 1, maxLength: 4e3, description: "The notification text (about 45 characters show collapsed on Android, about 178 expanded on iOS)." },
1177
+ image_url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A public https image (JPEG or PNG, under 1 MB) shown in the notification; iOS shows it only with a Notification Service Extension in the app." },
1178
+ data: { type: "object", description: 'Key-value data for the app, values as text, e.g. {"screen": "offers", "eventId": "eid-2026"}; up to 4 KB.' },
1179
+ android_channel_id: { type: "string", maxLength: 200, description: "The Android notification channel id, e.g. promotions." },
1180
+ click_action: { type: "string", maxLength: 500, description: "The Android click action, e.g. OPEN_PROMOTION." },
1181
+ sound: { type: "string", maxLength: 200, description: "The sound on Android and iOS, e.g. default." },
1182
+ badge: { type: "integer", minimum: 0, maximum: 99999, description: "The iOS app icon badge number." },
1183
+ priority: { type: "string", enum: ["normal", "high"], description: "Delivery priority on Android and iOS: normal or high (wakes the device)." },
1184
+ ttl_seconds: { type: "integer", minimum: 0, maximum: 2419200, description: "How long Firebase keeps trying to deliver, in seconds (up to 28 days)." },
1185
+ collapse_key: { type: "string", maxLength: 64, description: "Messages with the same key replace each other while waiting for the device." },
1186
+ analytics_label: { type: "string", pattern: "^[a-zA-Z0-9-_.~%]{1,50}$", description: "A label for Firebase's delivery reports, e.g. eid-2026-tr." },
1187
+ android: { type: "object", description: 'Raw Android options (FCM AndroidConfig), merged over the ones above, e.g. {"notification": {"color": "#ff0000"}}.' },
1188
+ apns: { type: "object", description: "Raw iOS options (FCM ApnsConfig: headers and payload), merged over the ones above." },
1189
+ webpush: { type: "object", description: "Raw web push options (FCM WebpushConfig)." }
1190
+ };
1191
+ function buildMessage(args) {
1192
+ const targets = [args.token, args.topic, args.condition].filter((value) => value !== void 0);
1193
+ if (targets.length !== 1) throw new ToolFailure("Give one target: topic, condition or token. Nothing was sent.");
1194
+ if (args.condition !== void 0) {
1195
+ const topics = args.condition.match(/'[^']+'\s+in\s+topics/g) ?? [];
1196
+ if (!topics.length) throw new ToolFailure("condition names no topic: write each as 'name' in topics. Nothing was sent.");
1197
+ if (topics.length > 5) throw new ToolFailure(`condition names ${topics.length} topics; Firebase allows 5. Nothing was sent.`);
1198
+ }
1199
+ const message = {};
1200
+ if (args.token !== void 0) message["token"] = args.token;
1201
+ if (args.topic !== void 0) message["topic"] = args.topic.replace(/^\/topics\//, "");
1202
+ if (args.condition !== void 0) message["condition"] = args.condition;
1203
+ const notification = compact({ title: args.title, body: args.body, image: args.image_url });
1204
+ if (Object.keys(notification).length) message["notification"] = notification;
1205
+ if (args.data !== void 0) {
1206
+ const entries = Object.entries(args.data);
1207
+ if (entries.some(([, value]) => typeof value !== "string")) throw new ToolFailure('data values must be text, e.g. {"count": "3"}. Nothing was sent.');
1208
+ if (jsonSize(args.data) > MAX_DATA_BYTES) throw new ToolFailure("data is larger than the 4 KB Firebase allows. Nothing was sent.");
1209
+ if (entries.length) message["data"] = args.data;
1210
+ }
1211
+ if (!message["notification"] && !message["data"] && !args.android && !args.apns && !args.webpush) {
1212
+ throw new ToolFailure("The message is empty: give title and body, data, or platform options. Nothing was sent.");
1213
+ }
1214
+ const androidNotification = compact({ channel_id: args.android_channel_id, click_action: args.click_action, sound: args.sound });
1215
+ const android = compact({
1216
+ priority: args.priority?.toUpperCase(),
1217
+ ttl: args.ttl_seconds !== void 0 ? `${args.ttl_seconds}s` : void 0,
1218
+ collapse_key: args.collapse_key,
1219
+ notification: Object.keys(androidNotification).length ? androidNotification : void 0
1220
+ });
1221
+ const aps = compact({ sound: args.sound, badge: args.badge, "mutable-content": args.image_url ? 1 : void 0 });
1222
+ const apnsHeaders = compact({
1223
+ "apns-priority": args.priority ? args.priority === "high" ? "10" : "5" : void 0,
1224
+ "apns-collapse-id": args.collapse_key,
1225
+ "apns-expiration": args.ttl_seconds !== void 0 ? String(Math.floor(Date.now() / 1e3) + args.ttl_seconds) : void 0
1226
+ });
1227
+ const apns = compact({
1228
+ headers: Object.keys(apnsHeaders).length ? apnsHeaders : void 0,
1229
+ payload: Object.keys(aps).length ? { aps } : void 0,
1230
+ fcm_options: args.image_url ? { image: args.image_url } : void 0
1231
+ });
1232
+ if (Object.keys(android).length || args.android) message["android"] = merge(android, args.android);
1233
+ if (Object.keys(apns).length || args.apns) message["apns"] = merge(apns, args.apns);
1234
+ if (args.webpush) message["webpush"] = args.webpush;
1235
+ if (args.analytics_label) message["fcm_options"] = { analytics_label: args.analytics_label };
1236
+ return message;
1237
+ }
1238
+ function targetOf(message) {
1239
+ if (typeof message["topic"] === "string") return `topic ${message["topic"]}`;
1240
+ if (typeof message["condition"] === "string") return `condition ${truncate(message["condition"], 200)}`;
1241
+ return "one device token";
1242
+ }
1243
+ function preview(message) {
1244
+ return message["token"] !== void 0 ? { ...message, token: "(device token)" } : message;
1245
+ }
1246
+ var connector = defineConnector({
1247
+ vendor: "firebase",
1248
+ label: LABEL2,
1249
+ origins: [FCM_ORIGIN, TOKEN_ORIGIN],
1250
+ credentials: ["accounts"],
1251
+ credentialLabels: { accounts: "Firebase service accounts" },
1252
+ tools: [
1253
+ {
1254
+ name: "list_projects",
1255
+ kind: "read",
1256
+ title: "List the connected Firebase projects",
1257
+ description: "Lists the connected Firebase projects from the connection's settings, without calling Firebase: project id, app name, service account, the apps (platform and id) and the FCM topics with what each audience is. Use it to pick the project and the topic of a push. No topics means the app has none configured: send to a token, or to a topic every install subscribes to.",
1258
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1259
+ async run(_args, h) {
1260
+ return {
1261
+ projects: projects(h).map((project) => compact({
1262
+ project: project.projectId,
1263
+ appName: project.appName,
1264
+ serviceAccount: project.clientEmail,
1265
+ apps: project.apps.length ? project.apps : void 0,
1266
+ topics: project.topics
1267
+ }))
1268
+ };
1269
+ }
1270
+ },
1271
+ {
1272
+ name: "check_projects",
1273
+ kind: "read",
1274
+ title: "Check the Firebase connection",
1275
+ description: "Checks every connected project with Firebase: signs in with its service account and has Firebase validate a test message without delivering it. Returns ok per project, or Firebase's reason for the first one that fails.",
1276
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1277
+ async run(_args, h) {
1278
+ const all = projects(h);
1279
+ const results = [];
1280
+ for (const project of all) {
1281
+ try {
1282
+ await send(h, project, { message: { topic: CHECK_TOPIC, notification: { title: "Connection check", body: "Connection check" } } }, { validateOnly: true });
1283
+ } catch (error) {
1284
+ if (error instanceof ToolFailure && all.length > 1) {
1285
+ throw new ToolFailure(`The Firebase project ${project.projectId} (${results.length + 1} of ${all.length}) failed the check: ${error.message}`, error.details);
1286
+ }
1287
+ throw error;
1288
+ }
1289
+ results.push({ project: project.projectId, appName: project.appName, ok: true });
1290
+ }
1291
+ return { projects: results };
1292
+ }
1293
+ },
1294
+ {
1295
+ name: "validate_message",
1296
+ kind: "read",
1297
+ title: "Validate a Firebase push message",
1298
+ description: "Has Firebase check a push message without delivering it: the same arguments as send_message. Returns the message as it would be sent, or Firebase's reason for refusing it.",
1299
+ inputSchema: { type: "object", properties: MESSAGE_PROPERTIES, additionalProperties: false },
1300
+ async run(args, h) {
1301
+ const project = projectFor(projects(h), args.project);
1302
+ const message = buildMessage(args);
1303
+ await send(h, project, { message }, { validateOnly: true });
1304
+ return { valid: true, project: project.projectId, appName: project.appName, target: targetOf(message), message: preview(message) };
1305
+ }
1306
+ },
1307
+ {
1308
+ name: "send_message",
1309
+ kind: "create",
1310
+ check: "list_projects",
1311
+ title: "Send a Firebase push notification",
1312
+ description: "Sends a push notification through Firebase Cloud Messaging to the users subscribed to a topic, to a condition of topics, or to one device token: title, text, optional image, data for the app, and Android and iOS options (channel, sound, badge, priority, time to live, collapse key). It is delivered at once and cannot be recalled; validate_message checks it first. Returns the message id.",
1313
+ inputSchema: { type: "object", properties: MESSAGE_PROPERTIES, additionalProperties: false },
1314
+ async run(args, h) {
1315
+ const project = projectFor(projects(h), args.project);
1316
+ const message = buildMessage(args);
1317
+ try {
1318
+ const { data } = await send(h, project, { message }, { validateOnly: false });
1319
+ return compact({ sent: true, project: project.projectId, appName: project.appName, target: targetOf(message), messageId: data?.name });
1320
+ } catch (error) {
1321
+ if (error instanceof OutcomeUnknown) {
1322
+ throw new ToolFailure(
1323
+ `${error.message.replace("whether the change was made", "whether the message was sent")} Firebase keeps no list of sent messages to look it up: send it again only if a second notification is acceptable.`,
1324
+ { outcome: "unknown" }
1325
+ );
1326
+ }
1327
+ throw error;
1328
+ }
1329
+ }
1330
+ }
1331
+ ]
1332
+ });
1333
+ module.exports = connector;