@adport/provider-snapchat 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +197 -3
- package/dist/index.js +832 -53
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -22,7 +22,7 @@ async function exchangeSnapchatCode(input, fetchImpl = fetch) {
|
|
|
22
22
|
signal: AbortSignal.timeout(3e4)
|
|
23
23
|
});
|
|
24
24
|
if (!response.ok) throw new AdportError("PROVIDER_ERROR", `snapchat: OAuth exchange failed (HTTP ${response.status})`);
|
|
25
|
-
const parsed = tokenSchema.safeParse(await response.json());
|
|
25
|
+
const parsed = tokenSchema.safeParse(await response.json().catch(() => void 0));
|
|
26
26
|
if (!parsed.success || !parsed.data.refresh_token) throw new AdportError("PROVIDER_ERROR", "snapchat: OAuth response did not include a valid refresh token");
|
|
27
27
|
return parsed.data.refresh_token;
|
|
28
28
|
}
|
|
@@ -37,6 +37,12 @@ var tokenSchema = z.object({
|
|
|
37
37
|
expires_in: z.number().positive(),
|
|
38
38
|
refresh_token: z.string().min(1).optional()
|
|
39
39
|
});
|
|
40
|
+
function snapchatUploadPath(path, mediaId, action) {
|
|
41
|
+
if (!/^[A-Za-z0-9_-]+$/.test(mediaId)) throw new AdportError("INVALID_INPUT", "snapchat: invalid media ID");
|
|
42
|
+
const url = new URL(path, SNAPCHAT_API_BASE);
|
|
43
|
+
if (url.origin !== "https://adsapi.snapchat.com" || ![`/v1/media/${mediaId}/multipart-upload-v2`, `/us/v1/media/${mediaId}/multipart-upload-v2`].includes(url.pathname) || url.username || url.password || url.hash || url.searchParams.size !== 1 || url.searchParams.get("action") !== action) throw new AdportError("PROVIDER_ERROR", "snapchat: upload path changed media/action scope");
|
|
44
|
+
return url;
|
|
45
|
+
}
|
|
40
46
|
var SnapchatAdsClient = class {
|
|
41
47
|
constructor(credentials, fetchImpl = fetch) {
|
|
42
48
|
this.credentials = credentials;
|
|
@@ -48,7 +54,7 @@ var SnapchatAdsClient = class {
|
|
|
48
54
|
token;
|
|
49
55
|
refreshToken;
|
|
50
56
|
refreshing;
|
|
51
|
-
async collection(path, plural,
|
|
57
|
+
async collection(path, plural, singular2, schema, params = {}) {
|
|
52
58
|
let url = this.url(path, params);
|
|
53
59
|
const resourcePath = url.pathname;
|
|
54
60
|
const visited = /* @__PURE__ */ new Set();
|
|
@@ -59,28 +65,94 @@ var SnapchatAdsClient = class {
|
|
|
59
65
|
}
|
|
60
66
|
visited.add(url.href);
|
|
61
67
|
const data = await this.send(url, "GET");
|
|
62
|
-
rows.push(...this.items(data, plural,
|
|
68
|
+
rows.push(...this.items(data, plural, singular2, schema));
|
|
63
69
|
const next = data.paging?.next_link;
|
|
64
70
|
if (!next) return rows;
|
|
65
71
|
url = this.url(next);
|
|
66
72
|
if (url.pathname !== resourcePath) throw new AdportError("PROVIDER_ERROR", "snapchat: pagination changed resource scope");
|
|
67
73
|
}
|
|
68
74
|
}
|
|
69
|
-
async mutate(path, method, body, plural,
|
|
75
|
+
async mutate(path, method, body, plural, singular2, schema) {
|
|
76
|
+
return (await this.mutation(path, method, body, plural, singular2, schema)).items;
|
|
77
|
+
}
|
|
78
|
+
async mutation(path, method, body, plural, singular2, schema) {
|
|
79
|
+
const data = await this.send(this.url(path), method, body, false, true);
|
|
80
|
+
const items = this.items(data, plural, singular2, schema);
|
|
81
|
+
const warnings = this.warnings(data, plural);
|
|
82
|
+
return { items, warnings };
|
|
83
|
+
}
|
|
84
|
+
async page(path, plural, singular2, schema, params) {
|
|
85
|
+
const url = this.url(path, params), data = await this.send(url, "GET");
|
|
86
|
+
const rows = this.items(data, plural, singular2, schema);
|
|
87
|
+
let cursor;
|
|
88
|
+
if (data.paging?.next_link) {
|
|
89
|
+
const next = this.url(data.paging.next_link);
|
|
90
|
+
if (next.pathname !== url.pathname || !(cursor = next.searchParams.get("cursor") ?? void 0) || cursor === params.cursor) throw new AdportError("PROVIDER_ERROR", "snapchat: pagination changed scope or repeated cursor");
|
|
91
|
+
}
|
|
92
|
+
return { items: rows, truncated: Boolean(cursor), ...cursor ? { next_cursor: cursor } : {}, warnings: this.warnings(data, plural) };
|
|
93
|
+
}
|
|
94
|
+
async request(path, method, schema, body) {
|
|
70
95
|
const data = await this.send(this.url(path), method, body);
|
|
71
|
-
|
|
96
|
+
const parsed = schema.safeParse(data);
|
|
97
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "snapchat: malformed API response", { response_issues: parsed.error.issues.map((issue) => ({ path: issue.path, code: issue.code })) });
|
|
98
|
+
return parsed.data;
|
|
72
99
|
}
|
|
73
|
-
|
|
100
|
+
/** A read-only, account-bound Public Profile API call, never a caller-supplied URL. */
|
|
101
|
+
async sharingPolicies(accountId, resourceType) {
|
|
102
|
+
if (!/^[A-Za-z0-9_-]+$/.test(accountId)) throw new AdportError("INVALID_INPUT", "snapchat: invalid ad-account ID");
|
|
103
|
+
const path = `/v1/adaccounts/${accountId}/sharing_policies`;
|
|
104
|
+
let url = new URL(`https://businessapi.snapchat.com${path}?shared_resource_types=${resourceType}`);
|
|
105
|
+
const policies = [], seen = /* @__PURE__ */ new Set();
|
|
106
|
+
while (true) {
|
|
107
|
+
if (seen.has(url.href) || seen.size >= 1e3) throw new AdportError("PROVIDER_ERROR", "snapchat: sharing-policy pagination did not terminate");
|
|
108
|
+
seen.add(url.href);
|
|
109
|
+
const data = await this.send(url, "GET");
|
|
110
|
+
const parsed = z.array(z.object({ sharing_policy_id: z.string(), source: z.object({ resource_type: z.string(), resource_id: z.string() }) })).safeParse(data.sharing_policies);
|
|
111
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "snapchat: malformed sharing policies");
|
|
112
|
+
policies.push(...parsed.data.filter((row) => row.source.resource_type === resourceType));
|
|
113
|
+
if (!data.paging?.next_link) return policies;
|
|
114
|
+
url = new URL(data.paging.next_link, url);
|
|
115
|
+
if (url.origin !== "https://businessapi.snapchat.com" || url.pathname !== path || url.username || url.password || url.hash || url.searchParams.get("shared_resource_types") !== resourceType) throw new AdportError("PROVIDER_ERROR", "snapchat: sharing-policy pagination changed scope");
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Only INIT-provided paths for the exact media and action may carry authorization. */
|
|
119
|
+
async uploadPart(path, mediaId, action, form, schema) {
|
|
120
|
+
const url = snapchatUploadPath(path, mediaId, action);
|
|
121
|
+
const parsed = schema.safeParse(await this.send(url, "POST", form));
|
|
122
|
+
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "snapchat: malformed media upload response");
|
|
123
|
+
return parsed.data;
|
|
124
|
+
}
|
|
125
|
+
items(data, plural, singular2, schema) {
|
|
74
126
|
const items = z.array(z.looseObject({ sub_request_status: z.string() })).safeParse(data[plural]);
|
|
75
127
|
if (!items.success) throw new AdportError("PROVIDER_ERROR", `snapchat: malformed ${plural} response`);
|
|
76
|
-
|
|
128
|
+
const rows = [], ids = [];
|
|
129
|
+
let failed = !success(data.request_status), malformed = false;
|
|
130
|
+
for (const item of items.data) {
|
|
131
|
+
const raw = item[singular2];
|
|
132
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw) && typeof raw.id === "string") ids.push(String(raw.id));
|
|
77
133
|
if (!success(item.sub_request_status)) {
|
|
78
|
-
|
|
134
|
+
failed = true;
|
|
135
|
+
continue;
|
|
79
136
|
}
|
|
80
|
-
const parsed = schema.safeParse(item[
|
|
81
|
-
if (!parsed.success)
|
|
82
|
-
|
|
83
|
-
|
|
137
|
+
const parsed = schema.safeParse(item[singular2]);
|
|
138
|
+
if (!parsed.success) {
|
|
139
|
+
malformed = true;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
rows.push(parsed.data);
|
|
143
|
+
}
|
|
144
|
+
if (failed || malformed) throw new AdportError("PROVIDER_ERROR", `snapchat: ${malformed ? `malformed ${singular2} response` : `${singular2} sub-request failed`}; reconcile returned IDs before retrying`, { requestId: data.request_id, resource_ids: ids, errors: items.data.filter((item) => !success(item.sub_request_status)).map((item) => this.errorDetails(item)), warnings: this.warnings(data, plural) });
|
|
145
|
+
return rows;
|
|
146
|
+
}
|
|
147
|
+
redact(value) {
|
|
148
|
+
return [this.credentials.clientSecret, this.credentials.clientId, this.credentials.refreshToken, this.refreshToken, this.token?.value].reduce((text, secret) => secret ? text.replaceAll(secret, "[redacted]") : text, value).replace(/Bearer\s+\S+/gi, "Bearer [redacted]").replace(/\b[a-f0-9]{64}\b/gi, "[redacted hash]").slice(0, 2e3);
|
|
149
|
+
}
|
|
150
|
+
errorDetails(input) {
|
|
151
|
+
return Object.fromEntries(["error_code", "display_message", "debug_message", "sub_request_error_reason"].flatMap((key) => typeof input[key] === "string" || typeof input[key] === "number" ? [[key, this.redact(String(input[key]))]] : []));
|
|
152
|
+
}
|
|
153
|
+
warnings(data, plural) {
|
|
154
|
+
const items = Array.isArray(data[plural]) ? data[plural] : [];
|
|
155
|
+
return [data, ...items].flatMap((row) => Array.isArray(row.sub_request_warnings) ? row.sub_request_warnings.map((value) => this.redact(typeof value === "string" ? value : JSON.stringify(value))) : []);
|
|
84
156
|
}
|
|
85
157
|
url(path, params = {}) {
|
|
86
158
|
const url = new URL(path, SNAPCHAT_API_BASE);
|
|
@@ -90,30 +162,33 @@ var SnapchatAdsClient = class {
|
|
|
90
162
|
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
|
|
91
163
|
return url;
|
|
92
164
|
}
|
|
93
|
-
async send(url, method, body, retry = true) {
|
|
165
|
+
async send(url, method, body, retry = true, acceptBatchFailure = false) {
|
|
94
166
|
const token = await this.accessToken();
|
|
167
|
+
const multipart = body instanceof FormData;
|
|
95
168
|
const response = await this.fetchImpl(url.href, {
|
|
96
169
|
method,
|
|
97
170
|
headers: {
|
|
98
171
|
authorization: `Bearer ${token}`,
|
|
99
|
-
...body !== void 0 ? { "content-type": method === "PATCH" ? "application/json-patch+json" : "application/json" } : {}
|
|
172
|
+
...body !== void 0 && !multipart ? { "content-type": method === "PATCH" ? "application/json-patch+json" : "application/json" } : {}
|
|
100
173
|
},
|
|
101
|
-
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
174
|
+
...body !== void 0 ? { body: multipart ? body : JSON.stringify(body) } : {},
|
|
102
175
|
redirect: "error",
|
|
103
176
|
signal: AbortSignal.timeout(3e4)
|
|
104
177
|
});
|
|
105
178
|
if (response.status === 401 && method === "GET" && retry) {
|
|
106
179
|
if (this.token?.value === token) this.token = void 0;
|
|
107
|
-
return this.send(url, method, body, false);
|
|
180
|
+
return this.send(url, method, body, false, acceptBatchFailure);
|
|
108
181
|
}
|
|
109
182
|
if (!response.ok) {
|
|
110
183
|
const advice = response.status === 403 ? " Check app approval and the user\u2019s ad-account permissions; reconnecting alone may not resolve this." : "";
|
|
111
|
-
|
|
184
|
+
const raw = await response.json().catch(() => void 0);
|
|
185
|
+
const details = raw && typeof raw === "object" && !Array.isArray(raw) ? this.errorDetails(raw) : {};
|
|
186
|
+
throw new AdportError("PROVIDER_ERROR", `snapchat: HTTP ${response.status}.${advice}${details.display_message || details.debug_message ? ` ${details.display_message ?? details.debug_message}` : ""}`, { http_status: response.status, ...details });
|
|
112
187
|
}
|
|
113
|
-
const parsed = envelopeSchema.safeParse(await response.json());
|
|
188
|
+
const parsed = envelopeSchema.safeParse(await response.json().catch(() => void 0));
|
|
114
189
|
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "snapchat: malformed API envelope");
|
|
115
|
-
if (!success(parsed.data.request_status)) {
|
|
116
|
-
throw new AdportError("PROVIDER_ERROR", "snapchat: API request failed", { requestId: parsed.data.request_id });
|
|
190
|
+
if (!success(parsed.data.request_status) && !acceptBatchFailure) {
|
|
191
|
+
throw new AdportError("PROVIDER_ERROR", "snapchat: API request failed", { requestId: parsed.data.request_id, ...this.errorDetails(parsed.data) });
|
|
117
192
|
}
|
|
118
193
|
return parsed.data;
|
|
119
194
|
}
|
|
@@ -138,7 +213,7 @@ var SnapchatAdsClient = class {
|
|
|
138
213
|
signal: AbortSignal.timeout(3e4)
|
|
139
214
|
});
|
|
140
215
|
if (!response.ok) throw new AdportError("PROVIDER_ERROR", `snapchat: OAuth refresh failed (HTTP ${response.status}); re-authorize if the grant was revoked or expired`);
|
|
141
|
-
const parsed = tokenSchema.safeParse(await response.json());
|
|
216
|
+
const parsed = tokenSchema.safeParse(await response.json().catch(() => void 0));
|
|
142
217
|
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "snapchat: malformed OAuth response");
|
|
143
218
|
const token = parsed.data;
|
|
144
219
|
if (token.refresh_token && token.refresh_token !== this.refreshToken) {
|
|
@@ -152,10 +227,18 @@ var SnapchatAdsClient = class {
|
|
|
152
227
|
|
|
153
228
|
// src/provider.ts
|
|
154
229
|
import {
|
|
155
|
-
AdportError as
|
|
230
|
+
AdportError as AdportError4,
|
|
156
231
|
resolveDateRange
|
|
157
232
|
} from "@adport/core";
|
|
158
233
|
|
|
234
|
+
// src/creatives.ts
|
|
235
|
+
import { AdportError as AdportError2, LocalMediaResolver } from "@adport/core";
|
|
236
|
+
import { z as z4 } from "zod";
|
|
237
|
+
|
|
238
|
+
// src/creative-tools.ts
|
|
239
|
+
import { creativesOutput, defineTool, guardedWriteTool, mediaSourceFields } from "@adport/core";
|
|
240
|
+
import { z as z3 } from "zod";
|
|
241
|
+
|
|
159
242
|
// src/schemas.ts
|
|
160
243
|
import { z as z2 } from "zod";
|
|
161
244
|
var snapchatId = z2.string().regex(/^[A-Za-z0-9_-]+$/);
|
|
@@ -204,16 +287,707 @@ var setBudgetSchema = z2.object({
|
|
|
204
287
|
budget_micros: snapchatMicros.positive()
|
|
205
288
|
});
|
|
206
289
|
|
|
290
|
+
// src/creative-tools.ts
|
|
291
|
+
var name = z3.string().trim().min(1).max(375);
|
|
292
|
+
var strings = z3.array(z3.string().min(1)).max(500);
|
|
293
|
+
var https = z3.string().url().max(2048).refine((value) => {
|
|
294
|
+
const u = new URL(value);
|
|
295
|
+
return u.protocol === "https:" && !u.username && !u.password;
|
|
296
|
+
}, "Use an HTTPS URL without embedded credentials");
|
|
297
|
+
var scalarOrArray = z3.union([z3.string().min(1), strings]);
|
|
298
|
+
var include = z3.enum(["INCLUDE", "EXCLUDE"]);
|
|
299
|
+
var geo = z3.object({ country_code: z3.string().regex(/^[a-zA-Z]{2}$/), region_id: strings.optional(), metro: strings.optional(), postal_code: strings.optional(), operation: include.optional() }).strict();
|
|
300
|
+
var targeting = z3.object({
|
|
301
|
+
geos: z3.array(geo).min(1).max(500).optional(),
|
|
302
|
+
demographics: z3.array(z3.object({ gender: scalarOrArray.optional(), languages: strings.optional(), age_groups: strings.optional(), min_age: z3.string().regex(/^\d+$/).optional(), max_age: z3.string().regex(/^\d+$/).optional(), operation: z3.literal("INCLUDE").optional() }).strict()).max(500).optional(),
|
|
303
|
+
devices: z3.array(z3.object({ os_type: scalarOrArray.optional(), os_version_min: z3.string().optional(), os_version_max: z3.string().optional(), connection_type: scalarOrArray.optional(), carrier: scalarOrArray.optional(), marketing_name: scalarOrArray.optional() }).strict()).max(500).optional(),
|
|
304
|
+
interests: z3.array(z3.object({ category_id: scalarOrArray, operation: include.optional() }).strict()).max(500).optional(),
|
|
305
|
+
segments: z3.array(z3.object({ segment_id: scalarOrArray, operation: include.optional() }).strict()).max(500).optional(),
|
|
306
|
+
regulated_content: z3.boolean().optional(),
|
|
307
|
+
auto_expansion_options: z3.object({ interest_expansion_option: z3.object({ enabled: z3.boolean() }).strict().optional(), custom_audience_expansion_option: z3.object({ enabled: z3.boolean() }).strict().optional() }).strict().optional()
|
|
308
|
+
}).strict();
|
|
309
|
+
var placement = z3.object({ config: z3.enum(["AUTOMATIC", "CUSTOM"]), platforms: strings.optional(), snapchat_positions: strings.optional() }).strict();
|
|
310
|
+
var bidStrategy = z3.enum(["AUTO_BID", "LOWEST_COST_WITH_MAX_BID", "TARGET_COST"]);
|
|
311
|
+
var schedule = { start_time: z3.iso.datetime({ offset: true }).optional(), end_time: z3.iso.datetime({ offset: true }).optional() };
|
|
312
|
+
var groupFields = { name: name.optional(), ...schedule, placement_v2: placement.optional(), pacing_type: z3.enum(["STANDARD", "ACCELERATED"]).optional(), brand_safety_config: z3.object({ inventory_option: z3.enum(["FULL_INVENTORY", "LIMITED_INVENTORY"]) }).strict().optional() };
|
|
313
|
+
var createGroup = z3.object({
|
|
314
|
+
...groupFields,
|
|
315
|
+
name,
|
|
316
|
+
campaign_id: snapchatId,
|
|
317
|
+
targeting,
|
|
318
|
+
placement_v2: placement.default({ config: "AUTOMATIC" }),
|
|
319
|
+
type: z3.enum(["SNAP_ADS", "LENS", "FILTER"]).default("SNAP_ADS"),
|
|
320
|
+
optimization_goal: z3.enum(["IMPRESSIONS", "SWIPES", "APP_INSTALLS", "VIDEO_VIEWS", "VIDEO_VIEWS_15_SEC", "USES", "STORY_OPENS", "PIXEL_PAGE_VIEW", "PIXEL_ADD_TO_CART", "LANDING_PAGE_VIEW", "LEAD_FORM_SUBMISSIONS", "PIXEL_PURCHASE", "PIXEL_SIGNUP", "APP_ADD_TO_CART", "APP_PURCHASE", "APP_SIGNUP"]),
|
|
321
|
+
bid_strategy: bidStrategy,
|
|
322
|
+
bid_micro: snapchatMicros.positive().optional(),
|
|
323
|
+
daily_budget_micro: snapchatMicros.min(5e6).optional(),
|
|
324
|
+
lifetime_budget_micro: snapchatMicros.positive().optional(),
|
|
325
|
+
pixel_id: snapchatId.optional(),
|
|
326
|
+
event_sources: z3.object({ MOBILE_APP: z3.array(snapchatId).length(1) }).strict().optional(),
|
|
327
|
+
status: snapchatStatus.default("PAUSED")
|
|
328
|
+
}).refine((v) => Boolean(v.daily_budget_micro) !== Boolean(v.lifetime_budget_micro), "Provide exactly one daily or lifetime budget").refine((v) => v.bid_strategy === "AUTO_BID" || Boolean(v.bid_micro), "This bid strategy requires bid_micro");
|
|
329
|
+
var updateGroup = z3.object({ ad_squad_id: snapchatId, ...groupFields }).refine((v) => Object.keys(v).length > 1, "Provide an ad-squad field");
|
|
330
|
+
var adFields = { name: name.optional(), ...schedule, third_party_paid_impression_tracking_urls: z3.array(https).max(20).optional(), third_party_on_swipe_tracking_urls: z3.array(https).max(20).optional() };
|
|
331
|
+
var createAd = z3.object({ ...adFields, name, ad_squad_id: snapchatId, creative_id: snapchatId, type: z3.enum(["SNAP_AD", "APP_INSTALL", "REMOTE_WEBPAGE", "DEEP_LINK", "STORY", "AD_TO_LENS", "AD_TO_CALL", "AD_TO_MESSAGE", "LENS", "LENS_WEB_VIEW", "LENS_APP_INSTALL", "LENS_DEEP_LINK", "COLLECTION", "LEAD_GENERATION", "REMINDER"]), status: snapchatStatus.default("PAUSED") });
|
|
332
|
+
var updateAd = z3.object({ ad_id: snapchatId, ...adFields }).refine((v) => Object.keys(v).length > 1, "Provide an ad field");
|
|
333
|
+
var appFields = { app_name: z3.string().min(1).max(30), ios_app_id: z3.string().min(1).optional(), android_app_url: z3.string().min(1).optional(), icon_media_id: snapchatId, product_page_id: z3.string().min(1).optional() };
|
|
334
|
+
var app = z3.object(appFields).strict().refine((v) => Boolean(v.ios_app_id || v.android_app_url), "Provide an iOS or Android app");
|
|
335
|
+
var web = z3.object({ url: https, block_preload: z3.boolean().optional() }).strict();
|
|
336
|
+
var deepFields = { app_name: z3.string().min(1).max(30), ios_app_id: z3.string().min(1).optional(), android_app_url: z3.string().min(1).optional(), icon_media_id: snapchatId, deep_link_uri: z3.string().url(), web_view_fallback_url: https.optional(), fallback_type: z3.enum(["APP_INSTALL", "WEB_SITE"]).optional(), product_page_id: z3.string().optional() };
|
|
337
|
+
var deep = z3.object(deepFields).strict().refine((v) => Boolean(v.ios_app_id || v.android_app_url), "Provide an iOS or Android app");
|
|
338
|
+
var creativeFields = { name: name.optional(), headline: z3.string().min(1).max(34).optional(), brand_name: z3.string().min(1).max(32).optional(), call_to_action: z3.string().regex(/^[A-Z_]+$/).optional(), shareable: z3.boolean().optional(), favorite_display_mode: z3.enum(["SHOW", "HIDE"]).optional(), cta_color_display_mode: z3.enum(["AUTO_COLOR_DETECTION", "DEFAULT_COLOR"]).optional(), top_snap_media_id: snapchatId.optional(), profile_id: snapchatId.optional(), web_view_properties: web.partial().optional(), app_install_properties: z3.object(appFields).strict().partial().optional(), deep_link_properties: z3.object(deepFields).strict().partial().optional() };
|
|
339
|
+
var createCreative = z3.object({ ...creativeFields, name, headline: z3.string().min(1).max(34), profile_id: snapchatId, type: z3.enum(["SNAP_AD", "WEB_VIEW", "APP_INSTALL", "DEEP_LINK", "PREVIEW", "COMPOSITE", "AD_TO_LENS"]), top_snap_media_id: snapchatId.optional(), web_view_properties: web.optional(), app_install_properties: app.optional(), deep_link_properties: deep.optional(), preview_properties: z3.object({ preview_media_id: snapchatId, preview_headline: z3.string().min(1), logo_media_id: snapchatId.optional() }).strict().optional(), preview_creative_id: snapchatId.optional(), composite_properties: z3.object({ creative_ids: z3.array(snapchatId).min(1).max(100) }).strict().optional(), ad_to_lens_properties: z3.object({ lens_media_id: snapchatId }).strict().optional() }).refine((v) => v.type === "PREVIEW" || v.type === "COMPOSITE" || Boolean(v.top_snap_media_id), "This creative type requires top_snap_media_id").refine((v) => v.type !== "WEB_VIEW" || Boolean(v.web_view_properties), "WEB_VIEW requires web_view_properties").refine((v) => v.type !== "APP_INSTALL" || Boolean(v.app_install_properties), "APP_INSTALL requires app_install_properties").refine((v) => v.type !== "DEEP_LINK" || Boolean(v.deep_link_properties), "DEEP_LINK requires deep_link_properties").refine((v) => v.type !== "PREVIEW" || Boolean(v.preview_properties), "PREVIEW requires preview_properties").refine((v) => v.type !== "COMPOSITE" || Boolean(v.preview_creative_id && v.composite_properties), "COMPOSITE requires preview and child creatives").refine((v) => v.type !== "AD_TO_LENS" || Boolean(v.ad_to_lens_properties), "AD_TO_LENS requires lens media");
|
|
340
|
+
var updateCreative = z3.object({ creative_id: snapchatId, ...creativeFields }).refine((v) => Object.keys(v).length > 1, "Provide a creative field");
|
|
341
|
+
var uploadMedia = z3.object({ snapchat_media_id: snapchatId, ...mediaSourceFields }).refine((v) => Boolean(v.media_id) !== Boolean(v.file_path), "Provide a project media_id or local file_path");
|
|
342
|
+
function snapchatCreativeTools(provider) {
|
|
343
|
+
const account = { account_id: snapchatId }, page = { limit: z3.number().int().min(1).max(1e3).default(50), cursor: z3.string().min(1).optional() };
|
|
344
|
+
const read = (name3, description, input, handler) => defineTool({ name: name3, namespace: "snapchat", description, input, annotations: { readOnly: true }, handler });
|
|
345
|
+
const write = (name3, description, payload, kind = "update") => guardedWriteTool({ name: name3, namespace: "snapchat", provider: "snapchat", description, payload, kind });
|
|
346
|
+
return [
|
|
347
|
+
read("snapchat_get_entity", "Read one campaign, ad squad, ad, creative or media item and verify its account and parent hierarchy.", z3.object({ ...account, entity: z3.enum(["campaigns", "adsquads", "ads", "creatives", "media"]), resource_id: snapchatId }), (v) => provider.creatives.owned(v.account_id, v.entity, v.resource_id)),
|
|
348
|
+
read("snapchat_adsquads", "Read ad-squad targeting, schedules, budgets and bids with native cursor pagination.", z3.object({ ...account, campaign_id: snapchatId.optional(), ...page }), (v) => provider.creatives.page(v, "adsquads")),
|
|
349
|
+
read("snapchat_ads", "Read ad settings, creative references and configured/review/delivery statuses.", z3.object({ ...account, ad_squad_id: snapchatId.optional(), ...page }), (v) => provider.creatives.page(v, "ads")),
|
|
350
|
+
defineTool({ name: "snapchat_creatives", namespace: "snapchat", description: "View selected-account creative copy and native image/video media. Shared creative copy edits affect all linked ads and trigger review.", input: z3.object({ ...account, ...page, limit: z3.number().int().min(1).max(50).default(20) }), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (v) => provider.creatives.gallery(v) }),
|
|
351
|
+
read("snapchat_media", "List selected-account media metadata, upload readiness and native preview/download links.", z3.object({ ...account, ...page }), (v) => provider.creatives.page(v, "media")),
|
|
352
|
+
read("snapchat_public_profiles", "List Public Profile IDs already shared with this ad account. Does not create sharing policies or widen access.", z3.object(account), (v) => provider.creatives.shared(v.account_id, "public_profiles")),
|
|
353
|
+
read("snapchat_targeting_options", "Read native geo, demographic, device and interest choices. Country-specific dimensions require country_code.", z3.object({ ...account, dimension: z3.enum(["country", "region", "metro", "postal_code", "gender", "language", "age_group", "connection_type", "os_type", "os_version", "carrier", "marketing_name", "scls"]), country_code: z3.string().regex(/^[a-zA-Z]{2}$/).optional(), is_hec: z3.boolean().optional(), os_type: z3.enum(["iOS", "Android"]).optional(), ...page }), (v) => provider.creatives.targetingOptions(v)),
|
|
354
|
+
write("snapchat_create_adsquad", "Create an account-owned campaign\u2019s ad squad, paused by policy. Budgets and bids are integer micros; explicit targeting is required. Deprecated MIN_ROAS is excluded.", createGroup, "create"),
|
|
355
|
+
write("snapchat_update_adsquad", "Patch supplied name, schedule, placement or brand-safety fields without resetting omitted settings.", updateGroup),
|
|
356
|
+
write("snapchat_update_targeting", "Patch only supplied targeting dimensions; arrays replace their previous dimension. Targeting edits trigger review and can briefly pause delivery.", z3.object({ ad_squad_id: snapchatId, targeting }).refine((v) => Object.keys(v.targeting).length > 0, "Provide targeting fields")),
|
|
357
|
+
write("snapchat_set_adsquad_budget", "Change the existing daily/lifetime ad-squad budget in integer micros, with current-value policy checks.", z3.object({ ad_squad_id: snapchatId, budget_micros: snapchatMicros.positive() })),
|
|
358
|
+
write("snapchat_set_adsquad_bidding", "Change bid strategy and/or monetary bid in integer micros. Preserves omitted settings and checks current monetary deltas.", z3.object({ ad_squad_id: snapchatId, bid_strategy: bidStrategy.optional(), bid_micros: snapchatMicros.positive().optional() }).refine((v) => Boolean(v.bid_strategy || v.bid_micros), "Provide a bid field")),
|
|
359
|
+
write("snapchat_create_ad", "Create a paused ad linked to an account-owned creative and ad squad; validates native creative/ad format compatibility.", createAd, "create"),
|
|
360
|
+
write("snapchat_update_ad", "Patch an account-owned ad\u2019s name, schedule or tracking tags. Use a new paused ad to select a different creative.", updateAd),
|
|
361
|
+
...["adsquad", "ad"].map((entity) => write(`snapchat_set_${entity}_status`, "Pause or activate an account-owned child after checking its parent hierarchy.", z3.object({ [entity === "ad" ? "ad_id" : "ad_squad_id"]: snapchatId, status: snapchatStatus }))),
|
|
362
|
+
write("snapchat_create_creative", "Create a reusable Snap, web, app, deep-link, story or lens-attachment creative from owned ready media and an already-shared Public Profile. Does not create or activate ads.", createCreative, "create"),
|
|
363
|
+
write("snapchat_update_creative", "Patch supplied creative copy, CTA or attachment fields. All ads sharing this creative are affected and reviewed. Top Snap replacement is limited to unused creatives.", updateCreative),
|
|
364
|
+
write("snapchat_create_media", "Create an account-owned IMAGE/VIDEO media container. No bytes are uploaded until a separate checksum-bound upload is approved.", z3.object({ name, type: z3.enum(["IMAGE", "VIDEO"]), ai_content_source: z3.literal("USER_AI_GEN").optional() }), "create"),
|
|
365
|
+
write("snapchat_upload_media", "Upload SHA-256-bound image/video bytes to a PENDING_UPLOAD media container. Uses native multipart/chunk paths with exact media ownership checks.", uploadMedia),
|
|
366
|
+
write("snapchat_delete_entity", "Permanently delete a verified campaign, ad squad or ad. Prefer pausing for reversible delivery changes.", z3.object({ entity: z3.enum(["campaigns", "adsquads", "ads"]), resource_id: snapchatId }), "remove")
|
|
367
|
+
];
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// src/creatives.ts
|
|
371
|
+
var rowSchema = z4.looseObject({ id: snapchatId });
|
|
372
|
+
var singular = { campaigns: "campaign", adsquads: "adsquad", ads: "ad", creatives: "creative", media: "media" };
|
|
373
|
+
var record = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
374
|
+
var nonempty = (v) => typeof v === "string" && v.length > 0;
|
|
375
|
+
var safeUrl = (v) => {
|
|
376
|
+
if (!nonempty(v)) return void 0;
|
|
377
|
+
try {
|
|
378
|
+
const u = new URL(v);
|
|
379
|
+
return u.protocol === "https:" && !u.username && !u.password ? v : void 0;
|
|
380
|
+
} catch {
|
|
381
|
+
return void 0;
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
var moneyFields = ["daily_budget_micro", "lifetime_budget_micro", "bid_micro"];
|
|
385
|
+
var formats = { SNAP_AD: "SNAP_AD", APP_INSTALL: "APP_INSTALL", REMOTE_WEBPAGE: "WEB_VIEW", DEEP_LINK: "DEEP_LINK", STORY: "COMPOSITE", AD_TO_LENS: "AD_TO_LENS", AD_TO_CALL: "AD_TO_CALL", AD_TO_MESSAGE: "AD_TO_MESSAGE", LENS: "LENS", LENS_WEB_VIEW: "LENS_WEB_VIEW", LENS_APP_INSTALL: "LENS_APP_INSTALL", LENS_DEEP_LINK: "LENS_DEEP_LINK", COLLECTION: "COLLECTION", LEAD_GENERATION: "LEAD_GENERATION", REMINDER: "REMINDER" };
|
|
386
|
+
var ctas = {
|
|
387
|
+
WEB_VIEW: ["APPLY_NOW", "MORE", "ORDER_NOW", "PLAY", "READ", "SHOP_NOW", "SHOW", "SIGN_UP", "VIEW", "WATCH", "DONATE", "DOWNLOAD", "RESPOND", "BUY_TICKETS", "SHOWTIMES", "BOOK_NOW", "GET_NOW", "LISTEN", "TRY", "VOTE", "VIEW_MENU", "PRE_REGISTER", "PLAY_GAME"],
|
|
388
|
+
APP_INSTALL: ["BOOK_NOW", "DONATE", "DOWNLOAD", "GET_NOW", "INSTALL_NOW", "ORDER_NOW", "PLAY", "SHOP_NOW", "SIGN_UP", "TRY", "USE_APP", "WATCH", "VOTE", "DIRECTIONS", "PLAY_GAME"],
|
|
389
|
+
DEEP_LINK: ["DONATE", "PLAY", "SHOP_NOW", "SIGN_UP", "USE_APP", "MORE", "OPEN_APP", "TRY", "WATCH", "VIEW_PROFILE", "VOTE", "DIRECTIONS", "PRE_REGISTER", "PLAY_GAME", "DOWNLOAD"],
|
|
390
|
+
AD_TO_LENS: ["PLAY", "TRY", "SHOP_NOW", "VOTE"]
|
|
391
|
+
};
|
|
392
|
+
function creativeFields2(type, fields) {
|
|
393
|
+
for (const [key, types] of [["web_view_properties", ["WEB_VIEW", "LENS_WEB_VIEW"]], ["app_install_properties", ["APP_INSTALL", "LENS_APP_INSTALL"]], ["deep_link_properties", ["DEEP_LINK", "LENS_DEEP_LINK"]]]) if (fields[key] !== void 0 && !types.includes(type)) throw new AdportError2("INVALID_INPUT", `snapchat: ${key} does not match creative type`);
|
|
394
|
+
if (fields.call_to_action !== void 0 && ctas[type] && !ctas[type].includes(String(fields.call_to_action))) throw new AdportError2("INVALID_INPUT", "snapchat: CTA is not supported by this creative type");
|
|
395
|
+
}
|
|
396
|
+
var SnapchatCreativeService = class {
|
|
397
|
+
constructor(client, media = new LocalMediaResolver()) {
|
|
398
|
+
this.client = client;
|
|
399
|
+
this.media = media;
|
|
400
|
+
}
|
|
401
|
+
client;
|
|
402
|
+
media;
|
|
403
|
+
async owned(account, entity, resourceId) {
|
|
404
|
+
snapchatId.parse(account);
|
|
405
|
+
snapchatId.parse(resourceId);
|
|
406
|
+
const rows = await this.client.collection(`${entity}/${resourceId}`, entity, singular[entity], rowSchema);
|
|
407
|
+
const row = rows.find((row2) => row2.id === resourceId);
|
|
408
|
+
if (rows.length !== 1 || !row || row.ad_account_id !== void 0 && row.ad_account_id !== account) throw new AdportError2("INVALID_INPUT", "snapchat: entity ID or account ownership mismatch");
|
|
409
|
+
if (entity === "adsquads") await this.owned(account, "campaigns", snapchatId.parse(row.campaign_id));
|
|
410
|
+
else if (entity === "ads") await this.owned(account, "adsquads", snapchatId.parse(row.ad_squad_id));
|
|
411
|
+
else if (row.ad_account_id !== account) throw new AdportError2("INVALID_INPUT", "snapchat: entity does not belong to selected account");
|
|
412
|
+
return row;
|
|
413
|
+
}
|
|
414
|
+
async shared(account, type) {
|
|
415
|
+
return { items: await this.client.sharingPolicies(snapchatId.parse(account), type), truncated: false };
|
|
416
|
+
}
|
|
417
|
+
async available(account, type, value) {
|
|
418
|
+
if (type === "pixels") {
|
|
419
|
+
if (!(await this.client.collection(`adaccounts/${account}/pixels`, "pixels", "pixel", rowSchema)).some((row) => row.id === value)) throw new AdportError2("INVALID_INPUT", "snapchat: Pixel is not available to the selected account");
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
if (!(await this.client.sharingPolicies(account, type)).some((row) => row.source.resource_id === value)) throw new AdportError2("INVALID_INPUT", `snapchat: ${type} ID is not available to the selected account`);
|
|
423
|
+
}
|
|
424
|
+
async page(input, entity) {
|
|
425
|
+
const account = snapchatId.parse(input.account_id);
|
|
426
|
+
let parent = `adaccounts/${account}`;
|
|
427
|
+
if (input.campaign_id) {
|
|
428
|
+
await this.owned(account, "campaigns", input.campaign_id);
|
|
429
|
+
parent = `campaigns/${input.campaign_id}`;
|
|
430
|
+
}
|
|
431
|
+
if (input.ad_squad_id) {
|
|
432
|
+
await this.owned(account, "adsquads", input.ad_squad_id);
|
|
433
|
+
parent = `adsquads/${input.ad_squad_id}`;
|
|
434
|
+
}
|
|
435
|
+
const data = await this.client.page(`${parent}/${entity}`, entity, singular[entity], rowSchema, { limit: String(input.limit), ...input.cursor ? { cursor: input.cursor } : {} });
|
|
436
|
+
if (data.items.some((row) => row.ad_account_id !== void 0 && row.ad_account_id !== account || input.campaign_id && row.campaign_id !== input.campaign_id || input.ad_squad_id && row.ad_squad_id !== input.ad_squad_id)) throw new AdportError2("PROVIDER_ERROR", "snapchat: collection returned a foreign account or parent");
|
|
437
|
+
return data;
|
|
438
|
+
}
|
|
439
|
+
async targetingOptions(input) {
|
|
440
|
+
snapchatId.parse(input.account_id);
|
|
441
|
+
let path;
|
|
442
|
+
if (["region", "metro", "postal_code"].includes(input.dimension)) {
|
|
443
|
+
if (!input.country_code) throw new AdportError2("INVALID_INPUT", "snapchat: this dimension requires country_code");
|
|
444
|
+
path = `targeting/geo/${input.country_code.toLowerCase()}/${input.dimension}`;
|
|
445
|
+
} else if (input.dimension === "os_version") {
|
|
446
|
+
if (!input.os_type) throw new AdportError2("INVALID_INPUT", "snapchat: os_version requires os_type");
|
|
447
|
+
path = `targeting/device/${input.os_type}/os_version`;
|
|
448
|
+
} else {
|
|
449
|
+
const paths = { country: "geo/country", gender: "demographics/gender", language: "demographics/languages", age_group: "demographics/age_group", connection_type: "device/connection_type", os_type: "device/os_type", carrier: "device/carrier", marketing_name: "device/marketing_name", scls: "v1/interests/scls" };
|
|
450
|
+
if (!paths[input.dimension]) throw new AdportError2("INVALID_INPUT", "snapchat: unsupported targeting dimension");
|
|
451
|
+
path = `targeting/${paths[input.dimension]}`;
|
|
452
|
+
}
|
|
453
|
+
if (input.dimension === "scls" && (!input.country_code || input.limit < 50)) throw new AdportError2("INVALID_INPUT", "snapchat: SCLS requires country_code and limit of at least 50");
|
|
454
|
+
const params = new URLSearchParams({ limit: String(input.limit), ...input.cursor ? { cursor: input.cursor } : {}, ...input.dimension === "scls" && input.country_code ? { country_code: input.country_code.toLowerCase(), ...input.is_hec !== void 0 ? { is_hec: String(input.is_hec) } : {} } : {} });
|
|
455
|
+
const data = await this.client.request(`${path}?${params}`, "GET", z4.looseObject({ targeting_dimensions: z4.array(z4.looseObject({ sub_request_status: z4.string() })), paging: z4.object({ next_link: z4.string().optional() }).optional() }));
|
|
456
|
+
if (data.targeting_dimensions.some((row) => row.sub_request_status.toUpperCase() !== "SUCCESS")) throw new AdportError2("PROVIDER_ERROR", "snapchat: targeting dimension sub-request failed");
|
|
457
|
+
let cursor;
|
|
458
|
+
if (data.paging?.next_link) {
|
|
459
|
+
const next = new URL(data.paging.next_link, "https://adsapi.snapchat.com/v1/");
|
|
460
|
+
if (next.origin !== "https://adsapi.snapchat.com" || next.pathname !== `/v1/${path}` || next.username || next.password || next.hash || !(cursor = next.searchParams.get("cursor") ?? void 0) || cursor === input.cursor) throw new AdportError2("PROVIDER_ERROR", "snapchat: targeting pagination changed scope");
|
|
461
|
+
}
|
|
462
|
+
return { items: data.targeting_dimensions, truncated: Boolean(cursor), ...cursor ? { next_cursor: cursor } : {} };
|
|
463
|
+
}
|
|
464
|
+
async gallery(input) {
|
|
465
|
+
const data = await this.page(input, "creatives"), warnings = data.warnings.map((message) => ({ provider: "snapchat", message }));
|
|
466
|
+
const mediaIds = [...new Set(data.items.flatMap((row) => [row.top_snap_media_id, record(row.preview_properties).preview_media_id, record(row.app_install_properties).icon_media_id, record(row.deep_link_properties).icon_media_id]).filter(nonempty))];
|
|
467
|
+
const media = /* @__PURE__ */ new Map();
|
|
468
|
+
let cursor = 0;
|
|
469
|
+
await Promise.all(Array.from({ length: Math.min(4, mediaIds.length) }, async () => {
|
|
470
|
+
while (cursor < mediaIds.length) {
|
|
471
|
+
const value = mediaIds[cursor++];
|
|
472
|
+
try {
|
|
473
|
+
media.set(value, await this.owned(input.account_id, "media", value));
|
|
474
|
+
} catch (error) {
|
|
475
|
+
warnings.push({ provider: "snapchat", message: `Media ${value} unavailable: ${error instanceof Error ? error.message : "provider read failed"}` });
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}));
|
|
479
|
+
const creatives = data.items.map((row) => {
|
|
480
|
+
const native = media.get(String(row.top_snap_media_id)) ?? media.get(String(record(row.preview_properties).preview_media_id));
|
|
481
|
+
const url = ["IMAGE", "VIDEO"].includes(String(native?.type)) ? safeUrl(native?.download_link) : void 0, type = native?.type === "VIDEO" ? "video" : "image";
|
|
482
|
+
const editable = row.type !== "PREVIEW" && row.type !== "COMPOSITE";
|
|
483
|
+
return { id: row.id, provider: "snapchat", account_id: input.account_id, name: String(row.name ?? row.id), type: String(row.type ?? "CREATIVE"), ...nonempty(row.review_status) ? { status: row.review_status } : {}, headlines: nonempty(row.headline) ? [row.headline] : nonempty(record(row.preview_properties).preview_headline) ? [String(record(row.preview_properties).preview_headline)] : [], descriptions: nonempty(row.brand_name) ? [row.brand_name] : [], landing_urls: [safeUrl(record(row.web_view_properties).url), safeUrl(record(row.deep_link_properties).web_view_fallback_url)].filter(nonempty), media: url ? [{ type, url }] : [], actions: editable ? [{ label: "Edit shared creative (all linked ads)", tool: "snapchat_update_creative", arguments: { account_id: input.account_id, creative_id: row.id }, fields: [{ key: "name", label: "Creative name", type: "text", value: String(row.name ?? ""), max_length: 375 }, ...nonempty(row.headline) ? [{ key: "headline", label: "Headline", type: "text", value: row.headline, max_length: 34 }] : [], ...nonempty(row.brand_name) ? [{ key: "brand_name", label: "Brand override", type: "text", value: row.brand_name, max_length: 32 }] : []] }] : [] };
|
|
484
|
+
});
|
|
485
|
+
return { ...data, creatives, warnings };
|
|
486
|
+
}
|
|
487
|
+
async readyMedia(account, value, type) {
|
|
488
|
+
const media = await this.owned(account, "media", value);
|
|
489
|
+
if (media.media_status !== "READY" || type && media.type !== type) throw new AdportError2("INVALID_INPUT", "snapchat: referenced media is not READY or has the wrong type");
|
|
490
|
+
return media;
|
|
491
|
+
}
|
|
492
|
+
async topMedia(account, value) {
|
|
493
|
+
const media = await this.readyMedia(account, value);
|
|
494
|
+
if (!["IMAGE", "VIDEO"].includes(String(media.type))) throw new AdportError2("INVALID_INPUT", "snapchat: Top Snap must use IMAGE or VIDEO media");
|
|
495
|
+
}
|
|
496
|
+
async checkTargeting(account, value) {
|
|
497
|
+
if (!Array.isArray(value.geos) || !value.geos.length) throw new AdportError2("INVALID_INPUT", "snapchat: targeting requires at least one country");
|
|
498
|
+
const geos = value.geos.map(record), countries = new Set(geos.filter((geo2) => geo2.operation !== "EXCLUDE").map((geo2) => String(geo2.country_code).toUpperCase()));
|
|
499
|
+
if (!countries.size) throw new AdportError2("INVALID_INPUT", "snapchat: targeting requires an included country");
|
|
500
|
+
const demographics = Array.isArray(value.demographics) ? value.demographics.map(record) : [];
|
|
501
|
+
if (countries.size > 1 && !demographics.some((row) => Array.isArray(row.languages) && row.languages.length === 1)) throw new AdportError2("INVALID_INPUT", "snapchat: multi-country targeting requires a single-language demographic entry");
|
|
502
|
+
if (demographics.some((row) => row.min_age && row.max_age && Number(row.min_age) > Number(row.max_age))) throw new AdportError2("INVALID_INPUT", "snapchat: minimum age exceeds maximum age");
|
|
503
|
+
if (Array.isArray(value.segments) && value.segments.length) {
|
|
504
|
+
const segments = await this.client.collection(`adaccounts/${account}/segments`, "segments", "segment", rowSchema), known = new Set(segments.map((row) => row.id));
|
|
505
|
+
if (segments.some((row) => row.ad_account_id !== void 0 && row.ad_account_id !== account)) throw new AdportError2("PROVIDER_ERROR", "snapchat: segment collection returned a foreign account");
|
|
506
|
+
for (const target of value.segments.map(record)) for (const segment of Array.isArray(target.segment_id) ? target.segment_id : [target.segment_id]) if (!known.has(String(segment))) throw new AdportError2("INVALID_INPUT", "snapchat: targeting segment is not available to this account");
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
async mutate(account, entity, path, method, body, expected) {
|
|
510
|
+
const data = await this.client.mutation(path, method, body, entity, singular[entity], rowSchema), ids = data.items.map((row2) => row2.id), row = data.items[0];
|
|
511
|
+
if (data.items.length !== 1 || !row || row.ad_account_id !== void 0 && row.ad_account_id !== account || Object.entries(expected).some(([key, value]) => value !== void 0 && String(row[key]) !== String(value))) throw new AdportError2("PROVIDER_ERROR", "snapchat: mutation receipt ID/account/status/money mismatch; reconcile before retrying", { resource_ids: ids, warnings: data.warnings });
|
|
512
|
+
if (["campaigns", "creatives", "media"].includes(entity) && row.ad_account_id !== account) throw new AdportError2("PROVIDER_ERROR", "snapchat: mutation receipt missing account ownership", { resource_ids: ids });
|
|
513
|
+
return { applied: true, resourceIds: ids, ...data.warnings.length ? { details: { warnings: data.warnings } } : {} };
|
|
514
|
+
}
|
|
515
|
+
async plan(op, guard) {
|
|
516
|
+
const account = snapchatId.parse(op.accountId), p = op.payload, coercions = [], budgetDeltas = [], changes = [];
|
|
517
|
+
const expectedKind = op.tool.startsWith("snapchat_create_") ? "create" : op.tool === "snapchat_delete_entity" ? "remove" : "update";
|
|
518
|
+
if (op.provider !== "snapchat" || op.kind !== expectedKind) throw new AdportError2("INVALID_INPUT", "snapchat: provider or write kind mismatch");
|
|
519
|
+
let entity, path, method = "PATCH", fields, current = {}, expected = {};
|
|
520
|
+
const paused = (value) => {
|
|
521
|
+
if (guard.forcePausedCreation && value !== "PAUSED") coercions.push("status coerced to PAUSED by policy (paused_creation)");
|
|
522
|
+
return guard.forcePausedCreation ? "PAUSED" : value;
|
|
523
|
+
};
|
|
524
|
+
switch (op.tool) {
|
|
525
|
+
case "snapchat_create_adsquad": {
|
|
526
|
+
const input = createGroup.parse(p);
|
|
527
|
+
await this.owned(account, "campaigns", input.campaign_id);
|
|
528
|
+
await this.checkTargeting(account, input.targeting);
|
|
529
|
+
if (input.pixel_id) await this.available(account, "pixels", input.pixel_id);
|
|
530
|
+
for (const app2 of input.event_sources?.MOBILE_APP ?? []) await this.available(account, "mobile_apps", app2);
|
|
531
|
+
fields = { ...input, status: paused(input.status), billing_event: "IMPRESSION", delivery_constraint: input.daily_budget_micro ? "DAILY_BUDGET" : "LIFETIME_BUDGET" };
|
|
532
|
+
entity = "adsquads";
|
|
533
|
+
path = `campaigns/${input.campaign_id}/adsquads`;
|
|
534
|
+
method = "POST";
|
|
535
|
+
expected = { campaign_id: input.campaign_id };
|
|
536
|
+
break;
|
|
537
|
+
}
|
|
538
|
+
case "snapchat_update_adsquad": {
|
|
539
|
+
const { ad_squad_id, ...input } = updateGroup.parse(p);
|
|
540
|
+
current = await this.owned(account, "adsquads", ad_squad_id);
|
|
541
|
+
entity = "adsquads";
|
|
542
|
+
path = `campaigns/${current.campaign_id}/adsquads/${ad_squad_id}`;
|
|
543
|
+
fields = input;
|
|
544
|
+
expected = { id: ad_squad_id, campaign_id: current.campaign_id };
|
|
545
|
+
break;
|
|
546
|
+
}
|
|
547
|
+
case "snapchat_update_targeting": {
|
|
548
|
+
const nativeId = snapchatId.parse(p.ad_squad_id), input = targeting.parse(p.targeting);
|
|
549
|
+
current = await this.owned(account, "adsquads", nativeId);
|
|
550
|
+
const merged = { ...record(current.targeting), ...input };
|
|
551
|
+
await this.checkTargeting(account, merged);
|
|
552
|
+
entity = "adsquads";
|
|
553
|
+
path = `campaigns/${current.campaign_id}/adsquads/${nativeId}`;
|
|
554
|
+
fields = { targeting: input };
|
|
555
|
+
expected = { id: nativeId, campaign_id: current.campaign_id };
|
|
556
|
+
changes.push("Targeting edits trigger review; delivery can pause temporarily and resume after approval.");
|
|
557
|
+
break;
|
|
558
|
+
}
|
|
559
|
+
case "snapchat_set_adsquad_budget": {
|
|
560
|
+
const nativeId = snapchatId.parse(p.ad_squad_id);
|
|
561
|
+
current = await this.owned(account, "adsquads", nativeId);
|
|
562
|
+
const daily = current.delivery_constraint === "DAILY_BUDGET", lifetime = current.delivery_constraint === "LIFETIME_BUDGET";
|
|
563
|
+
if (!daily && !lifetime) throw new AdportError2("INVALID_INPUT", "snapchat: current budget type is unavailable or uses a different buying model");
|
|
564
|
+
const field = daily ? "daily_budget_micro" : "lifetime_budget_micro", value = snapchatMicros.positive().parse(p.budget_micros);
|
|
565
|
+
if (current[field] === void 0 || daily && value < 5e6) throw new AdportError2("INVALID_INPUT", "snapchat: current budget missing or daily budget below minimum");
|
|
566
|
+
entity = "adsquads";
|
|
567
|
+
path = `campaigns/${current.campaign_id}/adsquads/${nativeId}`;
|
|
568
|
+
fields = { [field]: value };
|
|
569
|
+
expected = { id: nativeId, campaign_id: current.campaign_id };
|
|
570
|
+
break;
|
|
571
|
+
}
|
|
572
|
+
case "snapchat_set_adsquad_bidding": {
|
|
573
|
+
const nativeId = snapchatId.parse(p.ad_squad_id);
|
|
574
|
+
current = await this.owned(account, "adsquads", nativeId);
|
|
575
|
+
fields = { ...p.bid_strategy !== void 0 ? { bid_strategy: z4.enum(["AUTO_BID", "LOWEST_COST_WITH_MAX_BID", "TARGET_COST"]).parse(p.bid_strategy) } : {}, ...p.bid_micros !== void 0 ? { bid_micro: snapchatMicros.positive().parse(p.bid_micros) } : {} };
|
|
576
|
+
if ((fields.bid_strategy ?? current.bid_strategy) !== "AUTO_BID" && !(fields.bid_micro ?? current.bid_micro)) throw new AdportError2("INVALID_INPUT", "snapchat: selected strategy requires a monetary bid");
|
|
577
|
+
entity = "adsquads";
|
|
578
|
+
path = `campaigns/${current.campaign_id}/adsquads/${nativeId}`;
|
|
579
|
+
expected = { id: nativeId, campaign_id: current.campaign_id };
|
|
580
|
+
break;
|
|
581
|
+
}
|
|
582
|
+
case "snapchat_create_ad": {
|
|
583
|
+
const input = createAd.parse(p);
|
|
584
|
+
await this.owned(account, "adsquads", input.ad_squad_id);
|
|
585
|
+
const creative = await this.owned(account, "creatives", input.creative_id);
|
|
586
|
+
if (formats[input.type] !== creative.type) throw new AdportError2("INVALID_INPUT", "snapchat: ad type is incompatible with creative type");
|
|
587
|
+
entity = "ads";
|
|
588
|
+
path = `adsquads/${input.ad_squad_id}/ads`;
|
|
589
|
+
method = "POST";
|
|
590
|
+
fields = { ...input, status: paused(input.status) };
|
|
591
|
+
expected = { ad_squad_id: input.ad_squad_id, creative_id: input.creative_id };
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
case "snapchat_update_ad": {
|
|
595
|
+
const { ad_id, ...input } = updateAd.parse(p);
|
|
596
|
+
current = await this.owned(account, "ads", ad_id);
|
|
597
|
+
entity = "ads";
|
|
598
|
+
path = `adsquads/${current.ad_squad_id}/ads/${ad_id}`;
|
|
599
|
+
fields = input;
|
|
600
|
+
expected = { id: ad_id, ad_squad_id: current.ad_squad_id };
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
case "snapchat_set_ad_status":
|
|
604
|
+
case "snapchat_set_adsquad_status": {
|
|
605
|
+
entity = op.tool === "snapchat_set_ad_status" ? "ads" : "adsquads";
|
|
606
|
+
const nativeId = snapchatId.parse(p[entity === "ads" ? "ad_id" : "ad_squad_id"]);
|
|
607
|
+
current = await this.owned(account, entity, nativeId);
|
|
608
|
+
fields = { status: z4.enum(["ACTIVE", "PAUSED"]).parse(p.status) };
|
|
609
|
+
path = entity === "ads" ? `adsquads/${current.ad_squad_id}/ads/${nativeId}` : `campaigns/${current.campaign_id}/adsquads/${nativeId}`;
|
|
610
|
+
expected = { id: nativeId, [entity === "ads" ? "ad_squad_id" : "campaign_id"]: current[entity === "ads" ? "ad_squad_id" : "campaign_id"] };
|
|
611
|
+
break;
|
|
612
|
+
}
|
|
613
|
+
case "snapchat_create_creative": {
|
|
614
|
+
const { profile_id, ...input } = createCreative.parse(p);
|
|
615
|
+
await this.available(account, "public_profiles", profile_id);
|
|
616
|
+
creativeFields2(input.type, input);
|
|
617
|
+
if (input.top_snap_media_id) await this.topMedia(account, input.top_snap_media_id);
|
|
618
|
+
for (const value of [input.preview_properties?.preview_media_id, input.preview_properties?.logo_media_id, input.app_install_properties?.icon_media_id, input.deep_link_properties?.icon_media_id].filter(nonempty)) await this.readyMedia(account, value, "IMAGE");
|
|
619
|
+
if (input.ad_to_lens_properties) await this.readyMedia(account, input.ad_to_lens_properties.lens_media_id, "LENS_PACKAGE");
|
|
620
|
+
if (input.preview_creative_id && (await this.owned(account, "creatives", input.preview_creative_id)).type !== "PREVIEW") throw new AdportError2("INVALID_INPUT", "snapchat: story preview must be a PREVIEW creative");
|
|
621
|
+
for (const value of input.composite_properties?.creative_ids ?? []) await this.owned(account, "creatives", value);
|
|
622
|
+
fields = { ...input, ad_account_id: account, profile_properties: { profile_id } };
|
|
623
|
+
entity = "creatives";
|
|
624
|
+
path = `adaccounts/${account}/creatives`;
|
|
625
|
+
method = "POST";
|
|
626
|
+
expected = { type: input.type };
|
|
627
|
+
break;
|
|
628
|
+
}
|
|
629
|
+
case "snapchat_update_creative": {
|
|
630
|
+
const { creative_id, profile_id, ...input } = updateCreative.parse(p);
|
|
631
|
+
current = await this.owned(account, "creatives", creative_id);
|
|
632
|
+
creativeFields2(String(current.type), input);
|
|
633
|
+
const ads = await this.client.collection(`adaccounts/${account}/ads`, "ads", "ad", rowSchema, { limit: "1000" });
|
|
634
|
+
if (ads.some((row) => row.ad_account_id !== void 0 && row.ad_account_id !== account)) throw new AdportError2("PROVIDER_ERROR", "snapchat: linked-ad collection returned a foreign account");
|
|
635
|
+
const linked = ads.filter((row) => row.creative_id === creative_id);
|
|
636
|
+
changes.push(`Shared creative edit affects all ${linked.length} linked ad(s) and triggers review: ${linked.map((row) => row.id).join(", ") || "none currently"}.`);
|
|
637
|
+
if (input.top_snap_media_id) {
|
|
638
|
+
if (linked.length) throw new AdportError2("INVALID_INPUT", "snapchat: replace Top Snap media only on an unused creative; create a new creative/ad for media changes to linked ads");
|
|
639
|
+
await this.topMedia(account, input.top_snap_media_id);
|
|
640
|
+
}
|
|
641
|
+
if (profile_id) await this.available(account, "public_profiles", profile_id);
|
|
642
|
+
for (const value of [input.app_install_properties?.icon_media_id, input.deep_link_properties?.icon_media_id].filter(nonempty)) await this.readyMedia(account, value, "IMAGE");
|
|
643
|
+
fields = { ...input, ...profile_id ? { profile_properties: { profile_id } } : {} };
|
|
644
|
+
entity = "creatives";
|
|
645
|
+
path = `adaccounts/${account}/creatives/${creative_id}`;
|
|
646
|
+
expected = { id: creative_id };
|
|
647
|
+
break;
|
|
648
|
+
}
|
|
649
|
+
case "snapchat_create_media": {
|
|
650
|
+
fields = { ...z4.object({ name: z4.string().min(1).max(375), type: z4.enum(["IMAGE", "VIDEO"]), ai_content_source: z4.literal("USER_AI_GEN").optional() }).parse(p), ad_account_id: account };
|
|
651
|
+
entity = "media";
|
|
652
|
+
path = `adaccounts/${account}/media`;
|
|
653
|
+
method = "POST";
|
|
654
|
+
expected = { type: fields.type, media_status: "PENDING_UPLOAD" };
|
|
655
|
+
break;
|
|
656
|
+
}
|
|
657
|
+
case "snapchat_upload_media": {
|
|
658
|
+
const input = uploadMedia.parse(p), current2 = await this.owned(account, "media", input.snapchat_media_id);
|
|
659
|
+
if (current2.media_status !== "PENDING_UPLOAD" || !["IMAGE", "VIDEO"].includes(String(current2.type))) throw new AdportError2("INVALID_INPUT", "snapchat: uploads require a PENDING_UPLOAD IMAGE or VIDEO container");
|
|
660
|
+
const file = await this.media.read(input, { maxBytes: current2.type === "IMAGE" ? 5e6 : 100 * 1024 * 1024, contentTypes: current2.type === "IMAGE" ? ["image/png", "image/jpeg"] : ["video/mp4", "video/quicktime"] });
|
|
661
|
+
return { summary: `Upload Snapchat ${current2.type} media ${current2.id}`, changes: [`Upload ${file.name}, ${file.bytes.byteLength} bytes, SHA-256 ${file.sha256}; no ad is created or activated.`], coercions, budgetDeltas, execute: async () => {
|
|
662
|
+
const resultSchema = z4.looseObject({ result: rowSchema });
|
|
663
|
+
let uploaded;
|
|
664
|
+
const chunkBytes = 32e6;
|
|
665
|
+
if (file.bytes.byteLength <= chunkBytes) {
|
|
666
|
+
const form = new FormData();
|
|
667
|
+
form.set("file", new Blob([file.bytes], { type: file.contentType }), file.name);
|
|
668
|
+
uploaded = (await this.client.request(`media/${current2.id}/upload`, "POST", resultSchema, form)).result;
|
|
669
|
+
} else {
|
|
670
|
+
const initForm = new FormData();
|
|
671
|
+
initForm.set("file_name", file.name);
|
|
672
|
+
initForm.set("file_size", String(file.bytes.byteLength));
|
|
673
|
+
initForm.set("number_of_parts", String(Math.ceil(file.bytes.byteLength / chunkBytes)));
|
|
674
|
+
const init = await this.client.request(`media/${current2.id}/multipart-upload-v2?action=INIT`, "POST", z4.looseObject({ upload_id: z4.string().min(1), add_path: z4.string(), finalize_path: z4.string() }), initForm);
|
|
675
|
+
snapchatUploadPath(init.add_path, current2.id, "ADD");
|
|
676
|
+
snapchatUploadPath(init.finalize_path, current2.id, "FINALIZE");
|
|
677
|
+
for (let offset = 0, part = 1; offset < file.bytes.byteLength; offset += chunkBytes, part++) {
|
|
678
|
+
const form2 = new FormData();
|
|
679
|
+
form2.set("upload_id", init.upload_id);
|
|
680
|
+
form2.set("part_number", String(part));
|
|
681
|
+
form2.set("file", new Blob([file.bytes.subarray(offset, offset + chunkBytes)], { type: file.contentType }), `${file.name}.part${part}`);
|
|
682
|
+
await this.client.uploadPart(init.add_path, current2.id, "ADD", form2, z4.looseObject({ request_status: z4.string() }));
|
|
683
|
+
}
|
|
684
|
+
const form = new FormData();
|
|
685
|
+
form.set("upload_id", init.upload_id);
|
|
686
|
+
uploaded = (await this.client.uploadPart(init.finalize_path, current2.id, "FINALIZE", form, resultSchema)).result;
|
|
687
|
+
}
|
|
688
|
+
if (uploaded.id !== current2.id || uploaded.ad_account_id !== account || uploaded.type !== current2.type || !["PENDING_UPLOAD", "READY"].includes(String(uploaded.media_status))) throw new AdportError2("PROVIDER_ERROR", "snapchat: upload receipt ownership/type/readiness mismatch; read media before retrying", { resource_ids: [current2.id] });
|
|
689
|
+
return { applied: true, resourceIds: [current2.id], details: { media_status: uploaded.media_status, sha256: file.sha256 } };
|
|
690
|
+
} };
|
|
691
|
+
}
|
|
692
|
+
case "snapchat_delete_entity": {
|
|
693
|
+
const input = z4.object({ entity: z4.enum(["campaigns", "adsquads", "ads"]), resource_id: snapchatId }).parse(p);
|
|
694
|
+
await this.owned(account, input.entity, input.resource_id);
|
|
695
|
+
return { summary: `Permanently delete Snapchat ${input.entity} ${input.resource_id}`, changes: [`DELETE ${input.entity}/${input.resource_id}. This cannot be undone; review the parent/child hierarchy before approval.`], coercions, budgetDeltas, execute: async () => {
|
|
696
|
+
const data = await this.client.request(`${input.entity}/${input.resource_id}`, "DELETE", z4.looseObject({ [input.entity]: z4.array(z4.unknown()) }));
|
|
697
|
+
if (data[input.entity].length) throw new AdportError2("PROVIDER_ERROR", "snapchat: unexpected delete receipt; reconcile entity before retrying", { resource_ids: [input.resource_id] });
|
|
698
|
+
return { applied: true, resourceIds: [input.resource_id] };
|
|
699
|
+
} };
|
|
700
|
+
}
|
|
701
|
+
default:
|
|
702
|
+
throw new AdportError2("INVALID_INPUT", `snapchat: unsupported write ${op.tool}`);
|
|
703
|
+
}
|
|
704
|
+
const effective = { ...current, ...fields };
|
|
705
|
+
if (effective.start_time && effective.end_time && Date.parse(String(effective.end_time)) <= Date.parse(String(effective.start_time))) throw new AdportError2("INVALID_INPUT", "snapchat: end_time must follow start_time");
|
|
706
|
+
for (const key of moneyFields) if (fields[key] !== void 0) budgetDeltas.push({ target: `${entity} ${String(current.id ?? "new")} ${key}`, ...current[key] !== void 0 ? { fromMicros: snapchatMicros.parse(Number(current[key])) } : {}, toMicros: snapchatMicros.positive().parse(fields[key]) });
|
|
707
|
+
const critical = ["status", "daily_budget_micro", "lifetime_budget_micro", "bid_micro", "bid_strategy", "name", "top_snap_media_id", "headline", "brand_name", "type", "billing_event", "delivery_constraint", "optimization_goal", "ai_content_source"];
|
|
708
|
+
for (const key of critical) if (fields[key] !== void 0) expected[key] = fields[key];
|
|
709
|
+
const body = method === "POST" ? { [entity]: [fields] } : patches(current, fields);
|
|
710
|
+
return { summary: `Snapchat ${op.tool.replace("snapchat_", "").replaceAll("_", " ")}`, changes: [...changes, `${method} ${path}: ${JSON.stringify(body)}`], coercions, budgetDeltas, execute: () => this.mutate(account, entity, path, method, body, expected) };
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
function patches(current, fields, prefix = "") {
|
|
714
|
+
return Object.entries(fields).flatMap(([key, value]) => {
|
|
715
|
+
const path = `${prefix}/${key}`;
|
|
716
|
+
if (value && typeof value === "object" && !Array.isArray(value) && current[key] && typeof current[key] === "object" && !Array.isArray(current[key])) return patches(record(current[key]), value, path);
|
|
717
|
+
return [{ op: current[key] === void 0 ? "add" : "replace", path, value }];
|
|
718
|
+
});
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// src/management.ts
|
|
722
|
+
import { createHash } from "crypto";
|
|
723
|
+
import { AdportError as AdportError3 } from "@adport/core";
|
|
724
|
+
import { z as z6 } from "zod";
|
|
725
|
+
|
|
726
|
+
// src/management-tools.ts
|
|
727
|
+
import { defineTool as defineTool2, guardedWriteTool as guardedWriteTool2 } from "@adport/core";
|
|
728
|
+
import { z as z5 } from "zod";
|
|
729
|
+
var name2 = z5.string().trim().min(1).max(375);
|
|
730
|
+
var days = z5.number().int().min(1).max(395);
|
|
731
|
+
var retention = z5.union([days, z5.literal(9999)]);
|
|
732
|
+
var common = { name: name2, description: z5.string().max(2e3).optional() };
|
|
733
|
+
var events = z5.enum(["APP_INSTALL", "PURCHASE", "SAVE", "START_CHECKOUT", "ADD_CART", "VIEW_CONTENT", "ADD_BILLING", "SIGN_UP", "SEARCH", "LEVEL_COMPLETE", "APP_OPEN", "PAGE_VIEW", "SUBSCRIBE", "AD_CLICK", "AD_VIEW", "COMPLETE_TUTORIAL", "INVITE", "LOGIN", "SHARE", "RESERVE", "ACHIEVEMENT_UNLOCKED", "ADD_TO_WISHLIST", "SPENT_CREDITS", "RATE", "START_TRIAL", "LIST_VIEW", "CUSTOM_EVENT_1", "CUSTOM_EVENT_2", "CUSTOM_EVENT_3", "CUSTOM_EVENT_4", "CUSTOM_EVENT_5"]);
|
|
734
|
+
var eventList = z5.array(events).min(1).max(31).refine((v) => new Set(v).size === v.length, "Events must be unique");
|
|
735
|
+
var customerAudience = z5.object({ ...common, retention_in_days: retention.default(180) });
|
|
736
|
+
var websiteAudience = z5.object({ ...common, pixel_id: snapchatId, retention_in_days: days.default(180), events: eventList });
|
|
737
|
+
var mobileAudience = z5.object({ ...common, mobile_app_id: snapchatId, retention_in_days: days.default(180), events: eventList });
|
|
738
|
+
var engagementAudience = z5.object({ ...common, engagement_specs: z5.array(z5.object({ engagement_type: z5.enum(["SNAP_ADS_SWIPE_UP", "SNAP_ADS_TOP_VIEW_THRU_100", "PROMOTED_STORY_TAP", "CREATIVE_TOOLS_USE", "PAID_IMPRESSIONS", "NATIVE_LEAD_GEN_SUBMITTED"]), source_type: z5.enum(["AD_SQUAD", "CAMPAIGN", "AD_ACCOUNT"]), source_id: snapchatId }).strict()).min(1).max(100) });
|
|
739
|
+
var profileAudience = z5.object({ ...common, profile_id: snapchatId, engagement_type: z5.enum(["SUBSCRIBERS", "ENGAGERS"]), retention_in_days: days.max(180).default(180) });
|
|
740
|
+
var lookalike = z5.object({ ...common, seed_segment_id: snapchatId, countries: z5.array(z5.string().regex(/^[A-Z]{2}$/)).min(1).max(100), type: z5.enum(["BALANCE", "SIMILARITY", "REACH"]).default("BALANCE"), retention_in_days: days.max(180).default(180) });
|
|
741
|
+
var audienceUpdate = z5.object({ segment_id: snapchatId, name: name2.optional(), description: z5.string().max(2e3).optional(), retention_in_days: retention.optional() }).refine((v) => Object.keys(v).length > 1, "Provide an audience field");
|
|
742
|
+
var audienceUsers = z5.object({ segment_id: snapchatId, schema: z5.enum(["EMAIL_SHA256", "MOBILE_AD_ID_SHA256", "PHONE_SHA256"]), hashes: z5.array(z5.string().regex(/^[a-f0-9]{64}$/)).min(1).max(1e4).refine((v) => new Set(v).size === v.length, "Hashes must be unique") });
|
|
743
|
+
var conversionSource = { source_type: z5.enum(["PIXEL", "MOBILE_APP"]), source_id: snapchatId };
|
|
744
|
+
var conversionCreate = z5.object({ ...common, ...conversionSource, event_type: events, rules: z5.array(z5.object({ key: z5.enum(["EVENT_TAG", "ITEM_ID", "ITEM_CATEGORY", "CURRENCY", "SEARCH_STRING", "SIGN_UP_METHOD", "PAGE_URL", "CATEGORY", "CATEGORY_ID", "BRAND", "DELIVERY_METHOD", "CUSTOMER_STATUS", "PRICE", "NUMBER_ITEMS"]), values: z5.array(z5.union([z5.string().max(2e3), z5.number().finite()])).min(1).max(100), operator: z5.enum(["EQUAL_TO", "NOT_EQUAL_TO", "I_CONTAINS", "I_NOT_CONTAINS", "CONTAINS", "NOT_CONTAINS", "STARTS_WITH", "I_STARTS_WITH", "I_EQUAL_TO", "I_NOT_EQUAL_TO", "LESS_THAN", "LESS_THAN_OR_EQUALS", "GREATER_THAN", "GREATER_THAN_OR_EQUALS"]) }).strict()).min(1).max(100) }).superRefine((v, ctx) => {
|
|
745
|
+
for (const [index, rule] of v.rules.entries()) {
|
|
746
|
+
const numeric = ["PRICE", "NUMBER_ITEMS"].includes(rule.key);
|
|
747
|
+
if (rule.values.some((value) => typeof value === "number" !== numeric) || !numeric && /^(LESS|GREATER)_/.test(rule.operator) || numeric && !["EQUAL_TO", "NOT_EQUAL_TO", "LESS_THAN", "LESS_THAN_OR_EQUALS", "GREATER_THAN", "GREATER_THAN_OR_EQUALS"].includes(rule.operator)) ctx.addIssue({ code: "custom", path: ["rules", index], message: "Rule value type/operator does not match the native key" });
|
|
748
|
+
}
|
|
749
|
+
});
|
|
750
|
+
var measurementUpdate = z5.object({ ad_squad_id: snapchatId, pixel_id: snapchatId.optional(), mobile_app_id: snapchatId.optional() }).refine((v) => Boolean(v.pixel_id || v.mobile_app_id), "Provide an existing measurement source");
|
|
751
|
+
function snapchatManagementTools(provider) {
|
|
752
|
+
const account = { account_id: snapchatId }, page = { limit: z5.number().int().min(1).max(1e3).default(50), cursor: z5.string().min(1).optional() };
|
|
753
|
+
const read = (name3, description, input, handler) => defineTool2({ name: name3, namespace: "snapchat", description, input, annotations: { readOnly: true }, handler });
|
|
754
|
+
const write = (name3, description, payload, kind = "update") => guardedWriteTool2({ name: name3, namespace: "snapchat", provider: "snapchat", description, payload, kind });
|
|
755
|
+
return [
|
|
756
|
+
read("snapchat_audiences", "Read selected-account audience segment metadata and readiness; does not retrieve individual users.", z5.object({ ...account, ...page }), (v) => provider.management.audiences(v)),
|
|
757
|
+
read("snapchat_get_audience", "Read an account-owned audience by ID, including native seed/specification and readiness fields.", z5.object({ ...account, segment_id: snapchatId }), (v) => provider.management.audience(v.account_id, v.segment_id)),
|
|
758
|
+
read("snapchat_pixels", "Read pixels already available to this account. Pixel creation is done in Snap Ads Manager; this tool does not install tracking or send events.", z5.object(account), (v) => provider.management.pixels(v.account_id)),
|
|
759
|
+
read("snapchat_mobile_apps", "List Snap App IDs already shared with the selected account; does not create or widen sharing.", z5.object(account), (v) => provider.creatives.shared(v.account_id, "mobile_apps")),
|
|
760
|
+
read("snapchat_custom_conversions", "Read native custom conversion definitions for an account-available Pixel or Snap App.", z5.object({ ...account, ...conversionSource, ...page }), (v) => provider.management.conversions(v)),
|
|
761
|
+
read("snapchat_audience_size", "Read the non-binding audience size for an account-owned ad squad using native audience_size_v2.", z5.object({ ...account, ad_squad_id: snapchatId }), (v) => provider.management.audienceSize(v.account_id, v.ad_squad_id)),
|
|
762
|
+
write("snapchat_create_customer_audience", "Create an empty FIRST_PARTY audience. No customer records are uploaded; 9999 means lifetime retention.", customerAudience, "create"),
|
|
763
|
+
write("snapchat_create_website_audience", "Create a website-event audience from an account-available Pixel. Snap requires historical-event prefill; does not install tracking or send events.", websiteAudience, "create"),
|
|
764
|
+
write("snapchat_create_mobile_audience", "Create a mobile-event audience from an already-available Snap App ID with historical-event prefill.", mobileAudience, "create"),
|
|
765
|
+
write("snapchat_create_engagement_audience", "Create an audience from verified ad-account/campaign/ad-squad engagements. Native retention is 395 days; source entries are ORed.", engagementAudience, "create"),
|
|
766
|
+
write("snapchat_create_profile_audience", "Create a subscribers/engagers audience from an already-shared Public Profile, with up to 180 days retention.", profileAudience, "create"),
|
|
767
|
+
write("snapchat_create_lookalike", "Create a lookalike from an owned first-party or profile-engagement seed using native countries, similarity mode and retention.", lookalike, "create"),
|
|
768
|
+
write("snapchat_update_audience", "Update an owned audience\u2019s metadata/retention while preserving omitted mutable fields. Does not replace its event or seed specification.", audienceUpdate),
|
|
769
|
+
write("snapchat_add_audience_users", "Add up to 10000 pre-normalized lowercase SHA-256 identifiers to an owned FIRST_PARTY audience. Preview shows counts/digest, never identifiers. Raw personal data is rejected.", audienceUsers),
|
|
770
|
+
write("snapchat_remove_audience_users", "Remove up to 10000 SHA-256 identifiers from an owned FIRST_PARTY audience. Membership changes affect ads targeting the segment.", audienceUsers, "remove"),
|
|
771
|
+
write("snapchat_clear_audience_users", "Remove all members from an owned FIRST_PARTY audience. This cannot be undone without uploading the identifiers again.", z5.object({ segment_id: snapchatId }), "remove"),
|
|
772
|
+
write("snapchat_delete_audience", "Permanently delete an owned audience. Existing targeting references can stop matching; use the separate preview/apply gate.", z5.object({ segment_id: snapchatId }), "remove"),
|
|
773
|
+
write("snapchat_rename_pixel", "Rename an account-owned Pixel. Shared pixels from other accounts cannot be renamed through this account.", z5.object({ pixel_id: snapchatId, name: name2 })),
|
|
774
|
+
write("snapchat_set_adsquad_measurement", "Associate existing account-available Pixel/Snap App IDs with a verified ad squad using partial JSON Patch. Does not install code or send events.", measurementUpdate),
|
|
775
|
+
write("snapchat_create_custom_conversion", "Create a typed native Pixel/App custom conversion rule after verifying source access. Does not transmit a conversion event.", conversionCreate, "create"),
|
|
776
|
+
write("snapchat_delete_custom_conversion", "Permanently delete a custom conversion after verifying access to its Pixel/App source.", z5.object({ custom_conversion_id: snapchatId }), "remove")
|
|
777
|
+
];
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// src/management.ts
|
|
781
|
+
var rowSchema2 = z6.looseObject({ id: snapchatId });
|
|
782
|
+
var record2 = (v) => v && typeof v === "object" && !Array.isArray(v) ? v : {};
|
|
783
|
+
var sourceType = z6.enum(["PIXEL", "MOBILE_APP"]);
|
|
784
|
+
function matches(actual, expected) {
|
|
785
|
+
if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => matches(actual[index], value));
|
|
786
|
+
if (expected && typeof expected === "object") return actual !== null && typeof actual === "object" && !Array.isArray(actual) && Object.entries(expected).every(([key, value]) => matches(actual[key], value));
|
|
787
|
+
return actual === expected;
|
|
788
|
+
}
|
|
789
|
+
var SnapchatManagementService = class {
|
|
790
|
+
constructor(client, creatives) {
|
|
791
|
+
this.client = client;
|
|
792
|
+
this.creatives = creatives;
|
|
793
|
+
}
|
|
794
|
+
client;
|
|
795
|
+
creatives;
|
|
796
|
+
async audience(account, segment) {
|
|
797
|
+
const rows = await this.client.collection(`segments/${snapchatId.parse(segment)}`, "segments", "segment", rowSchema2);
|
|
798
|
+
if (rows.length !== 1 || rows[0].id !== segment || rows[0].ad_account_id !== snapchatId.parse(account)) throw new AdportError3("INVALID_INPUT", "snapchat: audience is not owned by the selected account");
|
|
799
|
+
return rows[0];
|
|
800
|
+
}
|
|
801
|
+
async audiences(input) {
|
|
802
|
+
return this.client.page(`adaccounts/${snapchatId.parse(input.account_id)}/segments`, "segments", "segment", rowSchema2, { limit: String(input.limit), ...input.cursor ? { cursor: input.cursor } : {} });
|
|
803
|
+
}
|
|
804
|
+
async pixels(account) {
|
|
805
|
+
const items = await this.client.collection(`adaccounts/${snapchatId.parse(account)}/pixels`, "pixels", "pixel", rowSchema2);
|
|
806
|
+
return { items, truncated: false, setup_note: "Snap documents Pixel creation in Ads Manager. Reading or renaming a Pixel does not install tracking or send events." };
|
|
807
|
+
}
|
|
808
|
+
async source(account, type, resource, requireOwner = false) {
|
|
809
|
+
snapchatId.parse(resource);
|
|
810
|
+
if (type === "PIXEL") {
|
|
811
|
+
const pixel = (await this.pixels(account)).items.find((row) => row.id === resource);
|
|
812
|
+
if (!pixel || requireOwner && pixel.ad_account_id !== account) throw new AdportError3("INVALID_INPUT", "snapchat: Pixel is not available to, or owned by, the selected account");
|
|
813
|
+
return pixel;
|
|
814
|
+
}
|
|
815
|
+
if (requireOwner) throw new AdportError3("INVALID_INPUT", "snapchat: Snap App custom conversions are shared resources without proven ad-account ownership; deletion is unavailable through this account scope");
|
|
816
|
+
if (!(await this.client.sharingPolicies(account, "mobile_apps")).some((row) => row.source.resource_id === resource)) throw new AdportError3("INVALID_INPUT", "snapchat: Snap App is not available to the selected account");
|
|
817
|
+
return { id: resource };
|
|
818
|
+
}
|
|
819
|
+
async conversions(input) {
|
|
820
|
+
await this.source(input.account_id, input.source_type, input.source_id);
|
|
821
|
+
const path = `${input.source_type === "PIXEL" ? "pixels" : "mobile_apps"}/${input.source_id}/custom_conversions`;
|
|
822
|
+
const data = await this.client.page(path, "custom_conversions", "custom_conversion", rowSchema2, { limit: String(input.limit), ...input.cursor ? { cursor: input.cursor } : {} });
|
|
823
|
+
if (data.items.some((row) => record2(row.event_source).id !== input.source_id || record2(row.event_source).type !== input.source_type)) throw new AdportError3("PROVIDER_ERROR", "snapchat: custom conversion source mismatch");
|
|
824
|
+
return data;
|
|
825
|
+
}
|
|
826
|
+
async audienceSize(account, group) {
|
|
827
|
+
await this.creatives.owned(account, "adsquads", group);
|
|
828
|
+
const data = await this.client.request(`adsquads/${group}/audience_size_v2`, "GET", z6.looseObject({ audience_size: z6.looseObject({ ad_squad_id: snapchatId.optional(), audience_size_minimum: z6.number().nonnegative(), audience_size_maximum: z6.number().nonnegative() }) }));
|
|
829
|
+
if (data.audience_size.ad_squad_id && data.audience_size.ad_squad_id !== group || data.audience_size.audience_size_minimum > data.audience_size.audience_size_maximum) throw new AdportError3("PROVIDER_ERROR", "snapchat: audience-size bounds or ad-squad ID mismatch");
|
|
830
|
+
return data.audience_size;
|
|
831
|
+
}
|
|
832
|
+
async mutate(account, path, method, body, plural, singular2, expected) {
|
|
833
|
+
const data = await this.client.mutation(path, method, body, plural, singular2, rowSchema2), ids = data.items.map((row2) => row2.id), row = data.items[0];
|
|
834
|
+
if (data.items.length !== 1 || !row || row.ad_account_id !== void 0 && row.ad_account_id !== account || Object.entries(expected).some(([key, value]) => key === "retention_in_days" ? Number(row[key]) !== value : !matches(row[key], value))) throw new AdportError3("PROVIDER_ERROR", "snapchat: management receipt ownership/value mismatch; reconcile before retrying", { resource_ids: ids, warnings: data.warnings });
|
|
835
|
+
if (["segments", "pixels"].includes(plural) && row.ad_account_id !== account) throw new AdportError3("PROVIDER_ERROR", "snapchat: management receipt missing account ownership", { resource_ids: ids });
|
|
836
|
+
return { applied: true, resourceIds: ids, ...data.warnings.length ? { details: { warnings: data.warnings } } : {} };
|
|
837
|
+
}
|
|
838
|
+
async plan(op, _guard) {
|
|
839
|
+
const account = snapchatId.parse(op.accountId), p = op.payload, expectedKind = op.tool.startsWith("snapchat_create_") ? "create" : /snapchat_(?:delete|remove|clear)_/.test(op.tool) ? "remove" : "update";
|
|
840
|
+
if (op.provider !== "snapchat" || op.kind !== expectedKind) throw new AdportError3("INVALID_INPUT", "snapchat: provider or write kind mismatch");
|
|
841
|
+
let body = {}, path = `adaccounts/${account}/segments`, method = "POST", plural = "segments", singular2 = "segment", expected = {};
|
|
842
|
+
const notes = [];
|
|
843
|
+
switch (op.tool) {
|
|
844
|
+
case "snapchat_create_customer_audience":
|
|
845
|
+
body = { ...customerAudience.parse(p), source_type: "FIRST_PARTY" };
|
|
846
|
+
break;
|
|
847
|
+
case "snapchat_create_website_audience": {
|
|
848
|
+
const { events: events2, ...input } = websiteAudience.parse(p);
|
|
849
|
+
await this.source(account, "PIXEL", input.pixel_id);
|
|
850
|
+
body = { ...input, source_type: "PIXEL", prefill: true, pixel_spec_object: { or: { event: events2.map((eq) => ({ eq })) } } };
|
|
851
|
+
break;
|
|
852
|
+
}
|
|
853
|
+
case "snapchat_create_mobile_audience": {
|
|
854
|
+
const { events: events2, mobile_app_id, ...input } = mobileAudience.parse(p);
|
|
855
|
+
await this.source(account, "MOBILE_APP", mobile_app_id);
|
|
856
|
+
body = { ...input, source_type: "MOBILE", prefill: true, mobile_metadata: { mobile_snapkit_id: mobile_app_id, mobile_app_spec: { or: { event: events2.map((eq) => ({ eq })) } } } };
|
|
857
|
+
break;
|
|
858
|
+
}
|
|
859
|
+
case "snapchat_create_engagement_audience": {
|
|
860
|
+
const input = engagementAudience.parse(p);
|
|
861
|
+
for (const spec of input.engagement_specs) {
|
|
862
|
+
if (spec.source_type === "AD_ACCOUNT") {
|
|
863
|
+
if (spec.source_id !== account) throw new AdportError3("INVALID_INPUT", "snapchat: engagement source belongs to a different account");
|
|
864
|
+
} else await this.creatives.owned(account, spec.source_type === "CAMPAIGN" ? "campaigns" : "adsquads", spec.source_id);
|
|
865
|
+
}
|
|
866
|
+
body = { ...input, source_type: "ENGAGEMENT", source_subtype: "AD_ENGAGEMENT", retention_in_days: 395 };
|
|
867
|
+
break;
|
|
868
|
+
}
|
|
869
|
+
case "snapchat_create_profile_audience": {
|
|
870
|
+
const { profile_id, engagement_type, ...input } = profileAudience.parse(p);
|
|
871
|
+
if (!(await this.client.sharingPolicies(account, "public_profiles")).some((row) => row.source.resource_id === profile_id)) throw new AdportError3("INVALID_INPUT", "snapchat: profile audience source is not available to this account");
|
|
872
|
+
body = { ...input, source_type: "PROFILE_ENGAGEMENT", creation_spec: { engagement_type, source_profile_id: profile_id } };
|
|
873
|
+
break;
|
|
874
|
+
}
|
|
875
|
+
case "snapchat_create_lookalike": {
|
|
876
|
+
const { seed_segment_id, countries, type, ...input } = lookalike.parse(p), seed = await this.audience(account, seed_segment_id);
|
|
877
|
+
if (!["FIRST_PARTY", "PROFILE_ENGAGEMENT"].includes(String(seed.source_type))) throw new AdportError3("INVALID_INPUT", "snapchat: this tool supports documented first-party and profile-engagement lookalike seeds");
|
|
878
|
+
body = { ...input, source_type: "LOOKALIKE", creation_spec: { seed_segment_id, countries, type } };
|
|
879
|
+
break;
|
|
880
|
+
}
|
|
881
|
+
case "snapchat_update_audience": {
|
|
882
|
+
const { segment_id, ...input } = audienceUpdate.parse(p), current = await this.audience(account, segment_id);
|
|
883
|
+
body = { id: segment_id, name: current.name, retention_in_days: current.retention_in_days, ...current.description !== void 0 ? { description: current.description } : {}, ...input };
|
|
884
|
+
const days2 = Number(body.retention_in_days), maximum = ["LOOKALIKE", "PROFILE_ENGAGEMENT"].includes(String(current.source_type)) ? 180 : 395;
|
|
885
|
+
if (typeof body.name !== "string" || !Number.isInteger(days2) || days2 < 1 || days2 > maximum && !(current.source_type === "FIRST_PARTY" && days2 === 9999) || current.source_type === "ENGAGEMENT" && days2 !== 395) throw new AdportError3("INVALID_INPUT", "snapchat: current metadata missing or retention invalid for this audience type");
|
|
886
|
+
body.retention_in_days = days2;
|
|
887
|
+
method = "PUT";
|
|
888
|
+
expected = { id: segment_id, name: body.name, retention_in_days: days2 };
|
|
889
|
+
break;
|
|
890
|
+
}
|
|
891
|
+
case "snapchat_add_audience_users":
|
|
892
|
+
case "snapchat_remove_audience_users": {
|
|
893
|
+
const input = audienceUsers.parse(p), current = await this.audience(account, input.segment_id);
|
|
894
|
+
if (current.source_type !== "FIRST_PARTY") throw new AdportError3("INVALID_INPUT", "snapchat: direct membership uploads require an owned FIRST_PARTY audience");
|
|
895
|
+
const remove = op.tool === "snapchat_remove_audience_users", digest = createHash("sha256").update(JSON.stringify({ schema: input.schema, hashes: input.hashes })).digest("hex");
|
|
896
|
+
return { summary: `${remove ? "Remove" : "Add"} ${input.hashes.length} hashed Snapchat audience identifiers`, changes: [`${remove ? "DELETE" : "POST"} segments/${input.segment_id}/users; schema ${input.schema}; ${input.hashes.length} identifiers; payload SHA-256 ${digest}. Membership changes affect ads targeting this segment. No identifiers are shown in the preview.`], coercions: [], budgetDeltas: [], execute: async () => {
|
|
897
|
+
const data = await this.client.mutation(`segments/${input.segment_id}/users`, remove ? "DELETE" : "POST", { users: [{ ...remove ? { id: input.segment_id } : {}, schema: [input.schema], data: input.hashes.map((value) => [value]) }] }, "users", "user", z6.object({ number_uploaded_users: z6.number().int().nonnegative() }));
|
|
898
|
+
if (data.items.length !== 1 || data.items[0].number_uploaded_users !== input.hashes.length) throw new AdportError3("PROVIDER_ERROR", "snapchat: audience upload receipt count mismatch; reconcile before retrying", { resource_ids: [input.segment_id], received_count: data.items[0]?.number_uploaded_users });
|
|
899
|
+
return { applied: true, resourceIds: [input.segment_id], details: { uploaded_identifiers: data.items[0].number_uploaded_users, schema: input.schema, payload_sha256: digest, warnings: data.warnings } };
|
|
900
|
+
} };
|
|
901
|
+
}
|
|
902
|
+
case "snapchat_clear_audience_users": {
|
|
903
|
+
const segment = snapchatId.parse(p.segment_id), current = await this.audience(account, segment);
|
|
904
|
+
if (current.source_type !== "FIRST_PARTY") throw new AdportError3("INVALID_INPUT", "snapchat: clearing members requires an owned FIRST_PARTY audience");
|
|
905
|
+
return { summary: `Remove all members from Snapchat audience ${segment}`, changes: ["Permanently remove all members. Ads targeting this audience stop matching until it is populated again."], coercions: [], budgetDeltas: [], execute: () => this.mutate(account, `segments/${segment}/all_users`, "DELETE", void 0, "segments", "segment", { id: segment }) };
|
|
906
|
+
}
|
|
907
|
+
case "snapchat_delete_audience": {
|
|
908
|
+
const segment = snapchatId.parse(p.segment_id);
|
|
909
|
+
await this.audience(account, segment);
|
|
910
|
+
return this.deletion(`segments/${segment}`, "segments", segment, "Audience deletion cannot be undone. Existing targeting references can stop matching.");
|
|
911
|
+
}
|
|
912
|
+
case "snapchat_rename_pixel": {
|
|
913
|
+
const pixelId = snapchatId.parse(p.pixel_id);
|
|
914
|
+
await this.source(account, "PIXEL", pixelId, true);
|
|
915
|
+
body = { id: pixelId, name: z6.string().min(1).max(375).parse(p.name), ad_account_id: account };
|
|
916
|
+
plural = "pixels";
|
|
917
|
+
singular2 = "pixel";
|
|
918
|
+
path = `adaccounts/${account}/pixels`;
|
|
919
|
+
method = "PUT";
|
|
920
|
+
expected = { id: pixelId, name: body.name };
|
|
921
|
+
break;
|
|
922
|
+
}
|
|
923
|
+
case "snapchat_set_adsquad_measurement": {
|
|
924
|
+
const input = measurementUpdate.parse(p), current = await this.creatives.owned(account, "adsquads", input.ad_squad_id);
|
|
925
|
+
const patch = [];
|
|
926
|
+
if (input.pixel_id) {
|
|
927
|
+
await this.source(account, "PIXEL", input.pixel_id);
|
|
928
|
+
patch.push({ op: current.pixel_id === void 0 ? "add" : "replace", path: "/pixel_id", value: input.pixel_id });
|
|
929
|
+
expected.pixel_id = input.pixel_id;
|
|
930
|
+
}
|
|
931
|
+
if (input.mobile_app_id) {
|
|
932
|
+
await this.source(account, "MOBILE_APP", input.mobile_app_id);
|
|
933
|
+
const value = { ...record2(current.event_sources), MOBILE_APP: [input.mobile_app_id] };
|
|
934
|
+
patch.push({ op: current.event_sources === void 0 ? "add" : "replace", path: "/event_sources", value });
|
|
935
|
+
expected.event_sources = value;
|
|
936
|
+
}
|
|
937
|
+
expected.id = input.ad_squad_id;
|
|
938
|
+
expected.campaign_id = current.campaign_id;
|
|
939
|
+
return { summary: `Associate Snapchat ad-squad measurement ${input.ad_squad_id}`, changes: [`PATCH ${JSON.stringify(patch)}. This does not install tracking or send events.`], coercions: [], budgetDeltas: [], execute: () => this.mutate(account, `campaigns/${current.campaign_id}/adsquads/${input.ad_squad_id}`, "PATCH", patch, "adsquads", "adsquad", expected) };
|
|
940
|
+
}
|
|
941
|
+
case "snapchat_create_custom_conversion": {
|
|
942
|
+
const { source_type, source_id, ...input } = conversionCreate.parse(p);
|
|
943
|
+
await this.source(account, source_type, source_id);
|
|
944
|
+
body = input;
|
|
945
|
+
plural = "custom_conversions";
|
|
946
|
+
singular2 = "custom_conversion";
|
|
947
|
+
path = `${source_type === "PIXEL" ? "pixels" : "mobile_apps"}/${source_id}/custom_conversions`;
|
|
948
|
+
expected = { event_source: { id: source_id, type: source_type }, name: input.name, event_type: input.event_type, rules: input.rules };
|
|
949
|
+
notes.push("Create a new shared-source measurement definition only. No tracking code is installed or conversion event sent.");
|
|
950
|
+
break;
|
|
951
|
+
}
|
|
952
|
+
case "snapchat_delete_custom_conversion": {
|
|
953
|
+
const conversion = snapchatId.parse(p.custom_conversion_id), rows = await this.client.collection(`custom_conversions/${conversion}`, "custom_conversions", "custom_conversion", rowSchema2), current = rows[0];
|
|
954
|
+
if (rows.length !== 1 || current?.id !== conversion) throw new AdportError3("PROVIDER_ERROR", "snapchat: custom conversion ID mismatch");
|
|
955
|
+
const source = record2(current.event_source);
|
|
956
|
+
await this.source(account, sourceType.parse(source.type), snapchatId.parse(source.id), true);
|
|
957
|
+
return this.deletion(`custom_conversions/${conversion}`, "custom_conversions", conversion, "Permanently delete this source\u2019s custom conversion definition. Reporting and optimization referencing it may be affected.");
|
|
958
|
+
}
|
|
959
|
+
default:
|
|
960
|
+
throw new AdportError3("INVALID_INPUT", `snapchat: unsupported write ${op.tool}`);
|
|
961
|
+
}
|
|
962
|
+
if (plural === "segments") {
|
|
963
|
+
body.ad_account_id = account;
|
|
964
|
+
expected = { ...expected, ...body.source_type ? { source_type: body.source_type } : {}, ...body.name ? { name: body.name } : {}, ...body.retention_in_days !== void 0 ? { retention_in_days: Number(body.retention_in_days) } : {} };
|
|
965
|
+
}
|
|
966
|
+
return { summary: `Snapchat ${op.tool.replace("snapchat_", "").replaceAll("_", " ")}`, changes: [...notes, `${method} ${path}: ${JSON.stringify({ [plural]: [body] })}`], coercions: [], budgetDeltas: [], execute: () => this.mutate(account, path, method, { [plural]: [body] }, plural, singular2, expected) };
|
|
967
|
+
}
|
|
968
|
+
deletion(path, plural, resourceId, description) {
|
|
969
|
+
return { summary: `Delete Snapchat ${path}`, changes: [description, `DELETE ${path}`], coercions: [], budgetDeltas: [], execute: async () => {
|
|
970
|
+
const data = await this.client.request(path, "DELETE", z6.looseObject({ [plural]: z6.array(z6.unknown()) }));
|
|
971
|
+
if (data[plural].length) throw new AdportError3("PROVIDER_ERROR", "snapchat: unexpected deletion receipt; reconcile before retrying", { resource_ids: [resourceId] });
|
|
972
|
+
return { applied: true, resourceIds: [resourceId] };
|
|
973
|
+
} };
|
|
974
|
+
}
|
|
975
|
+
};
|
|
976
|
+
|
|
207
977
|
// src/provider.ts
|
|
208
978
|
var MICROS = 1e6;
|
|
209
979
|
var FIELDS = "spend,impressions,swipes,conversion_purchases,conversion_purchases_value";
|
|
210
980
|
var BREAKDOWN = { account: "campaign", campaign: "campaign", ad_group: "adsquad", ad: "ad" };
|
|
211
981
|
var SnapchatAdsProvider = class {
|
|
212
|
-
constructor(client) {
|
|
982
|
+
constructor(client, media) {
|
|
213
983
|
this.client = client;
|
|
984
|
+
this.creatives = new SnapchatCreativeService(client, media);
|
|
985
|
+
this.management = new SnapchatManagementService(client, this.creatives);
|
|
214
986
|
}
|
|
215
987
|
client;
|
|
216
988
|
id = "snapchat";
|
|
989
|
+
creatives;
|
|
990
|
+
management;
|
|
217
991
|
capabilities() {
|
|
218
992
|
return { serverDryRun: false };
|
|
219
993
|
}
|
|
@@ -246,12 +1020,12 @@ var SnapchatAdsProvider = class {
|
|
|
246
1020
|
const accountIds = query.accountIds ?? (await this.listAccounts()).map((a) => a.id);
|
|
247
1021
|
const rows = [];
|
|
248
1022
|
const limit = query.limit ?? 1e3;
|
|
249
|
-
if (!Number.isSafeInteger(limit) || limit < 1) throw new
|
|
1023
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError4("INVALID_INPUT", "snapchat: report limit must be a positive integer");
|
|
250
1024
|
for (const id of accountIds) {
|
|
251
1025
|
const accountId = snapchatId.parse(id);
|
|
252
1026
|
const accounts = await this.client.collection(`adaccounts/${accountId}`, "adaccounts", "adaccount", accountSchema);
|
|
253
1027
|
const account = accounts.find((a) => a.id === accountId);
|
|
254
|
-
if (!account) throw new
|
|
1028
|
+
if (!account) throw new AdportError4("PROVIDER_ERROR", "snapchat: requested account missing from response");
|
|
255
1029
|
const breakdown = BREAKDOWN[query.level];
|
|
256
1030
|
const totals = await this.client.collection(`adaccounts/${accountId}/stats`, "total_stats", "total_stat", statSchema, {
|
|
257
1031
|
granularity: "TOTAL",
|
|
@@ -264,14 +1038,14 @@ var SnapchatAdsProvider = class {
|
|
|
264
1038
|
});
|
|
265
1039
|
const stats = totals.flatMap((total) => {
|
|
266
1040
|
if (total.id !== accountId || !total.breakdown_stats || !Array.isArray(total.breakdown_stats[breakdown])) {
|
|
267
|
-
throw new
|
|
1041
|
+
throw new AdportError4("PROVIDER_ERROR", "snapchat: malformed or incorrectly scoped report breakdown");
|
|
268
1042
|
}
|
|
269
1043
|
return total.breakdown_stats[breakdown];
|
|
270
1044
|
});
|
|
271
1045
|
if (query.level === "account") {
|
|
272
1046
|
const sums = {};
|
|
273
1047
|
for (const field of FIELDS.split(",")) {
|
|
274
|
-
if (stats.every((row) => row.stats[field] !== void 0)) sums[field] = stats.reduce((sum, row) => sum + row.stats[field], 0);
|
|
1048
|
+
if (stats.length && stats.every((row) => row.stats[field] !== void 0)) sums[field] = stats.reduce((sum, row) => sum + row.stats[field], 0);
|
|
275
1049
|
}
|
|
276
1050
|
rows.push({ provider: this.id, accountId, entity: { level: "account", id: accountId, name: account.name, status: account.status }, metrics: normalize(sums, query.metrics) });
|
|
277
1051
|
} else {
|
|
@@ -290,15 +1064,15 @@ var SnapchatAdsProvider = class {
|
|
|
290
1064
|
return { ...preview, serverValidated: false };
|
|
291
1065
|
}
|
|
292
1066
|
async applyWrite(op, guard) {
|
|
293
|
-
return
|
|
1067
|
+
return (await this.plan(op, guard)).execute();
|
|
294
1068
|
}
|
|
295
1069
|
async plan(op, guard) {
|
|
296
1070
|
const accountId = snapchatId.parse(op.accountId);
|
|
297
|
-
if (op.provider !== this.id) throw new
|
|
1071
|
+
if (op.provider !== this.id) throw new AdportError4("INVALID_INPUT", "snapchat: provider mismatch");
|
|
298
1072
|
if (op.tool === "snapchat_create_campaign" && op.kind === "create") {
|
|
299
1073
|
const input2 = createCampaignSchema.parse(op.payload);
|
|
300
1074
|
if (input2.end_time && Date.parse(input2.end_time) <= Date.parse(input2.start_time)) {
|
|
301
|
-
throw new
|
|
1075
|
+
throw new AdportError4("INVALID_INPUT", "snapchat: end_time must be after start_time");
|
|
302
1076
|
}
|
|
303
1077
|
const status = guard.forcePausedCreation ? "PAUSED" : input2.status;
|
|
304
1078
|
const body = { campaigns: [{ ...input2, ad_account_id: accountId, status, buy_model: "AUCTION" }] };
|
|
@@ -310,17 +1084,23 @@ var SnapchatAdsProvider = class {
|
|
|
310
1084
|
const value2 = input2[field2];
|
|
311
1085
|
return value2 === void 0 ? [] : [{ target: `new campaign ${field2}`, toMicros: value2 }];
|
|
312
1086
|
}),
|
|
313
|
-
execute: async () =>
|
|
1087
|
+
execute: async () => {
|
|
1088
|
+
const data = await this.client.mutation(`adaccounts/${accountId}/campaigns`, "POST", body, "campaigns", "campaign", campaignSchema);
|
|
1089
|
+
const ids = data.items.map((c) => c.id);
|
|
1090
|
+
if (data.items.length !== 1 || data.items.some((c) => c.ad_account_id !== accountId || c.status !== status || c.name !== input2.name || input2.daily_budget_micro !== void 0 && c.daily_budget_micro !== input2.daily_budget_micro || input2.lifetime_spend_cap_micro !== void 0 && c.lifetime_spend_cap_micro !== input2.lifetime_spend_cap_micro)) throw new AdportError4("PROVIDER_ERROR", "snapchat: campaign creation receipt mismatch; reconcile before retrying", { resource_ids: ids, warnings: data.warnings });
|
|
1091
|
+
return { applied: true, resourceIds: ids, ...data.warnings.length ? { details: { warnings: data.warnings } } : {} };
|
|
1092
|
+
}
|
|
314
1093
|
};
|
|
315
1094
|
}
|
|
316
1095
|
if (op.kind !== "update" || !["snapchat_set_campaign_status", "snapchat_set_budget"].includes(op.tool)) {
|
|
317
|
-
|
|
1096
|
+
if (/^snapchat_(?:create_(?:customer_audience|website_audience|mobile_audience|engagement_audience|profile_audience|lookalike|custom_conversion)|update_audience|add_audience_users|remove_audience_users|clear_audience_users|delete_audience|rename_pixel|set_adsquad_measurement|delete_custom_conversion)$/.test(op.tool)) return this.management.plan(op, guard);
|
|
1097
|
+
return this.creatives.plan(op, guard);
|
|
318
1098
|
}
|
|
319
1099
|
const input = op.tool === "snapchat_set_budget" ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);
|
|
320
1100
|
const campaigns = await this.client.collection(`campaigns/${input.campaign_id}`, "campaigns", "campaign", campaignSchema);
|
|
321
1101
|
const current = campaigns.find((c) => c.id === input.campaign_id);
|
|
322
1102
|
if (!current || current.ad_account_id !== accountId) {
|
|
323
|
-
throw new
|
|
1103
|
+
throw new AdportError4("INVALID_INPUT", "snapchat: campaign does not belong to selected account");
|
|
324
1104
|
}
|
|
325
1105
|
const field = "budget_micros" in input ? input.field : "status";
|
|
326
1106
|
const value = "budget_micros" in input ? input.budget_micros : input.status;
|
|
@@ -331,14 +1111,11 @@ var SnapchatAdsProvider = class {
|
|
|
331
1111
|
changes: [`~ ${current.id} ${field}: ${previous ?? "unset"} \u2192 ${value}`],
|
|
332
1112
|
coercions: [],
|
|
333
1113
|
budgetDeltas: typeof value === "number" ? [{ target: `campaign ${current.id} ${field}`, ...typeof previous === "number" ? { fromMicros: previous } : {}, toMicros: value }] : [],
|
|
334
|
-
execute: async () =>
|
|
335
|
-
`adaccounts/${accountId}/campaigns/${current.id}`,
|
|
336
|
-
"
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
"campaign",
|
|
340
|
-
campaignSchema
|
|
341
|
-
)).map((c) => c.id)
|
|
1114
|
+
execute: async () => {
|
|
1115
|
+
const data = await this.client.mutation(`adaccounts/${accountId}/campaigns/${current.id}`, "PATCH", patch, "campaigns", "campaign", campaignSchema), ids = data.items.map((c) => c.id);
|
|
1116
|
+
if (data.items.length !== 1 || data.items.some((c) => c.id !== current.id || c.ad_account_id !== accountId || c[field] !== value)) throw new AdportError4("PROVIDER_ERROR", "snapchat: campaign update receipt mismatch; reconcile before retrying", { resource_ids: ids, warnings: data.warnings });
|
|
1117
|
+
return { applied: true, resourceIds: ids, ...data.warnings.length ? { details: { warnings: data.warnings } } : {} };
|
|
1118
|
+
}
|
|
342
1119
|
};
|
|
343
1120
|
}
|
|
344
1121
|
};
|
|
@@ -365,9 +1142,9 @@ function nextDate(date) {
|
|
|
365
1142
|
return new Date(Date.parse(`${date}T00:00:00Z`) + 864e5).toISOString().slice(0, 10);
|
|
366
1143
|
}
|
|
367
1144
|
function accountMidnight(date, timezone) {
|
|
368
|
-
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new
|
|
1145
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new AdportError4("INVALID_INPUT", "snapchat: invalid report date");
|
|
369
1146
|
const target = Date.parse(`${date}T00:00:00Z`);
|
|
370
|
-
if (!Number.isFinite(target) || new Date(target).toISOString().slice(0, 10) !== date) throw new
|
|
1147
|
+
if (!Number.isFinite(target) || new Date(target).toISOString().slice(0, 10) !== date) throw new AdportError4("INVALID_INPUT", "snapchat: invalid report date");
|
|
371
1148
|
const format = new Intl.DateTimeFormat("en-GB", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
|
|
372
1149
|
let value = target;
|
|
373
1150
|
for (let i = 0; i < 4; i++) {
|
|
@@ -376,23 +1153,25 @@ function accountMidnight(date, timezone) {
|
|
|
376
1153
|
if (rendered === target) return new Date(value).toISOString();
|
|
377
1154
|
value += target - rendered;
|
|
378
1155
|
}
|
|
379
|
-
throw new
|
|
1156
|
+
throw new AdportError4("INVALID_INPUT", "snapchat: account timezone has no midnight for this report date");
|
|
380
1157
|
}
|
|
381
1158
|
|
|
382
1159
|
// src/tools.ts
|
|
383
|
-
import { z as
|
|
384
|
-
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
1160
|
+
import { z as z7 } from "zod";
|
|
1161
|
+
import { defineTool as defineTool3, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
|
|
385
1162
|
function snapchatTools(provider) {
|
|
386
1163
|
return [
|
|
387
|
-
|
|
1164
|
+
...snapchatCreativeTools(provider),
|
|
1165
|
+
...snapchatManagementTools(provider),
|
|
1166
|
+
defineTool3({
|
|
388
1167
|
name: "snapchat_list_campaigns",
|
|
389
1168
|
namespace: "snapchat",
|
|
390
1169
|
description: "List Snapchat campaigns in the selected ad account.",
|
|
391
|
-
input:
|
|
1170
|
+
input: z7.object({ account_id: snapchatId }),
|
|
392
1171
|
annotations: { readOnly: true },
|
|
393
1172
|
handler: (input) => provider.listCampaigns(input.account_id)
|
|
394
1173
|
}),
|
|
395
|
-
|
|
1174
|
+
guardedWriteTool3({
|
|
396
1175
|
name: "snapchat_create_campaign",
|
|
397
1176
|
namespace: "snapchat",
|
|
398
1177
|
provider: "snapchat",
|
|
@@ -400,7 +1179,7 @@ function snapchatTools(provider) {
|
|
|
400
1179
|
description: "Create a Snapchat campaign, paused by default. Budget fields use integer micro-currency. Preview is local, not server validation.",
|
|
401
1180
|
payload: createCampaignSchema
|
|
402
1181
|
}),
|
|
403
|
-
|
|
1182
|
+
guardedWriteTool3({
|
|
404
1183
|
name: "snapchat_set_campaign_status",
|
|
405
1184
|
namespace: "snapchat",
|
|
406
1185
|
provider: "snapchat",
|
|
@@ -408,7 +1187,7 @@ function snapchatTools(provider) {
|
|
|
408
1187
|
description: "Pause or activate a Snapchat campaign after verifying account ownership.",
|
|
409
1188
|
payload: setStatusSchema
|
|
410
1189
|
}),
|
|
411
|
-
|
|
1190
|
+
guardedWriteTool3({
|
|
412
1191
|
name: "snapchat_set_budget",
|
|
413
1192
|
namespace: "snapchat",
|
|
414
1193
|
provider: "snapchat",
|
|
@@ -421,8 +1200,8 @@ function snapchatTools(provider) {
|
|
|
421
1200
|
|
|
422
1201
|
// src/index.ts
|
|
423
1202
|
async function resolveSnapchatCredentials(store) {
|
|
424
|
-
const
|
|
425
|
-
const data =
|
|
1203
|
+
const record3 = await store.get("snapchat");
|
|
1204
|
+
const data = record3?.data;
|
|
426
1205
|
if (data?.client_id && data.client_secret && data.refresh_token) return {
|
|
427
1206
|
clientId: data.client_id,
|
|
428
1207
|
clientSecret: data.client_secret,
|