@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.
Files changed (67) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1131 -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 +1 -1
@@ -0,0 +1,2511 @@
1
+ /* shopify connector module (MIT License). Built from src/vendors/shopify; 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(text) {
24
+ return encoder.encode(text);
25
+ }
26
+ function utf8Length(text) {
27
+ return encoder.encode(text).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(text) {
43
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
44
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.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
+ async function sha256Hex(text) {
51
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(text)));
52
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
53
+ }
54
+ function truncate(text, max) {
55
+ if (text.length <= max) return text;
56
+ const points = Array.from(text);
57
+ if (points.length <= max) return text;
58
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
59
+ }
60
+ function cleanVendorText(text, max = 300) {
61
+ if (typeof text !== "string") return void 0;
62
+ if (/^\s*</.test(text)) return void 0;
63
+ const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
64
+ return line ? truncate(line, max) : void 0;
65
+ }
66
+ function formatNumber(value) {
67
+ return value.toLocaleString("en-US");
68
+ }
69
+
70
+ // src/core/output.ts
71
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
72
+ function jsonSize(value) {
73
+ return utf8Length(JSON.stringify(value) ?? "");
74
+ }
75
+ function cutStrings(value, max) {
76
+ if (typeof value === "string") return truncate(value, max);
77
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
78
+ if (typeof value === "object" && value !== null) {
79
+ const out = {};
80
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
81
+ return out;
82
+ }
83
+ return value;
84
+ }
85
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
86
+ if (jsonSize(value) <= limit) return { value, truncated: false };
87
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
88
+ const cut = cutStrings(value, max);
89
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
90
+ }
91
+ return void 0;
92
+ }
93
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
94
+ const build = (count) => {
95
+ const cut = count < input.items.length;
96
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
97
+ const next = cut ? input.resumeAt(count) : input.nextPage;
98
+ if (next) result2["nextCursor"] = next;
99
+ if (cut) result2["truncated"] = true;
100
+ return result2;
101
+ };
102
+ const all = build(input.items.length);
103
+ if (jsonSize(all) <= limit) return all;
104
+ let low = 1;
105
+ let high = input.items.length - 1;
106
+ while (low < high) {
107
+ const middle = Math.ceil((low + high) / 2);
108
+ if (jsonSize(build(middle)) <= limit) low = middle;
109
+ else high = middle - 1;
110
+ }
111
+ const best = build(low);
112
+ if (jsonSize(best) <= limit) return best;
113
+ const shrunk = shrinkToFit(best, limit);
114
+ if (shrunk) return { ...shrunk.value, truncated: true };
115
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
116
+ }
117
+ function encodeCursor(tool, state) {
118
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
119
+ }
120
+ function decodeCursor(tool, cursor) {
121
+ if (cursor === void 0 || cursor === "") return null;
122
+ try {
123
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
124
+ if (typeof state === "object" && state !== null && state.t === tool) {
125
+ return state;
126
+ }
127
+ } catch {
128
+ }
129
+ throw new ToolFailure(
130
+ "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."
131
+ );
132
+ }
133
+
134
+ // src/core/credentials.ts
135
+ function requiredAlternatives(module2) {
136
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
137
+ }
138
+ function unmetAlternatives(alternatives, has) {
139
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
140
+ if (lacking.some((list) => list.length === 0)) return [];
141
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
142
+ }
143
+ function andList(items) {
144
+ if (items.length <= 2) return items.join(" and ");
145
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
146
+ }
147
+ function orList(items) {
148
+ if (items.length <= 1) return items.join("");
149
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
150
+ }
151
+
152
+ // src/core/files.ts
153
+ var ATTACHMENT_URI = "attachment:///";
154
+ var MAX_NAME = 200;
155
+ function fileLimitOf(ctx) {
156
+ const maxBytes = ctx.files?.maxBytes;
157
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
158
+ }
159
+ function fileName(name2) {
160
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
161
+ const points = Array.from(clean);
162
+ if (points.length <= MAX_NAME) return clean || "file";
163
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
164
+ return points.slice(0, MAX_NAME - extension.length).join("") + extension;
165
+ }
166
+ function fileType(mimeType) {
167
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
168
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
169
+ }
170
+ function resourceBlock(file) {
171
+ return {
172
+ type: "resource",
173
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
174
+ };
175
+ }
176
+
177
+ // src/core/http.ts
178
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
179
+ var USER_AGENT = "agent-connectors";
180
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
181
+ function errorCode(error) {
182
+ const code = error?.code;
183
+ return typeof code === "string" ? code : void 0;
184
+ }
185
+ function describe(error) {
186
+ const name2 = error?.name;
187
+ const code = errorCode(error);
188
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
189
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
190
+ if (code === "TOO_LARGE") return "the reply was too large";
191
+ return cleanVendorText(error?.message, 200) ?? "a network error";
192
+ }
193
+ function retryAfterSeconds(headers, now = Date.now()) {
194
+ const retryAfter = headers.get("retry-after");
195
+ if (retryAfter) {
196
+ const seconds = Number(retryAfter);
197
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
198
+ const date = Date.parse(retryAfter);
199
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
200
+ }
201
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
202
+ if (reset) {
203
+ const value = Number(reset);
204
+ if (Number.isFinite(value) && value >= 0) {
205
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
206
+ }
207
+ }
208
+ return void 0;
209
+ }
210
+ function vendorCode(data) {
211
+ if (typeof data !== "object" || data === null) return void 0;
212
+ for (const key of ["error", "code"]) {
213
+ const value = data[key];
214
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
215
+ }
216
+ return void 0;
217
+ }
218
+ function vendorMessage(data) {
219
+ if (typeof data === "string") return cleanVendorText(data);
220
+ if (typeof data !== "object" || data === null) return void 0;
221
+ const record = data;
222
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
223
+ const value = record[key];
224
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
225
+ const nested = value?.message;
226
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
227
+ }
228
+ if (Array.isArray(record["errors"])) {
229
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
230
+ if (messages.length) return cleanVendorText(messages.join("; "));
231
+ }
232
+ return void 0;
233
+ }
234
+ var TooLarge = class extends Error {
235
+ constructor(limit) {
236
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
237
+ this.limit = limit;
238
+ }
239
+ limit;
240
+ };
241
+ async function readCapped(response, maxBytes) {
242
+ const declared = Number(response.headers.get("content-length"));
243
+ if (Number.isFinite(declared) && declared > maxBytes) {
244
+ await response.body?.cancel().catch(() => {
245
+ });
246
+ throw new TooLarge(maxBytes);
247
+ }
248
+ if (!response.body) return new Uint8Array(0);
249
+ const reader = response.body.getReader();
250
+ const chunks = [];
251
+ let total = 0;
252
+ for (; ; ) {
253
+ const { done, value } = await reader.read();
254
+ if (done) break;
255
+ total += value.byteLength;
256
+ if (total > maxBytes) {
257
+ await reader.cancel().catch(() => {
258
+ });
259
+ throw new TooLarge(maxBytes);
260
+ }
261
+ chunks.push(value);
262
+ }
263
+ const bytes = new Uint8Array(total);
264
+ let offset = 0;
265
+ for (const chunk of chunks) {
266
+ bytes.set(chunk, offset);
267
+ offset += chunk.byteLength;
268
+ }
269
+ return bytes;
270
+ }
271
+ function parseBody(bytes, contentType) {
272
+ if (bytes.length === 0) return null;
273
+ const text = utf8Decode(bytes);
274
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
275
+ try {
276
+ return JSON.parse(text);
277
+ } catch {
278
+ }
279
+ }
280
+ return text;
281
+ }
282
+ function createHttp(env) {
283
+ const { label, ctx } = env;
284
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
285
+ 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.`;
286
+ function failureFor(status, headers, data, request) {
287
+ const message = vendorMessage(data);
288
+ const said = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
289
+ const retryAfter = retryAfterSeconds(headers);
290
+ const code = vendorCode(data);
291
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
292
+ const custom = request.errors?.[status];
293
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
294
+ if (status >= 500) {
295
+ if (request.write) {
296
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said}, so it is not known whether the change was made.`);
297
+ }
298
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. Try again later.${nothingChanged}`), { status, ...extra });
299
+ }
300
+ if (status === 429) {
301
+ return new ToolFailure(
302
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
303
+ { status, ...extra }
304
+ );
305
+ }
306
+ if (status === 401) {
307
+ return new ToolFailure(
308
+ withCustom(`${label} rejected the credentials (HTTP 401)${said}. ${checkCredentials}${nothingChanged}`),
309
+ { status, ...extra }
310
+ );
311
+ }
312
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
313
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
314
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${nothingChanged}`), { status, ...extra });
315
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
316
+ }
317
+ async function api(request) {
318
+ const method = request.method ?? "GET";
319
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
320
+ throw new Error(`read-only tool sent ${method}`);
321
+ }
322
+ const origin = request.origin ?? env.origins[0];
323
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
324
+ const url = new URL(request.path, origin);
325
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
326
+ for (const [key, value] of Object.entries(request.query ?? {})) {
327
+ if (value === void 0 || value === null) continue;
328
+ if (Array.isArray(value)) {
329
+ url.searchParams.delete(key);
330
+ for (const item of value) url.searchParams.append(key, String(item));
331
+ } else {
332
+ url.searchParams.set(key, String(value));
333
+ }
334
+ }
335
+ const headers = {
336
+ accept: "application/json",
337
+ "user-agent": USER_AGENT,
338
+ ...request.auth === false ? {} : env.authHeaders(),
339
+ ...request.headers
340
+ };
341
+ let body;
342
+ if (request.json !== void 0) {
343
+ body = JSON.stringify(request.json);
344
+ headers["content-type"] = "application/json";
345
+ } else if (request.body) {
346
+ body = request.body;
347
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
348
+ }
349
+ const started = Date.now();
350
+ if (request.write) env.onWriteSent();
351
+ let response;
352
+ try {
353
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
354
+ } catch (error) {
355
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
356
+ if (errorCode(error) === "URL_REFUSED") {
357
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
358
+ }
359
+ if (request.write) {
360
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
361
+ }
362
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
363
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
364
+ }
365
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
366
+ let bytes;
367
+ try {
368
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
369
+ } catch (error) {
370
+ if (request.write && (response.ok || response.status >= 500)) {
371
+ 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.`);
372
+ }
373
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
374
+ }
375
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
376
+ if (response.ok) return { status: response.status, headers: response.headers, data };
377
+ throw failureFor(response.status, response.headers, data, request);
378
+ }
379
+ async function media(rawUrl, options) {
380
+ const { what } = options;
381
+ let url;
382
+ try {
383
+ url = new URL(rawUrl);
384
+ } catch {
385
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
386
+ }
387
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
388
+ const started = Date.now();
389
+ let response;
390
+ try {
391
+ response = await ctx.fetch(url.toString(), {
392
+ method: "GET",
393
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
394
+ ...ctx.signal ? { signal: ctx.signal } : {}
395
+ });
396
+ } catch (error) {
397
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
398
+ if (errorCode(error) === "URL_REFUSED") {
399
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
400
+ }
401
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
402
+ }
403
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
404
+ if (!response.ok) {
405
+ await response.body?.cancel().catch(() => {
406
+ });
407
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
408
+ }
409
+ try {
410
+ const bytes = await readCapped(response, options.maxBytes);
411
+ return { bytes, contentType: response.headers.get("content-type") };
412
+ } catch (error) {
413
+ if (error instanceof TooLarge) {
414
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
415
+ }
416
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
417
+ }
418
+ }
419
+ return { api, media };
420
+ }
421
+
422
+ // src/core/origins.ts
423
+ function parseSiteUrl(value) {
424
+ const text = typeof value === "string" ? value.trim() : "";
425
+ if (!text) return { ok: false, problem: "is empty" };
426
+ let url;
427
+ try {
428
+ url = new URL(text.includes("://") ? text : `https://${text}`);
429
+ } catch {
430
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
431
+ }
432
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
433
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
434
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
435
+ return { ok: true, url, origin: url.origin };
436
+ }
437
+
438
+ // src/core/schema.ts
439
+ var patterns = /* @__PURE__ */ new Map();
440
+ function patternOf(source) {
441
+ let compiled = patterns.get(source);
442
+ if (!compiled) {
443
+ compiled = new RegExp(source, "u");
444
+ patterns.set(source, compiled);
445
+ }
446
+ return compiled;
447
+ }
448
+ function isPlainObject(value) {
449
+ return typeof value === "object" && value !== null && !Array.isArray(value);
450
+ }
451
+ function isHttpUrl(value) {
452
+ try {
453
+ const url = new URL(value);
454
+ return url.protocol === "https:" || url.protocol === "http:";
455
+ } catch {
456
+ return false;
457
+ }
458
+ }
459
+ function name(path) {
460
+ return `\`${path}\``;
461
+ }
462
+ function child(path, key) {
463
+ return path ? `${path}.${key}` : key;
464
+ }
465
+ function checkValue(schema, value, path, issues) {
466
+ switch (schema.type) {
467
+ case "object":
468
+ checkObject(schema, value, path, issues);
469
+ return;
470
+ case "array": {
471
+ if (!Array.isArray(value)) {
472
+ issues.push(`${name(path)} must be an array`);
473
+ return;
474
+ }
475
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
476
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
477
+ }
478
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
479
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
480
+ }
481
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
482
+ issues.push(`${name(path)} must not repeat an item`);
483
+ }
484
+ if (schema.items) {
485
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
486
+ }
487
+ break;
488
+ }
489
+ case "string": {
490
+ if (typeof value !== "string") {
491
+ issues.push(`${name(path)} must be a string`);
492
+ return;
493
+ }
494
+ const length = Array.from(value).length;
495
+ if (schema.minLength !== void 0 && length < schema.minLength) {
496
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
497
+ }
498
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
499
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
500
+ }
501
+ if (schema.format === "uri" && !isHttpUrl(value)) {
502
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
503
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
504
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
505
+ }
506
+ break;
507
+ }
508
+ case "integer":
509
+ case "number": {
510
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
511
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
512
+ return;
513
+ }
514
+ if (schema.minimum !== void 0 && value < schema.minimum) {
515
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
516
+ }
517
+ if (schema.maximum !== void 0 && value > schema.maximum) {
518
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
519
+ }
520
+ break;
521
+ }
522
+ case "boolean":
523
+ if (typeof value !== "boolean") {
524
+ issues.push(`${name(path)} must be true or false`);
525
+ return;
526
+ }
527
+ break;
528
+ default:
529
+ break;
530
+ }
531
+ if (schema.enum && !schema.enum.includes(value)) {
532
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
533
+ }
534
+ }
535
+ function checkObject(schema, value, path, issues) {
536
+ if (!isPlainObject(value)) {
537
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
538
+ return;
539
+ }
540
+ const properties = schema.properties ?? {};
541
+ for (const key of schema.required ?? []) {
542
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
543
+ }
544
+ const unknown = [];
545
+ for (const [key, item] of Object.entries(value)) {
546
+ const property = properties[key];
547
+ if (!property) {
548
+ if (schema.additionalProperties === false) unknown.push(key);
549
+ continue;
550
+ }
551
+ if (item === void 0 || item === null) continue;
552
+ checkValue(property, item, child(path, key), issues);
553
+ }
554
+ if (unknown.length) {
555
+ const known = Object.keys(properties);
556
+ 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(", ")})` : ""));
557
+ }
558
+ }
559
+ function copyDefault(value) {
560
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
561
+ }
562
+ function validateArguments(schema, args) {
563
+ const input = args === void 0 || args === null ? {} : args;
564
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
565
+ const value = { ...input };
566
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
567
+ const issues = [];
568
+ checkObject(schema, value, "", issues);
569
+ if (issues.length) return { ok: false, issues };
570
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
571
+ if (value[key] === null) delete value[key];
572
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
573
+ }
574
+ return { ok: true, value };
575
+ }
576
+
577
+ // src/core/upload-hosts.ts
578
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
579
+ function uploadHostProblem(entry) {
580
+ if (typeof entry !== "string") return "must be a host name";
581
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
582
+ const labels = name2.split(".");
583
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
584
+ 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";
585
+ }
586
+ if (labels.length < 2) return "needs at least two labels, like example.com";
587
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
588
+ return void 0;
589
+ }
590
+
591
+ // src/core/connector.ts
592
+ var ANNOTATIONS = {
593
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
594
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
595
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
596
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
597
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
598
+ };
599
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
600
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
601
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
602
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
603
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
604
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
605
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
606
+ function deepFreeze(value) {
607
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
608
+ Object.freeze(value);
609
+ for (const item of Object.values(value)) deepFreeze(item);
610
+ }
611
+ return value;
612
+ }
613
+ function assertDefinition(def) {
614
+ const problem = (message) => {
615
+ throw new Error(`connector "${def.vendor}": ${message}`);
616
+ };
617
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
618
+ if (!def.label?.trim()) problem("label is required");
619
+ const originFields = def.originFields ?? [];
620
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
621
+ for (const origin of def.origins) {
622
+ let url;
623
+ try {
624
+ url = new URL(origin);
625
+ } catch {
626
+ }
627
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
628
+ }
629
+ for (const name2 of def.credentials) {
630
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
631
+ }
632
+ for (const [index, name2] of originFields.entries()) {
633
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
634
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
635
+ }
636
+ const names = /* @__PURE__ */ new Set();
637
+ for (const tool of def.tools) {
638
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
639
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
640
+ names.add(tool.name);
641
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
642
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
643
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
644
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
645
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
646
+ }
647
+ }
648
+ for (const tool of def.tools) {
649
+ if (tool.kind === "read") continue;
650
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
651
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
652
+ }
653
+ assertUploadHosts(def, problem);
654
+ assertRequiredCredentials(def, problem);
655
+ assertAccountPickers(def, problem);
656
+ }
657
+ function assertUploadHosts(def, problem) {
658
+ const hosts = def.uploadHosts;
659
+ if (hosts === void 0) return;
660
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
661
+ hosts.forEach((entry, index) => {
662
+ const wrong = uploadHostProblem(entry);
663
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
664
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
665
+ });
666
+ }
667
+ function assertRequiredCredentials(def, problem) {
668
+ const required = def.requiredCredentials;
669
+ if (required === void 0) return;
670
+ if (!Array.isArray(required) || !required.length) {
671
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
672
+ }
673
+ required.forEach((list, index) => {
674
+ const which = `requiredCredentials[${index}]`;
675
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
676
+ list.forEach((name2, position) => {
677
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
678
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
679
+ });
680
+ });
681
+ const lists = required;
682
+ lists.forEach((list, index) => {
683
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
684
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
685
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
686
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
687
+ }
688
+ });
689
+ }
690
+ function isDotPath(value) {
691
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
692
+ }
693
+ function assertAccountPickers(def, problem) {
694
+ const pickers = def.accountPickers;
695
+ if (pickers === void 0) return;
696
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
697
+ const keys = /* @__PURE__ */ new Set();
698
+ for (const item of pickers) {
699
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
700
+ const picker = item;
701
+ const key = picker["key"];
702
+ 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}$`);
703
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
704
+ keys.add(key);
705
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
706
+ const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
707
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
708
+ const { label, description, multiple, legacyField } = picker;
709
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
710
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
711
+ fail("description, when given, must be a text of 1 to 1024 characters");
712
+ }
713
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
714
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
715
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
716
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
717
+ for (const field of ["idField", "nameField"]) {
718
+ if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
719
+ }
720
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
721
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
722
+ }
723
+ }
724
+ }
725
+ function copyPicker(picker) {
726
+ return {
727
+ key: picker.key,
728
+ label: picker.label,
729
+ ...picker.description !== void 0 ? { description: picker.description } : {},
730
+ multiple: picker.multiple,
731
+ tool: picker.tool,
732
+ idField: picker.idField,
733
+ nameField: picker.nameField,
734
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
735
+ };
736
+ }
737
+ function result(payload, isError, files = []) {
738
+ return {
739
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
740
+ ...isError ? { isError: true } : {}
741
+ };
742
+ }
743
+ function failure(message, details = {}) {
744
+ return result({ error: message, ...details }, true);
745
+ }
746
+ function trimmed(values) {
747
+ const out = {};
748
+ if (typeof values !== "object" || values === null) return out;
749
+ for (const [key, value] of Object.entries(values)) {
750
+ if (value === void 0 || value === null) continue;
751
+ const text = String(value).trim();
752
+ if (text) out[key] = text;
753
+ }
754
+ return out;
755
+ }
756
+ function defineConnector(def) {
757
+ assertDefinition(def);
758
+ const { label } = def;
759
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
760
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
761
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
762
+ const required = requiredAlternatives(def);
763
+ const notConnected = (unmet) => {
764
+ const [first] = unmet;
765
+ if (unmet.length === 1 && first) {
766
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
767
+ }
768
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
769
+ };
770
+ const descriptors = def.tools.map((tool) => ({
771
+ name: tool.name,
772
+ title: tool.title,
773
+ description: tool.description,
774
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
775
+ annotations: { ...ANNOTATIONS[tool.kind] }
776
+ }));
777
+ async function call(toolName, args, ctx) {
778
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
779
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
780
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
781
+ const log = (text) => {
782
+ try {
783
+ ctx.log?.(text);
784
+ } catch {
785
+ }
786
+ };
787
+ const given = trimmed(ctx.credentials);
788
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
789
+ const has = (name2) => Boolean(credentials[name2]);
790
+ const unmet = unmetAlternatives(required, has);
791
+ if (unmet.length) return failure(notConnected(unmet));
792
+ const complete = required.filter((list) => list.every(has));
793
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
794
+ const fieldOrigins = /* @__PURE__ */ new Map();
795
+ for (const name2 of def.originFields ?? []) {
796
+ if (!given[name2] && !inUse.includes(name2)) continue;
797
+ const site = parseSiteUrl(given[name2] ?? "");
798
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
799
+ fieldOrigins.set(name2, site.origin);
800
+ }
801
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
802
+ const parsed = validateArguments(tool.inputSchema, args);
803
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
804
+ const frozenCredentials = Object.freeze({ ...credentials });
805
+ let writeSent = false;
806
+ const fileLimit = fileLimitOf(ctx);
807
+ const files = [];
808
+ let fileBytes = 0;
809
+ const http = createHttp({
810
+ vendor: def.vendor,
811
+ label,
812
+ tool: tool.name,
813
+ readOnly: tool.kind === "read",
814
+ origins,
815
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
816
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
817
+ ctx,
818
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
819
+ log,
820
+ onWriteSent: () => {
821
+ writeSent = true;
822
+ }
823
+ });
824
+ const helpers = {
825
+ tool: tool.name,
826
+ credentials: frozenCredentials,
827
+ ctx,
828
+ origins: Object.freeze([...origins]),
829
+ originOf: (credential) => {
830
+ const origin = fieldOrigins.get(credential);
831
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
832
+ return origin;
833
+ },
834
+ api: http.api,
835
+ media: http.media,
836
+ page: (input) => fitPage(input),
837
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
838
+ makeCursor: (state) => encodeCursor(tool.name, state),
839
+ fileLimit: () => fileLimit,
840
+ file: ({ name: name2, mimeType, bytes }) => {
841
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
842
+ const total = fileBytes + bytes.byteLength;
843
+ if (total > fileLimit) {
844
+ 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.`);
845
+ }
846
+ fileBytes = total;
847
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
848
+ files.push({ ...info, bytes });
849
+ return { ...info };
850
+ },
851
+ log
852
+ };
853
+ try {
854
+ const data = await tool.run(parsed.value, helpers);
855
+ const fitted = shrinkToFit(data ?? {});
856
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
857
+ const payload = fitted.value;
858
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
859
+ } catch (error) {
860
+ if (error instanceof OutcomeUnknown) {
861
+ return result({
862
+ outcome: "unknown",
863
+ check: tool.check,
864
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
865
+ }, true);
866
+ }
867
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
868
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
869
+ if (writeSent) {
870
+ return result({
871
+ outcome: "unknown",
872
+ check: tool.check,
873
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
874
+ }, true);
875
+ }
876
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
877
+ }
878
+ }
879
+ return deepFreeze({
880
+ vendor: def.vendor,
881
+ origins: [...def.origins],
882
+ originFields: [...def.originFields ?? []],
883
+ uploadHosts: [...def.uploadHosts ?? []],
884
+ credentials: [...def.credentials],
885
+ requiredCredentials: required.map((list) => [...list]),
886
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
887
+ tools: descriptors,
888
+ call
889
+ });
890
+ }
891
+
892
+ // src/core/jwt.ts
893
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
894
+
895
+ // src/vendors/shopify/graphql.ts
896
+ var API_VERSION = "2026-07";
897
+ var SHOP_HOST = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.myshopify\.com$/;
898
+ function shopOrigin(h) {
899
+ const origin = h.originOf("shopdomain");
900
+ const url = new URL(origin);
901
+ if (!SHOP_HOST.test(url.hostname) || url.port) {
902
+ throw new ToolFailure(
903
+ `The Shopify shop domain must be the store's own <shop>.myshopify.com address (Shopify admin \u2192 Settings \u2192 Domains lists it), not ${url.host}. Nothing was sent to Shopify.`
904
+ );
905
+ }
906
+ return origin;
907
+ }
908
+ function readCost(extensions) {
909
+ const cost = extensions?.cost;
910
+ if (typeof cost !== "object" || cost === null) return void 0;
911
+ const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
912
+ return {
913
+ requested: number(cost.requestedQueryCost),
914
+ actual: number(cost.actualQueryCost),
915
+ available: number(cost.throttleStatus?.currentlyAvailable),
916
+ restoreRate: number(cost.throttleStatus?.restoreRate)
917
+ };
918
+ }
919
+ function waitSeconds(cost) {
920
+ if (!cost || cost.requested === void 0 || cost.available === void 0 || !cost.restoreRate) return void 0;
921
+ return Math.max(1, Math.ceil((cost.requested - cost.available) / cost.restoreRate));
922
+ }
923
+ async function graphql(h, query, variables = {}, options = {}) {
924
+ const origin = shopOrigin(h);
925
+ const nothing = options.write ? " Nothing was changed." : "";
926
+ const { data: body } = await h.api({
927
+ method: "POST",
928
+ origin,
929
+ path: `/admin/api/${API_VERSION}/graphql.json`,
930
+ json: { query, variables, ...options.operationName ? { operationName: options.operationName } : {} },
931
+ ...options.write ? { write: true } : { safe: true },
932
+ errors: {
933
+ 402: "Shopify refused the request: the store is frozen or has no active plan",
934
+ 403: "Shopify refused the request: the app lacks an access scope, or the staff permission, for it",
935
+ 404: "Shopify found no store API at that address: check the shop domain (<shop>.myshopify.com)",
936
+ 423: "Shopify refused the request: the store is locked"
937
+ }
938
+ });
939
+ if (typeof body !== "object" || body === null) {
940
+ if (options.write) throw new OutcomeUnknown("Shopify answered with something other than GraphQL JSON, so it is not known whether the change was made.");
941
+ throw new ToolFailure("Shopify answered with something other than GraphQL JSON.");
942
+ }
943
+ const errors = Array.isArray(body.errors) ? body.errors : typeof body.errors === "string" ? [{ message: body.errors }] : [];
944
+ const cost = readCost(body.extensions) ?? errors.map((error) => readCost(error?.extensions)).find(Boolean);
945
+ if (!errors.length) return { data: body.data ?? {}, warnings: [], ...cost ? { cost } : {} };
946
+ const codes = errors.map((error) => typeof error?.extensions?.code === "string" ? error.extensions.code : void 0);
947
+ const messages = errors.map((error) => cleanVendorText(error?.message, 300)).filter((message) => Boolean(message));
948
+ const said = [...new Set(messages)].slice(0, 5).join("; ") || "it answered with errors";
949
+ if (codes.includes("THROTTLED")) {
950
+ const retryAfter = waitSeconds(cost);
951
+ throw new ToolFailure(
952
+ `Shopify rate limit reached (the request costs more than the app has left right now).${nothing} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a few seconds before retrying."),
953
+ { vendorCode: "THROTTLED", ...retryAfter !== void 0 ? { retryAfter } : {} }
954
+ );
955
+ }
956
+ if (options.write && codes.some((code2) => code2 === "INTERNAL_SERVER_ERROR" || code2 === "TIMEOUT")) {
957
+ throw new OutcomeUnknown(`Shopify reported an internal error (${said}), so it is not known whether the change was made.`);
958
+ }
959
+ const hasData = typeof body.data === "object" && body.data !== null && Object.values(body.data).some((value) => value !== null);
960
+ if (hasData) return { data: body.data, warnings: [...new Set(messages)], ...cost ? { cost } : {} };
961
+ const code = codes.find((item) => item !== void 0);
962
+ const hint = code === "ACCESS_DENIED" ? " The app may lack an access scope, or protected customer data access, for this." : code === "MAX_COST_EXCEEDED" ? " Ask for fewer items or fields." : "";
963
+ throw new ToolFailure(`Shopify did not run the request: ${said.replace(/[.!]+$/, "")}.${hint}${nothing}`, code ? { vendorCode: code } : {});
964
+ }
965
+ function userErrorText(list) {
966
+ if (!Array.isArray(list) || !list.length) return void 0;
967
+ return list.slice(0, 10).map((error) => {
968
+ const field = Array.isArray(error?.field) && error.field.length ? error.field.join(".") : void 0;
969
+ const message = cleanVendorText(error?.message, 300) ?? "refused";
970
+ return field ? `${field}: ${message}` : message;
971
+ }).join("; ");
972
+ }
973
+ function assertNoUserErrors(payload, what) {
974
+ const text = userErrorText(payload?.userErrors);
975
+ if (!text) return;
976
+ const code = payload.userErrors.find((error) => typeof error?.code === "string")?.code;
977
+ throw new ToolFailure(`Shopify did not ${what}: ${text.replace(/[.!]+$/, "")}. Nothing was changed.`, code ? { vendorCode: code } : {});
978
+ }
979
+ function gid(type, value, argument) {
980
+ const text = String(value).trim();
981
+ if (/^\d{1,20}$/.test(text)) return `gid://shopify/${type}/${text}`;
982
+ if (new RegExp(`^gid://shopify/${type}/\\d{1,20}(\\?[\\w=&.-]{1,200})?$`).test(text)) return text;
983
+ throw new ToolFailure(`${argument} must be a ${type} id: a number, or gid://shopify/${type}/<number>. Nothing was sent.`);
984
+ }
985
+ function searchValue(value) {
986
+ return /^[A-Za-z0-9_.@#-]+$/.test(value) ? value : `"${value.replace(/[\\"]/g, (char) => `\\${char}`)}"`;
987
+ }
988
+ async function idempotencyKey(parts) {
989
+ const window = Math.floor(Date.now() / (15 * 60 * 1e3));
990
+ const hex = await sha256Hex(JSON.stringify([parts, window]));
991
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-${(parseInt(hex[16], 16) & 3 | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
992
+ }
993
+ function invalidCursor() {
994
+ return new ToolFailure("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.");
995
+ }
996
+ function listPosition(h, schema, args) {
997
+ const state = h.cursor(args["cursor"]);
998
+ if (!state) {
999
+ const { cursor: _cursor, ...filters } = args;
1000
+ return { skip: 0, filters };
1001
+ }
1002
+ let parsed;
1003
+ try {
1004
+ parsed = JSON.parse(String(state["f"] ?? "{}"));
1005
+ } catch {
1006
+ throw invalidCursor();
1007
+ }
1008
+ const checked = validateArguments(schema, parsed);
1009
+ const skip = Number(state["o"]);
1010
+ const after = state["a"];
1011
+ if (!checked.ok || "cursor" in checked.value || !Number.isInteger(skip) || skip < 0 || after !== void 0 && typeof after !== "string") throw invalidCursor();
1012
+ return { ...typeof after === "string" ? { after } : {}, skip, filters: checked.value };
1013
+ }
1014
+ function pageCursors(h, position, pageInfo) {
1015
+ const f = JSON.stringify(position.filters);
1016
+ const next = pageInfo?.hasNextPage === true && typeof pageInfo?.endCursor === "string" ? pageInfo.endCursor : void 0;
1017
+ return {
1018
+ resumeAt: (index) => h.makeCursor({ ...position.after ? { a: position.after } : {}, o: position.skip + index, f }),
1019
+ ...next ? { nextPage: h.makeCursor({ a: next, o: 0, f }) } : {}
1020
+ };
1021
+ }
1022
+ function lex(source) {
1023
+ const tokens = [];
1024
+ const length = source.length;
1025
+ let at = 0;
1026
+ const fail = (what) => {
1027
+ throw new ToolFailure(`The GraphQL document could not be read: ${what}. Nothing was sent.`);
1028
+ };
1029
+ while (at < length) {
1030
+ const char = source[at];
1031
+ if (char === " " || char === " " || char === "\n" || char === "\r" || char === "," || char === "\uFEFF") {
1032
+ at++;
1033
+ } else if (char === "#") {
1034
+ while (at < length && source[at] !== "\n" && source[at] !== "\r") at++;
1035
+ } else if (char === '"') {
1036
+ if (source.startsWith('"""', at)) {
1037
+ at += 3;
1038
+ while (at < length && !source.startsWith('"""', at)) at += source.startsWith('\\"""', at) ? 4 : 1;
1039
+ if (at >= length) fail("a block string is not closed");
1040
+ at += 3;
1041
+ } else {
1042
+ at++;
1043
+ while (at < length && source[at] !== '"') {
1044
+ if (source[at] === "\n" || source[at] === "\r") fail("a string is not closed");
1045
+ at += source[at] === "\\" ? 2 : 1;
1046
+ }
1047
+ if (at >= length) fail("a string is not closed");
1048
+ at++;
1049
+ }
1050
+ tokens.push({ kind: "value", text: '"' });
1051
+ } else if (char === ".") {
1052
+ if (!source.startsWith("...", at)) fail('a lone "."');
1053
+ tokens.push({ kind: "punct", text: "..." });
1054
+ at += 3;
1055
+ } else if ("!$&()[]{}:=@|".includes(char)) {
1056
+ tokens.push({ kind: "punct", text: char });
1057
+ at++;
1058
+ } else if (/[_A-Za-z]/.test(char)) {
1059
+ let end = at + 1;
1060
+ while (end < length && /[_0-9A-Za-z]/.test(source[end])) end++;
1061
+ tokens.push({ kind: "name", text: source.slice(at, end) });
1062
+ at = end;
1063
+ } else if (char === "-" || /[0-9]/.test(char)) {
1064
+ let end = at + 1;
1065
+ while (end < length && /[0-9eE.+-]/.test(source[end])) end++;
1066
+ tokens.push({ kind: "value", text: source.slice(at, end) });
1067
+ at = end;
1068
+ } else {
1069
+ fail(`an unexpected character at position ${at}`);
1070
+ }
1071
+ }
1072
+ return tokens;
1073
+ }
1074
+ function readDocument(source) {
1075
+ const tokens = lex(source);
1076
+ const operations = [];
1077
+ const names = /* @__PURE__ */ new Set();
1078
+ const directives = /* @__PURE__ */ new Set();
1079
+ tokens.forEach((token, index2) => {
1080
+ if (token.kind !== "name") return;
1081
+ names.add(token.text);
1082
+ if (tokens[index2 - 1]?.text === "@") directives.add(token.text);
1083
+ });
1084
+ const fail = (what) => {
1085
+ throw new ToolFailure(`The GraphQL document could not be read: ${what}. Nothing was sent.`);
1086
+ };
1087
+ const skipSelection = (open) => {
1088
+ let depth = 0;
1089
+ for (let index2 = open; index2 < tokens.length; index2++) {
1090
+ const text = tokens[index2].text;
1091
+ if (text === "{") depth++;
1092
+ else if (text === "}" && --depth === 0) return index2 + 1;
1093
+ }
1094
+ return fail('a "{" is not closed');
1095
+ };
1096
+ const selectionStart = (from) => {
1097
+ let parens = 0;
1098
+ for (let index2 = from; index2 < tokens.length; index2++) {
1099
+ const text = tokens[index2].text;
1100
+ if (text === "(") parens++;
1101
+ else if (text === ")") parens--;
1102
+ else if (text === "{" && parens === 0) return index2;
1103
+ }
1104
+ return fail("a definition has no selection set");
1105
+ };
1106
+ let index = 0;
1107
+ while (index < tokens.length) {
1108
+ const token = tokens[index];
1109
+ if (token.text === "{") {
1110
+ operations.push("query");
1111
+ index = skipSelection(index);
1112
+ } else if (token.kind === "name" && (token.text === "query" || token.text === "mutation" || token.text === "subscription")) {
1113
+ operations.push(token.text);
1114
+ index = skipSelection(selectionStart(index + 1));
1115
+ } else if (token.kind === "name" && token.text === "fragment") {
1116
+ index = skipSelection(selectionStart(index + 1));
1117
+ } else {
1118
+ fail("only query, mutation and fragment definitions can be sent");
1119
+ }
1120
+ }
1121
+ if (!operations.length) fail("it holds no operation");
1122
+ return { operations, names, directives };
1123
+ }
1124
+
1125
+ // src/vendors/shopify/index.ts
1126
+ var ID = (type, what) => ({ type: "string", pattern: `^(\\d{1,20}|gid://shopify/${type}/\\d{1,20})$`, description: `${what} (a number or gid://shopify/${type}/\u2026).` });
1127
+ var ID_LIST = (type, what) => ({ type: "array", items: ID(type, type), maxItems: 100, uniqueItems: true, description: what });
1128
+ var MONEY = (what) => ({ type: "string", pattern: "^\\d{1,12}(\\.\\d{1,4})?$", description: what });
1129
+ var CURSOR = { type: "string", description: "nextCursor from the previous result (the other arguments then come from it)." };
1130
+ var FIRST = (fallback) => ({ type: "integer", minimum: 1, maximum: 100, default: fallback, description: `Items per page, 1 to 100 (default ${fallback}).` });
1131
+ var SEARCH = (examples) => ({ type: "string", minLength: 1, maxLength: 1e3, description: `Shopify search syntax, e.g. ${examples}.` });
1132
+ var REVERSE = { type: "boolean", default: true, description: "Newest or highest first (default true)." };
1133
+ var STOCK_NAMES = ["available", "on_hand", "committed", "incoming", "reserved"];
1134
+ var INVENTORY_REASONS = ["correction", "cycle_count_available", "damaged", "received", "restock", "shrinkage", "promotion", "quality_control", "safety_stock", "other"];
1135
+ var IDEMPOTENT_MUTATIONS = ["inventoryActivate", "inventoryAdjustQuantities", "inventorySetQuantities", "inventoryMoveQuantities", "refundCreate"];
1136
+ var BLOCKED_MUTATIONS = [
1137
+ "webhookSubscriptionCreate",
1138
+ "webhookSubscriptionUpdate",
1139
+ "eventBridgeWebhookSubscriptionCreate",
1140
+ "eventBridgeWebhookSubscriptionUpdate",
1141
+ "pubSubWebhookSubscriptionCreate",
1142
+ "pubSubWebhookSubscriptionUpdate",
1143
+ "carrierServiceCreate",
1144
+ "carrierServiceUpdate",
1145
+ "fulfillmentServiceCreate",
1146
+ "fulfillmentServiceUpdate",
1147
+ "eventBridgeServerPixelUpdate",
1148
+ "pubSubServerPixelUpdate",
1149
+ "delegateAccessTokenCreate",
1150
+ "storefrontAccessTokenCreate",
1151
+ "bulkOperationRunMutation"
1152
+ ];
1153
+ function compact(value) {
1154
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
1155
+ }
1156
+ function amountOf(set) {
1157
+ const amount = set?.shopMoney?.amount ?? set?.amount;
1158
+ return typeof amount === "string" || typeof amount === "number" ? String(amount) : void 0;
1159
+ }
1160
+ function nonZero(value) {
1161
+ return value !== void 0 && Number(value) !== 0 ? value : void 0;
1162
+ }
1163
+ function withWarnings(result2, response) {
1164
+ return response.warnings.length ? { ...result2, warnings: response.warnings.slice(0, 5) } : result2;
1165
+ }
1166
+ function priceRange(range) {
1167
+ const low = range?.minVariantPrice?.amount;
1168
+ const high = range?.maxVariantPrice?.amount;
1169
+ if (low === void 0) return void 0;
1170
+ return high !== void 0 && Number(high) !== Number(low) ? `${low}\u2013${high}` : String(low);
1171
+ }
1172
+ function trimListProduct(product) {
1173
+ return compact({
1174
+ id: product?.id,
1175
+ title: typeof product?.title === "string" ? truncate(product.title, 300) : void 0,
1176
+ handle: product?.handle,
1177
+ status: product?.status,
1178
+ vendor: product?.vendor,
1179
+ productType: product?.productType,
1180
+ tags: Array.isArray(product?.tags) && product.tags.length ? product.tags.slice(0, 20) : void 0,
1181
+ price: priceRange(product?.priceRangeV2),
1182
+ currency: product?.priceRangeV2?.minVariantPrice?.currencyCode,
1183
+ variants: product?.variantsCount?.count,
1184
+ totalInventory: product?.tracksInventory ? product?.totalInventory : void 0,
1185
+ onlineStoreUrl: product?.onlineStoreUrl,
1186
+ image: product?.featuredMedia?.preview?.image?.url,
1187
+ updatedAt: product?.updatedAt,
1188
+ publishedAt: product?.publishedAt
1189
+ });
1190
+ }
1191
+ function trimVariant(variant) {
1192
+ return compact({
1193
+ id: variant?.id,
1194
+ title: variant?.title,
1195
+ sku: variant?.sku,
1196
+ barcode: variant?.barcode,
1197
+ price: variant?.price,
1198
+ compareAtPrice: variant?.compareAtPrice,
1199
+ options: Array.isArray(variant?.selectedOptions) ? variant.selectedOptions.map((option) => `${option?.name}: ${option?.value}`).join(", ") : void 0,
1200
+ inventoryQuantity: variant?.inventoryItem?.tracked === false ? void 0 : variant?.inventoryQuantity,
1201
+ inventoryPolicy: variant?.inventoryPolicy,
1202
+ availableForSale: variant?.availableForSale,
1203
+ taxable: variant?.taxable,
1204
+ inventoryItemId: variant?.inventoryItem?.id,
1205
+ tracked: variant?.inventoryItem?.tracked,
1206
+ requiresShipping: variant?.inventoryItem?.requiresShipping
1207
+ });
1208
+ }
1209
+ function trimProduct(product) {
1210
+ const html = typeof product?.descriptionHtml === "string" ? product.descriptionHtml : "";
1211
+ const points = Array.from(html);
1212
+ return compact({
1213
+ ...trimListProduct(product),
1214
+ descriptionHtml: points.length > 1e4 ? points.slice(0, 1e4).join("") : html,
1215
+ descriptionCut: points.length > 1e4 ? true : void 0,
1216
+ seo: product?.seo?.title || product?.seo?.description ? compact({ title: product.seo.title, description: product.seo.description }) : void 0,
1217
+ category: product?.category?.fullName,
1218
+ options: Array.isArray(product?.options) ? product.options.map((option) => ({ name: option?.name, values: Array.isArray(option?.optionValues) ? option.optionValues.map((value) => value?.name) : [] })) : void 0,
1219
+ media: Array.isArray(product?.media?.nodes) && product.media.nodes.length ? product.media.nodes.map((media) => compact({ id: media?.id, type: media?.mediaContentType, status: media?.status, alt: media?.alt, url: media?.preview?.image?.url })) : void 0,
1220
+ collections: Array.isArray(product?.collections?.nodes) && product.collections.nodes.length ? product.collections.nodes.map((collection) => compact({ id: collection?.id, title: collection?.title, handle: collection?.handle })) : void 0,
1221
+ onlineStorePreviewUrl: product?.onlineStorePreviewUrl,
1222
+ createdAt: product?.createdAt
1223
+ });
1224
+ }
1225
+ function trimListOrder(order) {
1226
+ return compact({
1227
+ id: order?.id,
1228
+ name: order?.name,
1229
+ createdAt: order?.createdAt,
1230
+ financialStatus: order?.displayFinancialStatus,
1231
+ fulfillmentStatus: order?.displayFulfillmentStatus,
1232
+ total: amountOf(order?.currentTotalPriceSet),
1233
+ currency: order?.currencyCode,
1234
+ refunded: nonZero(amountOf(order?.totalRefundedSet)),
1235
+ items: order?.subtotalLineItemsQuantity,
1236
+ returnStatus: order?.returnStatus && order.returnStatus !== "NO_RETURN" ? order.returnStatus : void 0,
1237
+ cancelledAt: order?.cancelledAt,
1238
+ closed: order?.closed === true ? true : void 0,
1239
+ test: order?.test === true ? true : void 0,
1240
+ tags: Array.isArray(order?.tags) && order.tags.length ? order.tags.slice(0, 20) : void 0
1241
+ });
1242
+ }
1243
+ function trimAddress(address) {
1244
+ if (!address || typeof address !== "object") return void 0;
1245
+ return compact({
1246
+ name: address.name,
1247
+ company: address.company,
1248
+ address1: address.address1,
1249
+ address2: address.address2,
1250
+ city: address.city,
1251
+ province: address.province,
1252
+ zip: address.zip,
1253
+ country: address.country,
1254
+ countryCode: address.countryCodeV2,
1255
+ phone: address.phone
1256
+ });
1257
+ }
1258
+ function trimOrder(order) {
1259
+ const customer = order?.customer;
1260
+ return compact({
1261
+ ...trimListOrder(order),
1262
+ processedAt: order?.processedAt,
1263
+ cancelReason: order?.cancelReason,
1264
+ closedAt: order?.closedAt,
1265
+ note: order?.note,
1266
+ sourceName: order?.sourceName,
1267
+ paymentGateways: Array.isArray(order?.paymentGatewayNames) && order.paymentGatewayNames.length ? order.paymentGatewayNames : void 0,
1268
+ subtotal: amountOf(order?.subtotalPriceSet),
1269
+ shipping: nonZero(amountOf(order?.totalShippingPriceSet)),
1270
+ tax: nonZero(amountOf(order?.totalTaxSet)),
1271
+ discounts: nonZero(amountOf(order?.totalDiscountsSet)),
1272
+ lineItems: Array.isArray(order?.lineItems?.nodes) ? order.lineItems.nodes.map((item) => compact({
1273
+ id: item?.id,
1274
+ name: item?.name,
1275
+ sku: item?.sku,
1276
+ quantity: item?.quantity,
1277
+ currentQuantity: item?.currentQuantity !== item?.quantity ? item?.currentQuantity : void 0,
1278
+ unitPrice: amountOf(item?.originalUnitPriceSet),
1279
+ variantId: item?.variant?.id
1280
+ })) : void 0,
1281
+ moreLineItems: order?.lineItems?.pageInfo?.hasNextPage === true ? true : void 0,
1282
+ fulfillmentOrders: Array.isArray(order?.fulfillmentOrders?.nodes) && order.fulfillmentOrders.nodes.length ? order.fulfillmentOrders.nodes.map((fulfillmentOrder) => compact({
1283
+ id: fulfillmentOrder?.id,
1284
+ status: fulfillmentOrder?.status,
1285
+ requestStatus: fulfillmentOrder?.requestStatus,
1286
+ location: fulfillmentOrder?.assignedLocation?.name,
1287
+ locationId: fulfillmentOrder?.assignedLocation?.location?.id,
1288
+ lineItems: Array.isArray(fulfillmentOrder?.lineItems?.nodes) ? fulfillmentOrder.lineItems.nodes.map((line) => compact({
1289
+ id: line?.id,
1290
+ name: line?.lineItem?.name,
1291
+ remainingQuantity: line?.remainingQuantity,
1292
+ totalQuantity: line?.totalQuantity
1293
+ })) : void 0
1294
+ })) : void 0,
1295
+ fulfillments: Array.isArray(order?.fulfillments) && order.fulfillments.length ? order.fulfillments.map((fulfillment) => compact({
1296
+ id: fulfillment?.id,
1297
+ status: fulfillment?.status,
1298
+ createdAt: fulfillment?.createdAt,
1299
+ tracking: Array.isArray(fulfillment?.trackingInfo) && fulfillment.trackingInfo.length ? fulfillment.trackingInfo.map((info) => compact({ company: info?.company, number: info?.number, url: info?.url })) : void 0
1300
+ })) : void 0,
1301
+ refunds: Array.isArray(order?.refunds) && order.refunds.length ? order.refunds.map((refund) => compact({ id: refund?.id, createdAt: refund?.createdAt, amount: amountOf(refund?.totalRefundedSet), note: refund?.note })) : void 0,
1302
+ customer: customer ? compact({
1303
+ id: customer.id,
1304
+ firstName: customer.firstName,
1305
+ lastName: customer.lastName,
1306
+ email: customer.defaultEmailAddress?.emailAddress,
1307
+ phone: customer.defaultPhoneNumber?.phoneNumber
1308
+ }) : void 0,
1309
+ email: order?.email,
1310
+ phone: order?.phone,
1311
+ shippingAddress: trimAddress(order?.shippingAddress),
1312
+ billingAddress: trimAddress(order?.billingAddress)
1313
+ });
1314
+ }
1315
+ function trimCustomer(customer) {
1316
+ return compact({
1317
+ id: customer?.id,
1318
+ firstName: customer?.firstName,
1319
+ lastName: customer?.lastName,
1320
+ email: customer?.defaultEmailAddress?.emailAddress,
1321
+ phone: customer?.defaultPhoneNumber?.phoneNumber,
1322
+ state: customer?.state,
1323
+ numberOfOrders: customer?.numberOfOrders,
1324
+ amountSpent: amountOf(customer?.amountSpent),
1325
+ currency: customer?.amountSpent?.currencyCode,
1326
+ tags: Array.isArray(customer?.tags) && customer.tags.length ? customer.tags.slice(0, 20) : void 0,
1327
+ createdAt: customer?.createdAt,
1328
+ updatedAt: customer?.updatedAt
1329
+ });
1330
+ }
1331
+ function trimDiscount(id, discount) {
1332
+ const codes = discount?.codes?.nodes;
1333
+ return compact({
1334
+ id,
1335
+ kind: typeof discount?.__typename === "string" ? discount.__typename.replace(/^Discount/, "") : void 0,
1336
+ title: discount?.title,
1337
+ status: discount?.status,
1338
+ summary: discount?.summary,
1339
+ codes: Array.isArray(codes) && codes.length ? codes.map((code) => code?.code) : void 0,
1340
+ startsAt: discount?.startsAt,
1341
+ endsAt: discount?.endsAt,
1342
+ usageLimit: discount?.usageLimit,
1343
+ used: discount?.asyncUsageCount,
1344
+ oncePerCustomer: discount?.appliesOncePerCustomer === true ? true : void 0
1345
+ });
1346
+ }
1347
+ var PRODUCT_LIST_FIELDS = `id title handle status vendor productType tags updatedAt publishedAt totalInventory tracksInventory
1348
+ variantsCount { count } priceRangeV2 { minVariantPrice { amount currencyCode } maxVariantPrice { amount } }
1349
+ onlineStoreUrl featuredMedia { preview { image { url } } }`;
1350
+ var PRODUCT_DETAIL = `fragment ProductDetail on Product {
1351
+ ${PRODUCT_LIST_FIELDS}
1352
+ createdAt descriptionHtml onlineStorePreviewUrl
1353
+ seo { title description }
1354
+ category { fullName }
1355
+ options { name optionValues { name } }
1356
+ media(first: 20) { nodes { id alt mediaContentType status preview { image { url } } } }
1357
+ collections(first: 20) { nodes { id title handle } }
1358
+ variants(first: 100, after: $variantsAfter) {
1359
+ nodes { id title sku barcode price compareAtPrice inventoryQuantity inventoryPolicy availableForSale taxable selectedOptions { name value } inventoryItem { id tracked requiresShipping } }
1360
+ pageInfo { hasNextPage endCursor }
1361
+ }
1362
+ }`;
1363
+ var CODE_DISCOUNT_FIELDS = `
1364
+ ... on DiscountCodeBasic { title status summary startsAt endsAt usageLimit asyncUsageCount appliesOncePerCustomer codes(first: 3) { nodes { code } } }
1365
+ ... on DiscountCodeBxgy { title status summary startsAt endsAt usageLimit asyncUsageCount codes(first: 3) { nodes { code } } }
1366
+ ... on DiscountCodeFreeShipping { title status summary startsAt endsAt usageLimit asyncUsageCount codes(first: 3) { nodes { code } } }
1367
+ ... on DiscountCodeApp { title status startsAt endsAt usageLimit asyncUsageCount codes(first: 3) { nodes { code } } }`;
1368
+ var ORDER_DETAIL = `fragment OrderDetail on Order {
1369
+ id name createdAt processedAt cancelledAt cancelReason closed closedAt test tags note returnStatus sourceName paymentGatewayNames
1370
+ displayFinancialStatus displayFulfillmentStatus currencyCode subtotalLineItemsQuantity
1371
+ subtotalPriceSet { shopMoney { amount } } totalShippingPriceSet { shopMoney { amount } } totalTaxSet { shopMoney { amount } }
1372
+ totalDiscountsSet { shopMoney { amount } } currentTotalPriceSet { shopMoney { amount } } totalRefundedSet { shopMoney { amount } }
1373
+ lineItems(first: 50) { nodes { id name sku quantity currentQuantity variant { id } originalUnitPriceSet { shopMoney { amount } } } pageInfo { hasNextPage } }
1374
+ fulfillmentOrders(first: 5) { nodes { id status requestStatus assignedLocation { name location { id } }
1375
+ lineItems(first: 30) { nodes { id remainingQuantity totalQuantity lineItem { name } } } } }
1376
+ fulfillments(first: 10) { id status createdAt trackingInfo(first: 5) { company number url } }
1377
+ refunds(first: 10) { id createdAt note totalRefundedSet { shopMoney { amount } } }
1378
+ customer @include(if: $contact) { id firstName lastName defaultEmailAddress { emailAddress } defaultPhoneNumber { phoneNumber } }
1379
+ email @include(if: $contact)
1380
+ phone @include(if: $contact)
1381
+ shippingAddress @include(if: $contact) { name company address1 address2 city province zip country countryCodeV2 phone }
1382
+ billingAddress @include(if: $contact) { name company address1 address2 city province zip country countryCodeV2 phone }
1383
+ }`;
1384
+ var INVENTORY_LEVELS = `fragment Levels on InventoryItem {
1385
+ id sku tracked
1386
+ inventoryLevels(first: 50) { nodes { updatedAt location { id name } quantities(names: ${JSON.stringify(STOCK_NAMES)}) { name quantity } } }
1387
+ }`;
1388
+ var LIST_PRODUCTS_SCHEMA = {
1389
+ type: "object",
1390
+ properties: {
1391
+ query: SEARCH('"status:active", "title:mug*", "vendor:Acme", "sku:MUG-1", "tag:sale", "inventory_total:<5"'),
1392
+ sort_key: { type: "string", enum: ["UPDATED_AT", "CREATED_AT", "TITLE", "INVENTORY_TOTAL", "PUBLISHED_AT", "PRODUCT_TYPE", "VENDOR", "ID"], default: "UPDATED_AT" },
1393
+ reverse: REVERSE,
1394
+ first: FIRST(25),
1395
+ cursor: CURSOR
1396
+ },
1397
+ additionalProperties: false
1398
+ };
1399
+ var LIST_ORDERS_SCHEMA = {
1400
+ type: "object",
1401
+ properties: {
1402
+ query: SEARCH('"financial_status:paid", "fulfillment_status:unfulfilled", "created_at:>=2026-11-01", "name:#1001", "status:open"'),
1403
+ sort_key: { type: "string", enum: ["CREATED_AT", "PROCESSED_AT", "UPDATED_AT", "TOTAL_PRICE", "ORDER_NUMBER", "ID"], default: "CREATED_AT" },
1404
+ reverse: REVERSE,
1405
+ first: FIRST(25),
1406
+ cursor: CURSOR
1407
+ },
1408
+ additionalProperties: false
1409
+ };
1410
+ var LIST_CUSTOMERS_SCHEMA = {
1411
+ type: "object",
1412
+ properties: {
1413
+ query: SEARCH('"email:ada@example.com", "tag:vip", "orders_count:>5", "country:Germany"'),
1414
+ sort_key: { type: "string", enum: ["UPDATED_AT", "CREATED_AT", "NAME", "ID"], default: "UPDATED_AT" },
1415
+ reverse: REVERSE,
1416
+ include_contact: { type: "boolean", default: false, description: "Add each customer's email and phone." },
1417
+ first: FIRST(25),
1418
+ cursor: CURSOR
1419
+ },
1420
+ additionalProperties: false
1421
+ };
1422
+ var LIST_COLLECTIONS_SCHEMA = {
1423
+ type: "object",
1424
+ properties: {
1425
+ query: SEARCH('"title:summer*", "collection_type:smart"'),
1426
+ sort_key: { type: "string", enum: ["UPDATED_AT", "TITLE", "ID"], default: "UPDATED_AT" },
1427
+ reverse: REVERSE,
1428
+ first: FIRST(50),
1429
+ cursor: CURSOR
1430
+ },
1431
+ additionalProperties: false
1432
+ };
1433
+ var LIST_DISCOUNTS_SCHEMA = {
1434
+ type: "object",
1435
+ properties: {
1436
+ code: { type: "string", minLength: 1, maxLength: 255, description: "One discount by its exact code." },
1437
+ query: SEARCH('"status:active", "title:winter*", "type:percentage"'),
1438
+ sort_key: { type: "string", enum: ["CREATED_AT", "UPDATED_AT", "STARTS_AT", "ENDS_AT", "TITLE", "ID"], default: "CREATED_AT" },
1439
+ reverse: REVERSE,
1440
+ first: FIRST(25),
1441
+ cursor: CURSOR
1442
+ },
1443
+ additionalProperties: false
1444
+ };
1445
+ var LIST_LOCATIONS_SCHEMA = {
1446
+ type: "object",
1447
+ properties: {
1448
+ include_inactive: { type: "boolean", default: false, description: "Also list deactivated locations." },
1449
+ first: FIRST(50),
1450
+ cursor: CURSOR
1451
+ },
1452
+ additionalProperties: false
1453
+ };
1454
+ var VARIANT_FIELDS = {
1455
+ price: MONEY('The price, e.g. "19.90".'),
1456
+ compare_at_price: { type: "string", pattern: "^(\\d{1,12}(\\.\\d{1,4})?)?$", description: 'The compare-at (crossed-out) price; "" removes it.' },
1457
+ sku: { type: "string", maxLength: 255 },
1458
+ barcode: { type: "string", maxLength: 255 },
1459
+ inventory_policy: { type: "string", enum: ["DENY", "CONTINUE"], description: "CONTINUE keeps selling when out of stock." },
1460
+ taxable: { type: "boolean" },
1461
+ track_inventory: { type: "boolean", description: "Shopify tracks its stock." },
1462
+ cost: MONEY("Cost per item."),
1463
+ requires_shipping: { type: "boolean" }
1464
+ };
1465
+ function variantInput(variant, existing) {
1466
+ const item = compact({ sku: existing ? variant.sku : void 0, tracked: variant.track_inventory, cost: variant.cost, requiresShipping: variant.requires_shipping });
1467
+ return {
1468
+ ...compact({
1469
+ price: variant.price,
1470
+ compareAtPrice: variant.compare_at_price,
1471
+ sku: existing ? void 0 : variant.sku,
1472
+ barcode: variant.barcode,
1473
+ inventoryPolicy: variant.inventory_policy,
1474
+ taxable: variant.taxable,
1475
+ inventoryItem: Object.keys(item).length ? item : void 0
1476
+ }),
1477
+ ...existing && variant.compare_at_price === "" ? { compareAtPrice: null } : {}
1478
+ };
1479
+ }
1480
+ function productSetInput(args) {
1481
+ const options = args.options ?? [];
1482
+ const variants = args.variants?.length ? args.variants : [{}];
1483
+ const refuse = (sentence) => {
1484
+ throw new ToolFailure(`${sentence} Nothing was sent.`);
1485
+ };
1486
+ let productOptions;
1487
+ let variantInputs;
1488
+ if (!options.length) {
1489
+ if (variants.length > 1) refuse("Several variants need options (such as Size or Color) that tell them apart.");
1490
+ if (variants[0]?.option_values) refuse("option_values need options on the product.");
1491
+ productOptions = [{ name: "Title", values: [{ name: "Default Title" }] }];
1492
+ variantInputs = [{ optionValues: [{ optionName: "Title", name: "Default Title" }] }];
1493
+ } else {
1494
+ productOptions = options.map((option) => ({ name: option.name, values: option.values.map((value) => ({ name: value })) }));
1495
+ const seen = /* @__PURE__ */ new Set();
1496
+ variantInputs = variants.map((variant, index) => {
1497
+ const chosen = variant.option_values ?? {};
1498
+ const optionValues = options.map((option) => {
1499
+ const value = chosen[option.name];
1500
+ if (typeof value !== "string" || !option.values.includes(value)) {
1501
+ refuse(`variants[${index}].option_values needs a value for ${option.name}, one of: ${option.values.join(", ")}.`);
1502
+ }
1503
+ return { optionName: option.name, name: value };
1504
+ });
1505
+ const extra = Object.keys(chosen).filter((name2) => !options.some((option) => option.name === name2));
1506
+ if (extra.length) refuse(`variants[${index}].option_values names ${extra.join(", ")}, which is not one of the options.`);
1507
+ const key = JSON.stringify(optionValues);
1508
+ if (seen.has(key)) refuse(`variants[${index}] repeats the option values of an earlier variant.`);
1509
+ seen.add(key);
1510
+ return { optionValues };
1511
+ });
1512
+ }
1513
+ variantInputs = variantInputs.map((input, index) => {
1514
+ const variant = variants[index] ?? {};
1515
+ const quantities = variant.inventory_quantities ?? [];
1516
+ return compact({
1517
+ ...input,
1518
+ ...variantInput({ ...variant, track_inventory: variant.track_inventory ?? (quantities.length ? true : void 0) }, false),
1519
+ inventoryQuantities: quantities.length ? quantities.map((entry, at) => ({ locationId: gid("Location", entry.location_id, `variants[${index}].inventory_quantities[${at}].location_id`), name: "available", quantity: entry.quantity })) : void 0
1520
+ });
1521
+ });
1522
+ return compact({
1523
+ title: args.title,
1524
+ descriptionHtml: args.description_html,
1525
+ vendor: args.vendor,
1526
+ productType: args.product_type,
1527
+ tags: args.tags,
1528
+ handle: args.handle,
1529
+ status: args.status,
1530
+ seo: args.seo_title || args.seo_description ? compact({ title: args.seo_title, description: args.seo_description }) : void 0,
1531
+ collections: Array.isArray(args.collection_ids) ? args.collection_ids.map((id, at) => gid("Collection", id, `collection_ids[${at}]`)) : void 0,
1532
+ productOptions,
1533
+ variants: variantInputs,
1534
+ files: Array.isArray(args.images) && args.images.length ? args.images.map((image) => compact({ originalSource: image.url, alt: image.alt, contentType: "IMAGE" })) : void 0
1535
+ });
1536
+ }
1537
+ async function findDuplicates(h, handle, skus) {
1538
+ if (!handle && !skus.length) return [];
1539
+ const { data } = await graphql(h, `query Duplicates($handle: String!, $hasHandle: Boolean!, $skuQuery: String!, $hasSkus: Boolean!) {
1540
+ byHandle: productByIdentifier(identifier: { handle: $handle }) @include(if: $hasHandle) { id title }
1541
+ bySku: productVariants(first: 10, query: $skuQuery) @include(if: $hasSkus) { nodes { sku product { id title } } }
1542
+ }`, {
1543
+ handle: handle ?? "",
1544
+ hasHandle: Boolean(handle),
1545
+ skuQuery: skus.map((sku) => `sku:${searchValue(sku)}`).join(" OR "),
1546
+ hasSkus: skus.length > 0
1547
+ });
1548
+ const found = [];
1549
+ if (data?.byHandle?.id) found.push(`the handle ${handle} is taken by ${data.byHandle.id} ("${truncate(String(data.byHandle.title ?? ""), 80)}")`);
1550
+ for (const node of Array.isArray(data?.bySku?.nodes) ? data.bySku.nodes : []) {
1551
+ if (skus.includes(node?.sku)) found.push(`the SKU ${node.sku} is on ${node?.product?.id} ("${truncate(String(node?.product?.title ?? ""), 80)}")`);
1552
+ }
1553
+ return found;
1554
+ }
1555
+ var connector = defineConnector({
1556
+ vendor: "shopify",
1557
+ label: "Shopify",
1558
+ origins: [],
1559
+ originFields: ["shopdomain"],
1560
+ credentials: ["shopdomain", "access_token"],
1561
+ credentialLabels: { shopdomain: "Shopify shop domain", access_token: "Shopify access token" },
1562
+ authHeaders: (credentials) => ({ "x-shopify-access-token": credentials["access_token"] ?? "" }),
1563
+ tools: [
1564
+ {
1565
+ name: "get_shop",
1566
+ kind: "read",
1567
+ title: "Get the Shopify shop and the app's access scopes",
1568
+ description: "The connected shop (name, myshopify domain, primary domain, currency, time zone, plan) and the access scopes the app was granted, which decide what the other tools may do. Use it to check the connection.",
1569
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1570
+ async run(_args, h) {
1571
+ const response = await graphql(h, `query ShopIdentity {
1572
+ shop { id name myshopifyDomain url currencyCode ianaTimezone weightUnit enabledPresentmentCurrencies primaryDomain { host url } plan { publicDisplayName partnerDevelopment shopifyPlus } }
1573
+ currentAppInstallation { accessScopes { handle } }
1574
+ }`);
1575
+ const shop = response.data?.shop;
1576
+ if (!shop?.id) throw new ToolFailure("Shopify answered without the shop.");
1577
+ const configured = new URL(shopOrigin(h)).hostname;
1578
+ return withWarnings(compact({
1579
+ id: shop.id,
1580
+ name: shop.name,
1581
+ myshopifyDomain: shop.myshopifyDomain,
1582
+ primaryDomain: shop.primaryDomain?.url,
1583
+ currency: shop.currencyCode,
1584
+ presentmentCurrencies: Array.isArray(shop.enabledPresentmentCurrencies) && shop.enabledPresentmentCurrencies.length > 1 ? shop.enabledPresentmentCurrencies : void 0,
1585
+ timezone: shop.ianaTimezone,
1586
+ weightUnit: shop.weightUnit,
1587
+ plan: shop.plan?.publicDisplayName,
1588
+ developmentStore: shop.plan?.partnerDevelopment === true ? true : void 0,
1589
+ accessScopes: Array.isArray(response.data?.currentAppInstallation?.accessScopes) ? response.data.currentAppInstallation.accessScopes.map((scope) => scope?.handle).filter(Boolean) : void 0,
1590
+ apiVersion: API_VERSION,
1591
+ warning: shop.myshopifyDomain && shop.myshopifyDomain !== configured ? `The token belongs to ${shop.myshopifyDomain}, not to ${configured} as connected.` : void 0
1592
+ }), response);
1593
+ }
1594
+ },
1595
+ {
1596
+ name: "list_products",
1597
+ kind: "read",
1598
+ title: "List Shopify products",
1599
+ description: "Lists products, most recently updated first: id, title, handle, status, vendor, type, tags, price range, variant count, stock and image. query takes Shopify search syntax (status, title, vendor, product_type, sku, tag, inventory_total ...). Pass nextCursor back as cursor for more.",
1600
+ inputSchema: LIST_PRODUCTS_SCHEMA,
1601
+ async run(args, h) {
1602
+ const position = listPosition(h, LIST_PRODUCTS_SCHEMA, args);
1603
+ const f = position.filters;
1604
+ const response = await graphql(h, `query Products($first: Int!, $after: String, $query: String, $sortKey: ProductSortKeys, $reverse: Boolean) {
1605
+ products(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) { nodes { ${PRODUCT_LIST_FIELDS} } pageInfo { hasNextPage endCursor } }
1606
+ }`, { first: f["first"] ?? 25, after: position.after ?? null, query: f["query"] ?? null, sortKey: f["sort_key"] ?? "UPDATED_AT", reverse: f["reverse"] ?? true });
1607
+ const connection = response.data?.products;
1608
+ const products = Array.isArray(connection?.nodes) ? connection.nodes : [];
1609
+ return h.page({
1610
+ key: "products",
1611
+ items: products.map(trimListProduct).slice(position.skip),
1612
+ extra: response.warnings.length ? { warnings: response.warnings.slice(0, 5) } : {},
1613
+ ...pageCursors(h, position, connection?.pageInfo)
1614
+ });
1615
+ }
1616
+ },
1617
+ {
1618
+ name: "get_product",
1619
+ kind: "read",
1620
+ title: "Get a Shopify product",
1621
+ description: "One product by id or handle: description HTML, SEO, options, media, collections, and its variants with price, compare-at price, SKU, barcode, stock, inventory policy and inventory item id. Pass nextCursor back as cursor, with the same id or handle, for more variants.",
1622
+ inputSchema: {
1623
+ type: "object",
1624
+ properties: {
1625
+ id: ID("Product", "The product id"),
1626
+ handle: { type: "string", pattern: "^[a-z0-9][a-z0-9-]{0,254}$", description: "Or the product handle." },
1627
+ cursor: CURSOR
1628
+ },
1629
+ additionalProperties: false
1630
+ },
1631
+ async run(args, h) {
1632
+ if (args.id === void 0 === (args.handle === void 0)) throw new ToolFailure("Give id or handle (one of them). Nothing was sent.");
1633
+ const state = h.cursor(args.cursor);
1634
+ const after = typeof state?.["a"] === "string" ? state["a"] : null;
1635
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
1636
+ const response = args.id !== void 0 ? await graphql(h, `query Product($id: ID!, $variantsAfter: String) { product(id: $id) { ...ProductDetail } }
1637
+ ${PRODUCT_DETAIL}`, {
1638
+ id: gid("Product", args.id, "id"),
1639
+ variantsAfter: after
1640
+ }) : await graphql(h, `query ProductByHandle($handle: String!, $variantsAfter: String) { product: productByIdentifier(identifier: { handle: $handle }) { ...ProductDetail } }
1641
+ ${PRODUCT_DETAIL}`, {
1642
+ handle: args.handle,
1643
+ variantsAfter: after
1644
+ });
1645
+ const product = response.data?.product;
1646
+ if (!product) throw new ToolFailure(`Shopify found no product with that ${args.id !== void 0 ? "id" : "handle"}.`);
1647
+ const variants = Array.isArray(product.variants?.nodes) ? product.variants.nodes : [];
1648
+ const next = product.variants?.pageInfo?.hasNextPage === true && typeof product.variants.pageInfo.endCursor === "string" ? product.variants.pageInfo.endCursor : void 0;
1649
+ return h.page({
1650
+ key: "variants",
1651
+ items: variants.map(trimVariant).slice(skip),
1652
+ extra: withWarnings({ ...trimProduct(product), variantCount: product.variantsCount?.count }, response),
1653
+ resumeAt: (index) => h.makeCursor({ ...after ? { a: after } : {}, o: skip + index }),
1654
+ ...next ? { nextPage: h.makeCursor({ a: next, o: 0 }) } : {}
1655
+ });
1656
+ }
1657
+ },
1658
+ {
1659
+ name: "create_product",
1660
+ kind: "create",
1661
+ check: "list_products",
1662
+ title: "Create a Shopify product",
1663
+ description: "Creates a product with its options and variants (prices, SKUs, stock per location) and images from public URLs (Shopify fetches them), as a draft unless status says otherwise. ACTIVE is not on sale until it is published to a sales channel (publish_product). It refuses a handle or SKU the shop already has, unless allow_duplicates is true.",
1664
+ inputSchema: {
1665
+ type: "object",
1666
+ properties: {
1667
+ title: { type: "string", minLength: 1, maxLength: 255 },
1668
+ description_html: { type: "string", maxLength: 5e5, description: "The description as HTML." },
1669
+ vendor: { type: "string", maxLength: 255 },
1670
+ product_type: { type: "string", maxLength: 255 },
1671
+ tags: { type: "array", items: { type: "string", minLength: 1, maxLength: 255 }, maxItems: 250 },
1672
+ handle: { type: "string", pattern: "^[a-z0-9][a-z0-9-]{0,254}$", description: "The URL handle (default: from the title)." },
1673
+ status: { type: "string", enum: ["DRAFT", "ACTIVE", "UNLISTED", "ARCHIVED"], default: "DRAFT" },
1674
+ seo_title: { type: "string", maxLength: 255 },
1675
+ seo_description: { type: "string", maxLength: 1e3 },
1676
+ collection_ids: ID_LIST("Collection", "Manual collections to add it to."),
1677
+ images: {
1678
+ type: "array",
1679
+ maxItems: 20,
1680
+ items: {
1681
+ type: "object",
1682
+ properties: { url: { type: "string", format: "uri", maxLength: 2e3, description: "A public image URL." }, alt: { type: "string", maxLength: 512 } },
1683
+ required: ["url"],
1684
+ additionalProperties: false
1685
+ }
1686
+ },
1687
+ options: {
1688
+ type: "array",
1689
+ maxItems: 3,
1690
+ description: 'Up to 3 options, e.g. [{"name": "Size", "values": ["S", "M"]}]; none for a product with one variant.',
1691
+ items: {
1692
+ type: "object",
1693
+ properties: {
1694
+ name: { type: "string", minLength: 1, maxLength: 255 },
1695
+ values: { type: "array", items: { type: "string", minLength: 1, maxLength: 255 }, minItems: 1, maxItems: 100, uniqueItems: true }
1696
+ },
1697
+ required: ["name", "values"],
1698
+ additionalProperties: false
1699
+ }
1700
+ },
1701
+ variants: {
1702
+ type: "array",
1703
+ maxItems: 100,
1704
+ description: "The variants: one per option combination to sell (or one, without options).",
1705
+ items: {
1706
+ type: "object",
1707
+ properties: {
1708
+ option_values: { type: "object", description: 'The value of each option, e.g. {"Size": "M"}.' },
1709
+ ...VARIANT_FIELDS,
1710
+ inventory_quantities: {
1711
+ type: "array",
1712
+ maxItems: 50,
1713
+ items: {
1714
+ type: "object",
1715
+ properties: { location_id: ID("Location", "A location id from list_locations"), quantity: { type: "integer", minimum: 0, maximum: 1e9 } },
1716
+ required: ["location_id", "quantity"],
1717
+ additionalProperties: false
1718
+ },
1719
+ description: "Available stock per location."
1720
+ }
1721
+ },
1722
+ additionalProperties: false
1723
+ }
1724
+ },
1725
+ allow_duplicates: { type: "boolean", default: false, description: "Create it even if the handle or a SKU is in use." }
1726
+ },
1727
+ required: ["title"],
1728
+ additionalProperties: false
1729
+ },
1730
+ async run(args, h) {
1731
+ const input = productSetInput(args);
1732
+ if (!args.allow_duplicates) {
1733
+ const skus = (args.variants ?? []).map((variant) => variant?.sku).filter((sku) => typeof sku === "string" && sku !== "");
1734
+ const duplicates = await findDuplicates(h, args.handle, [...new Set(skus)]);
1735
+ if (duplicates.length) {
1736
+ throw new ToolFailure(`Shopify already has this product, it seems: ${duplicates.join("; ")}. Update that one, or pass allow_duplicates: true. Nothing was changed.`);
1737
+ }
1738
+ }
1739
+ const response = await graphql(h, `mutation CreateProduct($input: ProductSetInput!) {
1740
+ productSet(input: $input, synchronous: true) {
1741
+ product { id title handle status onlineStorePreviewUrl variants(first: 100) { nodes { id title sku price inventoryItem { id } } } }
1742
+ userErrors { field message code }
1743
+ }
1744
+ }`, { input }, { write: true });
1745
+ const payload = response.data?.productSet;
1746
+ assertNoUserErrors(payload, "create the product");
1747
+ const product = payload?.product;
1748
+ if (!product?.id) throw new ToolFailure("Shopify answered without the new product. Look for it with list_products before trying again.");
1749
+ return withWarnings(compact({
1750
+ id: product.id,
1751
+ title: product.title,
1752
+ handle: product.handle,
1753
+ status: product.status,
1754
+ onlineStorePreviewUrl: product.onlineStorePreviewUrl,
1755
+ variants: Array.isArray(product.variants?.nodes) ? product.variants.nodes.map((variant) => compact({ id: variant?.id, title: variant?.title, sku: variant?.sku, price: variant?.price, inventoryItemId: variant?.inventoryItem?.id })) : void 0,
1756
+ note: product.status === "ACTIVE" ? "Active, but on no sales channel yet: publish it with publish_product." : product.status === "DRAFT" ? "A draft: customers do not see it." : void 0
1757
+ }), response);
1758
+ }
1759
+ },
1760
+ {
1761
+ name: "update_product",
1762
+ kind: "update",
1763
+ check: "get_product",
1764
+ title: "Update a Shopify product",
1765
+ description: "Changes a product's title, description, vendor, type, tags (the list replaces the old one), handle (the old URL redirects), status, SEO and manual collections (join or leave). Only the fields given change. Prices and SKUs are per variant: update_variants; images are added with add_product_images.",
1766
+ inputSchema: {
1767
+ type: "object",
1768
+ properties: {
1769
+ id: ID("Product", "The product id"),
1770
+ title: { type: "string", minLength: 1, maxLength: 255 },
1771
+ description_html: { type: "string", maxLength: 5e5 },
1772
+ vendor: { type: "string", maxLength: 255 },
1773
+ product_type: { type: "string", maxLength: 255 },
1774
+ tags: { type: "array", items: { type: "string", minLength: 1, maxLength: 255 }, maxItems: 250, description: "Replaces all tags." },
1775
+ handle: { type: "string", pattern: "^[a-z0-9][a-z0-9-]{0,254}$" },
1776
+ status: { type: "string", enum: ["DRAFT", "ACTIVE", "UNLISTED", "ARCHIVED"] },
1777
+ seo_title: { type: "string", maxLength: 255 },
1778
+ seo_description: { type: "string", maxLength: 1e3 },
1779
+ collections_to_join: ID_LIST("Collection", "Manual collections to add it to."),
1780
+ collections_to_leave: ID_LIST("Collection", "Manual collections to take it out of.")
1781
+ },
1782
+ required: ["id"],
1783
+ additionalProperties: false
1784
+ },
1785
+ async run(args, h) {
1786
+ const product = compact({
1787
+ id: gid("Product", args.id, "id"),
1788
+ title: args.title,
1789
+ descriptionHtml: args.description_html,
1790
+ vendor: args.vendor,
1791
+ productType: args.product_type,
1792
+ tags: args.tags,
1793
+ handle: args.handle,
1794
+ redirectNewHandle: args.handle !== void 0 ? true : void 0,
1795
+ status: args.status,
1796
+ seo: args.seo_title !== void 0 || args.seo_description !== void 0 ? compact({ title: args.seo_title, description: args.seo_description }) : void 0,
1797
+ collectionsToJoin: args.collections_to_join?.map((id, at) => gid("Collection", id, `collections_to_join[${at}]`)),
1798
+ collectionsToLeave: args.collections_to_leave?.map((id, at) => gid("Collection", id, `collections_to_leave[${at}]`))
1799
+ });
1800
+ if (args.description_html === "") product["descriptionHtml"] = "";
1801
+ if (args.tags?.length === 0) product["tags"] = [];
1802
+ if (Object.keys(product).length === 1) throw new ToolFailure("Nothing to change: give at least one field besides id. Nothing was sent.");
1803
+ const response = await graphql(h, `mutation UpdateProduct($product: ProductUpdateInput!) {
1804
+ productUpdate(product: $product) {
1805
+ product { id title handle status vendor productType tags updatedAt onlineStoreUrl seo { title description } }
1806
+ userErrors { field message }
1807
+ }
1808
+ }`, { product }, { write: true });
1809
+ const payload = response.data?.productUpdate;
1810
+ assertNoUserErrors(payload, "update the product");
1811
+ const saved = payload?.product;
1812
+ return withWarnings(compact({
1813
+ id: saved?.id,
1814
+ title: saved?.title,
1815
+ handle: saved?.handle,
1816
+ status: saved?.status,
1817
+ vendor: saved?.vendor,
1818
+ productType: saved?.productType,
1819
+ tags: saved?.tags,
1820
+ seo: saved?.seo?.title || saved?.seo?.description ? compact({ title: saved.seo.title, description: saved.seo.description }) : void 0,
1821
+ onlineStoreUrl: saved?.onlineStoreUrl,
1822
+ updatedAt: saved?.updatedAt
1823
+ }), response);
1824
+ }
1825
+ },
1826
+ {
1827
+ // A create, not an update: every call adds the images again.
1828
+ name: "add_product_images",
1829
+ kind: "create",
1830
+ check: "get_product",
1831
+ title: "Add images to a Shopify product",
1832
+ description: "Adds images to a product from public URLs; Shopify downloads and processes them in the background. Each call adds them again: it is not retried, and after an unclear outcome look at the product's media with get_product before sending it again. Returns the product's media count and its newest media with their processing status.",
1833
+ inputSchema: {
1834
+ type: "object",
1835
+ properties: {
1836
+ product_id: ID("Product", "The product id"),
1837
+ images: {
1838
+ type: "array",
1839
+ minItems: 1,
1840
+ maxItems: 20,
1841
+ items: {
1842
+ type: "object",
1843
+ properties: { url: { type: "string", format: "uri", maxLength: 2e3, description: "A public image URL." }, alt: { type: "string", maxLength: 512 } },
1844
+ required: ["url"],
1845
+ additionalProperties: false
1846
+ },
1847
+ description: "The images to add, from public URLs."
1848
+ }
1849
+ },
1850
+ required: ["product_id", "images"],
1851
+ additionalProperties: false
1852
+ },
1853
+ async run(args, h) {
1854
+ const media = args.images.map((image) => compact({ originalSource: image.url, alt: image.alt, mediaContentType: "IMAGE" }));
1855
+ const response = await graphql(h, `mutation AddProductImages($product: ProductUpdateInput!, $media: [CreateMediaInput!], $count: Int!) {
1856
+ productUpdate(product: $product, media: $media) {
1857
+ product { id title mediaCount { count } media(first: $count, sortKey: CREATED_AT, reverse: true) { nodes { id alt mediaContentType status preview { image { url } } } } }
1858
+ userErrors { field message }
1859
+ }
1860
+ }`, { product: { id: gid("Product", args.product_id, "product_id") }, media, count: media.length }, { write: true });
1861
+ const payload = response.data?.productUpdate;
1862
+ assertNoUserErrors(payload, "add the images");
1863
+ const saved = payload?.product;
1864
+ const newest = Array.isArray(saved?.media?.nodes) ? saved.media.nodes : [];
1865
+ return withWarnings(compact({
1866
+ id: saved?.id,
1867
+ title: saved?.title,
1868
+ imagesAdded: media.length,
1869
+ mediaCount: saved?.mediaCount?.count,
1870
+ newestMedia: newest.length ? newest.map((item) => compact({ id: item?.id, type: item?.mediaContentType, status: item?.status, alt: item?.alt, url: item?.preview?.image?.url })) : void 0,
1871
+ note: "Shopify processes new images in the background: their status turns READY, or FAILED for a URL it could not fetch."
1872
+ }), response);
1873
+ }
1874
+ },
1875
+ {
1876
+ name: "update_variants",
1877
+ kind: "update",
1878
+ check: "get_product",
1879
+ title: "Update Shopify variants",
1880
+ description: 'Changes variants of one product: price, compare-at price ("" removes it), SKU, barcode, inventory policy, taxable, whether stock is tracked, cost and shipping. All or nothing: if Shopify refuses one, none change. Stock quantities: set_inventory_quantity.',
1881
+ inputSchema: {
1882
+ type: "object",
1883
+ properties: {
1884
+ product_id: ID("Product", "The product id"),
1885
+ variants: {
1886
+ type: "array",
1887
+ minItems: 1,
1888
+ maxItems: 100,
1889
+ items: {
1890
+ type: "object",
1891
+ properties: { id: ID("ProductVariant", "The variant id"), ...VARIANT_FIELDS },
1892
+ required: ["id"],
1893
+ additionalProperties: false
1894
+ }
1895
+ }
1896
+ },
1897
+ required: ["product_id", "variants"],
1898
+ additionalProperties: false
1899
+ },
1900
+ async run(args, h) {
1901
+ const variants = args.variants.map((variant, index) => {
1902
+ const input = { id: gid("ProductVariant", variant.id, `variants[${index}].id`), ...variantInput(variant, true) };
1903
+ if (Object.keys(input).length === 1) throw new ToolFailure(`variants[${index}] changes nothing: give a field besides id. Nothing was sent.`);
1904
+ return input;
1905
+ });
1906
+ const response = await graphql(h, `mutation UpdateVariants($productId: ID!, $variants: [ProductVariantsBulkInput!]!) {
1907
+ productVariantsBulkUpdate(productId: $productId, variants: $variants) {
1908
+ productVariants { id title sku barcode price compareAtPrice inventoryPolicy taxable inventoryItem { id tracked requiresShipping } }
1909
+ userErrors { field message code }
1910
+ }
1911
+ }`, { productId: gid("Product", args.product_id, "product_id"), variants }, { write: true });
1912
+ const payload = response.data?.productVariantsBulkUpdate;
1913
+ assertNoUserErrors(payload, "update the variants");
1914
+ return withWarnings({ variants: Array.isArray(payload?.productVariants) ? payload.productVariants.map(trimVariant) : [] }, response);
1915
+ }
1916
+ },
1917
+ {
1918
+ name: "list_publications",
1919
+ kind: "read",
1920
+ title: "List Shopify sales channels",
1921
+ description: "Lists the shop's publications (sales channels such as the Online Store) with their ids for publish_product; with product_id, whether that product is published on each of them.",
1922
+ inputSchema: {
1923
+ type: "object",
1924
+ properties: { product_id: ID("Product", "A product to show the publishing state of") },
1925
+ additionalProperties: false
1926
+ },
1927
+ async run(args, h) {
1928
+ if (args.product_id === void 0) {
1929
+ const response2 = await graphql(h, `query Publications { publications(first: 50) { nodes { id name autoPublish supportsFuturePublishing catalog { title } } } }`);
1930
+ const nodes2 = Array.isArray(response2.data?.publications?.nodes) ? response2.data.publications.nodes : [];
1931
+ return withWarnings({
1932
+ publications: nodes2.map((publication) => compact({
1933
+ id: publication?.id,
1934
+ name: publication?.catalog?.title ?? publication?.name,
1935
+ autoPublish: publication?.autoPublish === true ? true : void 0,
1936
+ futurePublishing: publication?.supportsFuturePublishing === true ? true : void 0
1937
+ }))
1938
+ }, response2);
1939
+ }
1940
+ const response = await graphql(h, `query ProductPublications($id: ID!) {
1941
+ product(id: $id) { id title status resourcePublicationsV2(first: 50, onlyPublished: false) { nodes { isPublished publishDate publication { id name catalog { title } } } } }
1942
+ }`, { id: gid("Product", args.product_id, "product_id") });
1943
+ const product = response.data?.product;
1944
+ if (!product) throw new ToolFailure("Shopify found no product with that id.");
1945
+ const nodes = Array.isArray(product.resourcePublicationsV2?.nodes) ? product.resourcePublicationsV2.nodes : [];
1946
+ return withWarnings({
1947
+ product: compact({ id: product.id, title: product.title, status: product.status }),
1948
+ publications: nodes.map((node) => compact({
1949
+ id: node?.publication?.id,
1950
+ name: node?.publication?.catalog?.title ?? node?.publication?.name,
1951
+ published: node?.isPublished === true,
1952
+ publishDate: node?.publishDate
1953
+ }))
1954
+ }, response);
1955
+ }
1956
+ },
1957
+ {
1958
+ name: "publish_product",
1959
+ kind: "update",
1960
+ check: "list_publications",
1961
+ title: "Publish a Shopify product to sales channels",
1962
+ description: "Publishes a product on sales channels (publication ids from list_publications), or takes it off them with unpublish: true. Customers see it only when its status is ACTIVE too.",
1963
+ inputSchema: {
1964
+ type: "object",
1965
+ properties: {
1966
+ product_id: ID("Product", "The product id"),
1967
+ publication_ids: ID_LIST("Publication", "The publications (sales channels)."),
1968
+ unpublish: { type: "boolean", default: false, description: "Take it off these channels instead." }
1969
+ },
1970
+ required: ["product_id", "publication_ids"],
1971
+ additionalProperties: false
1972
+ },
1973
+ async run(args, h) {
1974
+ if (!args.publication_ids.length) throw new ToolFailure("publication_ids must name at least one publication. Nothing was sent.");
1975
+ const field = args.unpublish ? "publishableUnpublish" : "publishablePublish";
1976
+ const response = await graphql(h, `mutation Publish($id: ID!, $input: [PublicationInput!]!) {
1977
+ ${field}(id: $id, input: $input) { publishable { ... on Product { id title status } } userErrors { field message } }
1978
+ }`, {
1979
+ id: gid("Product", args.product_id, "product_id"),
1980
+ input: args.publication_ids.map((id, at) => ({ publicationId: gid("Publication", id, `publication_ids[${at}]`) }))
1981
+ }, { write: true });
1982
+ const payload = response.data?.[field];
1983
+ assertNoUserErrors(payload, args.unpublish ? "unpublish the product" : "publish the product");
1984
+ const product = payload?.publishable;
1985
+ return withWarnings(compact({
1986
+ id: product?.id,
1987
+ title: product?.title,
1988
+ status: product?.status,
1989
+ published: !args.unpublish,
1990
+ publications: args.publication_ids.length,
1991
+ note: !args.unpublish && product?.status && product.status !== "ACTIVE" ? `Published, but its status is ${product.status}: customers see it once it is ACTIVE.` : void 0
1992
+ }), response);
1993
+ }
1994
+ },
1995
+ {
1996
+ name: "list_collections",
1997
+ kind: "read",
1998
+ title: "List Shopify collections",
1999
+ description: "Lists collections with their id, title, handle, product count, and for a smart collection its rules. Pass nextCursor back as cursor for more.",
2000
+ inputSchema: LIST_COLLECTIONS_SCHEMA,
2001
+ async run(args, h) {
2002
+ const position = listPosition(h, LIST_COLLECTIONS_SCHEMA, args);
2003
+ const f = position.filters;
2004
+ const response = await graphql(h, `query Collections($first: Int!, $after: String, $query: String, $sortKey: CollectionSortKeys, $reverse: Boolean) {
2005
+ collections(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) {
2006
+ nodes { id title handle updatedAt sortOrder productsCount { count } ruleSet { appliedDisjunctively rules { column relation condition } } }
2007
+ pageInfo { hasNextPage endCursor }
2008
+ }
2009
+ }`, { first: f["first"] ?? 50, after: position.after ?? null, query: f["query"] ?? null, sortKey: f["sort_key"] ?? "UPDATED_AT", reverse: f["reverse"] ?? true });
2010
+ const connection = response.data?.collections;
2011
+ const nodes = Array.isArray(connection?.nodes) ? connection.nodes : [];
2012
+ return h.page({
2013
+ key: "collections",
2014
+ items: nodes.map((collection) => compact({
2015
+ id: collection?.id,
2016
+ title: collection?.title,
2017
+ handle: collection?.handle,
2018
+ kind: collection?.ruleSet ? "smart" : "manual",
2019
+ products: collection?.productsCount?.count,
2020
+ rules: Array.isArray(collection?.ruleSet?.rules) && collection.ruleSet.rules.length ? collection.ruleSet.rules.map((rule) => `${rule?.column} ${rule?.relation} ${rule?.condition ?? ""}`.trim()).join(collection.ruleSet.appliedDisjunctively ? " OR " : " AND ") : void 0,
2021
+ sortOrder: collection?.sortOrder,
2022
+ updatedAt: collection?.updatedAt
2023
+ })).slice(position.skip),
2024
+ extra: response.warnings.length ? { warnings: response.warnings.slice(0, 5) } : {},
2025
+ ...pageCursors(h, position, connection?.pageInfo)
2026
+ });
2027
+ }
2028
+ },
2029
+ {
2030
+ name: "list_locations",
2031
+ kind: "read",
2032
+ title: "List Shopify locations",
2033
+ description: "Lists the shop's locations (warehouses, stores) with their ids for stock: name, whether active and fulfilling online orders, and city and country.",
2034
+ inputSchema: LIST_LOCATIONS_SCHEMA,
2035
+ async run(args, h) {
2036
+ const position = listPosition(h, LIST_LOCATIONS_SCHEMA, args);
2037
+ const f = position.filters;
2038
+ const response = await graphql(h, `query Locations($first: Int!, $after: String, $includeInactive: Boolean) {
2039
+ locations(first: $first, after: $after, includeInactive: $includeInactive) { nodes { id name isActive fulfillsOnlineOrders address { city countryCode } } pageInfo { hasNextPage endCursor } }
2040
+ }`, { first: f["first"] ?? 50, after: position.after ?? null, includeInactive: f["include_inactive"] ?? false });
2041
+ const connection = response.data?.locations;
2042
+ const nodes = Array.isArray(connection?.nodes) ? connection.nodes : [];
2043
+ return h.page({
2044
+ key: "locations",
2045
+ items: nodes.map((location) => compact({
2046
+ id: location?.id,
2047
+ name: location?.name,
2048
+ active: location?.isActive,
2049
+ fulfillsOnlineOrders: location?.fulfillsOnlineOrders,
2050
+ city: location?.address?.city,
2051
+ country: location?.address?.countryCode
2052
+ })).slice(position.skip),
2053
+ ...pageCursors(h, position, connection?.pageInfo)
2054
+ });
2055
+ }
2056
+ },
2057
+ {
2058
+ name: "get_inventory",
2059
+ kind: "read",
2060
+ title: "Get Shopify stock levels",
2061
+ description: "The stock of one variant (or inventory item) at each location: available, on hand, committed, incoming and reserved, with the location ids and the inventory item id set_inventory_quantity needs.",
2062
+ inputSchema: {
2063
+ type: "object",
2064
+ properties: {
2065
+ variant_id: ID("ProductVariant", "The variant id"),
2066
+ inventory_item_id: ID("InventoryItem", "Or the inventory item id")
2067
+ },
2068
+ additionalProperties: false
2069
+ },
2070
+ async run(args, h) {
2071
+ if (args.variant_id === void 0 === (args.inventory_item_id === void 0)) throw new ToolFailure("Give variant_id or inventory_item_id (one of them). Nothing was sent.");
2072
+ const response = args.variant_id !== void 0 ? await graphql(h, `query VariantStock($id: ID!) { productVariant(id: $id) { id title product { id title } inventoryItem { ...Levels } } }
2073
+ ${INVENTORY_LEVELS}`, { id: gid("ProductVariant", args.variant_id, "variant_id") }) : await graphql(h, `query ItemStock($id: ID!) { inventoryItem(id: $id) { ...Levels variant { id title product { id title } } } }
2074
+ ${INVENTORY_LEVELS}`, { id: gid("InventoryItem", args.inventory_item_id, "inventory_item_id") });
2075
+ const variant = args.variant_id !== void 0 ? response.data?.productVariant : response.data?.inventoryItem?.variant;
2076
+ const item = args.variant_id !== void 0 ? response.data?.productVariant?.inventoryItem : response.data?.inventoryItem;
2077
+ if (!item) throw new ToolFailure(`Shopify found no ${args.variant_id !== void 0 ? "variant" : "inventory item"} with that id.`);
2078
+ const levels = Array.isArray(item.inventoryLevels?.nodes) ? item.inventoryLevels.nodes : [];
2079
+ return withWarnings(compact({
2080
+ inventoryItemId: item.id,
2081
+ sku: item.sku,
2082
+ tracked: item.tracked,
2083
+ variant: variant ? compact({ id: variant.id, title: variant.title, product: variant.product?.title, productId: variant.product?.id }) : void 0,
2084
+ levels: levels.map((level) => ({
2085
+ locationId: level?.location?.id,
2086
+ location: level?.location?.name,
2087
+ ...Object.fromEntries((Array.isArray(level?.quantities) ? level.quantities : []).map((quantity) => [quantity?.name, quantity?.quantity])),
2088
+ updatedAt: level?.updatedAt
2089
+ }))
2090
+ }), response);
2091
+ }
2092
+ },
2093
+ {
2094
+ name: "set_inventory_quantity",
2095
+ kind: "update",
2096
+ check: "get_inventory",
2097
+ title: "Set a Shopify stock quantity",
2098
+ description: "Sets the available (or on hand) quantity of one variant at one location. Shopify applies it only if the stock is still expected_quantity (the number seen when deciding; without it, the stock is read right before). skip_quantity_check: true overwrites whatever is there. The same call sent again within 15 minutes is applied once.",
2099
+ inputSchema: {
2100
+ type: "object",
2101
+ properties: {
2102
+ variant_id: ID("ProductVariant", "The variant id"),
2103
+ inventory_item_id: ID("InventoryItem", "Or its inventory item id"),
2104
+ location_id: ID("Location", "The location id (list_locations or get_inventory)"),
2105
+ quantity: { type: "integer", minimum: -1e6, maximum: 1e9, description: "The new quantity." },
2106
+ expected_quantity: { type: "integer", minimum: -1e6, maximum: 1e9, description: "The current quantity seen when deciding." },
2107
+ skip_quantity_check: { type: "boolean", default: false, description: "Overwrite without comparing (only when this system is the source of truth)." },
2108
+ name: { type: "string", enum: ["available", "on_hand"], default: "available" },
2109
+ reason: { type: "string", enum: INVENTORY_REASONS, default: "correction" },
2110
+ reference_document_uri: { type: "string", maxLength: 500, pattern: "^[a-z][a-z0-9+.-]*:\\S+$", description: "A URI of the document behind the change, e.g. a purchase order." },
2111
+ idempotency_key: { type: "string", minLength: 8, maxLength: 255, pattern: "^[A-Za-z0-9_.:-]+$", description: "Your own key for this change (default: made from the arguments)." }
2112
+ },
2113
+ required: ["location_id", "quantity"],
2114
+ additionalProperties: false
2115
+ },
2116
+ async run(args, h) {
2117
+ if (args.variant_id === void 0 === (args.inventory_item_id === void 0)) throw new ToolFailure("Give variant_id or inventory_item_id (one of them). Nothing was sent.");
2118
+ if (args.skip_quantity_check && args.expected_quantity !== void 0) throw new ToolFailure("Give expected_quantity or skip_quantity_check, not both. Nothing was sent.");
2119
+ const locationId = gid("Location", args.location_id, "location_id");
2120
+ let itemId = args.inventory_item_id !== void 0 ? gid("InventoryItem", args.inventory_item_id, "inventory_item_id") : void 0;
2121
+ let previous = args.skip_quantity_check ? null : args.expected_quantity;
2122
+ if (itemId === void 0 || previous === void 0) {
2123
+ const level = `id tracked inventoryLevel(locationId: $locationId) { quantities(names: [$name]) { name quantity } }`;
2124
+ const response2 = itemId === void 0 ? await graphql(h, `query Stock($id: ID!, $locationId: ID!, $name: String!) { productVariant(id: $id) { inventoryItem { ${level} } } }`, {
2125
+ id: gid("ProductVariant", args.variant_id, "variant_id"),
2126
+ locationId,
2127
+ name: args.name
2128
+ }) : await graphql(h, `query Stock($id: ID!, $locationId: ID!, $name: String!) { inventoryItem(id: $id) { ${level} } }`, { id: itemId, locationId, name: args.name });
2129
+ const item = itemId === void 0 ? response2.data?.productVariant?.inventoryItem : response2.data?.inventoryItem;
2130
+ if (!item?.id) throw new ToolFailure(`Shopify found no ${itemId === void 0 ? "variant" : "inventory item"} with that id. Nothing was changed.`);
2131
+ itemId = item.id;
2132
+ if (previous === void 0) {
2133
+ if (!item.inventoryLevel) {
2134
+ throw new ToolFailure(
2135
+ "The item is not stocked at that location: activate it there first (inventoryActivate, through graphql_mutation), or choose a location get_inventory lists. Nothing was changed."
2136
+ );
2137
+ }
2138
+ const current = (Array.isArray(item.inventoryLevel.quantities) ? item.inventoryLevel.quantities : []).find((quantity) => quantity?.name === args.name);
2139
+ previous = typeof current?.quantity === "number" ? current.quantity : null;
2140
+ }
2141
+ }
2142
+ const input = compact({
2143
+ name: args.name,
2144
+ reason: args.reason,
2145
+ referenceDocumentUri: args.reference_document_uri,
2146
+ quantities: [{ inventoryItemId: itemId, locationId, quantity: args.quantity, changeFromQuantity: previous ?? null }]
2147
+ });
2148
+ const key = args.idempotency_key ?? await idempotencyKey(input);
2149
+ const response = await graphql(h, `mutation SetQuantity($input: InventorySetQuantitiesInput!, $key: String!) {
2150
+ inventorySetQuantities(input: $input) @idempotent(key: $key) {
2151
+ inventoryAdjustmentGroup { createdAt reason referenceDocumentUri changes { name delta quantityAfterChange location { id name } } }
2152
+ userErrors { code field message }
2153
+ }
2154
+ }`, { input, key }, { write: true });
2155
+ const payload = response.data?.inventorySetQuantities;
2156
+ const stale = Array.isArray(payload?.userErrors) && payload.userErrors.some((error) => error?.code === "CHANGE_FROM_QUANTITY_STALE");
2157
+ if (stale) {
2158
+ throw new ToolFailure(
2159
+ `The stock is no longer ${previous}: it changed since it was read. Read it again with get_inventory and decide again. Nothing was changed.`,
2160
+ { vendorCode: "CHANGE_FROM_QUANTITY_STALE" }
2161
+ );
2162
+ }
2163
+ assertNoUserErrors(payload, "set the quantity");
2164
+ const group = payload?.inventoryAdjustmentGroup;
2165
+ return withWarnings(compact({
2166
+ inventoryItemId: itemId,
2167
+ locationId,
2168
+ name: args.name,
2169
+ previousQuantity: previous,
2170
+ quantity: args.quantity,
2171
+ changed: Boolean(group),
2172
+ changes: Array.isArray(group?.changes) && group.changes.length ? group.changes.map((change) => compact({ name: change?.name, delta: change?.delta, quantityAfterChange: change?.quantityAfterChange, location: change?.location?.name })) : void 0,
2173
+ idempotencyKey: key
2174
+ }), response);
2175
+ }
2176
+ },
2177
+ {
2178
+ name: "list_orders",
2179
+ kind: "read",
2180
+ title: "List Shopify orders",
2181
+ description: "Lists orders, newest first: id, name (#1001), date, payment and fulfillment status, total, refunds, item count, returns and tags. No customer details. query takes Shopify search syntax. Shopify shows the last 60 days unless the app may read all orders. Pass nextCursor back as cursor for more.",
2182
+ inputSchema: LIST_ORDERS_SCHEMA,
2183
+ async run(args, h) {
2184
+ const position = listPosition(h, LIST_ORDERS_SCHEMA, args);
2185
+ const f = position.filters;
2186
+ const response = await graphql(h, `query Orders($first: Int!, $after: String, $query: String, $sortKey: OrderSortKeys, $reverse: Boolean) {
2187
+ orders(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) {
2188
+ nodes { id name createdAt displayFinancialStatus displayFulfillmentStatus cancelledAt closed test tags returnStatus currencyCode subtotalLineItemsQuantity
2189
+ currentTotalPriceSet { shopMoney { amount } } totalRefundedSet { shopMoney { amount } } }
2190
+ pageInfo { hasNextPage endCursor }
2191
+ }
2192
+ }`, { first: f["first"] ?? 25, after: position.after ?? null, query: f["query"] ?? null, sortKey: f["sort_key"] ?? "CREATED_AT", reverse: f["reverse"] ?? true });
2193
+ const connection = response.data?.orders;
2194
+ const orders = Array.isArray(connection?.nodes) ? connection.nodes : [];
2195
+ return h.page({
2196
+ key: "orders",
2197
+ items: orders.map(trimListOrder).slice(position.skip),
2198
+ extra: response.warnings.length ? { warnings: response.warnings.slice(0, 5) } : {},
2199
+ ...pageCursors(h, position, connection?.pageInfo)
2200
+ });
2201
+ }
2202
+ },
2203
+ {
2204
+ name: "get_order",
2205
+ kind: "read",
2206
+ title: "Get a Shopify order",
2207
+ description: "One order by id or name (#1001): totals, line items, fulfillment orders with what is left to ship (the ids fulfill_order needs), fulfillments with tracking, refunds, note and tags; with include_customer_details the customer, email, phone and addresses (which need Shopify's protected customer data access).",
2208
+ inputSchema: {
2209
+ type: "object",
2210
+ properties: {
2211
+ id: ID("Order", "The order id"),
2212
+ name: { type: "string", minLength: 1, maxLength: 100, description: "Or the order name, e.g. #1001." },
2213
+ include_customer_details: { type: "boolean", default: false }
2214
+ },
2215
+ additionalProperties: false
2216
+ },
2217
+ async run(args, h) {
2218
+ if (args.id === void 0 === (args.name === void 0)) throw new ToolFailure("Give id or name (one of them). Nothing was sent.");
2219
+ let order;
2220
+ let response;
2221
+ if (args.id !== void 0) {
2222
+ response = await graphql(h, `query Order($id: ID!, $contact: Boolean!) { order(id: $id) { ...OrderDetail } }
2223
+ ${ORDER_DETAIL}`, {
2224
+ id: gid("Order", args.id, "id"),
2225
+ contact: args.include_customer_details
2226
+ });
2227
+ order = response.data?.order;
2228
+ } else {
2229
+ const name2 = args.name;
2230
+ const lookup = await graphql(h, "query OrderIdByName($query: String!) { orders(first: 5, query: $query) { nodes { id name } } }", { query: `name:${searchValue(name2)}` });
2231
+ const wanted = name2.replace(/^#/, "");
2232
+ const match = (Array.isArray(lookup.data?.orders?.nodes) ? lookup.data.orders.nodes : []).find((node) => String(node?.name ?? "").replace(/^#/, "") === wanted);
2233
+ if (typeof match?.id !== "string") throw new ToolFailure("Shopify found no order with that name.");
2234
+ response = await graphql(h, `query Order($id: ID!, $contact: Boolean!) { order(id: $id) { ...OrderDetail } }
2235
+ ${ORDER_DETAIL}`, {
2236
+ id: match.id,
2237
+ contact: args.include_customer_details
2238
+ });
2239
+ order = response.data?.order;
2240
+ }
2241
+ if (!order) throw new ToolFailure(`Shopify found no order with that ${args.id !== void 0 ? "id" : "name"}.`);
2242
+ return withWarnings(trimOrder(order), response);
2243
+ }
2244
+ },
2245
+ {
2246
+ name: "fulfill_order",
2247
+ kind: "create",
2248
+ check: "get_order",
2249
+ title: "Fulfill a Shopify order",
2250
+ description: "Marks items of one fulfillment order as shipped (ids from get_order): all that is left, or the line items and quantities given, with optional tracking. notify_customer: true makes Shopify email the customer. Needs the staff permission to fulfill orders.",
2251
+ inputSchema: {
2252
+ type: "object",
2253
+ properties: {
2254
+ fulfillment_order_id: ID("FulfillmentOrder", "The fulfillment order id"),
2255
+ line_items: {
2256
+ type: "array",
2257
+ maxItems: 250,
2258
+ items: {
2259
+ type: "object",
2260
+ properties: { id: ID("FulfillmentOrderLineItem", "The fulfillment order line item id"), quantity: { type: "integer", minimum: 1 } },
2261
+ required: ["id", "quantity"],
2262
+ additionalProperties: false
2263
+ },
2264
+ description: "Only these items and quantities (default: everything left)."
2265
+ },
2266
+ tracking_company: { type: "string", maxLength: 255, description: 'The carrier, e.g. "DHL Express".' },
2267
+ tracking_number: { type: "string", maxLength: 255 },
2268
+ tracking_url: { type: "string", format: "uri", maxLength: 2e3 },
2269
+ notify_customer: { type: "boolean", default: false }
2270
+ },
2271
+ required: ["fulfillment_order_id"],
2272
+ additionalProperties: false
2273
+ },
2274
+ async run(args, h) {
2275
+ const tracking = compact({ company: args.tracking_company, number: args.tracking_number, url: args.tracking_url });
2276
+ const fulfillment = compact({
2277
+ lineItemsByFulfillmentOrder: [compact({
2278
+ fulfillmentOrderId: gid("FulfillmentOrder", args.fulfillment_order_id, "fulfillment_order_id"),
2279
+ fulfillmentOrderLineItems: Array.isArray(args.line_items) && args.line_items.length ? args.line_items.map((item, at) => ({ id: gid("FulfillmentOrderLineItem", item.id, `line_items[${at}].id`), quantity: item.quantity })) : void 0
2280
+ })],
2281
+ trackingInfo: Object.keys(tracking).length ? tracking : void 0,
2282
+ notifyCustomer: args.notify_customer
2283
+ });
2284
+ const response = await graphql(h, `mutation Fulfill($fulfillment: FulfillmentInput!) {
2285
+ fulfillmentCreate(fulfillment: $fulfillment) {
2286
+ fulfillment { id status createdAt trackingInfo(first: 5) { company number url } fulfillmentLineItems(first: 50) { nodes { quantity lineItem { name sku } } } }
2287
+ userErrors { field message }
2288
+ }
2289
+ }`, { fulfillment }, { write: true });
2290
+ const payload = response.data?.fulfillmentCreate;
2291
+ assertNoUserErrors(payload, "fulfill the items");
2292
+ const created = payload?.fulfillment;
2293
+ return withWarnings(compact({
2294
+ id: created?.id,
2295
+ status: created?.status,
2296
+ createdAt: created?.createdAt,
2297
+ tracking: Array.isArray(created?.trackingInfo) && created.trackingInfo.length ? created.trackingInfo.map((info) => compact(info ?? {})) : void 0,
2298
+ items: Array.isArray(created?.fulfillmentLineItems?.nodes) ? created.fulfillmentLineItems.nodes.map((item) => compact({ name: item?.lineItem?.name, sku: item?.lineItem?.sku, quantity: item?.quantity })) : void 0,
2299
+ customerNotified: args.notify_customer
2300
+ }), response);
2301
+ }
2302
+ },
2303
+ {
2304
+ name: "list_customers",
2305
+ kind: "read",
2306
+ title: "List Shopify customers",
2307
+ description: "Lists customers, most recently updated first: id, name, state, number of orders, amount spent and tags; with include_contact their email and phone. query takes Shopify search syntax, such as an exact email. Names and contacts need Shopify's protected customer data access. Pass nextCursor back as cursor for more.",
2308
+ inputSchema: LIST_CUSTOMERS_SCHEMA,
2309
+ async run(args, h) {
2310
+ const position = listPosition(h, LIST_CUSTOMERS_SCHEMA, args);
2311
+ const f = position.filters;
2312
+ const response = await graphql(h, `query Customers($first: Int!, $after: String, $query: String, $sortKey: CustomerSortKeys, $reverse: Boolean, $contact: Boolean!) {
2313
+ customers(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) {
2314
+ nodes { id firstName lastName state tags numberOfOrders amountSpent { amount currencyCode } createdAt updatedAt
2315
+ defaultEmailAddress @include(if: $contact) { emailAddress } defaultPhoneNumber @include(if: $contact) { phoneNumber } }
2316
+ pageInfo { hasNextPage endCursor }
2317
+ }
2318
+ }`, { first: f["first"] ?? 25, after: position.after ?? null, query: f["query"] ?? null, sortKey: f["sort_key"] ?? "UPDATED_AT", reverse: f["reverse"] ?? true, contact: f["include_contact"] === true });
2319
+ const connection = response.data?.customers;
2320
+ const customers = Array.isArray(connection?.nodes) ? connection.nodes : [];
2321
+ return h.page({
2322
+ key: "customers",
2323
+ items: customers.map(trimCustomer).slice(position.skip),
2324
+ extra: response.warnings.length ? { warnings: response.warnings.slice(0, 5) } : {},
2325
+ ...pageCursors(h, position, connection?.pageInfo)
2326
+ });
2327
+ }
2328
+ },
2329
+ {
2330
+ name: "list_discounts",
2331
+ kind: "read",
2332
+ title: "List Shopify discounts",
2333
+ description: "Lists discounts, code and automatic: kind, title, status, summary, codes, dates, usage limit and times used; or one by its exact code. Pass nextCursor back as cursor for more.",
2334
+ inputSchema: LIST_DISCOUNTS_SCHEMA,
2335
+ async run(args, h) {
2336
+ if (typeof args["code"] === "string") {
2337
+ if (args["query"] !== void 0 || args["cursor"] !== void 0) throw new ToolFailure("code finds one discount: give it without query or cursor. Nothing was sent.");
2338
+ const response2 = await graphql(h, `query DiscountByCode($code: String!) { codeDiscountNodeByCode(code: $code) { id codeDiscount { __typename ${CODE_DISCOUNT_FIELDS} } } }`, { code: args["code"] });
2339
+ const node = response2.data?.codeDiscountNodeByCode;
2340
+ return withWarnings({ discounts: node ? [trimDiscount(node.id, node.codeDiscount)] : [] }, response2);
2341
+ }
2342
+ const position = listPosition(h, LIST_DISCOUNTS_SCHEMA, args);
2343
+ const f = position.filters;
2344
+ const response = await graphql(h, `query Discounts($first: Int!, $after: String, $query: String, $sortKey: DiscountSortKeys, $reverse: Boolean) {
2345
+ discountNodes(first: $first, after: $after, query: $query, sortKey: $sortKey, reverse: $reverse) {
2346
+ nodes { id discount { __typename ${CODE_DISCOUNT_FIELDS}
2347
+ ... on DiscountAutomaticBasic { title status summary startsAt endsAt }
2348
+ ... on DiscountAutomaticBxgy { title status summary startsAt endsAt }
2349
+ ... on DiscountAutomaticFreeShipping { title status summary startsAt endsAt }
2350
+ ... on DiscountAutomaticApp { title status startsAt endsAt } } }
2351
+ pageInfo { hasNextPage endCursor }
2352
+ }
2353
+ }`, { first: f["first"] ?? 25, after: position.after ?? null, query: f["query"] ?? null, sortKey: f["sort_key"] ?? "CREATED_AT", reverse: f["reverse"] ?? true });
2354
+ const connection = response.data?.discountNodes;
2355
+ const nodes = Array.isArray(connection?.nodes) ? connection.nodes : [];
2356
+ return h.page({
2357
+ key: "discounts",
2358
+ items: nodes.map((node) => trimDiscount(node?.id, node?.discount)).slice(position.skip),
2359
+ extra: response.warnings.length ? { warnings: response.warnings.slice(0, 5) } : {},
2360
+ ...pageCursors(h, position, connection?.pageInfo)
2361
+ });
2362
+ }
2363
+ },
2364
+ {
2365
+ name: "create_discount_code",
2366
+ kind: "create",
2367
+ check: "list_discounts",
2368
+ title: "Create a Shopify discount code",
2369
+ description: "Creates a discount code for all customers: a percentage or a fixed amount off all items, or off some products, variants or collections, with optional start and end, total usage limit, once per customer, a minimum subtotal or quantity, and which other discounts it combines with. It works from starts_at (default now). Shopify refuses a code that exists.",
2370
+ inputSchema: {
2371
+ type: "object",
2372
+ properties: {
2373
+ code: { type: "string", minLength: 1, maxLength: 255, description: "What customers enter." },
2374
+ title: { type: "string", maxLength: 255, description: "The name in the admin (default: the code)." },
2375
+ percentage: { type: "number", minimum: 0.01, maximum: 100, description: "Percent off, e.g. 15." },
2376
+ amount: MONEY("Or an amount off, in the shop's currency."),
2377
+ applies_on_each_item: { type: "boolean", default: false, description: "With amount: off each item, not once per order." },
2378
+ starts_at: { type: "string", maxLength: 40, description: "ISO date and time (default now)." },
2379
+ ends_at: { type: "string", maxLength: 40, description: "ISO date and time; none for no end." },
2380
+ usage_limit: { type: "integer", minimum: 1, description: "Uses in all." },
2381
+ once_per_customer: { type: "boolean", default: false },
2382
+ minimum_subtotal: MONEY("The smallest order subtotal it works with."),
2383
+ minimum_quantity: { type: "integer", minimum: 1, description: "Or the fewest items." },
2384
+ product_ids: ID_LIST("Product", "Only these products."),
2385
+ variant_ids: ID_LIST("ProductVariant", "Only these variants."),
2386
+ collection_ids: ID_LIST("Collection", "Only these collections."),
2387
+ combines_with_order_discounts: { type: "boolean", default: false },
2388
+ combines_with_product_discounts: { type: "boolean", default: false },
2389
+ combines_with_shipping_discounts: { type: "boolean", default: false }
2390
+ },
2391
+ required: ["code"],
2392
+ additionalProperties: false
2393
+ },
2394
+ async run(args, h) {
2395
+ const refuse = (sentence) => {
2396
+ throw new ToolFailure(`${sentence} Nothing was sent.`);
2397
+ };
2398
+ if (args.percentage === void 0 === (args.amount === void 0)) refuse("Give percentage or amount (one of them).");
2399
+ if (args.minimum_subtotal !== void 0 && args.minimum_quantity !== void 0) refuse("Give minimum_subtotal or minimum_quantity, not both.");
2400
+ const products = [...(args.product_ids ?? []).map((id, at) => gid("Product", id, `product_ids[${at}]`))];
2401
+ const variants = [...(args.variant_ids ?? []).map((id, at) => gid("ProductVariant", id, `variant_ids[${at}]`))];
2402
+ const collections = [...(args.collection_ids ?? []).map((id, at) => gid("Collection", id, `collection_ids[${at}]`))];
2403
+ if (collections.length && (products.length || variants.length)) refuse("Give collections or products and variants, not both.");
2404
+ for (const [name2, value] of [["starts_at", args.starts_at], ["ends_at", args.ends_at]]) {
2405
+ if (value !== void 0 && Number.isNaN(Date.parse(value))) refuse(`${name2} is not a date and time, e.g. 2026-12-01T00:00:00Z.`);
2406
+ }
2407
+ const items = collections.length ? { collections: { add: collections } } : products.length || variants.length ? { products: compact({ productsToAdd: products.length ? products : void 0, productVariantsToAdd: variants.length ? variants : void 0 }) } : { all: true };
2408
+ const input = compact({
2409
+ title: args.title ?? args.code,
2410
+ code: args.code,
2411
+ startsAt: args.starts_at ?? (/* @__PURE__ */ new Date()).toISOString(),
2412
+ endsAt: args.ends_at,
2413
+ usageLimit: args.usage_limit,
2414
+ appliesOncePerCustomer: args.once_per_customer,
2415
+ context: { all: "ALL" },
2416
+ customerGets: {
2417
+ value: args.percentage !== void 0 ? { percentage: Math.round(args.percentage * 100) / 1e4 } : { discountAmount: { amount: args.amount, appliesOnEachItem: args.applies_on_each_item } },
2418
+ items
2419
+ },
2420
+ minimumRequirement: args.minimum_subtotal !== void 0 ? { subtotal: { greaterThanOrEqualToSubtotal: args.minimum_subtotal } } : args.minimum_quantity !== void 0 ? { quantity: { greaterThanOrEqualToQuantity: String(args.minimum_quantity) } } : void 0,
2421
+ combinesWith: {
2422
+ orderDiscounts: args.combines_with_order_discounts,
2423
+ productDiscounts: args.combines_with_product_discounts,
2424
+ shippingDiscounts: args.combines_with_shipping_discounts
2425
+ }
2426
+ });
2427
+ const response = await graphql(h, `mutation CreateDiscount($basicCodeDiscount: DiscountCodeBasicInput!) {
2428
+ discountCodeBasicCreate(basicCodeDiscount: $basicCodeDiscount) {
2429
+ codeDiscountNode { id codeDiscount { __typename ... on DiscountCodeBasic { title status summary startsAt endsAt usageLimit appliesOncePerCustomer codes(first: 1) { nodes { code } } } } }
2430
+ userErrors { field message code }
2431
+ }
2432
+ }`, { basicCodeDiscount: input }, { write: true });
2433
+ const payload = response.data?.discountCodeBasicCreate;
2434
+ assertNoUserErrors(payload, "create the discount");
2435
+ const node = payload?.codeDiscountNode;
2436
+ return withWarnings(trimDiscount(node?.id, node?.codeDiscount), response);
2437
+ }
2438
+ },
2439
+ {
2440
+ name: "graphql_query",
2441
+ kind: "read",
2442
+ title: "Run a Shopify GraphQL query",
2443
+ description: `Runs one GraphQL query (not a mutation) on the shop's Admin API ${API_VERSION} with the connected app's scopes, for what the other tools do not cover: metafields, inventory items, returns, transactions, markets, bulk operation status and more. Returns data, errors next to partial data, and the query cost. Ask for few fields and items (connections with first/after); a query may cost at most 1,000 points. Reference: https://shopify.dev/docs/api/admin-graphql.`,
2444
+ inputSchema: {
2445
+ type: "object",
2446
+ properties: {
2447
+ query: { type: "string", minLength: 1, maxLength: 5e4, description: "The GraphQL document: query operations and fragments." },
2448
+ variables: { type: "object", description: "Its variables." },
2449
+ operation_name: { type: "string", pattern: "^[_A-Za-z][_0-9A-Za-z]{0,99}$", description: "Which operation to run, when the document has several." }
2450
+ },
2451
+ required: ["query"],
2452
+ additionalProperties: false
2453
+ },
2454
+ async run(args, h) {
2455
+ const document = readDocument(args.query);
2456
+ if (document.operations.some((operation) => operation !== "query")) {
2457
+ throw new ToolFailure("graphql_query runs queries only: send mutations with graphql_mutation. Nothing was sent.");
2458
+ }
2459
+ const response = await graphql(h, args.query, args.variables ?? {}, args.operation_name ? { operationName: args.operation_name } : {});
2460
+ return compact({ data: response.data, errors: response.warnings.length ? response.warnings : void 0, cost: response.cost });
2461
+ }
2462
+ },
2463
+ {
2464
+ name: "graphql_mutation",
2465
+ kind: "write",
2466
+ check: "graphql_query",
2467
+ title: "Run a Shopify GraphQL mutation",
2468
+ description: `Runs one GraphQL mutation on the shop's Admin API ${API_VERSION}, such as customerCreate, orderCancel, refundCreate, collectionCreate, productVariantsBulkCreate, productDelete, inventoryAdjustQuantities or tagsAdd. Inventory and refund mutations need @idempotent(key: "...") with a unique key. userErrors mean nothing changed. Sent once, never retried: check with graphql_query. Refused: webhook subscriptions, carrier and fulfillment service callbacks, server pixel endpoints, bulk mutations (bulkOperationRunMutation) and new access tokens.`,
2469
+ inputSchema: {
2470
+ type: "object",
2471
+ properties: {
2472
+ query: { type: "string", minLength: 1, maxLength: 5e4, description: "The GraphQL document with the mutation." },
2473
+ variables: { type: "object", description: "Its variables." },
2474
+ operation_name: { type: "string", pattern: "^[_A-Za-z][_0-9A-Za-z]{0,99}$", description: "Which operation to run, when the document has several." }
2475
+ },
2476
+ required: ["query"],
2477
+ additionalProperties: false
2478
+ },
2479
+ async run(args, h) {
2480
+ const document = readDocument(args.query);
2481
+ if (document.operations.includes("subscription")) throw new ToolFailure("Subscriptions cannot be sent. Nothing was sent.");
2482
+ if (!document.operations.includes("mutation")) throw new ToolFailure("The document holds no mutation: run queries with graphql_query. Nothing was sent.");
2483
+ const blocked = BLOCKED_MUTATIONS.filter((name2) => document.names.has(name2));
2484
+ if (blocked.length) throw new ToolFailure(`${blocked.join(", ")} cannot be sent through this connector. Nothing was sent.`);
2485
+ const needsKey = IDEMPOTENT_MUTATIONS.filter((name2) => document.names.has(name2));
2486
+ if (needsKey.length && !document.directives.has("idempotent")) {
2487
+ throw new ToolFailure(`${needsKey.join(", ")} needs @idempotent(key: "<a unique key>") after its arguments; reuse the key only to resend the same change. Nothing was sent.`);
2488
+ }
2489
+ const response = await graphql(h, args.query, args.variables ?? {}, { write: true, ...args.operation_name ? { operationName: args.operation_name } : {} });
2490
+ const data = response.data ?? {};
2491
+ const failed = [];
2492
+ let succeeded = 0;
2493
+ for (const [field, payload] of Object.entries(data)) {
2494
+ if (Array.isArray(payload?.userErrors) && payload.userErrors.length) failed.push(field);
2495
+ else succeeded++;
2496
+ }
2497
+ if (failed.length && !succeeded) {
2498
+ const texts = failed.map((field) => `${field}: ${data[field].userErrors.map((error) => `${Array.isArray(error?.field) ? `${error.field.join(".")} ` : ""}${String(error?.message ?? "")}`.trim()).join("; ")}`);
2499
+ throw new ToolFailure(`Shopify did not make the change: ${truncate(texts.join(" | "), 1500)}. Nothing was changed.`);
2500
+ }
2501
+ return compact({
2502
+ data,
2503
+ userErrors: failed.length ? `Shopify refused ${failed.join(", ")}; the rest was done.` : void 0,
2504
+ errors: response.warnings.length ? response.warnings : void 0,
2505
+ cost: response.cost
2506
+ });
2507
+ }
2508
+ }
2509
+ ]
2510
+ });
2511
+ module.exports = connector;