@adport/provider-google 0.7.0 → 0.9.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 +622 -5
- package/dist/index.js +2483 -180
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
// src/client.ts
|
|
2
2
|
import { AdportError } from "@adport/core";
|
|
3
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
4
|
+
var GOOGLE_DATA_MANAGER_SCOPE = "https://www.googleapis.com/auth/datamanager";
|
|
5
|
+
var isDataManagerFieldPath = (value) => typeof value === "string" && value.length <= 256 && /^(?:events|destinations|consent|encoding|encryptionInfo)(?:\[\d+\])?(?:\.[A-Za-z][A-Za-z0-9_]*(?:\[\d+\])?)*$/.test(value);
|
|
3
6
|
var TOKEN_URL = "https://oauth2.googleapis.com/token";
|
|
4
7
|
var API_BASE = "https://googleads.googleapis.com";
|
|
5
8
|
var DEFAULT_API_VERSION = "v25";
|
|
6
|
-
function normalizeCustomerId(
|
|
7
|
-
const normalized =
|
|
9
|
+
function normalizeCustomerId(id8) {
|
|
10
|
+
const normalized = id8.replace(/^customers\//, "").replace(/-/g, "").trim();
|
|
8
11
|
if (!/^\d{10}$/.test(normalized)) {
|
|
9
|
-
throw new AdportError("INVALID_INPUT", `"${
|
|
12
|
+
throw new AdportError("INVALID_INPUT", `"${id8}" is not a valid Google Ads customer id (expected 10 digits).`);
|
|
10
13
|
}
|
|
11
14
|
return normalized;
|
|
12
15
|
}
|
|
@@ -46,16 +49,72 @@ var GoogleAdsRestClient = class {
|
|
|
46
49
|
);
|
|
47
50
|
}
|
|
48
51
|
const data = await response.json();
|
|
49
|
-
this.accessToken = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1e3 };
|
|
52
|
+
this.accessToken = { token: data.access_token, expiresAt: Date.now() + (data.expires_in - 60) * 1e3, ...typeof data.scope === "string" ? { scopes: data.scope.split(/\s+/).filter(Boolean) } : {} };
|
|
50
53
|
return this.accessToken.token;
|
|
51
54
|
}
|
|
55
|
+
dataManagerLoginAccount(customerId) {
|
|
56
|
+
const account2 = normalizeCustomerId(customerId);
|
|
57
|
+
return normalizeCustomerId(this.credentials.loginCustomerIds?.[account2] ?? this.credentials.loginCustomerId ?? account2);
|
|
58
|
+
}
|
|
59
|
+
async dataManagerAccess() {
|
|
60
|
+
await this.getAccessToken();
|
|
61
|
+
const scopes = this.accessToken?.scopes;
|
|
62
|
+
return { required_scope: GOOGLE_DATA_MANAGER_SCOPE, scope_status: scopes ? scopes.includes(GOOGLE_DATA_MANAGER_SCOPE) ? "GRANTED" : "MISSING" : "UNKNOWN" };
|
|
63
|
+
}
|
|
64
|
+
dataManagerReceiptKey() {
|
|
65
|
+
return createHmac("sha256", this.credentials.clientSecret).update("adport.google.datamanager.v1\0").update(this.credentials.clientId).update("\0").update(this.credentials.refreshToken).digest();
|
|
66
|
+
}
|
|
67
|
+
dataManagerReceipt(value) {
|
|
68
|
+
const payload = Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
69
|
+
return `${payload}.${createHmac("sha256", this.dataManagerReceiptKey()).update(payload).digest("base64url")}`;
|
|
70
|
+
}
|
|
71
|
+
verifyDataManagerReceipt(receipt2) {
|
|
72
|
+
const invalid = () => new AdportError("INVALID_INPUT", "google: invalid Data Manager receipt; use the receipt from the approved ingestion");
|
|
73
|
+
if (receipt2.length > 4096 || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(receipt2)) throw invalid();
|
|
74
|
+
const [payload, signature] = receipt2.split("."), expected = createHmac("sha256", this.dataManagerReceiptKey()).update(payload).digest(), supplied = Buffer.from(signature, "base64url");
|
|
75
|
+
if (supplied.toString("base64url") !== signature || expected.length !== supplied.length || !timingSafeEqual(expected, supplied)) throw invalid();
|
|
76
|
+
try {
|
|
77
|
+
return JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
78
|
+
} catch {
|
|
79
|
+
throw invalid();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async dataManagerRequest(method, input2) {
|
|
83
|
+
if (method !== "ingest" && method !== "status") throw new AdportError("INVALID_INPUT", "google: unsupported Data Manager route");
|
|
84
|
+
const access = await this.dataManagerAccess();
|
|
85
|
+
if (access.scope_status === "MISSING") throw new AdportError("NOT_CONNECTED", "google: the existing OAuth grant does not include Data Manager. Reauthorize explicitly with the datamanager scope; existing Ads access is unchanged.", access);
|
|
86
|
+
const token = await this.getAccessToken(), url4 = new URL(`https://datamanager.googleapis.com/v1/${method === "ingest" ? "events:ingest" : "requestStatus:retrieve"}`);
|
|
87
|
+
if (method === "status") url4.searchParams.set("requestId", String(input2.requestId));
|
|
88
|
+
let response;
|
|
89
|
+
try {
|
|
90
|
+
response = await this.fetchImpl(url4, { method: method === "ingest" ? "POST" : "GET", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...method === "ingest" ? { body: JSON.stringify(input2) } : {}, redirect: "error", signal: AbortSignal.timeout(3e4) });
|
|
91
|
+
} catch {
|
|
92
|
+
throw new AdportError("PROVIDER_ERROR", "google: Data Manager response was not confirmed; the request was not retried. Reconcile an ingestion before sending it again.");
|
|
93
|
+
}
|
|
94
|
+
let body;
|
|
95
|
+
try {
|
|
96
|
+
body = await response.json();
|
|
97
|
+
} catch {
|
|
98
|
+
throw new AdportError("PROVIDER_ERROR", "google: invalid Data Manager response; do not assume ingestion or retry automatically");
|
|
99
|
+
}
|
|
100
|
+
if (!response.ok) {
|
|
101
|
+
const object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
102
|
+
const error = object5(object5(body).error), details = Array.isArray(error.details) ? error.details.map(object5) : [];
|
|
103
|
+
const reasons = details.flatMap((value) => typeof value.reason === "string" && /^[A-Z][A-Z0-9_]{0,127}$/.test(value.reason) ? [value.reason] : []).slice(0, 30);
|
|
104
|
+
const fields5 = details.flatMap((value) => Array.isArray(value.fieldViolations) ? value.fieldViolations.map(object5).flatMap((item) => isDataManagerFieldPath(item.field) ? [item.field] : []) : []).slice(0, 100);
|
|
105
|
+
const status = typeof error.status === "string" && /^[A-Z_]{1,64}$/.test(error.status) ? error.status : "UNKNOWN";
|
|
106
|
+
throw new AdportError("PROVIDER_ERROR", `google: Data Manager rejected the request (HTTP ${response.status}; ${status}${reasons.length ? `; ${reasons.join(", ")}` : ""}). No automatic retry.`, { http_status: response.status, status, reasons, fields: fields5 });
|
|
107
|
+
}
|
|
108
|
+
if (body === null || typeof body !== "object" || Array.isArray(body)) throw new AdportError("PROVIDER_ERROR", "google: invalid Data Manager response object");
|
|
109
|
+
return body;
|
|
110
|
+
}
|
|
52
111
|
async request(path, init) {
|
|
53
112
|
const token = await this.getAccessToken();
|
|
54
113
|
const headers = {
|
|
55
114
|
authorization: `Bearer ${token}`,
|
|
56
115
|
"content-type": "application/json"
|
|
57
116
|
};
|
|
58
|
-
const operatingCustomerId = path.match(/^customers\/(\d{10})
|
|
117
|
+
const operatingCustomerId = path.match(/^customers\/(\d{10})(?:\/|:)/)?.[1];
|
|
59
118
|
const mappedLoginCustomerId = operatingCustomerId ? this.credentials.loginCustomerIds?.[operatingCustomerId] : void 0;
|
|
60
119
|
const loginCustomerId = init.loginCustomerId === null ? void 0 : init.loginCustomerId ?? mappedLoginCustomerId ?? this.credentials.loginCustomerId;
|
|
61
120
|
if (loginCustomerId) {
|
|
@@ -79,20 +138,44 @@ var GoogleAdsRestClient = class {
|
|
|
79
138
|
// manager header has no effect and must not leak between cloud tenants.
|
|
80
139
|
loginCustomerId: null
|
|
81
140
|
});
|
|
82
|
-
return (data.resourceNames ?? []).map((
|
|
141
|
+
return (data.resourceNames ?? []).map((name5) => name5.replace("customers/", ""));
|
|
142
|
+
}
|
|
143
|
+
async keywordPlanning(customerId, method, body) {
|
|
144
|
+
return this.request(`customers/${normalizeCustomerId(customerId)}:${method}`, { method: "POST", body });
|
|
145
|
+
}
|
|
146
|
+
async fieldMetadata(query, pageSize, pageToken) {
|
|
147
|
+
const response = await this.request("googleAdsFields:search", {
|
|
148
|
+
method: "POST",
|
|
149
|
+
body: { query, pageSize, ...pageToken ? { pageToken } : {} },
|
|
150
|
+
// This is the API-wide catalog, not a manager/customer data operation.
|
|
151
|
+
loginCustomerId: null
|
|
152
|
+
});
|
|
153
|
+
return { apiVersion: this.version, response };
|
|
154
|
+
}
|
|
155
|
+
async uploadConversions(customerId, method, rows, validateOnly, jobId) {
|
|
156
|
+
return this.request(`customers/${normalizeCustomerId(customerId)}:${method}`, {
|
|
157
|
+
method: "POST",
|
|
158
|
+
body: { [method === "uploadConversionAdjustments" ? "conversionAdjustments" : "conversions"]: rows, partialFailure: true, validateOnly, ...jobId !== void 0 ? { jobId } : {} }
|
|
159
|
+
});
|
|
83
160
|
}
|
|
84
161
|
/** Paged GAQL search; accumulates rows up to options.maxRows (default 1000). */
|
|
85
162
|
async search(customerId, query, options = {}) {
|
|
86
163
|
const maxRows = options.maxRows ?? 1e3;
|
|
87
164
|
const rows = [];
|
|
165
|
+
const cursors = /* @__PURE__ */ new Set();
|
|
88
166
|
let pageToken;
|
|
89
167
|
do {
|
|
90
168
|
const data = await this.request(
|
|
91
169
|
`customers/${normalizeCustomerId(customerId)}/googleAds:search`,
|
|
92
|
-
{ method: "POST", body: { query, pageToken }, loginCustomerId: options.loginCustomerId }
|
|
170
|
+
{ method: "POST", body: { query: options.includeDrafts ? `${query}${/\bPARAMETERS\b/i.test(query) ? "," : " PARAMETERS"} include_drafts=true` : query, pageToken }, loginCustomerId: options.loginCustomerId }
|
|
93
171
|
);
|
|
172
|
+
if (!data || typeof data !== "object" || Array.isArray(data) || data.results !== void 0 && !Array.isArray(data.results) || data.nextPageToken !== void 0 && typeof data.nextPageToken !== "string") throw new AdportError("PROVIDER_ERROR", "google: GAQL result/pagination envelope could not be verified");
|
|
94
173
|
rows.push(...data.results ?? []);
|
|
95
174
|
pageToken = data.nextPageToken;
|
|
175
|
+
if (pageToken) {
|
|
176
|
+
if (typeof pageToken !== "string" || pageToken.length > 8192 || cursors.has(pageToken) || cursors.size >= 1e3) throw new AdportError("PROVIDER_ERROR", "google: GAQL pagination repeated a cursor or exceeded its safety bound");
|
|
177
|
+
cursors.add(pageToken);
|
|
178
|
+
}
|
|
96
179
|
} while (pageToken && rows.length < maxRows);
|
|
97
180
|
return rows.slice(0, maxRows);
|
|
98
181
|
}
|
|
@@ -100,19 +183,33 @@ var GoogleAdsRestClient = class {
|
|
|
100
183
|
* Service-specific mutate (campaigns, campaignBudgets, adGroups, adGroupCriteria, adGroupAds).
|
|
101
184
|
* validateOnly=true is the server-side dry run.
|
|
102
185
|
*/
|
|
103
|
-
async mutate(customerId, service, operations, { validateOnly }) {
|
|
104
|
-
const body = { operations, validateOnly };
|
|
105
|
-
if (
|
|
186
|
+
async mutate(customerId, service, operations, { validateOnly, responseContentType }) {
|
|
187
|
+
const body = { operations, validateOnly, ...responseContentType ? { responseContentType } : {} };
|
|
188
|
+
if (!["customerManagerLinks", "assetGroups", "assetGroupListingGroupFilters"].includes(service)) body.partialFailure = false;
|
|
106
189
|
return this.request(`customers/${normalizeCustomerId(customerId)}/${service}:mutate`, {
|
|
107
190
|
method: "POST",
|
|
108
191
|
body
|
|
109
192
|
});
|
|
110
193
|
}
|
|
194
|
+
async experimentAction(customerId, experimentId, action2, payload, validateOnly) {
|
|
195
|
+
if (!/^[1-9]\d*$/.test(experimentId) || !["endExperiment", "scheduleExperiment", "promoteExperiment", "graduateExperiment"].includes(action2)) throw new AdportError("INVALID_INPUT", "google: invalid experiment action");
|
|
196
|
+
return this.request(`customers/${normalizeCustomerId(customerId)}/experiments/${experimentId}:${action2}`, { method: "POST", body: { ...payload, validateOnly } });
|
|
197
|
+
}
|
|
198
|
+
async experimentAsyncErrors(customerId, experimentId, pageSize, pageToken) {
|
|
199
|
+
if (!/^[1-9]\d*$/.test(experimentId)) throw new AdportError("INVALID_INPUT", "google: invalid experiment ID");
|
|
200
|
+
const query = new URLSearchParams({ pageSize: String(pageSize), ...pageToken ? { pageToken } : {} });
|
|
201
|
+
return this.request(`customers/${normalizeCustomerId(customerId)}/experiments/${experimentId}:listExperimentAsyncErrors?${query}`, { method: "GET" });
|
|
202
|
+
}
|
|
203
|
+
async experimentOperation(customerId, operationName) {
|
|
204
|
+
const account2 = normalizeCustomerId(customerId), prefix = `customers/${account2}/operations/`, key2 = operationName.startsWith(prefix) ? operationName.slice(prefix.length) : "";
|
|
205
|
+
if (!key2 || key2.length > 512 || /[\s/\\?#%]/.test(key2) || key2 === "." || key2 === "..") throw new AdportError("INVALID_INPUT", "google: operation is not scoped to the selected account");
|
|
206
|
+
return this.request(`${prefix}${encodeURIComponent(key2)}`, { method: "GET" });
|
|
207
|
+
}
|
|
111
208
|
/** Cross-service atomic mutate (e.g. budget + campaign with temp resource ids). */
|
|
112
|
-
async googleAdsMutate(customerId, mutateOperations, { validateOnly }) {
|
|
209
|
+
async googleAdsMutate(customerId, mutateOperations, { validateOnly, responseContentType }) {
|
|
113
210
|
return this.request(`customers/${normalizeCustomerId(customerId)}/googleAds:mutate`, {
|
|
114
211
|
method: "POST",
|
|
115
|
-
body: { mutateOperations, validateOnly, partialFailure: false }
|
|
212
|
+
body: { mutateOperations, validateOnly, partialFailure: false, ...responseContentType ? { responseContentType } : {} }
|
|
116
213
|
});
|
|
117
214
|
}
|
|
118
215
|
};
|
|
@@ -144,9 +241,1846 @@ function formatGoogleAdsError(status, raw) {
|
|
|
144
241
|
|
|
145
242
|
// src/provider.ts
|
|
146
243
|
import {
|
|
147
|
-
|
|
244
|
+
creativeStatusAction as creativeStatusAction2,
|
|
245
|
+
creativesOutput as creativesOutput3,
|
|
246
|
+
AdportError as AdportError10,
|
|
148
247
|
resolveDateRange
|
|
149
248
|
} from "@adport/core";
|
|
249
|
+
|
|
250
|
+
// src/assets.ts
|
|
251
|
+
import { AdportError as AdportError2, LocalMediaResolver, creativesOutput, defineTool, guardedWriteTool, mediaSourceFields } from "@adport/core";
|
|
252
|
+
import { z } from "zod";
|
|
253
|
+
var id = z.string().regex(/^\d+$/);
|
|
254
|
+
var assetType = z.enum(["IMAGE", "YOUTUBE_VIDEO", "TEXT", "SITELINK", "CALLOUT", "STRUCTURED_SNIPPET"]);
|
|
255
|
+
var name = z.string().trim().min(1).max(128);
|
|
256
|
+
var url = z.string().url().refine((value) => {
|
|
257
|
+
const parsed = new URL(value);
|
|
258
|
+
return ["https:", "http:"].includes(parsed.protocol) && !parsed.username && !parsed.password;
|
|
259
|
+
});
|
|
260
|
+
var sitelink = z.object({
|
|
261
|
+
type: z.literal("SITELINK"),
|
|
262
|
+
link_text: z.string().min(1).max(25),
|
|
263
|
+
final_urls: z.array(url).min(1).max(10),
|
|
264
|
+
description1: z.string().max(35).optional(),
|
|
265
|
+
description2: z.string().max(35).optional()
|
|
266
|
+
}).refine((value) => value.description1 !== void 0 === (value.description2 !== void 0), "Provide both sitelink descriptions or neither");
|
|
267
|
+
var extension = z.discriminatedUnion("type", [
|
|
268
|
+
sitelink,
|
|
269
|
+
z.object({ type: z.literal("CALLOUT"), callout_text: z.string().min(1).max(25) }),
|
|
270
|
+
z.object({ type: z.literal("STRUCTURED_SNIPPET"), header: z.string().min(1).max(25), values: z.array(z.string().min(1).max(25)).min(3).max(10) })
|
|
271
|
+
]);
|
|
272
|
+
var createExtension = z.object({ name: name.optional(), content: extension });
|
|
273
|
+
var updateExtension = z.object({ asset_id: id, content: extension });
|
|
274
|
+
var uploadImage = z.object({ name: name.optional(), ...mediaSourceFields }).refine((value) => Boolean(value.media_id) !== Boolean(value.file_path), "Choose media_id or file_path");
|
|
275
|
+
var youtube = z.object({ name: name.optional(), youtube_video_id: z.string().regex(/^[A-Za-z0-9_-]{11}$/) });
|
|
276
|
+
var createText = z.object({ name: name.optional(), text: z.string().min(1).max(2048) }).strict();
|
|
277
|
+
var GOOGLE_ASSET_WRITES = /* @__PURE__ */ new Set(["google_create_extension_asset", "google_update_extension_asset", "google_upload_image_asset", "google_create_youtube_asset", "google_create_text_asset", "google_rename_asset"]);
|
|
278
|
+
var fields = ["asset.resource_name", "asset.id", "asset.name", "asset.type", "asset.final_urls", "asset.image_asset.full_size.url", "asset.image_asset.file_size", "asset.youtube_video_asset.youtube_video_id", "asset.text_asset.text", "asset.callout_asset.callout_text", "asset.sitelink_asset.link_text", "asset.sitelink_asset.description1", "asset.sitelink_asset.description2", "asset.structured_snippet_asset.header", "asset.structured_snippet_asset.values", "asset.policy_summary.approval_status", "asset.policy_summary.review_status"];
|
|
279
|
+
var record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
280
|
+
var text = (value) => typeof value === "string" ? value : "";
|
|
281
|
+
var urls = (value) => Array.isArray(value) ? value.filter((value2) => url.safeParse(value2).success) : [];
|
|
282
|
+
function extensionFields(content) {
|
|
283
|
+
if (content.type === "CALLOUT") return { calloutAsset: { calloutText: content.callout_text } };
|
|
284
|
+
if (content.type === "STRUCTURED_SNIPPET") return { structuredSnippetAsset: { header: content.header, values: content.values } };
|
|
285
|
+
return { finalUrls: content.final_urls, sitelinkAsset: { linkText: content.link_text, ...content.description1 !== void 0 ? { description1: content.description1, description2: content.description2 } : {} } };
|
|
286
|
+
}
|
|
287
|
+
var GoogleAssetService = class {
|
|
288
|
+
constructor(client, media = new LocalMediaResolver()) {
|
|
289
|
+
this.client = client;
|
|
290
|
+
this.media = media;
|
|
291
|
+
}
|
|
292
|
+
client;
|
|
293
|
+
media;
|
|
294
|
+
resource(account2, asset2) {
|
|
295
|
+
return `customers/${normalizeCustomerId(account2)}/assets/${id.parse(asset2)}`;
|
|
296
|
+
}
|
|
297
|
+
async owned(account2, asset2) {
|
|
298
|
+
const resource = this.resource(account2, asset2);
|
|
299
|
+
const rows = await this.client.search(account2, `SELECT ${fields.join(", ")} FROM asset WHERE asset.id = ${id.parse(asset2)} LIMIT 2`, { maxRows: 2 });
|
|
300
|
+
const value = record(rows[0]?.asset);
|
|
301
|
+
if (rows.length !== 1 || value.resourceName !== resource || value.id !== asset2) throw new AdportError2("INVALID_INPUT", "google: asset is not owned by the selected account");
|
|
302
|
+
return value;
|
|
303
|
+
}
|
|
304
|
+
async list(input2) {
|
|
305
|
+
const account2 = normalizeCustomerId(input2.account_id);
|
|
306
|
+
const requestedIds = input2.asset_ids?.map((value) => id.parse(value)), requestedTypes = input2.types?.map((value) => assetType.parse(value));
|
|
307
|
+
const after = input2.after_asset_id === void 0 ? void 0 : id.parse(input2.after_asset_id);
|
|
308
|
+
const conditions = [requestedIds?.length ? `asset.id IN (${requestedIds.join(",")})` : "", requestedTypes?.length ? `asset.type IN (${requestedTypes.map((value) => `'${value}'`).join(",")})` : "", after ? `asset.id > ${after}` : ""].filter(Boolean);
|
|
309
|
+
const rows = await this.client.search(account2, `SELECT ${fields.join(", ")} FROM asset${conditions.length ? ` WHERE ${conditions.join(" AND ")}` : ""} ORDER BY asset.id ASC LIMIT ${input2.limit + 1}`, { maxRows: input2.limit + 1 });
|
|
310
|
+
const all = rows.map((row2) => record(row2.asset));
|
|
311
|
+
if (all.some((value) => !id.safeParse(value.id).success || value.resourceName !== this.resource(account2, String(value.id)) || requestedIds?.length && !requestedIds.includes(String(value.id)) || requestedTypes?.length && !requestedTypes.includes(value.type))) throw new AdportError2("PROVIDER_ERROR", "google: asset list returned an invalid ID or account, or an unexpected filter match");
|
|
312
|
+
if (all.some((value, index) => BigInt(String(value.id)) <= BigInt(index ? String(all[index - 1].id) : after ?? "-1"))) throw new AdportError2("PROVIDER_ERROR", "google: asset pagination did not advance in native ID order");
|
|
313
|
+
const assets = all.slice(0, input2.limit);
|
|
314
|
+
const creatives = assets.map((asset2) => {
|
|
315
|
+
const image = record(asset2.imageAsset), full = record(image.fullSize), link = record(asset2.sitelinkAsset), callout = record(asset2.calloutAsset), snippet = record(asset2.structuredSnippetAsset), copy = record(asset2.textAsset), policy = record(asset2.policySummary);
|
|
316
|
+
const candidate = text(full.url);
|
|
317
|
+
let preview;
|
|
318
|
+
if (candidate) {
|
|
319
|
+
try {
|
|
320
|
+
const parsed = new URL(candidate);
|
|
321
|
+
if (parsed.protocol === "https:" && !parsed.username && !parsed.password && (parsed.hostname === "tpc.googlesyndication.com" || parsed.hostname.endsWith(".googleusercontent.com"))) preview = candidate;
|
|
322
|
+
} catch {
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
id: String(asset2.id),
|
|
327
|
+
provider: "google",
|
|
328
|
+
account_id: account2,
|
|
329
|
+
name: text(asset2.name) || text(link.linkText) || text(callout.calloutText) || `Asset ${asset2.id}`,
|
|
330
|
+
type: String(asset2.type ?? "ASSET"),
|
|
331
|
+
status: text(policy.approvalStatus) || void 0,
|
|
332
|
+
headlines: [text(link.linkText) || text(callout.calloutText) || text(snippet.header) || text(copy.text)].filter(Boolean),
|
|
333
|
+
descriptions: [text(link.description1), text(link.description2), ...Array.isArray(snippet.values) ? snippet.values.filter((value) => typeof value === "string") : []].filter(Boolean),
|
|
334
|
+
landing_urls: urls(asset2.finalUrls),
|
|
335
|
+
media: preview ? [{ type: "image", url: preview }] : [],
|
|
336
|
+
actions: [{ label: "Rename shared asset", tool: "google_rename_asset", arguments: { account_id: account2, asset_id: String(asset2.id) }, fields: [{ key: "name", label: "Asset name", type: "text", value: text(asset2.name), max_length: 128 }] }]
|
|
337
|
+
};
|
|
338
|
+
});
|
|
339
|
+
const truncated = rows.length > input2.limit;
|
|
340
|
+
return creativesOutput.extend({ assets: z.array(z.record(z.string(), z.unknown())) }).parse({ creatives, assets, truncated, ...truncated && assets.length ? { next_cursor: String(assets.at(-1).id) } : {} });
|
|
341
|
+
}
|
|
342
|
+
async plan(op) {
|
|
343
|
+
const account2 = normalizeCustomerId(op.accountId), input2 = op.payload;
|
|
344
|
+
const expectedKind = ["google_rename_asset", "google_update_extension_asset"].includes(op.tool) ? "update" : "create";
|
|
345
|
+
if (op.provider !== "google" || op.kind !== expectedKind) throw new AdportError2("INVALID_INPUT", "google: asset operation kind mismatch");
|
|
346
|
+
let operation, changes, summary;
|
|
347
|
+
if (op.tool === "google_upload_image_asset") {
|
|
348
|
+
const parsed = uploadImage.parse(input2), file = await this.media.read(parsed, { maxBytes: 5 * 1024 * 1024, contentTypes: ["image/png", "image/jpeg", "image/gif"] });
|
|
349
|
+
operation = { create: { ...parsed.name ? { name: parsed.name } : {}, imageAsset: { data: Buffer.from(file.bytes).toString("base64") } } };
|
|
350
|
+
summary = "Upload Google image asset";
|
|
351
|
+
changes = [`+ ${parsed.name || file.name}; ${file.contentType}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}`, "Create an unattached asset. No ad, association, campaign or YouTube upload is created. Google assets cannot be deleted."];
|
|
352
|
+
} else if (op.tool === "google_create_youtube_asset") {
|
|
353
|
+
const parsed = youtube.parse(input2);
|
|
354
|
+
operation = { create: { ...parsed.name ? { name: parsed.name } : {}, youtubeVideoAsset: { youtubeVideoId: parsed.youtube_video_id } } };
|
|
355
|
+
summary = "Reference an existing YouTube video as a Google asset";
|
|
356
|
+
changes = [`+ YouTube ${parsed.youtube_video_id}; name ${parsed.name ?? "(provider default)"}`, "References an existing video; no video is uploaded or published and no ad is attached. Google assets cannot be deleted."];
|
|
357
|
+
} else if (op.tool === "google_create_text_asset") {
|
|
358
|
+
const parsed = createText.parse(input2);
|
|
359
|
+
operation = { create: { ...parsed.name ? { name: parsed.name } : {}, textAsset: { text: parsed.text } } };
|
|
360
|
+
summary = "Create unattached Google text asset";
|
|
361
|
+
changes = [`+ ${JSON.stringify(operation.create)}`, "Shared text content is immutable. Link it separately to eligible placements; no serving association is created. Google validates placement-specific language and length rules when linked. Assets cannot be deleted."];
|
|
362
|
+
} else if (op.tool === "google_create_extension_asset") {
|
|
363
|
+
const parsed = createExtension.parse(input2), create3 = { ...parsed.name ? { name: parsed.name } : {}, ...extensionFields(parsed.content) };
|
|
364
|
+
operation = { create: create3 };
|
|
365
|
+
summary = `Create Google ${parsed.content.type} asset`;
|
|
366
|
+
changes = [`+ ${JSON.stringify(create3)}`, "Unattached shared asset; serving entities are unchanged. Google assets cannot be deleted."];
|
|
367
|
+
} else if (op.tool === "google_rename_asset") {
|
|
368
|
+
const parsed = z.object({ asset_id: id, name }).parse(input2), current = await this.owned(account2, parsed.asset_id);
|
|
369
|
+
operation = { update: { resourceName: this.resource(account2, parsed.asset_id), name: parsed.name }, updateMask: "name" };
|
|
370
|
+
summary = `Rename Google asset ${parsed.asset_id}`;
|
|
371
|
+
changes = [`~ name ${JSON.stringify(current.name ?? null)} \u2192 ${JSON.stringify(parsed.name)}`, "Name only; shared content and serving associations are unchanged."];
|
|
372
|
+
} else if (op.tool === "google_update_extension_asset") {
|
|
373
|
+
const parsed = updateExtension.parse(input2), current = await this.owned(account2, parsed.asset_id);
|
|
374
|
+
if (current.type !== parsed.content.type) throw new AdportError2("INVALID_INPUT", "google: extension type does not match the existing asset");
|
|
375
|
+
const content = extensionFields(parsed.content);
|
|
376
|
+
const mask = parsed.content.type === "CALLOUT" ? ["callout_asset.callout_text"] : parsed.content.type === "STRUCTURED_SNIPPET" ? ["structured_snippet_asset.header", "structured_snippet_asset.values"] : ["final_urls", "sitelink_asset.link_text", ...parsed.content.description1 !== void 0 ? ["sitelink_asset.description1", "sitelink_asset.description2"] : []];
|
|
377
|
+
operation = { update: { resourceName: this.resource(account2, parsed.asset_id), ...content }, updateMask: mask.join(",") };
|
|
378
|
+
summary = `Update shared Google ${parsed.content.type} asset ${parsed.asset_id}`;
|
|
379
|
+
changes = [`~ ${JSON.stringify(current)} \u2192 supplied content ${JSON.stringify(content)}`, "Every ad using this shared asset can change, including active ads. Serving statuses and association membership are unchanged."];
|
|
380
|
+
} else throw new AdportError2("INVALID_INPUT", "google: unsupported asset write");
|
|
381
|
+
return { summary, changes, coercions: [], budgetDeltas: [], execute: async (validateOnly) => {
|
|
382
|
+
const result2 = await this.client.mutate(account2, "assets", [operation], { validateOnly });
|
|
383
|
+
const resources = (result2.results ?? []).flatMap((value) => value.resourceName ? [value.resourceName] : []);
|
|
384
|
+
if (!validateOnly && (resources.length !== 1 || !new RegExp(`^customers/${account2}/assets/\\d+$`).test(resources[0]))) throw new AdportError2("PROVIDER_ERROR", "google: asset mutation receipt mismatch; reconcile before retrying", { resource_ids: resources });
|
|
385
|
+
return resources;
|
|
386
|
+
} };
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
function googleAssetTools(provider) {
|
|
390
|
+
const write = (name5, description, payload, kind) => guardedWriteTool({ name: name5, namespace: "google", provider: "google", description, payload, kind, destructive: kind === "update" });
|
|
391
|
+
return [
|
|
392
|
+
defineTool({ name: "google_assets", namespace: "google", description: "View account-owned shared assets, extension copy, image previews and native policy status. Continue with next_cursor as after_asset_id and the same filters. Assets cannot be deleted; remove serving associations instead. Name edits use the normal preview/apply gate.", input: z.object({ account_id: z.string(), asset_ids: z.array(id).min(1).max(100).optional(), types: z.array(assetType).min(1).optional(), after_asset_id: id.optional(), limit: z.number().int().positive().max(200).default(50) }), output: creativesOutput.extend({ assets: z.array(z.record(z.string(), z.unknown())) }), annotations: { readOnly: true }, presentation: "creatives", pagination: { cursorInput: "after_asset_id" }, handler: (input2) => provider.assets.list(input2) }),
|
|
393
|
+
write("google_upload_image_asset", "Upload a SHA-256-bound PNG/JPEG/GIF as an unattached Google asset. Hosted calls require project media_id. Preview uses native validate_only. Assets cannot be deleted; no ad or serving association is created.", uploadImage, "create"),
|
|
394
|
+
write("google_create_youtube_asset", "Reference an existing YouTube video ID as an unattached Google asset. Does not upload or publish a video or attach it to an ad. Assets cannot be deleted.", youtube, "create"),
|
|
395
|
+
write("google_create_text_asset", "Create immutable unattached text for headlines, descriptions or business name. Link separately to an eligible placement; Google validates its language-aware length rules on association. No serving change; assets cannot be deleted.", createText, "create"),
|
|
396
|
+
write("google_create_extension_asset", "Create an unattached sitelink, callout or structured-snippet asset with native server validation. Does not attach it to serving entities. Assets cannot be deleted.", createExtension, "create"),
|
|
397
|
+
write("google_rename_asset", "Change only an account-owned shared asset name. Content and serving associations remain unchanged.", z.object({ asset_id: id, name }), "update"),
|
|
398
|
+
write("google_update_extension_asset", "Update supplied shared extension content of the same type. All ads using this asset, including active ads, can change. Omitted sitelink descriptions are preserved. Preview is server-validated.", updateExtension, "update")
|
|
399
|
+
];
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// src/asset-links.ts
|
|
403
|
+
import { AdportError as AdportError3, defineTool as defineTool2, guardedWriteTool as guardedWriteTool2 } from "@adport/core";
|
|
404
|
+
import { z as z2 } from "zod";
|
|
405
|
+
var id2 = z2.string().regex(/^\d+$/);
|
|
406
|
+
var scope = z2.enum(["CUSTOMER", "CAMPAIGN", "AD_GROUP"]);
|
|
407
|
+
var field = z2.enum(["SITELINK", "CALLOUT", "STRUCTURED_SNIPPET", "AD_IMAGE", "BUSINESS_LOGO", "BUSINESS_NAME"]);
|
|
408
|
+
var base = { scope, parent_id: id2.optional() };
|
|
409
|
+
var target = z2.object(base).refine((input2) => input2.scope === "CUSTOMER" ? !input2.parent_id : Boolean(input2.parent_id), "Use no parent_id for CUSTOMER; provide the campaign/ad-group ID for other scopes");
|
|
410
|
+
var linkInput = target.safeExtend({ asset_id: id2, field_type: field, status: z2.enum(["PAUSED", "ENABLED"]).default("PAUSED") });
|
|
411
|
+
var statusInput = target.safeExtend({ asset_id: id2, field_type: field, status: z2.enum(["PAUSED", "ENABLED"]) });
|
|
412
|
+
var removeInput = target.safeExtend({ asset_id: id2, field_type: field });
|
|
413
|
+
var GOOGLE_ASSET_LINK_WRITES = /* @__PURE__ */ new Set(["google_link_asset", "google_set_asset_link_status", "google_unlink_asset"]);
|
|
414
|
+
var configs = {
|
|
415
|
+
CUSTOMER: { resource: "customer_asset", key: "customerAsset", service: "customerAssets" },
|
|
416
|
+
CAMPAIGN: { resource: "campaign_asset", key: "campaignAsset", service: "campaignAssets", parent: "campaign", parentService: "campaigns" },
|
|
417
|
+
AD_GROUP: { resource: "ad_group_asset", key: "adGroupAsset", service: "adGroupAssets", parent: "ad_group", parentService: "adGroups" }
|
|
418
|
+
};
|
|
419
|
+
var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
420
|
+
var GoogleAssetLinks = class {
|
|
421
|
+
constructor(client, assets) {
|
|
422
|
+
this.client = client;
|
|
423
|
+
this.assets = assets;
|
|
424
|
+
}
|
|
425
|
+
client;
|
|
426
|
+
assets;
|
|
427
|
+
async parent(account2, input2) {
|
|
428
|
+
const config2 = configs[input2.scope];
|
|
429
|
+
if (!config2.parent) return;
|
|
430
|
+
const expected = `customers/${account2}/${config2.parentService}/${input2.parent_id}`;
|
|
431
|
+
const rows = await this.client.search(account2, `SELECT ${config2.parent}.id, ${config2.parent}.resource_name, ${config2.parent}.status FROM ${config2.parent} WHERE ${config2.parent}.id = ${input2.parent_id} LIMIT 2`, { maxRows: 2, includeDrafts: true });
|
|
432
|
+
const key2 = config2.parent === "ad_group" ? "adGroup" : "campaign", value = record2(rows[0]?.[key2]);
|
|
433
|
+
if (rows.length !== 1 || value.resourceName !== expected || !["ENABLED", "PAUSED"].includes(String(value.status))) throw new AdportError3("INVALID_INPUT", "google: asset-link parent is not an available entity in this account");
|
|
434
|
+
}
|
|
435
|
+
async rows(account2, input2, assetId, fieldType2, limit = 2) {
|
|
436
|
+
const c = configs[input2.scope], conditions = [`${c.resource}.status != 'REMOVED'`];
|
|
437
|
+
if (c.parent) conditions.push(`${c.resource}.${c.parent} = 'customers/${account2}/${c.parentService}/${input2.parent_id}'`);
|
|
438
|
+
if (assetId) conditions.push(`${c.resource}.asset = 'customers/${account2}/assets/${assetId}'`);
|
|
439
|
+
if (fieldType2) conditions.push(`${c.resource}.field_type = '${fieldType2}'`);
|
|
440
|
+
return (await this.client.search(account2, `SELECT ${c.resource}.resource_name, ${c.resource}.asset, ${c.resource}.field_type, ${c.resource}.status FROM ${c.resource} WHERE ${conditions.join(" AND ")} LIMIT ${limit}`, { maxRows: limit, includeDrafts: input2.scope !== "CUSTOMER" })).map((row2) => record2(row2[c.key]));
|
|
441
|
+
}
|
|
442
|
+
async list(input2) {
|
|
443
|
+
const account2 = normalizeCustomerId(input2.account_id), parsed = target.parse(input2);
|
|
444
|
+
await this.parent(account2, parsed);
|
|
445
|
+
const rows = await this.rows(account2, parsed, void 0, void 0, input2.limit + 1), c = configs[input2.scope];
|
|
446
|
+
if (rows.some((row2) => typeof row2.resourceName !== "string" || !row2.resourceName.startsWith(`customers/${account2}/${c.service}/${input2.parent_id ? `${input2.parent_id}~` : ""}`) || typeof row2.asset !== "string" || !new RegExp(`^customers/${account2}/assets/\\d+$`).test(row2.asset))) throw new AdportError3("PROVIDER_ERROR", "google: asset-link list returned another account or parent");
|
|
447
|
+
return { links: rows.slice(0, input2.limit), truncated: rows.length > input2.limit };
|
|
448
|
+
}
|
|
449
|
+
async plan(op, guard) {
|
|
450
|
+
if (!GOOGLE_ASSET_LINK_WRITES.has(op.tool)) throw new AdportError3("INVALID_INPUT", "google: unsupported asset-link write");
|
|
451
|
+
const account2 = normalizeCustomerId(op.accountId), creating = op.tool === "google_link_asset", removing = op.tool === "google_unlink_asset";
|
|
452
|
+
if (op.provider !== "google" || op.kind !== (creating ? "create" : removing ? "remove" : "update")) throw new AdportError3("INVALID_INPUT", "google: asset-link operation kind mismatch");
|
|
453
|
+
const input2 = removing ? removeInput.parse(op.payload) : creating ? linkInput.parse(op.payload) : statusInput.parse(op.payload), c = configs[input2.scope];
|
|
454
|
+
await this.parent(account2, input2);
|
|
455
|
+
const asset2 = await this.assets.owned(account2, input2.asset_id);
|
|
456
|
+
const wanted = { SITELINK: "SITELINK", CALLOUT: "CALLOUT", STRUCTURED_SNIPPET: "STRUCTURED_SNIPPET", AD_IMAGE: "IMAGE", BUSINESS_LOGO: "IMAGE", BUSINESS_NAME: "TEXT" }[input2.field_type];
|
|
457
|
+
if (asset2.type !== wanted) throw new AdportError3("INVALID_INPUT", "google: asset type is incompatible with this association field");
|
|
458
|
+
const resource = `customers/${account2}/${c.service}/${input2.parent_id ? `${input2.parent_id}~` : ""}${input2.asset_id}~${input2.field_type}`;
|
|
459
|
+
const current = await this.rows(account2, input2, input2.asset_id, input2.field_type);
|
|
460
|
+
if (current.length > 1 || current.some((row2) => row2.resourceName !== resource || row2.asset !== `customers/${account2}/assets/${input2.asset_id}` || row2.fieldType !== input2.field_type)) throw new AdportError3("PROVIDER_ERROR", "google: asset association identity mismatch");
|
|
461
|
+
if (creating ? current.length !== 0 : current.length !== 1) throw new AdportError3("INVALID_INPUT", creating ? "google: association already exists; use its status tool" : "google: active or paused asset association was not found");
|
|
462
|
+
const requested = "status" in input2 ? input2.status : void 0, status = creating && guard.forcePausedCreation ? "PAUSED" : requested;
|
|
463
|
+
const coercions = creating && status !== requested ? ["asset-link status coerced to PAUSED by policy (paused_creation)"] : [];
|
|
464
|
+
const operation = removing ? { remove: resource } : creating ? { create: { asset: `customers/${account2}/assets/${input2.asset_id}`, fieldType: input2.field_type, status, ...c.parent ? { [c.parent === "ad_group" ? "adGroup" : c.parent]: `customers/${account2}/${c.parentService}/${input2.parent_id}` } : {} } } : { update: { resourceName: resource, status }, updateMask: "status" };
|
|
465
|
+
return { summary: `${removing ? "Remove" : creating ? "Create" : "Update"} Google ${input2.scope} asset association`, changes: [`${creating ? "+" : removing ? "-" : "~"} ${resource}; ${removing ? "remove association" : `${current[0]?.status ?? "absent"} \u2192 ${status}`}`, "Asset bytes and content are retained. This affects every serving use of this association; parent ad and campaign statuses are unchanged."], coercions, budgetDeltas: [], execute: async (validateOnly) => {
|
|
466
|
+
const result2 = await this.client.mutate(account2, c.service, [operation], { validateOnly });
|
|
467
|
+
const resources = (result2.results ?? []).flatMap((value) => value.resourceName ? [value.resourceName] : []);
|
|
468
|
+
if (!validateOnly && (resources.length !== 1 || resources[0] !== resource)) throw new AdportError3("PROVIDER_ERROR", "google: asset-association mutation receipt mismatch; reconcile before retrying", { resource_ids: resources });
|
|
469
|
+
return resources;
|
|
470
|
+
} };
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
function googleAssetLinkTools(provider) {
|
|
474
|
+
const write = (name5, description, payload, kind) => guardedWriteTool2({ name: name5, namespace: "google", provider: "google", description, payload, kind });
|
|
475
|
+
return [
|
|
476
|
+
defineTool2({ name: "google_asset_links", namespace: "google", description: "Read shared asset associations for one customer, campaign or ad group. Removed associations are excluded; native field types and statuses are preserved.", input: target.safeExtend({ account_id: z2.string(), limit: z2.number().int().positive().max(200).default(50) }), output: z2.object({ links: z2.array(z2.record(z2.string(), z2.unknown())), truncated: z2.boolean() }), annotations: { readOnly: true }, handler: (input2) => provider.assetLinks.list(input2) }),
|
|
477
|
+
write("google_link_asset", "Attach an account-owned extension/image/branding asset to a customer, campaign or ad group. Defaults paused; paused-creation policy is reported. Native validation checks placement eligibility. Does not create an ad or change parents.", linkInput, "create"),
|
|
478
|
+
write("google_set_asset_link_status", "Enable or pause an existing owned asset association. Enabling can change active ads that use this association; parent statuses are unchanged.", statusInput, "update"),
|
|
479
|
+
write("google_unlink_asset", "Remove one exact asset association, preserving the asset itself. Changes every serving use of this association. Native server validation runs before approval.", removeInput, "remove")
|
|
480
|
+
];
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// src/labels.ts
|
|
484
|
+
import { createHash } from "crypto";
|
|
485
|
+
import { AdportError as AdportError4, defineTool as defineTool3, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
|
|
486
|
+
import { z as z3 } from "zod";
|
|
487
|
+
var id3 = z3.string().regex(/^[1-9]\d*$/);
|
|
488
|
+
var hash = z3.string().regex(/^[a-f0-9]{64}$/);
|
|
489
|
+
var name2 = z3.string().trim().min(1).max(80);
|
|
490
|
+
var metadata = { name: name2, background_color: z3.string().regex(/^#(?:[a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/).optional(), description: z3.string().max(200).optional() };
|
|
491
|
+
var create = z3.object(metadata);
|
|
492
|
+
var selected = { label_id: id3, expected_label_hash: hash };
|
|
493
|
+
var update = z3.object({ ...selected, ...metadata, name: name2.optional() }).refine((value) => value.name !== void 0 || value.background_color !== void 0 || value.description !== void 0, "Supply at least one label field");
|
|
494
|
+
var remove = z3.object(selected);
|
|
495
|
+
var target2 = z3.discriminatedUnion("type", [
|
|
496
|
+
z3.object({ type: z3.literal("CAMPAIGN"), campaign_id: id3 }),
|
|
497
|
+
z3.object({ type: z3.literal("AD_GROUP"), campaign_id: id3, ad_group_id: id3 }),
|
|
498
|
+
z3.object({ type: z3.literal("AD_GROUP_AD"), campaign_id: id3, ad_group_id: id3, ad_id: id3 }),
|
|
499
|
+
z3.object({ type: z3.literal("AD_GROUP_CRITERION"), campaign_id: id3, ad_group_id: id3, criterion_id: id3 })
|
|
500
|
+
]);
|
|
501
|
+
var association = z3.object({ ...selected, target: target2 });
|
|
502
|
+
var fields2 = "label.resource_name, label.id, label.name, label.status, label.text_label.background_color, label.text_label.description";
|
|
503
|
+
var record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
504
|
+
var config = {
|
|
505
|
+
CAMPAIGN: { resource: "campaign_label", key: "campaignLabel", service: "campaignLabels", entity: "campaign", entityKey: "campaign", entityService: "campaigns", relation: "campaign" },
|
|
506
|
+
AD_GROUP: { resource: "ad_group_label", key: "adGroupLabel", service: "adGroupLabels", entity: "ad_group", entityKey: "adGroup", entityService: "adGroups", relation: "adGroup" },
|
|
507
|
+
AD_GROUP_AD: { resource: "ad_group_ad_label", key: "adGroupAdLabel", service: "adGroupAdLabels", entity: "ad_group_ad", entityKey: "adGroupAd", entityService: "adGroupAds", relation: "adGroupAd" },
|
|
508
|
+
AD_GROUP_CRITERION: { resource: "ad_group_criterion_label", key: "adGroupCriterionLabel", service: "adGroupCriterionLabels", entity: "ad_group_criterion", entityKey: "adGroupCriterion", entityService: "adGroupCriteria", relation: "adGroupCriterion" }
|
|
509
|
+
};
|
|
510
|
+
var GOOGLE_LABEL_WRITES = /* @__PURE__ */ new Set(["google_create_label", "google_update_label", "google_remove_label", "google_link_label", "google_unlink_label"]);
|
|
511
|
+
var GoogleLabelService = class {
|
|
512
|
+
constructor(client) {
|
|
513
|
+
this.client = client;
|
|
514
|
+
}
|
|
515
|
+
client;
|
|
516
|
+
labelResource(account2, labelId) {
|
|
517
|
+
return `customers/${account2}/labels/${labelId}`;
|
|
518
|
+
}
|
|
519
|
+
validateLabel(account2, value) {
|
|
520
|
+
const row2 = record3(value), text2 = record3(row2.textLabel);
|
|
521
|
+
if (!id3.safeParse(row2.id).success || row2.resourceName !== this.labelResource(account2, String(row2.id)) || row2.status !== "ENABLED" || !name2.safeParse(row2.name).success || !z3.object({ backgroundColor: metadata.background_color, description: metadata.description }).safeParse(text2).success) throw new AdportError4("PROVIDER_ERROR", "google: label response has an invalid identity, status or metadata");
|
|
522
|
+
return row2;
|
|
523
|
+
}
|
|
524
|
+
async list(input2) {
|
|
525
|
+
const account2 = normalizeCustomerId(input2.account_id);
|
|
526
|
+
if (input2.after_label_id) id3.parse(input2.after_label_id);
|
|
527
|
+
const result2 = await this.client.search(account2, `SELECT ${fields2} FROM label WHERE label.status != 'REMOVED'${input2.after_label_id ? ` AND label.id > ${input2.after_label_id}` : ""} ORDER BY label.id ASC LIMIT ${input2.limit + 1}`, { maxRows: input2.limit + 1 });
|
|
528
|
+
const values = result2.map((row2) => this.validateLabel(account2, row2.label));
|
|
529
|
+
if (values.some((row2, index) => BigInt(String(row2.id)) <= BigInt(index ? String(values[index - 1].id) : input2.after_label_id ?? "0"))) throw new AdportError4("PROVIDER_ERROR", "google: label pagination did not advance in native ID order");
|
|
530
|
+
const labels = values.slice(0, input2.limit), truncated = values.length > input2.limit;
|
|
531
|
+
return { labels, truncated, ...truncated ? { next_cursor: String(labels.at(-1).id) } : {} };
|
|
532
|
+
}
|
|
533
|
+
async get(accountId, labelId) {
|
|
534
|
+
const account2 = normalizeCustomerId(accountId);
|
|
535
|
+
id3.parse(labelId);
|
|
536
|
+
const result2 = await this.client.search(account2, `SELECT ${fields2} FROM label WHERE label.id = ${labelId} AND label.status != 'REMOVED' LIMIT 2`, { maxRows: 2 });
|
|
537
|
+
if (result2.length !== 1) throw new AdportError4("INVALID_INPUT", "google: label was not found in the selected account");
|
|
538
|
+
const label = this.validateLabel(account2, result2[0].label);
|
|
539
|
+
if (label.id !== labelId) throw new AdportError4("PROVIDER_ERROR", "google: requested label identity mismatch");
|
|
540
|
+
const text2 = record3(label.textLabel);
|
|
541
|
+
const snapshot = { resourceName: label.resourceName, id: label.id, status: label.status, name: label.name, backgroundColor: text2.backgroundColor ?? "", description: text2.description ?? "" };
|
|
542
|
+
return { label, snapshot_hash: createHash("sha256").update(JSON.stringify(snapshot)).digest("hex") };
|
|
543
|
+
}
|
|
544
|
+
async checkedLabel(account2, input2) {
|
|
545
|
+
const current = await this.get(account2, input2.label_id);
|
|
546
|
+
if (current.snapshot_hash !== input2.expected_label_hash) throw new AdportError4("INVALID_INPUT", "google: label metadata changed; read google_label_context and request a fresh preview");
|
|
547
|
+
return current.label;
|
|
548
|
+
}
|
|
549
|
+
entityResource(account2, value) {
|
|
550
|
+
const c = config[value.type];
|
|
551
|
+
const entityId = value.type === "CAMPAIGN" ? value.campaign_id : value.type === "AD_GROUP" ? value.ad_group_id : value.type === "AD_GROUP_AD" ? `${value.ad_group_id}~${value.ad_id}` : `${value.ad_group_id}~${value.criterion_id}`;
|
|
552
|
+
return { c, entityId, resource: `customers/${account2}/${c.entityService}/${entityId}` };
|
|
553
|
+
}
|
|
554
|
+
async checkTarget(account2, value) {
|
|
555
|
+
const { c, resource } = this.entityResource(account2, value);
|
|
556
|
+
const conditions = [`campaign.id = ${value.campaign_id}`];
|
|
557
|
+
if (value.type !== "CAMPAIGN") conditions.push(`ad_group.id = ${value.ad_group_id}`);
|
|
558
|
+
if (value.type === "AD_GROUP_AD") conditions.push(`ad_group_ad.ad.id = ${value.ad_id}`);
|
|
559
|
+
if (value.type === "AD_GROUP_CRITERION") conditions.push(`ad_group_criterion.criterion_id = ${value.criterion_id}`);
|
|
560
|
+
const parents = value.type === "CAMPAIGN" ? "" : `, campaign.id${value.type === "AD_GROUP" ? "" : ", ad_group.id"}`;
|
|
561
|
+
const result2 = await this.client.search(account2, `SELECT ${c.entity}.resource_name, ${c.entity}.status${parents} FROM ${c.entity} WHERE ${conditions.join(" AND ")} LIMIT 2`, { maxRows: 2 });
|
|
562
|
+
const row2 = result2[0], entity = record3(row2?.[c.entityKey]);
|
|
563
|
+
if (result2.length !== 1 || entity.resourceName !== resource || !["ENABLED", "PAUSED"].includes(String(entity.status)) || value.type !== "CAMPAIGN" && record3(row2?.campaign).id !== value.campaign_id || (value.type === "AD_GROUP_AD" || value.type === "AD_GROUP_CRITERION") && record3(row2?.adGroup).id !== value.ad_group_id) throw new AdportError4("INVALID_INPUT", "google: label target was not found in the selected account and parent hierarchy");
|
|
564
|
+
}
|
|
565
|
+
async links(account2, value, labelId, limit) {
|
|
566
|
+
const { c, resource } = this.entityResource(account2, value), nativeRelation = c.entity;
|
|
567
|
+
const result2 = await this.client.search(account2, `SELECT ${c.resource}.resource_name, ${c.resource}.label, ${c.resource}.${nativeRelation} FROM ${c.resource} WHERE ${c.resource}.${nativeRelation} = '${resource}'${labelId ? ` AND ${c.resource}.label = '${this.labelResource(account2, labelId)}'` : ""} LIMIT ${limit}`, { maxRows: limit });
|
|
568
|
+
const values = result2.map((row2) => record3(row2[c.key]));
|
|
569
|
+
if (new Set(values.map((row2) => row2.resourceName)).size !== values.length || values.some((row2) => {
|
|
570
|
+
const nativeLabel = typeof row2.label === "string" ? row2.label.match(new RegExp(`^customers/${account2}/labels/([1-9]\\d*)$`))?.[1] : void 0;
|
|
571
|
+
return !nativeLabel || labelId && nativeLabel !== labelId || row2[c.relation] !== resource || row2.resourceName !== `customers/${account2}/${c.service}/${this.entityResource(account2, value).entityId}~${nativeLabel}`;
|
|
572
|
+
})) throw new AdportError4("PROVIDER_ERROR", "google: label association identity mismatch");
|
|
573
|
+
return values;
|
|
574
|
+
}
|
|
575
|
+
async listAssociations(input2) {
|
|
576
|
+
const account2 = normalizeCustomerId(input2.account_id), value = target2.parse(input2.target);
|
|
577
|
+
await this.checkTarget(account2, value);
|
|
578
|
+
const values = await this.links(account2, value, void 0, input2.limit + 1);
|
|
579
|
+
return { associations: values.slice(0, input2.limit), truncated: values.length > input2.limit };
|
|
580
|
+
}
|
|
581
|
+
async plan(op) {
|
|
582
|
+
const creating = op.tool === "google_create_label" || op.tool === "google_link_label", removing = op.tool === "google_remove_label" || op.tool === "google_unlink_label";
|
|
583
|
+
if (op.provider !== "google" || !GOOGLE_LABEL_WRITES.has(op.tool) || op.kind !== (creating ? "create" : removing ? "remove" : "update")) throw new AdportError4("INVALID_INPUT", "google: label operation kind mismatch");
|
|
584
|
+
const account2 = normalizeCustomerId(op.accountId);
|
|
585
|
+
let service = "labels", operation, expectedResource, summary, changes;
|
|
586
|
+
const fieldChanges = [];
|
|
587
|
+
if (op.tool === "google_create_label") {
|
|
588
|
+
const input2 = create.parse(op.payload), textLabel = { ...input2.background_color !== void 0 ? { backgroundColor: input2.background_color } : {}, ...input2.description !== void 0 ? { description: input2.description } : {} };
|
|
589
|
+
operation = { create: { name: input2.name, ...Object.keys(textLabel).length ? { textLabel } : {} } };
|
|
590
|
+
summary = `Create Google label \u201C${input2.name}\u201D`;
|
|
591
|
+
changes = [`+ ${JSON.stringify(operation.create)}`, "Creates unattached classification metadata. Labels have no pause state; no serving association, campaign, ad or budget is changed."];
|
|
592
|
+
fieldChanges.push({ field: "Label name", before: "(new)", after: input2.name });
|
|
593
|
+
if (input2.background_color !== void 0) fieldChanges.push({ field: "Background color", before: "(new)", after: input2.background_color });
|
|
594
|
+
if (input2.description !== void 0) fieldChanges.push({ field: "Description", before: "(new)", after: input2.description });
|
|
595
|
+
} else if (op.tool === "google_update_label" || op.tool === "google_remove_label") {
|
|
596
|
+
const input2 = op.tool === "google_update_label" ? update.parse(op.payload) : remove.parse(op.payload), current = await this.checkedLabel(account2, input2);
|
|
597
|
+
expectedResource = this.labelResource(account2, input2.label_id);
|
|
598
|
+
if (op.tool === "google_remove_label") {
|
|
599
|
+
operation = { remove: expectedResource };
|
|
600
|
+
summary = `Remove Google label \u201C${current.name}\u201D`;
|
|
601
|
+
changes = [`- ${JSON.stringify(current)}`, "Removes the label and its associations, including on active entities. Label-based reports and automation can change. Entity serving statuses and budgets are preserved. The snapshot covers metadata, not an atomic association inventory."];
|
|
602
|
+
fieldChanges.push({ field: "Label", before: `${current.name} (${input2.label_id})`, after: "(removed)" });
|
|
603
|
+
} else {
|
|
604
|
+
const value = update.parse(input2), textLabel = {}, mask = [], fields5 = {};
|
|
605
|
+
if (value.name !== void 0) {
|
|
606
|
+
fields5.name = value.name;
|
|
607
|
+
mask.push("name");
|
|
608
|
+
}
|
|
609
|
+
if (value.background_color !== void 0) {
|
|
610
|
+
textLabel.backgroundColor = value.background_color;
|
|
611
|
+
mask.push("text_label.background_color");
|
|
612
|
+
}
|
|
613
|
+
if (value.description !== void 0) {
|
|
614
|
+
textLabel.description = value.description;
|
|
615
|
+
mask.push("text_label.description");
|
|
616
|
+
}
|
|
617
|
+
operation = { update: { resourceName: expectedResource, ...fields5, ...Object.keys(textLabel).length ? { textLabel } : {} }, updateMask: mask.join(",") };
|
|
618
|
+
summary = `Update Google label \u201C${current.name}\u201D`;
|
|
619
|
+
changes = [`~ ${JSON.stringify(current)} \u2192 supplied fields ${JSON.stringify(operation.update)}`, "Only supplied metadata fields change; omitted color and description are preserved. Applies to every use of this shared label, including reports and automation."];
|
|
620
|
+
if (value.name !== void 0) fieldChanges.push({ field: "Label name", before: String(current.name), after: value.name });
|
|
621
|
+
if (value.background_color !== void 0) fieldChanges.push({ field: "Background color", before: String(record3(current.textLabel).backgroundColor ?? ""), after: value.background_color });
|
|
622
|
+
if (value.description !== void 0) fieldChanges.push({ field: "Description", before: String(record3(current.textLabel).description ?? ""), after: value.description });
|
|
623
|
+
}
|
|
624
|
+
} else {
|
|
625
|
+
const input2 = association.parse(op.payload), label = await this.checkedLabel(account2, input2);
|
|
626
|
+
await this.checkTarget(account2, input2.target);
|
|
627
|
+
const { c, resource, entityId } = this.entityResource(account2, input2.target), current = await this.links(account2, input2.target, input2.label_id, 2);
|
|
628
|
+
if (creating ? current.length !== 0 : current.length !== 1) throw new AdportError4("INVALID_INPUT", creating ? "google: label association already exists; do not replay creation" : "google: label association was not found");
|
|
629
|
+
service = c.service;
|
|
630
|
+
expectedResource = `customers/${account2}/${service}/${entityId}~${input2.label_id}`;
|
|
631
|
+
operation = removing ? { remove: expectedResource } : { create: { [c.relation]: resource, label: this.labelResource(account2, input2.label_id) } };
|
|
632
|
+
summary = `${creating ? "Assign" : "Unassign"} Google label \u201C${label.name}\u201D`;
|
|
633
|
+
changes = [`${creating ? "+" : "-"} ${expectedResource}`, "Classification only, including on active entities; no pause field exists. Label-based reports and automation can change. Entity content, serving statuses and budgets are preserved."];
|
|
634
|
+
fieldChanges.push({ field: "Target", before: resource, after: resource }, { field: "Label assignment", before: creating ? "(unassigned)" : `${label.name} (${input2.label_id})`, after: removing ? "(unassigned)" : `${label.name} (${input2.label_id})` });
|
|
635
|
+
}
|
|
636
|
+
return { summary, changes, fieldChanges, notes: changes.slice(1), coercions: [], budgetDeltas: [], execute: async (validateOnly) => {
|
|
637
|
+
const result2 = await this.client.mutate(account2, service, [operation], { validateOnly });
|
|
638
|
+
const resources = (result2.results ?? []).flatMap((value) => value.resourceName ? [value.resourceName] : []);
|
|
639
|
+
if (!validateOnly && (resources.length !== 1 || (expectedResource ? resources[0] !== expectedResource : !new RegExp(`^customers/${account2}/labels/[1-9]\\d*$`).test(resources[0])))) throw new AdportError4("PROVIDER_ERROR", "google: label mutation receipt mismatch; reconcile before retrying", { resource_ids: resources });
|
|
640
|
+
return resources;
|
|
641
|
+
} };
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
function googleLabelTools(provider) {
|
|
645
|
+
const write = (name5, description, payload, kind) => guardedWriteTool3({ name: name5, namespace: "google", provider: "google", description, payload, kind });
|
|
646
|
+
return [
|
|
647
|
+
defineTool3({ name: "google_labels", namespace: "google", description: "Read enabled account-owned label metadata in native ID order. Continue next_cursor as after_label_id. Labels owned by managers are separate.", input: z3.object({ account_id: z3.string(), after_label_id: id3.optional(), limit: z3.number().int().positive().max(200).default(50) }), output: z3.object({ labels: z3.array(z3.record(z3.string(), z3.unknown())), truncated: z3.boolean(), next_cursor: id3.optional() }), annotations: { readOnly: true }, pagination: { cursorInput: "after_label_id" }, handler: (input2) => provider.labels.list(input2) }),
|
|
648
|
+
defineTool3({ name: "google_label_context", namespace: "google", description: "Read one enabled owned label and its metadata snapshot_hash. Supply that value as expected_label_hash for edits, removal or associations; association inventory is not included.", input: z3.object({ account_id: z3.string(), label_id: id3 }), output: z3.object({ label: z3.record(z3.string(), z3.unknown()), snapshot_hash: hash }), annotations: { readOnly: true }, handler: (input2) => provider.labels.get(input2.account_id, input2.label_id) }),
|
|
649
|
+
defineTool3({ name: "google_label_associations", namespace: "google", description: "Read label assignments for an owned campaign, ad group, ad or criterion after checking the full account/parent hierarchy. Reports truncation; manager-to-customer labels are separate.", input: z3.object({ account_id: z3.string(), target: target2, limit: z3.number().int().positive().max(200).default(100) }), output: z3.object({ associations: z3.array(z3.record(z3.string(), z3.unknown())), truncated: z3.boolean() }), annotations: { readOnly: true }, handler: (input2) => provider.labels.listAssociations(input2) }),
|
|
650
|
+
write("google_create_label", "Create unattached label metadata with native validate_only preview. Name 1\u201380 characters; optional hex background color and description up to 200 characters. No serving or budget change.", create, "create"),
|
|
651
|
+
write("google_update_label", "Edit supplied owned label metadata after matching google_label_context. Omitted fields are preserved; an empty description clears it. Changes every use of this shared label, including reports and automation.", update, "update"),
|
|
652
|
+
write("google_remove_label", "Remove an owned label and its assignments after matching its metadata snapshot. Affects all uses, including active entities and label-based reports or automation. Does not delete labeled entities.", remove, "remove"),
|
|
653
|
+
write("google_link_label", "Assign a current owned label to a verified campaign, ad group, ad or criterion. Classification can affect reports and automation; serving statuses and budgets are preserved. Rejects existing assignments.", association, "create"),
|
|
654
|
+
write("google_unlink_label", "Remove one exact owned label assignment, preserving the shared label and labeled entity. Requires current label metadata hash. Native validate_only runs before approval.", association, "remove")
|
|
655
|
+
];
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// src/conversions.ts
|
|
659
|
+
import { createHash as createHash2 } from "crypto";
|
|
660
|
+
import { AdportError as AdportError5, defineTool as defineTool4, guardedWriteTool as guardedWriteTool4 } from "@adport/core";
|
|
661
|
+
import { z as z4 } from "zod";
|
|
662
|
+
var id4 = z4.string().regex(/^[1-9]\d*$/);
|
|
663
|
+
var hash2 = z4.string().regex(/^[a-f0-9]{64}$/);
|
|
664
|
+
var currency = z4.string().regex(/^[A-Z]{3}$/);
|
|
665
|
+
var category = z4.enum(["DEFAULT", "PAGE_VIEW", "PURCHASE", "SIGNUP", "DOWNLOAD", "ADD_TO_CART", "BEGIN_CHECKOUT", "SUBSCRIBE_PAID", "PHONE_CALL_LEAD", "SUBMIT_LEAD_FORM", "BOOK_APPOINTMENT", "REQUEST_QUOTE", "GET_DIRECTIONS", "OUTBOUND_CLICK", "CONTACT", "ENGAGEMENT", "STORE_VISIT", "STORE_SALE", "QUALIFIED_LEAD", "CONVERTED_LEAD", "YOUTUBE_FOLLOW_ON_VIEWS"]);
|
|
666
|
+
var valueSettings = z4.object({ default_value: z4.number().finite().optional(), default_currency_code: currency.or(z4.literal("")).optional(), always_use_default_value: z4.boolean().optional() }).refine((value) => Object.values(value).some((item) => item !== void 0), "Supply a value setting");
|
|
667
|
+
var editable = { name: z4.string().trim().min(1).optional(), category: category.optional(), counting_type: z4.enum(["ONE_PER_CLICK", "MANY_PER_CLICK"]).optional(), primary_for_goal: z4.boolean().optional(), click_through_lookback_window_days: z4.number().int().positive().optional(), view_through_lookback_window_days: z4.number().int().nonnegative().optional(), phone_call_duration_seconds: z4.number().int().min(0).max(1e4).optional(), value_settings: valueSettings.optional(), attribution_model: z4.enum(["GOOGLE_ADS_LAST_CLICK", "GOOGLE_SEARCH_ATTRIBUTION_DATA_DRIVEN", "EXTERNAL"]).optional() };
|
|
668
|
+
var reference = { conversion_action_id: id4, expected_action_hash: hash2 };
|
|
669
|
+
var createAction = z4.object({ ...editable, name: z4.string().trim().min(1), type: z4.enum(["UPLOAD_CLICKS", "UPLOAD_CALLS", "WEBPAGE"]), category, counting_type: z4.enum(["ONE_PER_CLICK", "MANY_PER_CLICK"]), primary_for_goal: z4.boolean().default(false), expected_context_hash: hash2 });
|
|
670
|
+
var updateAction = z4.object({ ...reference, ...editable }).refine((value) => Object.entries(value).some(([key2, item]) => !["conversion_action_id", "expected_action_hash"].includes(key2) && item !== void 0), "Supply an editable field");
|
|
671
|
+
var statusAction = z4.object({ ...reference, status: z4.enum(["ENABLED", "REMOVED"]) });
|
|
672
|
+
var timestamp = z4.string().regex(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$/).refine((value) => {
|
|
673
|
+
const date2 = new Date(value.replace(" ", "T"));
|
|
674
|
+
const parts = value.slice(0, 19).split(/[- :]/).map(Number), calendar = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]));
|
|
675
|
+
return Number.isFinite(date2.getTime()) && calendar.toISOString().slice(0, 19) === value.slice(0, 19).replace(" ", "T");
|
|
676
|
+
}, "Use a real date/time with an explicit numeric timezone offset");
|
|
677
|
+
var identifierSource = z4.enum(["FIRST_PARTY", "THIRD_PARTY"]).optional();
|
|
678
|
+
var emailIdentifier = z4.object({ hashed_email: hash2, user_identifier_source: identifierSource }).strict();
|
|
679
|
+
var phoneIdentifier = z4.object({ hashed_phone_number: hash2, user_identifier_source: identifierSource }).strict();
|
|
680
|
+
var clickIdentifier = z4.union([emailIdentifier, phoneIdentifier]);
|
|
681
|
+
var addressIdentifier = z4.object({ address_info: z4.object({ hashed_first_name: hash2, hashed_last_name: hash2, country_code: z4.string().regex(/^[A-Z]{2}$/), postal_code: z4.string().min(1), city: z4.string().optional(), state: z4.string().optional(), hashed_street_address: hash2.optional() }).strict(), user_identifier_source: identifierSource }).strict();
|
|
682
|
+
var consent = z4.object({ ad_user_data: z4.enum(["GRANTED", "DENIED"]) }).strict();
|
|
683
|
+
var eventValue = { conversion_date_time: timestamp, conversion_value: z4.number().finite(), currency_code: currency, consent: consent.optional() };
|
|
684
|
+
var opaque = z4.string().min(1).max(4096);
|
|
685
|
+
var click = z4.object({ ...eventValue, gclid: opaque.optional(), gbraid: opaque.optional(), wbraid: opaque.optional(), order_id: opaque.optional(), user_identifiers: z4.array(clickIdentifier).min(1).max(5).optional(), external_attribution_data: z4.object({ external_attribution_credit: z4.number().min(0).max(1), external_attribution_model: z4.string().min(1) }).strict().optional(), conversion_environment: z4.enum(["APP", "WEB"]).optional(), customer_type: z4.enum(["NEW", "RETURNING"]).optional(), cart_data: z4.object({ merchant_id: id4, feed_country_code: z4.string().regex(/^[A-Z]{2}$/), feed_language_code: z4.string().regex(/^[a-z]{2}$/), local_transaction_cost: z4.number().finite().optional(), items: z4.array(z4.object({ product_id: z4.string().min(1), quantity: z4.number().int().positive(), unit_price: z4.number().finite() }).strict()).min(1).max(1e3) }).strict().optional() }).strict().superRefine((value, ctx) => {
|
|
686
|
+
if (!value.gclid && !value.gbraid && !value.wbraid && !value.user_identifiers) ctx.addIssue({ code: "custom", message: "Supply captured click identifiers or hashed user identifiers" });
|
|
687
|
+
if (value.user_identifiers && value.consent?.ad_user_data !== "GRANTED") ctx.addIssue({ code: "custom", message: "Hashed user identifiers require an explicit GRANTED ad_user_data consent value" });
|
|
688
|
+
if (value.user_identifiers && value.external_attribution_data) ctx.addIssue({ code: "custom", message: "External attribution with user identifiers would discard user data" });
|
|
689
|
+
if (!value.gclid && (value.gbraid || value.wbraid) && (value.user_identifiers || value.cart_data)) ctx.addIssue({ code: "custom", message: "Braid-only imports do not support user identifiers or cart data; do not silently discard those fields" });
|
|
690
|
+
});
|
|
691
|
+
var call = z4.object({ ...eventValue, caller_id: z4.string().regex(/^\+[1-9]\d{1,14}$/), call_start_date_time: timestamp }).strict().refine((value) => Date.parse(value.conversion_date_time.replace(" ", "T")) > Date.parse(value.call_start_date_time.replace(" ", "T")), "Conversion time must be after call start");
|
|
692
|
+
var adjustmentTarget = { order_id: opaque.optional(), gclid_date_time_pair: z4.object({ gclid: opaque, conversion_date_time: timestamp }).strict().optional(), adjustment_date_time: timestamp };
|
|
693
|
+
var adjustment = z4.discriminatedUnion("adjustment_type", [
|
|
694
|
+
z4.object({ ...adjustmentTarget, adjustment_type: z4.literal("RETRACTION") }).strict(),
|
|
695
|
+
z4.object({ ...adjustmentTarget, adjustment_type: z4.literal("RESTATEMENT"), restatement_value: z4.object({ adjusted_value: z4.number().finite(), currency_code: currency.optional() }).strict() }).strict(),
|
|
696
|
+
z4.object({ ...adjustmentTarget, adjustment_type: z4.literal("ENHANCEMENT"), order_id: opaque, user_identifiers: z4.array(z4.union([emailIdentifier, phoneIdentifier, addressIdentifier])).min(1).max(5), user_agent: z4.string().min(1).max(4096).optional() }).strict()
|
|
697
|
+
]).superRefine((value, ctx) => {
|
|
698
|
+
if (!value.order_id && !value.gclid_date_time_pair) ctx.addIssue({ code: "custom", message: "Supply the original order_id or gclid/date-time pair" });
|
|
699
|
+
if (value.adjustment_type !== "ENHANCEMENT" && value.order_id && value.gclid_date_time_pair) ctx.addIssue({ code: "custom", message: "Choose one original-conversion identifier" });
|
|
700
|
+
if (value.gclid_date_time_pair && Date.parse(value.adjustment_date_time.replace(" ", "T")) <= Date.parse(value.gclid_date_time_pair.conversion_date_time.replace(" ", "T"))) ctx.addIssue({ code: "custom", message: "Adjustment time must be after original conversion time" });
|
|
701
|
+
});
|
|
702
|
+
var clickUpload = z4.object({ ...reference, conversions: z4.array(click).min(1).max(2e3), job_id: z4.number().int().min(0).max(2147483647).optional() });
|
|
703
|
+
var callUpload = z4.object({ ...reference, conversions: z4.array(call).min(1).max(2e3) });
|
|
704
|
+
var adjustmentUpload = z4.object({ ...reference, adjustments: z4.array(adjustment).min(1).max(2e3), job_id: z4.number().int().min(0).max(2147483647).optional() });
|
|
705
|
+
var actionFields = "conversion_action.resource_name, conversion_action.id, conversion_action.name, conversion_action.status, conversion_action.type, conversion_action.category, conversion_action.owner_customer, conversion_action.primary_for_goal, conversion_action.counting_type, conversion_action.click_through_lookback_window_days, conversion_action.view_through_lookback_window_days, conversion_action.phone_call_duration_seconds, conversion_action.value_settings.default_value, conversion_action.value_settings.default_currency_code, conversion_action.value_settings.always_use_default_value, conversion_action.attribution_model_settings.attribution_model, conversion_action.attribution_model_settings.data_driven_model_status, conversion_action.tag_snippets";
|
|
706
|
+
var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
707
|
+
function canonical(value) {
|
|
708
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
709
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical(item)]));
|
|
710
|
+
return value;
|
|
711
|
+
}
|
|
712
|
+
var digest = (value) => createHash2("sha256").update(JSON.stringify(canonical(value))).digest("hex");
|
|
713
|
+
var camel = (key2) => key2.replace(/_([a-z])/g, (_match, char) => char.toUpperCase());
|
|
714
|
+
function wire(value) {
|
|
715
|
+
if (Array.isArray(value)) return value.map(wire);
|
|
716
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).map(([key2, item]) => [camel(key2), wire(item)]));
|
|
717
|
+
return value;
|
|
718
|
+
}
|
|
719
|
+
var GOOGLE_CONVERSION_WRITES = /* @__PURE__ */ new Set(["google_create_conversion_action", "google_update_conversion_action", "google_set_conversion_action_status", "google_remove_conversion_action", "google_upload_click_conversions", "google_upload_call_conversions", "google_upload_conversion_adjustments"]);
|
|
720
|
+
var GoogleConversionService = class {
|
|
721
|
+
constructor(client) {
|
|
722
|
+
this.client = client;
|
|
723
|
+
}
|
|
724
|
+
client;
|
|
725
|
+
async context(accountId) {
|
|
726
|
+
const account2 = normalizeCustomerId(accountId);
|
|
727
|
+
const rows = await this.client.search(account2, "SELECT customer.resource_name, customer.id, customer.currency_code, customer.conversion_tracking_setting.google_ads_conversion_customer, customer.conversion_tracking_setting.conversion_tracking_id, customer.conversion_tracking_setting.cross_account_conversion_tracking_id, customer.conversion_tracking_setting.accepted_customer_data_terms, customer.conversion_tracking_setting.conversion_tracking_status, customer.conversion_tracking_setting.enhanced_conversions_for_leads_enabled FROM customer LIMIT 2", { maxRows: 2 });
|
|
728
|
+
const customer = object(rows[0]?.customer), tracking = object(customer.conversionTrackingSetting);
|
|
729
|
+
if (rows.length !== 1 || customer.id !== account2 || customer.resourceName !== `customers/${account2}` || !currency.safeParse(customer.currencyCode).success) throw new AdportError5("PROVIDER_ERROR", "google: invalid conversion tracking customer identity");
|
|
730
|
+
const owner = tracking.googleAdsConversionCustomer;
|
|
731
|
+
if (owner !== void 0 && owner !== "" && (typeof owner !== "string" || !/^customers\/\d{10}$/.test(owner))) throw new AdportError5("PROVIDER_ERROR", "google: invalid conversion tracking owner");
|
|
732
|
+
const context = { customer, conversion_customer: typeof owner === "string" && owner ? owner : null };
|
|
733
|
+
return { ...context, snapshot_hash: digest({ account: account2, currency: customer.currencyCode, tracking }) };
|
|
734
|
+
}
|
|
735
|
+
action(value, account2, owner) {
|
|
736
|
+
const action2 = object(value), resource = typeof action2.resourceName === "string" ? action2.resourceName.match(/^customers\/(\d{10})\/conversionActions\/([1-9]\d*)$/) : null;
|
|
737
|
+
if (!resource || action2.id !== resource[2] || resource[1] !== account2 && `customers/${resource[1]}` !== owner || typeof action2.name !== "string" || typeof action2.type !== "string" || !["ENABLED", "HIDDEN", "REMOVED"].includes(String(action2.status)) || action2.ownerCustomer !== void 0 && action2.ownerCustomer !== "" && !/^customers\/\d{10}$/.test(String(action2.ownerCustomer))) throw new AdportError5("PROVIDER_ERROR", "google: invalid conversion action identity or configuration");
|
|
738
|
+
return action2;
|
|
739
|
+
}
|
|
740
|
+
async list(input2) {
|
|
741
|
+
const account2 = normalizeCustomerId(input2.account_id), context = await this.context(account2);
|
|
742
|
+
if (input2.after_action_id) id4.parse(input2.after_action_id);
|
|
743
|
+
const predicates = [...!input2.include_removed ? ["conversion_action.status != 'REMOVED'"] : [], ...input2.after_action_id ? [`conversion_action.id > ${input2.after_action_id}`] : []];
|
|
744
|
+
const rows = await this.client.search(account2, `SELECT ${actionFields} FROM conversion_action${predicates.length ? ` WHERE ${predicates.join(" AND ")}` : ""} ORDER BY conversion_action.id ASC LIMIT ${input2.limit + 1}`, { maxRows: input2.limit + 1 });
|
|
745
|
+
const actions = rows.map((row2) => this.action(row2.conversionAction, account2, context.conversion_customer));
|
|
746
|
+
if (actions.some((value, index) => BigInt(String(value.id)) <= BigInt(index ? String(actions[index - 1].id) : input2.after_action_id ?? "0"))) throw new AdportError5("PROVIDER_ERROR", "google: conversion action continuation did not advance");
|
|
747
|
+
const page = actions.slice(0, input2.limit), truncated = actions.length > input2.limit;
|
|
748
|
+
return { context, actions: page, truncated, ...truncated ? { next_cursor: String(page.at(-1).id) } : {} };
|
|
749
|
+
}
|
|
750
|
+
async get(accountId, actionId) {
|
|
751
|
+
const account2 = normalizeCustomerId(accountId);
|
|
752
|
+
id4.parse(actionId);
|
|
753
|
+
const context = await this.context(account2);
|
|
754
|
+
const rows = await this.client.search(account2, `SELECT ${actionFields} FROM conversion_action WHERE conversion_action.id = ${actionId} LIMIT 2`, { maxRows: 2 });
|
|
755
|
+
if (rows.length !== 1) throw new AdportError5("INVALID_INPUT", "google: conversion action was not available in the selected account");
|
|
756
|
+
const action2 = this.action(rows[0].conversionAction, account2, context.conversion_customer);
|
|
757
|
+
if (action2.id !== actionId) throw new AdportError5("PROVIDER_ERROR", "google: conversion action ID mismatch");
|
|
758
|
+
const { tagSnippets: _tags, attributionModelSettings, ...configuration } = action2;
|
|
759
|
+
const attribution = object(attributionModelSettings);
|
|
760
|
+
return { action: action2, context, editable: action2.ownerCustomer === `customers/${account2}` && String(action2.resourceName).startsWith(`customers/${account2}/`), snapshot_hash: digest({ context: context.snapshot_hash, ...configuration, attributionModel: attribution.attributionModel }) };
|
|
761
|
+
}
|
|
762
|
+
async checked(account2, input2, editing = true) {
|
|
763
|
+
const current = await this.get(account2, input2.conversion_action_id);
|
|
764
|
+
if (current.snapshot_hash !== input2.expected_action_hash) throw new AdportError5("PENDING_MISMATCH", "google: conversion action or tracking context changed; read it again before previewing");
|
|
765
|
+
if (editing && !current.editable) throw new AdportError5("INVALID_INPUT", "google: this action is shared, system-owned or owned by another conversion customer; select its explicitly authorized owner to edit it");
|
|
766
|
+
return current;
|
|
767
|
+
}
|
|
768
|
+
async plan(op) {
|
|
769
|
+
const account2 = normalizeCustomerId(op.accountId);
|
|
770
|
+
if (op.tool.startsWith("google_upload_")) return this.uploadPlan(op);
|
|
771
|
+
if (op.tool === "google_create_conversion_action") {
|
|
772
|
+
const input3 = createAction.parse(op.payload), context = await this.context(account2);
|
|
773
|
+
if (context.snapshot_hash !== input3.expected_context_hash) throw new AdportError5("PENDING_MISMATCH", "google: conversion tracking context changed; request a fresh preview");
|
|
774
|
+
if (context.conversion_customer && context.conversion_customer !== `customers/${account2}`) throw new AdportError5("INVALID_INPUT", "google: conversions are managed by another customer; select its explicitly authorized account to create an action");
|
|
775
|
+
const { expected_context_hash: _hash2, type, ...settings3 } = input3;
|
|
776
|
+
const create3 = { ...this.settings(settings3).body, type, status: "ENABLED" };
|
|
777
|
+
return this.mutate(account2, [{ create: create3 }], `Create Google conversion action "${input3.name}"`, [`+ ${input3.type} \xB7 ${input3.category} \xB7 ${input3.counting_type} \xB7 primary_for_goal=${input3.primary_for_goal}.`, "Creates configuration only; no conversion events, tag installation or campaign goal association."]);
|
|
778
|
+
}
|
|
779
|
+
if (op.tool === "google_remove_conversion_action") {
|
|
780
|
+
const input3 = removeAction.parse(op.payload), current2 = await this.checked(account2, input3);
|
|
781
|
+
return this.mutate(account2, [{ remove: current2.action.resourceName }], `Remove Google conversion action "${current2.action.name}"`, [`- ${current2.action.resourceName}. Recording, reporting and bidding goals that use this action can be affected.`]);
|
|
782
|
+
}
|
|
783
|
+
const status = op.tool === "google_set_conversion_action_status";
|
|
784
|
+
if (!status && op.tool !== "google_update_conversion_action") throw new AdportError5("INVALID_INPUT", "google: unsupported conversion operation");
|
|
785
|
+
const input2 = status ? statusAction.parse(op.payload) : updateAction.parse(op.payload), current = await this.checked(account2, input2);
|
|
786
|
+
if (current.action.status === "REMOVED" && !status) throw new AdportError5("INVALID_INPUT", "google: this conversion action has been removed; use the status tool to request native re-enablement first");
|
|
787
|
+
if ("status" in input2 && input2.status === "REMOVED") {
|
|
788
|
+
const plan2 = this.mutate(account2, [{ remove: current.action.resourceName }], `Remove Google conversion action "${current.action.name}"`, [`- ${current.action.resourceName}. Recording, reporting and bidding goals that use this action can be affected.`]);
|
|
789
|
+
return { ...plan2, fieldChanges: [{ field: "status", before: String(current.action.status), after: "REMOVED" }], notes: [...plan2.notes ?? [], "REMOVED uses the native remove operation; writing REMOVED directly to the status field was rejected by the live API."] };
|
|
790
|
+
}
|
|
791
|
+
const { conversion_action_id: _id, expected_action_hash: _hash, ...settings2 } = input2;
|
|
792
|
+
const { body, mask } = this.settings(settings2), changes = mask.map((field3) => ({ field: field3, before: JSON.stringify(this.path(current.action, field3) ?? null), after: JSON.stringify(this.path(body, field3) ?? null) }));
|
|
793
|
+
const plan = this.mutate(account2, [{ update: { resourceName: current.action.resourceName, ...body }, updateMask: mask.join(",") }], `Update Google conversion action "${current.action.name}"`, changes.map((value) => `~ ${value.field}: ${value.before} \u2192 ${value.after}`));
|
|
794
|
+
return { ...plan, fieldChanges: changes };
|
|
795
|
+
}
|
|
796
|
+
settings(input2) {
|
|
797
|
+
const body = {}, mask = [];
|
|
798
|
+
for (const [key2, value] of Object.entries(input2)) {
|
|
799
|
+
if (value === void 0) continue;
|
|
800
|
+
if (key2 === "value_settings") {
|
|
801
|
+
body.valueSettings = wire(value);
|
|
802
|
+
for (const field3 of Object.keys(object(value))) mask.push(`value_settings.${field3}`);
|
|
803
|
+
} else if (key2 === "attribution_model") {
|
|
804
|
+
body.attributionModelSettings = { attributionModel: value };
|
|
805
|
+
mask.push("attribution_model_settings.attribution_model");
|
|
806
|
+
} else {
|
|
807
|
+
body[camel(key2)] = /_days$|_seconds$/.test(key2) ? String(value) : value;
|
|
808
|
+
mask.push(key2);
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
return { body, mask };
|
|
812
|
+
}
|
|
813
|
+
path(row2, path) {
|
|
814
|
+
return path.split(".").reduce((value, key2) => object(value)[camel(key2)], row2);
|
|
815
|
+
}
|
|
816
|
+
mutate(account2, operations, summary, changes) {
|
|
817
|
+
return { summary, changes, coercions: [], budgetDeltas: [], notes: ["Conversion values use whole currency units, not budget micros. Goal classification, counting, attribution, windows and status changes can affect reporting and bidding.", "primary_for_goal=false excludes ordinary goals but does not override a custom conversion goal. Omitted fields are preserved; action type and ownership are immutable here."], execute: async (validateOnly) => {
|
|
818
|
+
const result2 = await this.client.mutate(account2, "conversionActions", operations, { validateOnly });
|
|
819
|
+
if (validateOnly) return [];
|
|
820
|
+
const names = result2.results?.map((value) => value.resourceName);
|
|
821
|
+
if (!names?.length || names.some((value) => typeof value !== "string" || !new RegExp(`^customers/${account2}/conversionActions/[1-9]\\d*$`).test(value))) throw new AdportError5("PROVIDER_ERROR", "google: conversion mutation was not confirmed; inspect native state before retrying");
|
|
822
|
+
return names;
|
|
823
|
+
} };
|
|
824
|
+
}
|
|
825
|
+
async uploadPlan(op) {
|
|
826
|
+
const kind = op.tool === "google_upload_click_conversions" ? "click" : op.tool === "google_upload_call_conversions" ? "call" : op.tool === "google_upload_conversion_adjustments" ? "adjustment" : void 0;
|
|
827
|
+
if (!kind) throw new AdportError5("INVALID_INPUT", "google: unsupported conversion upload");
|
|
828
|
+
const input2 = kind === "click" ? clickUpload.parse(op.payload) : kind === "call" ? callUpload.parse(op.payload) : adjustmentUpload.parse(op.payload);
|
|
829
|
+
const account2 = normalizeCustomerId(op.accountId), current = await this.checked(account2, input2, false);
|
|
830
|
+
const action2 = current.action, tracking = object(current.context.customer.conversionTrackingSetting);
|
|
831
|
+
if (action2.status !== "ENABLED" || !current.context.conversion_customer || action2.ownerCustomer !== current.context.conversion_customer) throw new AdportError5("INVALID_INPUT", "google: upload action must be enabled and owned by the verified conversion tracking customer");
|
|
832
|
+
if (kind === "click" && action2.type !== "UPLOAD_CLICKS" || kind === "call" && action2.type !== "UPLOAD_CALLS") throw new AdportError5("INVALID_INPUT", "google: conversion action type does not match this upload service");
|
|
833
|
+
const source = "adjustments" in input2 ? input2.adjustments : input2.conversions;
|
|
834
|
+
const records = source.map((value) => ({ ...object(wire(value)), conversionAction: action2.resourceName }));
|
|
835
|
+
const keys = source.map((value) => kind === "adjustment" ? `${value.adjustment_type}:${value.order_id ?? digest(value.gclid_date_time_pair)}:${value.adjustment_date_time}` : kind === "call" ? `${value.caller_id}:${value.call_start_date_time}:${value.conversion_date_time}` : value.order_id ? `order:${value.order_id}` : `event:${value.gclid ?? value.wbraid ?? value.gbraid ?? digest(value.user_identifiers)}:${value.conversion_date_time}`);
|
|
836
|
+
if (new Set(keys).size !== keys.length) throw new AdportError5("INVALID_INPUT", "google: duplicate conversion identities in this batch");
|
|
837
|
+
if (source.some((value) => Array.isArray(value.user_identifiers)) && tracking.acceptedCustomerDataTerms !== true) throw new AdportError5("INVALID_INPUT", "google: native customer-data terms are not accepted; no identifiers were uploaded and no terms were accepted");
|
|
838
|
+
if (kind === "click") {
|
|
839
|
+
const external = object(action2.attributionModelSettings).attributionModel === "EXTERNAL";
|
|
840
|
+
if (source.some((value) => Boolean(value.external_attribution_data) !== external)) throw new AdportError5("INVALID_INPUT", "google: external attribution data must match the action attribution model");
|
|
841
|
+
}
|
|
842
|
+
const method = kind === "click" ? "uploadClickConversions" : kind === "call" ? "uploadCallConversions" : "uploadConversionAdjustments";
|
|
843
|
+
const batchHash = digest(records), count2 = records.length;
|
|
844
|
+
let details, warnings2 = [];
|
|
845
|
+
return { summary: `Upload ${count2} Google ${kind} conversion record${count2 === 1 ? "" : "s"} to "${action2.name}"`, changes: [`+ ${count2} records to ${action2.resourceName}; conversion owner ${action2.ownerCustomer}.`, `Approved batch SHA-256: ${batchHash}. Values are whole currency units.`, ...kind === "adjustment" ? ["Restatements change recorded values; retractions remove recorded conversions; enhancements add matching identifiers. These can affect reporting and bidding."] : ["These events can affect measured revenue, conversion counts and automated bidding."]], coercions: [], budgetDeltas: [], notes: ["Native validate_only previews submit no events. Validation does not establish future attribution, matching success or eventual reporting.", "Partial failures are evaluated per native row; unknown or failed rows are never retried automatically. Inspect row outcomes before any new upload.", "Click imports use the legacy Google Ads endpoint, restricted for new adopters since June 2026. New integrations require the separate Data Manager API and OAuth scope.", "Preview and audit summaries omit event identifiers; identical full arguments and the action/context hash remain bound to approval."], resultDetails: () => details, resultWarnings: () => warnings2, execute: async (validateOnly) => {
|
|
846
|
+
let response;
|
|
847
|
+
try {
|
|
848
|
+
response = await this.client.uploadConversions(account2, method, records, validateOnly, "job_id" in input2 ? input2.job_id : void 0);
|
|
849
|
+
} catch (error) {
|
|
850
|
+
const failure2 = this.uploadErrors(object(object(error).details).error, count2, kind);
|
|
851
|
+
throw new AdportError5("PROVIDER_ERROR", "google: conversion request failed; no automatic retry. Check native diagnostics before reuploading.", { batch_sha256: batchHash, record_count: count2, ...failure2 });
|
|
852
|
+
}
|
|
853
|
+
const failure = this.uploadErrors(response.partialFailureError, count2, kind);
|
|
854
|
+
if (validateOnly) {
|
|
855
|
+
if (Number(object(response.partialFailureError).code ?? 0) !== 0 || failure.errors.length || failure.unmapped) throw new AdportError5("PROVIDER_ERROR", "google: conversion validation failed; no events were submitted", { batch_sha256: batchHash, ...failure });
|
|
856
|
+
return [];
|
|
857
|
+
}
|
|
858
|
+
const results = Array.isArray(response.results) ? response.results : [];
|
|
859
|
+
const rows = records.map((_value, index) => {
|
|
860
|
+
const result2 = object(results[index]), failed2 = failure.errors.some((value) => value.index === index);
|
|
861
|
+
const expected = records[index];
|
|
862
|
+
const identityFields = ["gclid", "gbraid", "wbraid", "callerId", "callStartDateTime", "conversionDateTime", "adjustmentDateTime", "orderId", "adjustmentType"];
|
|
863
|
+
const matchesEcho = identityFields.every((key2) => {
|
|
864
|
+
const requested = expected[key2], returned = result2[key2];
|
|
865
|
+
if (requested === void 0 || returned === void 0) return true;
|
|
866
|
+
if (key2.endsWith("DateTime") && typeof requested === "string" && typeof returned === "string") return Date.parse(requested.replace(" ", "T")) === Date.parse(returned.replace(" ", "T"));
|
|
867
|
+
return requested === returned;
|
|
868
|
+
});
|
|
869
|
+
const matched = !failure.unmapped && results.length <= count2 && result2.conversionAction === action2.resourceName && matchesEcho;
|
|
870
|
+
return { index, status: matched && !failed2 ? "CONFIRMED" : failed2 && !Object.keys(result2).length ? "FAILED" : "UNKNOWN" };
|
|
871
|
+
});
|
|
872
|
+
const succeeded = rows.filter((value) => value.status === "CONFIRMED").length, failed = rows.filter((value) => value.status === "FAILED").length, unknown = count2 - succeeded - failed;
|
|
873
|
+
const jobId = typeof response.jobId === "string" && /^\d+$/.test(response.jobId) ? response.jobId : typeof response.jobId === "number" && Number.isSafeInteger(response.jobId) && response.jobId >= 0 ? String(response.jobId) : void 0;
|
|
874
|
+
const complete = succeeded === count2 && !failure.unmapped && results.length === count2 && !failure.errors.length;
|
|
875
|
+
details = { status: complete ? "COMPLETE" : "PARTIAL_OR_UNCONFIRMED", batch_sha256: batchHash, record_count: count2, confirmed_count: succeeded, failed_count: failed, unknown_count: unknown, rows, errors: failure.errors, ...jobId ? { job_id: jobId } : {}, ...failure.request_id ? { request_id: failure.request_id } : {} };
|
|
876
|
+
if (!succeeded) throw new AdportError5("PROVIDER_ERROR", "google: no conversion rows were confirmed. Inspect the returned row outcomes before retrying.", details);
|
|
877
|
+
if (!complete) warnings2 = [`Only ${succeeded} of ${count2} conversion rows were confirmed; ${failed} failed and ${unknown} remain unconfirmed. Inspect result.details and native diagnostics before uploading again.`];
|
|
878
|
+
return [String(action2.resourceName)];
|
|
879
|
+
} };
|
|
880
|
+
}
|
|
881
|
+
uploadErrors(value, count2, kind) {
|
|
882
|
+
const status = object(value), details = Array.isArray(status.details) ? status.details : [];
|
|
883
|
+
const errors = [];
|
|
884
|
+
let requestId, unmapped = false;
|
|
885
|
+
for (const detail of details) {
|
|
886
|
+
const item = object(detail);
|
|
887
|
+
if (typeof item.requestId === "string" && /^[A-Za-z0-9_-]{1,256}$/.test(item.requestId)) requestId = item.requestId;
|
|
888
|
+
for (const raw of Array.isArray(item.errors) ? item.errors : []) {
|
|
889
|
+
const error = object(raw), path = object(error.location).fieldPathElements;
|
|
890
|
+
const parts = Array.isArray(path) ? path.map(object) : [];
|
|
891
|
+
const at = parts.find((part) => part.fieldName === (kind === "adjustment" ? "conversionAdjustments" : "conversions") || part.fieldName === "conversion_adjustments");
|
|
892
|
+
const index = typeof at?.index === "number" && Number.isInteger(at.index) && at.index >= 0 && at.index < count2 ? at.index : void 0;
|
|
893
|
+
if (index === void 0) unmapped = true;
|
|
894
|
+
errors.push({ ...index !== void 0 ? { index } : {}, codes: Object.entries(object(error.errorCode)).filter(([key2, item2]) => /^[a-zA-Z]+Error$/.test(key2) && typeof item2 === "string" && /^[A-Z][A-Z0-9_]{0,99}$/.test(item2)).map(([key2, item2]) => `${key2}.${item2}`), fields: parts.flatMap((part) => typeof part.fieldName === "string" && /^[a-zA-Z_]+$/.test(part.fieldName) ? [part.fieldName] : []) });
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
if (Number(status.code ?? 0) !== 0 && !errors.length) unmapped = true;
|
|
898
|
+
return { errors, unmapped, ...requestId ? { request_id: requestId } : {} };
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
var removeAction = z4.object(reference);
|
|
902
|
+
var contextView = z4.object({ customer: z4.record(z4.string(), z4.unknown()), conversion_customer: z4.string().nullable(), snapshot_hash: hash2 });
|
|
903
|
+
var actionView = z4.object({ action: z4.record(z4.string(), z4.unknown()), context: contextView, editable: z4.boolean(), snapshot_hash: hash2 });
|
|
904
|
+
function googleConversionTools(provider) {
|
|
905
|
+
const write = (tool, description, payload, kind, additive = false) => guardedWriteTool4({ name: tool, namespace: "google", provider: "google", kind, destructive: !additive, description, payload });
|
|
906
|
+
return [
|
|
907
|
+
defineTool4({ name: "google_conversion_tracking_context", namespace: "google", description: "Read the selected customer conversion tracking owner, currency, tracking status and customer-data terms flags. Returns snapshot_hash for configuration creation; never accepts terms or changes tracking ownership.", input: z4.object({ account_id: z4.string() }), output: contextView, annotations: { readOnly: true }, handler: (input2) => provider.conversions.context(input2.account_id) }),
|
|
908
|
+
defineTool4({ name: "google_conversion_actions", namespace: "google", description: "List native conversion configuration available in the selected customer, including owner, type, status, goals, attribution, value settings and tag snippets. Continue next_cursor as after_action_id.", input: z4.object({ account_id: z4.string(), after_action_id: id4.optional(), include_removed: z4.boolean().default(false), limit: z4.number().int().positive().max(200).default(50) }), output: z4.object({ context: contextView, actions: z4.array(z4.record(z4.string(), z4.unknown())), truncated: z4.boolean(), next_cursor: id4.optional() }), pagination: { cursorInput: "after_action_id" }, annotations: { readOnly: true }, handler: (input2) => provider.conversions.list(input2) }),
|
|
909
|
+
defineTool4({ name: "google_get_conversion_action", namespace: "google", description: "Read one available action and snapshot_hash, bound to its native owner and selected-customer tracking context. Shared/system-owned actions remain read-only. Tag snippets are returned as text and never installed.", input: z4.object({ account_id: z4.string(), conversion_action_id: id4 }), output: actionView, annotations: { readOnly: true }, handler: (input2) => provider.conversions.get(input2.account_id, input2.conversion_action_id) }),
|
|
910
|
+
write("google_create_conversion_action", "Create an UPLOAD_CLICKS, UPLOAD_CALLS or WEBPAGE conversion configuration using expected_context_hash from tracking context. Explicit category/counting mode; secondary by default. Native validate_only preview; no events sent or tags installed.", createAction, "create", true),
|
|
911
|
+
write("google_update_conversion_action", "Edit owned conversion configuration using expected_action_hash. Omitted fields and omitted nested value settings are preserved with exact update masks. Classification, primary goal, values, counting, windows and attribution can affect reporting and bidding.", updateAction, "update"),
|
|
912
|
+
write("google_set_conversion_action_status", "Enable or remove an owned conversion action with expected_action_hash. REMOVED uses the native remove operation and can affect goals; re-enablement uses native ENABLED subject to type restrictions. HIDDEN is readable but excluded from writes after a live native denial.", statusAction, "update"),
|
|
913
|
+
write("google_remove_conversion_action", "Remove an owned conversion action with expected_action_hash. Recording, reports and goals using the action can be affected. Native validate_only preview; no conversion events are submitted.", removeAction, "remove"),
|
|
914
|
+
write("google_upload_click_conversions", "Upload 1\u20132000 captured click conversions or enhanced leads through the legacy Google Ads endpoint using expected_action_hash. Supports captured GCLID/GBRAID/WBRAID together, explicit consent and SHA-256 identifiers. Legacy access is restricted for new adopters; Data Manager is a separate API. Native validate_only preview; partial row outcomes are explicit.", clickUpload, "create"),
|
|
915
|
+
write("google_upload_call_conversions", "Upload 1\u20132000 call conversions to an enabled UPLOAD_CALLS action with expected_action_hash. Requires actual E.164 caller ID, call start, later conversion time, value and currency. Native validate_only preview; row failures/uncertainty are reported without automatic retries.", callUpload, "create"),
|
|
916
|
+
write("google_upload_conversion_adjustments", "Retract, restate or enhance 1\u20132000 existing conversions using expected_action_hash and their original order ID or supported GCLID/date-time pair. Restatements use the final total value; enhancements require order ID and separately hashed identifiers. Native validate_only preview; affects reporting/bidding and reports partial outcomes.", adjustmentUpload, "update")
|
|
917
|
+
];
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// src/data-manager.ts
|
|
921
|
+
import { createHash as createHash3 } from "crypto";
|
|
922
|
+
import { AdportError as AdportError6, defineTool as defineTool5, guardedWriteTool as guardedWriteTool5 } from "@adport/core";
|
|
923
|
+
import { z as z5 } from "zod";
|
|
924
|
+
var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
925
|
+
var id5 = z5.string().regex(/^[1-9]\d*$/);
|
|
926
|
+
var hash3 = z5.string().regex(/^[a-f0-9]{64}$/);
|
|
927
|
+
var opaque2 = z5.string().min(1).max(4096);
|
|
928
|
+
var identifierHash = z5.string().regex(/^[a-fA-F0-9]{64}$/);
|
|
929
|
+
var timestamp2 = z5.iso.datetime({ offset: true }).refine((value) => Number.isFinite(Date.parse(value)) && (value.match(/\.(\d+)/)?.[1]?.length ?? 0) <= 9, "Use a real RFC3339 timestamp with at most nanosecond precision");
|
|
930
|
+
var consent2 = z5.object({ ad_user_data: z5.enum(["CONSENT_GRANTED", "CONSENT_DENIED"]).optional(), ad_personalization: z5.enum(["CONSENT_GRANTED", "CONSENT_DENIED"]).optional() }).strict();
|
|
931
|
+
var device = z5.object({ user_agent: opaque2.optional(), ip_address: z5.union([z5.ipv4(), z5.ipv6()]).optional(), category: opaque2.optional(), language_code: z5.string().regex(/^[a-z]{2}$/).optional(), screen_height: z5.number().int().nonnegative().max(2147483647).optional(), screen_width: z5.number().int().nonnegative().max(2147483647).optional(), operating_system: opaque2.optional(), operating_system_version: opaque2.optional(), model: opaque2.optional(), brand: opaque2.optional(), browser: opaque2.optional(), browser_version: opaque2.optional() }).strict();
|
|
932
|
+
var identifier = z5.union([
|
|
933
|
+
z5.object({ email_address: identifierHash }).strict(),
|
|
934
|
+
z5.object({ phone_number: identifierHash }).strict(),
|
|
935
|
+
z5.object({ address: z5.object({ given_name: identifierHash, family_name: identifierHash, region_code: z5.string().regex(/^[A-Z]{2}$/), postal_code: z5.string().min(1).max(256) }).strict() }).strict()
|
|
936
|
+
]);
|
|
937
|
+
var variable = z5.object({ variable: z5.string().min(1).max(256), value: z5.string().max(4096) }).strict();
|
|
938
|
+
var event = z5.object({
|
|
939
|
+
event_timestamp: timestamp2,
|
|
940
|
+
last_updated_timestamp: timestamp2.optional(),
|
|
941
|
+
transaction_id: opaque2.optional(),
|
|
942
|
+
event_source: z5.enum(["WEB", "APP", "IN_STORE", "PHONE", "MESSAGE", "OTHER"]).optional(),
|
|
943
|
+
currency: z5.string().regex(/^[A-Z]{3}$/).optional(),
|
|
944
|
+
conversion_value: z5.number().finite().optional(),
|
|
945
|
+
conversion_count: z5.number().finite().nonnegative().optional(),
|
|
946
|
+
user_data: z5.object({ user_identifiers: z5.array(identifier).min(1).max(10) }).strict().optional(),
|
|
947
|
+
user_id: opaque2.optional(),
|
|
948
|
+
consent: consent2.optional(),
|
|
949
|
+
ad_identifiers: z5.object({ gclid: opaque2.optional(), gbraid: opaque2.optional(), wbraid: opaque2.optional(), session_attributes: z5.string().min(1).max(65536).optional(), landing_page_device_info: device.optional() }).strict().optional(),
|
|
950
|
+
event_device_info: device.optional(),
|
|
951
|
+
cart_data: z5.object({ merchant_id: id5.optional(), merchant_feed_label: opaque2.optional(), merchant_feed_language_code: z5.string().regex(/^[a-z]{2}$/).optional(), transaction_discount: z5.number().finite().optional(), coupon_codes: z5.array(opaque2).max(100).optional(), items: z5.array(z5.object({ item_id: opaque2, merchant_product_id: opaque2, quantity: z5.string().regex(/^[1-9]\d*$/).refine((value) => BigInt(value) <= 9223372036854775807n, "Quantity exceeds int64"), unit_price: z5.number().finite(), conversion_value: z5.number().finite().optional(), custom_variables: z5.array(variable).max(100).optional() }).strict()).min(1).max(1e3) }).strict().optional(),
|
|
952
|
+
custom_variables: z5.array(variable).max(100).optional(),
|
|
953
|
+
experimental_fields: z5.array(z5.object({ field: z5.string().min(1).max(256), value: z5.string().max(65536) }).strict()).max(100).optional(),
|
|
954
|
+
user_properties: z5.object({ customer_type: z5.enum(["NEW", "RETURNING", "REENGAGED"]).optional(), customer_value_bucket: z5.enum(["LOW", "MEDIUM", "HIGH"]).optional() }).strict().optional()
|
|
955
|
+
}).strict().superRefine((value, ctx) => {
|
|
956
|
+
const ad = value.ad_identifiers;
|
|
957
|
+
if (!value.user_data && !ad?.gclid && !ad?.gbraid && !ad?.wbraid && !ad?.session_attributes && !ad?.landing_page_device_info?.ip_address && !value.event_device_info?.ip_address) ctx.addIssue({ code: "custom", message: "Supply captured click/session identifiers, an event or landing IP address, or hashed user data" });
|
|
958
|
+
});
|
|
959
|
+
var ingest = z5.object({ conversion_action_id: id5, expected_action_hash: hash3, events: z5.array(event).min(1).max(2e3), consent: consent2.optional() }).strict().superRefine((value, ctx) => {
|
|
960
|
+
value.events.forEach((record4, index) => {
|
|
961
|
+
if (record4.user_data && (record4.consent ?? value.consent)?.ad_user_data !== "CONSENT_GRANTED") ctx.addIssue({ code: "custom", path: ["events", index, "consent"], message: "Hashed user data requires explicit CONSENT_GRANTED ad_user_data; never infer consent" });
|
|
962
|
+
});
|
|
963
|
+
});
|
|
964
|
+
var account = z5.string().regex(/^\d{10}$/);
|
|
965
|
+
var productAccount = z5.object({ accountType: z5.literal("GOOGLE_ADS"), accountId: account }).strict();
|
|
966
|
+
var destination = z5.object({ operatingAccount: productAccount, loginAccount: productAccount, productDestinationId: id5 }).strict();
|
|
967
|
+
var receipt = z5.object({ kind: z5.literal("google_conversion_ingestion_v1"), account_id: account, destination, request_id: z5.string().min(1).max(512).regex(/^[^\x00-\x20\x7f]+$/), batch_sha256: hash3, event_count: z5.number().int().min(1).max(2e3), expires_at: z5.number().int().positive().safe() }).strict();
|
|
968
|
+
var receiptInput = z5.string().min(1).max(4096);
|
|
969
|
+
function canonical2(value) {
|
|
970
|
+
if (Array.isArray(value)) return value.map(canonical2);
|
|
971
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical2(item)]));
|
|
972
|
+
return value;
|
|
973
|
+
}
|
|
974
|
+
var digest2 = (value) => createHash3("sha256").update(JSON.stringify(canonical2(value))).digest("hex");
|
|
975
|
+
function wire2(value) {
|
|
976
|
+
if (Array.isArray(value)) return value.map(wire2);
|
|
977
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).map(([key2, item]) => [key2.replace(/_([a-z])/g, (_match, char) => char.toUpperCase()), wire2(item)]));
|
|
978
|
+
return value;
|
|
979
|
+
}
|
|
980
|
+
function warnings(value) {
|
|
981
|
+
if (value === void 0) return [];
|
|
982
|
+
if (!Array.isArray(value)) return ["Data Manager returned unrecognized optional-field warnings; inspect diagnostics before relying on all supplied fields."];
|
|
983
|
+
return value.slice(0, 100).map((item) => {
|
|
984
|
+
const warning = object2(item), reason = typeof warning.reason === "string" && /^WARNING_REASON_[A-Z0-9_]{1,100}$/.test(warning.reason) ? warning.reason : "WARNING_REASON_UNKNOWN";
|
|
985
|
+
const field3 = isDataManagerFieldPath(warning.field) ? ` at ${warning.field}` : "";
|
|
986
|
+
return `Data Manager ${reason}${field3}; optional input may be ignored.`;
|
|
987
|
+
}).concat(value.length > 100 ? [`${value.length - 100} more field warnings were returned.`] : []);
|
|
988
|
+
}
|
|
989
|
+
var count = (value) => typeof value === "string" && /^\d+$/.test(value) ? value : typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? String(value) : void 0;
|
|
990
|
+
function diagnosticCounts(value, key2) {
|
|
991
|
+
const rows = object2(value)[key2];
|
|
992
|
+
if (rows === void 0) return [];
|
|
993
|
+
if (!Array.isArray(rows)) throw new AdportError6("PROVIDER_ERROR", "google: malformed Data Manager diagnostic counts");
|
|
994
|
+
return rows.map((item) => {
|
|
995
|
+
const row2 = object2(item), total = count(row2.recordCount ?? "0");
|
|
996
|
+
if (!total || typeof row2.reason !== "string" || !/^PROCESSING_(?:ERROR|WARNING)_[A-Z0-9_]{1,160}$/.test(row2.reason)) throw new AdportError6("PROVIDER_ERROR", "google: malformed Data Manager diagnostic reason/count");
|
|
997
|
+
return { reason: row2.reason, record_count: total };
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
var GoogleDataManagerService = class {
|
|
1001
|
+
constructor(client, conversions) {
|
|
1002
|
+
this.client = client;
|
|
1003
|
+
this.conversions = conversions;
|
|
1004
|
+
}
|
|
1005
|
+
client;
|
|
1006
|
+
conversions;
|
|
1007
|
+
async context(accountId) {
|
|
1008
|
+
const selected2 = normalizeCustomerId(accountId), tracking = await this.conversions.context(selected2), access = await this.client.dataManagerAccess();
|
|
1009
|
+
return { account_id: selected2, conversion_context: tracking, login_account_id: this.client.dataManagerLoginAccount(selected2), ...access, api_enablement: "NOT_CHECKED", note: "This read checks the existing OAuth response, not API enablement or event eligibility. UNKNOWN means the OAuth server omitted scopes. Enable Data Manager API and explicitly authorize its separate scope before ingestion; no permissions or terms are changed." };
|
|
1010
|
+
}
|
|
1011
|
+
async plan(op) {
|
|
1012
|
+
if (op.tool !== "google_ingest_conversion_events") throw new AdportError6("INVALID_INPUT", "google: unsupported Data Manager mutation");
|
|
1013
|
+
const input2 = ingest.parse(op.payload), selected2 = normalizeCustomerId(op.accountId), current = await this.conversions.get(selected2, input2.conversion_action_id), action2 = current.action;
|
|
1014
|
+
if (current.snapshot_hash !== input2.expected_action_hash) throw new AdportError6("PENDING_MISMATCH", "google: conversion action or tracking context changed; read it again before ingestion");
|
|
1015
|
+
if (action2.status !== "ENABLED" || !current.context.conversion_customer || action2.ownerCustomer !== current.context.conversion_customer || !["UPLOAD_CLICKS", "WEBPAGE"].includes(String(action2.type))) throw new AdportError6("INVALID_INPUT", "google: Data Manager requires an enabled UPLOAD_CLICKS or WEBPAGE action owned by the verified conversion tracking customer");
|
|
1016
|
+
if (input2.events.some((value) => action2.type === "UPLOAD_CLICKS" ? !value.event_source : !value.transaction_id || value.event_source !== void 0 && !["WEB", "APP"].includes(value.event_source))) throw new AdportError6("INVALID_INPUT", "google: offline events require event_source; WEBPAGE events require transaction_id and, if supplied, WEB or APP event_source");
|
|
1017
|
+
if (input2.events.some((value) => value.user_data) && object2(current.context.customer.conversionTrackingSetting).acceptedCustomerDataTerms !== true) throw new AdportError6("INVALID_INPUT", "google: native customer-data terms are not accepted; no user identifiers were uploaded and no terms were accepted");
|
|
1018
|
+
const keys = input2.events.map((value) => value.transaction_id ? `transaction:${value.transaction_id}` : digest2(value));
|
|
1019
|
+
if (new Set(keys).size !== keys.length) throw new AdportError6("INVALID_INPUT", "google: duplicate event identities in this batch; repeated transaction IDs may adjust prior conversions");
|
|
1020
|
+
const target4 = destination.parse({ operatingAccount: { accountType: "GOOGLE_ADS", accountId: current.context.conversion_customer.slice("customers/".length) }, loginAccount: { accountType: "GOOGLE_ADS", accountId: this.client.dataManagerLoginAccount(selected2) }, productDestinationId: input2.conversion_action_id });
|
|
1021
|
+
const body = { destinations: [target4], events: wire2(input2.events), ...input2.consent ? { consent: wire2(input2.consent) } : {}, ...input2.events.some((value) => value.user_data) ? { encoding: "HEX" } : {} };
|
|
1022
|
+
const batchHash = digest2(body), notes2 = ["Preview uses native validateOnly=true and ingests no events. It checks initial validation only; later matching, attribution and processing can still fail.", "Apply accepts a request for asynchronous processing. Use its signed receipt with google_conversion_request_status after the provider-recommended 30 minutes; acceptance is not proof of processed conversions.", "Repeated native transaction IDs may adjust previous events. Event data can affect conversion reporting and automated bidding. Values are whole currency units, not budget micros.", "Preview and audit summaries omit event/user identifiers. The complete payload, destination and snapshot remain bound to the approval token. No automatic retry, permission expansion or terms acceptance."];
|
|
1023
|
+
let details, resultWarnings = [];
|
|
1024
|
+
return { summary: `Ingest ${input2.events.length} Google conversion event${input2.events.length === 1 ? "" : "s"} with Data Manager`, changes: [`+ ${input2.events.length} ${action2.type} events to conversion action ${input2.conversion_action_id}; operating owner ${target4.operatingAccount.accountId}; login ${target4.loginAccount.accountId}; selected account ${selected2}.`, `Approved batch SHA-256: ${batchHash}. Processing is asynchronous.`], notes: notes2, coercions: [], budgetDeltas: [], resultDetails: () => details, resultWarnings: () => resultWarnings, execute: async (validateOnly) => {
|
|
1025
|
+
const result2 = await this.client.dataManagerRequest("ingest", { ...body, validateOnly });
|
|
1026
|
+
resultWarnings = warnings(result2.fieldWarnings);
|
|
1027
|
+
if (validateOnly) {
|
|
1028
|
+
notes2.push(...resultWarnings);
|
|
1029
|
+
return [];
|
|
1030
|
+
}
|
|
1031
|
+
const expiresAt = Math.floor(Date.now() / 1e3) + 7 * 86400;
|
|
1032
|
+
const bound = receipt.safeParse({ kind: "google_conversion_ingestion_v1", account_id: selected2, destination: target4, request_id: result2.requestId, batch_sha256: batchHash, event_count: input2.events.length, expires_at: expiresAt });
|
|
1033
|
+
if (!bound.success) throw new AdportError6("PROVIDER_ERROR", "google: ingestion acceptance was not confirmed by a valid request ID; do not retry automatically", { batch_sha256: batchHash, event_count: input2.events.length });
|
|
1034
|
+
details = { status: "ACCEPTED_FOR_PROCESSING", processed: false, request_id: bound.data.request_id, batch_sha256: batchHash, event_count: input2.events.length, resource_receipt: this.client.dataManagerReceipt(bound.data), receipt_expires_at: new Date(expiresAt * 1e3).toISOString(), next_tool: "google_conversion_request_status", recommended_wait_seconds: 1800, note: "Only request acceptance is confirmed. Inspect status and diagnostics; do not resend this batch automatically." };
|
|
1035
|
+
return [String(action2.resourceName)];
|
|
1036
|
+
} };
|
|
1037
|
+
}
|
|
1038
|
+
async status(accountId, resourceReceipt) {
|
|
1039
|
+
const selected2 = normalizeCustomerId(accountId), bound = receipt.safeParse(this.client.verifyDataManagerReceipt(resourceReceipt)), now = Math.floor(Date.now() / 1e3);
|
|
1040
|
+
if (!bound.success || bound.data.account_id !== selected2 || bound.data.expires_at <= now || bound.data.expires_at > now + 7 * 86400) throw new AdportError6("INVALID_INPUT", "google: expired or mismatched account ingestion receipt");
|
|
1041
|
+
const tracking = await this.conversions.context(selected2);
|
|
1042
|
+
if (tracking.conversion_customer !== `customers/${bound.data.destination.operatingAccount.accountId}`) throw new AdportError6("PENDING_MISMATCH", "google: conversion tracking owner changed since ingestion; status was not requested");
|
|
1043
|
+
const result2 = await this.client.dataManagerRequest("status", { requestId: bound.data.request_id }), rows = result2.requestStatusPerDestination;
|
|
1044
|
+
if (rows === void 0 || Array.isArray(rows) && rows.length === 0) return { request_id: bound.data.request_id, batch_sha256: bound.data.batch_sha256, expected_event_count: bound.data.event_count, status: "UNKNOWN", terminal: false, note: "No destination status is available yet. This is not success; wait before checking again. Do not resend events." };
|
|
1045
|
+
if (!Array.isArray(rows) || rows.length !== 1) throw new AdportError6("PROVIDER_ERROR", "google: Data Manager status destination count differs from the approved request");
|
|
1046
|
+
const row2 = object2(rows[0]), target4 = object2(row2.destination), expected = bound.data.destination;
|
|
1047
|
+
const matches = (value, wanted) => {
|
|
1048
|
+
const got = object2(value);
|
|
1049
|
+
return got.accountId === wanted.accountId && (got.accountType === "GOOGLE_ADS" || got.accountType === void 0 && got.product === "GOOGLE_ADS") && (got.product === void 0 || got.product === "GOOGLE_ADS");
|
|
1050
|
+
};
|
|
1051
|
+
if (!matches(target4.operatingAccount, expected.operatingAccount) || target4.productDestinationId !== expected.productDestinationId || target4.loginAccount !== void 0 && !matches(target4.loginAccount, expected.loginAccount) || target4.linkedAccount !== void 0) throw new AdportError6("PROVIDER_ERROR", "google: Data Manager returned a destination outside the approved ingestion receipt");
|
|
1052
|
+
const state = typeof row2.requestStatus === "string" && ["SUCCESS", "PARTIAL_SUCCESS", "FAILED", "PROCESSING", "REQUEST_STATUS_UNKNOWN"].includes(row2.requestStatus) ? row2.requestStatus : "UNKNOWN";
|
|
1053
|
+
const terminal = ["SUCCESS", "PARTIAL_SUCCESS", "FAILED"].includes(state), total = count(object2(row2.eventsIngestionStatus).recordCount), errors = diagnosticCounts(row2.errorInfo, "errorCounts"), fieldWarnings = diagnosticCounts(row2.warningInfo, "warningCounts");
|
|
1054
|
+
if (["audienceMembersIngestionStatus", "audienceMembersRemovalStatus", "removeAllAudienceMembersStatus"].some((key2) => row2[key2] !== void 0)) throw new AdportError6("PROVIDER_ERROR", "google: non-event Data Manager status returned for an event receipt");
|
|
1055
|
+
const expectedCount = String(bound.data.event_count), consistent = !terminal || total === expectedCount && [...errors, ...fieldWarnings].every((value) => BigInt(value.record_count) <= BigInt(expectedCount)) && (state !== "SUCCESS" || !errors.some((value) => BigInt(value.record_count) > 0n));
|
|
1056
|
+
return { request_id: bound.data.request_id, batch_sha256: bound.data.batch_sha256, expected_event_count: bound.data.event_count, status: consistent ? state : "UNKNOWN", native_status: state, terminal: terminal && consistent, ...total !== void 0 ? { record_count: total } : {}, counts_match: terminal ? consistent : null, errors, warnings: fieldWarnings, note: consistent ? "record_count includes successful and failed records. Error and warning reasons can overlap; do not subtract their counts to invent a successful count. SUCCESS may still have warnings." : "Native processed-record count is missing or differs from the approved batch; do not assume completion or resend automatically." };
|
|
1057
|
+
}
|
|
1058
|
+
};
|
|
1059
|
+
function googleDataManagerTools(provider) {
|
|
1060
|
+
return [
|
|
1061
|
+
defineTool5({ name: "google_data_manager_context", namespace: "google", description: "Read the verified conversion owner, configured login account and existing OAuth Data Manager scope status. Does not change grants, enable APIs, accept terms or upload events.", input: z5.object({ account_id: z5.string() }), annotations: { readOnly: true }, handler: (input2) => provider.dataManager.context(input2.account_id) }),
|
|
1062
|
+
guardedWriteTool5({ name: "google_ingest_conversion_events", namespace: "google", provider: "google", kind: "create", payload: ingest, description: "Ingest 1\u20132000 offline UPLOAD_CLICKS or multi-source WEBPAGE conversion events with Data Manager v1. Requires its separate OAuth scope/API enablement and an action snapshot. Native validateOnly preview; apply returns asynchronous acceptance and an account-bound status receipt. Hashed user data is HEX with explicit consent. No automatic retry." }),
|
|
1063
|
+
defineTool5({ name: "google_conversion_request_status", namespace: "google", description: "Read Data Manager processing status and error/warning counts using the signed receipt from this account\u2019s approved ingestion. Native request IDs alone do not authorize this account-less endpoint. Wait about 30 minutes after acceptance; do not resubmit a processing batch.", input: z5.object({ account_id: z5.string(), resource_receipt: receiptInput }), annotations: { readOnly: true }, handler: (input2) => provider.dataManager.status(input2.account_id, input2.resource_receipt) })
|
|
1064
|
+
];
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
// src/experiments.ts
|
|
1068
|
+
import { createHash as createHash4 } from "crypto";
|
|
1069
|
+
import { AdportError as AdportError7, defineTool as defineTool6, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
|
|
1070
|
+
import { z as z6 } from "zod";
|
|
1071
|
+
var object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1072
|
+
var list = (value) => Array.isArray(value) ? value : [];
|
|
1073
|
+
var id6 = z6.string().regex(/^[1-9]\d*$/);
|
|
1074
|
+
var hash4 = z6.string().regex(/^[a-f0-9]{64}$/);
|
|
1075
|
+
var name3 = z6.string().trim().min(1).max(1024);
|
|
1076
|
+
var date = z6.iso.date();
|
|
1077
|
+
var systemType = z6.enum(["SEARCH_CUSTOM", "DISPLAY_CUSTOM", "HOTEL_CUSTOM", "YOUTUBE_CUSTOM", "PMAX_REPLACEMENT_SHOPPING"]);
|
|
1078
|
+
var metricGoal = z6.object({ metric: z6.enum(["CLICKS", "IMPRESSIONS", "COST", "CONVERSIONS_PER_INTERACTION_RATE", "COST_PER_CONVERSION", "CONVERSIONS_VALUE_PER_COST", "AVERAGE_CPC", "CTR", "INCREMENTAL_CONVERSIONS", "COMPLETED_VIDEO_VIEWS", "CUSTOM_ALGORITHMS", "CONVERSIONS", "CONVERSION_VALUE"]), direction: z6.enum(["NO_CHANGE", "INCREASE", "DECREASE", "NO_CHANGE_OR_INCREASE", "NO_CHANGE_OR_DECREASE"]) }).strict();
|
|
1079
|
+
var experimentRef = { experiment_id: id6, expected_experiment_hash: hash4 };
|
|
1080
|
+
var settings = { name: name3.optional(), description: z6.string().max(2048).optional(), start_date: date.optional(), end_date: date.optional(), goals: z6.array(metricGoal).max(20).optional() };
|
|
1081
|
+
var performanceMax = z6.object({ budget_amount_micros: z6.number().int().positive().safe(), bidding_strategy_type: z6.enum(["MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE", "TARGET_CPA", "TARGET_ROAS"]), target_cpa_micros: z6.number().int().positive().safe().optional(), target_roas: z6.number().finite().positive().optional() }).strict().superRefine((value, ctx) => {
|
|
1082
|
+
const cpa = ["MAXIMIZE_CONVERSIONS", "TARGET_CPA"].includes(value.bidding_strategy_type);
|
|
1083
|
+
if (cpa ? value.target_roas !== void 0 : value.target_cpa_micros !== void 0) ctx.addIssue({ code: "custom", message: "Bidding target must match the selected strategy" });
|
|
1084
|
+
if (value.bidding_strategy_type === "TARGET_CPA" && value.target_cpa_micros === void 0 || value.bidding_strategy_type === "TARGET_ROAS" && value.target_roas === void 0) ctx.addIssue({ code: "custom", message: "Target bidding strategy requires its matching target" });
|
|
1085
|
+
});
|
|
1086
|
+
var treatment = z6.object({ name: name3, traffic_split_percent: z6.number().int().min(1).max(99), performance_max: performanceMax.optional() }).strict();
|
|
1087
|
+
var create2 = z6.object({ ...settings, name: name3, base_campaign_id: id6, expected_base_hash: hash4, type: systemType, suffix: z6.string().min(1).max(100), control_name: name3.default("Control"), control_traffic_split_percent: z6.number().int().min(1).max(99), treatments: z6.array(treatment).min(1).max(20), sync_enabled: z6.boolean().optional(), video_experiment_subtype: z6.enum(["ASSET", "ASSET_UPLIFT", "DEMAND_GEN_ASSET"]).optional() }).strict().superRefine((value, ctx) => {
|
|
1088
|
+
if (value.control_traffic_split_percent + value.treatments.reduce((sum, arm) => sum + arm.traffic_split_percent, 0) !== 100) ctx.addIssue({ code: "custom", message: "Control and treatment traffic shares must total 100" });
|
|
1089
|
+
if ((/* @__PURE__ */ new Set([value.control_name, ...value.treatments.map((arm) => arm.name)])).size !== value.treatments.length + 1) ctx.addIssue({ code: "custom", message: "Arm names must be unique within this experiment" });
|
|
1090
|
+
if (value.type === "YOUTUBE_CUSTOM" ? !value.video_experiment_subtype : value.video_experiment_subtype !== void 0) ctx.addIssue({ code: "custom", message: "Video subtype is required only for YOUTUBE_CUSTOM" });
|
|
1091
|
+
if (value.type !== "PMAX_REPLACEMENT_SHOPPING" && value.treatments.some((arm) => arm.performance_max)) ctx.addIssue({ code: "custom", message: "Performance Max settings apply only to PMAX_REPLACEMENT_SHOPPING" });
|
|
1092
|
+
if (value.start_date && value.end_date && value.start_date > value.end_date) ctx.addIssue({ code: "custom", message: "End date must not precede start date" });
|
|
1093
|
+
});
|
|
1094
|
+
var update2 = z6.object({ ...experimentRef, ...settings }).strict().refine((value) => Object.entries(value).some(([key2, item]) => !["experiment_id", "expected_experiment_hash"].includes(key2) && item !== void 0), "Supply an editable experiment field");
|
|
1095
|
+
var armPatch = z6.object({ arm_id: id6, name: name3.optional(), traffic_split_percent: z6.number().int().min(1).max(99).optional() }).strict();
|
|
1096
|
+
var patchArms = z6.object({ ...experimentRef, arms: z6.array(armPatch).min(1).max(100) }).strict();
|
|
1097
|
+
var addArms = z6.object({ ...experimentRef, treatments: z6.array(treatment).min(1).max(20), existing_arms: z6.array(armPatch).min(1).max(100) }).strict();
|
|
1098
|
+
var removeArms = z6.object({ ...experimentRef, arm_ids: z6.array(id6).min(1).max(100), remaining_arms: z6.array(armPatch).max(100) }).strict();
|
|
1099
|
+
var action = z6.object({ ...experimentRef, confirm_serving_changes: z6.literal(true) }).strict();
|
|
1100
|
+
var graduate = action.safeExtend({ campaign_id: id6, campaign_budget_id: id6, expected_budget_hash: hash4 });
|
|
1101
|
+
var exFields = "experiment.resource_name, experiment.experiment_id, experiment.name, experiment.description, experiment.suffix, experiment.type, experiment.status, experiment.start_date, experiment.end_date, experiment.sync_enabled, experiment.goals, experiment.video_experiment.video_experiment_subtype, experiment.optimize_assets_experiment.optimize_assets_experiment_subtype, experiment.long_running_operation, experiment.promote_status";
|
|
1102
|
+
var armFields = "experiment_arm.resource_name, experiment_arm.experiment, experiment_arm.name, experiment_arm.control, experiment_arm.traffic_split, experiment_arm.campaigns, experiment_arm.in_design_campaigns";
|
|
1103
|
+
var budgetFields = "campaign_budget.resource_name, campaign_budget.id, campaign_budget.name, campaign_budget.status, campaign_budget.amount_micros, campaign_budget.total_amount_micros, campaign_budget.explicitly_shared, campaign_budget.reference_count, campaign_budget.period, campaign_budget.delivery_method";
|
|
1104
|
+
var campaignFields = `campaign.resource_name, campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign.experiment_type, campaign.base_campaign, campaign.campaign_budget, campaign.bidding_strategy_type, campaign.bidding_strategy, campaign.manual_cpc.enhanced_cpc_enabled, campaign.maximize_conversions.target_cpa_micros, campaign.maximize_conversion_value.target_roas, campaign.target_cpa.target_cpa_micros, campaign.target_roas.target_roas, campaign.target_spend.cpc_bid_ceiling_micros, ${budgetFields}`;
|
|
1105
|
+
var kinds = { google_create_experiment: "create", google_update_experiment: "update", google_add_experiment_arms: "create", google_update_experiment_arms: "update", google_remove_experiment_arms: "remove", google_remove_experiment: "remove", google_schedule_experiment: "update", google_end_experiment: "update", google_promote_experiment: "update", google_graduate_experiment: "update" };
|
|
1106
|
+
var GOOGLE_EXPERIMENT_WRITES = new Set(Object.keys(kinds));
|
|
1107
|
+
function canonical3(value) {
|
|
1108
|
+
if (Array.isArray(value)) return value.map(canonical3);
|
|
1109
|
+
if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical3(item)]));
|
|
1110
|
+
return value;
|
|
1111
|
+
}
|
|
1112
|
+
var digest3 = (value) => createHash4("sha256").update(JSON.stringify(canonical3(value))).digest("hex");
|
|
1113
|
+
var camel2 = (key2) => key2.replace(/_([a-z])/g, (_match, char) => char.toUpperCase());
|
|
1114
|
+
function micros(value) {
|
|
1115
|
+
if (typeof value !== "string" || !/^\d+$/.test(value) || BigInt(value) > BigInt(Number.MAX_SAFE_INTEGER)) throw new AdportError7("PROVIDER_ERROR", "google: experiment budget micros are missing or outside the shared policy integer range");
|
|
1116
|
+
return Number(value);
|
|
1117
|
+
}
|
|
1118
|
+
function statusError(value) {
|
|
1119
|
+
const row2 = object3(value);
|
|
1120
|
+
return { code: typeof row2.code === "number" && Number.isInteger(row2.code) ? row2.code : null, errors: list(row2.details).flatMap((detail) => list(object3(detail).errors)).map((value2) => {
|
|
1121
|
+
const error = object3(value2);
|
|
1122
|
+
return { codes: Object.entries(object3(error.errorCode)).flatMap(([key2, val]) => typeof val === "string" && /^[A-Z_]+$/.test(val) ? [`${key2}.${val}`] : []), fields: list(object3(error.location).fieldPathElements).flatMap((item) => typeof object3(item).fieldName === "string" && /^[a-z][a-zA-Z0-9_]*$/.test(String(object3(item).fieldName)) ? [object3(item).fieldName] : []) };
|
|
1123
|
+
}) };
|
|
1124
|
+
}
|
|
1125
|
+
var GoogleExperimentService = class {
|
|
1126
|
+
constructor(client) {
|
|
1127
|
+
this.client = client;
|
|
1128
|
+
}
|
|
1129
|
+
client;
|
|
1130
|
+
async account(accountId) {
|
|
1131
|
+
const selected2 = normalizeCustomerId(accountId), rows = await this.client.search(selected2, "SELECT customer.resource_name, customer.id, customer.currency_code, customer.time_zone FROM customer LIMIT 2", { maxRows: 2 }), customer = object3(rows[0]?.customer);
|
|
1132
|
+
if (rows.length !== 1 || customer.id !== selected2 || customer.resourceName !== `customers/${selected2}` || typeof customer.currencyCode !== "string" || !/^[A-Z]{3}$/.test(customer.currencyCode) || typeof customer.timeZone !== "string" || !customer.timeZone) throw new AdportError7("PROVIDER_ERROR", "google: invalid experiment customer identity, currency or timezone");
|
|
1133
|
+
return customer;
|
|
1134
|
+
}
|
|
1135
|
+
experiment(value, selected2) {
|
|
1136
|
+
const row2 = object3(value), match = typeof row2.resourceName === "string" ? row2.resourceName.match(new RegExp(`^customers/${selected2}/experiments/([1-9]\\d*)$`)) : null;
|
|
1137
|
+
if (!match || row2.experimentId !== match[1] || typeof row2.name !== "string" || typeof row2.type !== "string" || typeof row2.status !== "string") throw new AdportError7("PROVIDER_ERROR", "google: invalid experiment identity or configuration");
|
|
1138
|
+
return row2;
|
|
1139
|
+
}
|
|
1140
|
+
campaignName(value, selected2) {
|
|
1141
|
+
if (typeof value !== "string" || !new RegExp(`^customers/${selected2}/campaigns/[1-9]\\d*$`).test(value)) throw new AdportError7("PROVIDER_ERROR", "google: experiment refers to a campaign outside the selected account");
|
|
1142
|
+
return value;
|
|
1143
|
+
}
|
|
1144
|
+
async campaigns(selected2, names) {
|
|
1145
|
+
const wanted = [...new Set(names.map((value) => this.campaignName(value, selected2)))].sort();
|
|
1146
|
+
if (!wanted.length) return [];
|
|
1147
|
+
if (wanted.length > 1e3) throw new AdportError7("INVALID_INPUT", "google: experiment campaign context exceeds the complete-read bound");
|
|
1148
|
+
const rows = await this.client.search(selected2, `SELECT ${campaignFields} FROM campaign WHERE campaign.resource_name IN (${wanted.map((value) => `'${value}'`).join(", ")}) LIMIT ${wanted.length + 1}`, { maxRows: wanted.length + 1, includeDrafts: true });
|
|
1149
|
+
const result2 = rows.map((value) => {
|
|
1150
|
+
const campaign = object3(value.campaign), budget = object3(value.campaignBudget), resource = this.campaignName(campaign.resourceName, selected2);
|
|
1151
|
+
if (!wanted.includes(resource) || campaign.id !== resource.split("/").at(-1) || !["ENABLED", "PAUSED", "REMOVED"].includes(String(campaign.status)) || campaign.campaignBudget !== budget.resourceName || typeof budget.resourceName !== "string" || !new RegExp(`^customers/${selected2}/campaignBudgets/[1-9]\\d*$`).test(budget.resourceName) || budget.period !== "DAILY") throw new AdportError7("PROVIDER_ERROR", "google: incomplete experiment campaign identity, status or daily budget");
|
|
1152
|
+
return { campaign, budget, budget_micros: micros(budget.amountMicros ?? "0") };
|
|
1153
|
+
});
|
|
1154
|
+
if (result2.length !== wanted.length || new Set(result2.map((value) => value.campaign.resourceName)).size !== result2.length) throw new AdportError7("INVALID_INPUT", "google: complete experiment campaign context was not available, including native drafts");
|
|
1155
|
+
return result2.sort((a, b) => String(a.campaign.resourceName).localeCompare(String(b.campaign.resourceName)));
|
|
1156
|
+
}
|
|
1157
|
+
async list(input2) {
|
|
1158
|
+
const selected2 = normalizeCustomerId(input2.account_id), predicates = [...!input2.include_removed ? ["experiment.status != 'REMOVED'"] : [], ...input2.after_experiment_id ? [`experiment.experiment_id > ${id6.parse(input2.after_experiment_id)}`] : []];
|
|
1159
|
+
const rows = await this.client.search(selected2, `SELECT ${exFields} FROM experiment${predicates.length ? ` WHERE ${predicates.join(" AND ")}` : ""} ORDER BY experiment.experiment_id ASC LIMIT ${input2.limit + 1}`, { maxRows: input2.limit + 1 }), experiments = rows.map((value) => this.experiment(value.experiment, selected2));
|
|
1160
|
+
if (experiments.some((value, index) => BigInt(String(value.experimentId)) <= BigInt(index ? String(experiments[index - 1].experimentId) : input2.after_experiment_id ?? "0"))) throw new AdportError7("PROVIDER_ERROR", "google: experiment continuation did not advance");
|
|
1161
|
+
return { experiments: experiments.slice(0, input2.limit), truncated: experiments.length > input2.limit, ...experiments.length > input2.limit ? { next_cursor: String(experiments[input2.limit - 1].experimentId) } : {} };
|
|
1162
|
+
}
|
|
1163
|
+
async context(input2) {
|
|
1164
|
+
const selected2 = normalizeCustomerId(input2.account_id), customer = await this.account(selected2);
|
|
1165
|
+
let experiment, arms = [], related = [];
|
|
1166
|
+
if (input2.experiment_id) {
|
|
1167
|
+
id6.parse(input2.experiment_id);
|
|
1168
|
+
const resource = `customers/${selected2}/experiments/${input2.experiment_id}`, rows = await this.client.search(selected2, `SELECT ${exFields} FROM experiment WHERE experiment.resource_name = '${resource}' LIMIT 2`, { maxRows: 2 });
|
|
1169
|
+
if (rows.length !== 1) throw new AdportError7("INVALID_INPUT", "google: experiment was not available in the selected account");
|
|
1170
|
+
experiment = this.experiment(rows[0].experiment, selected2);
|
|
1171
|
+
if (experiment.resourceName !== resource) throw new AdportError7("PROVIDER_ERROR", "google: experiment ID mismatch");
|
|
1172
|
+
const armRows = await this.client.search(selected2, `SELECT ${armFields} FROM experiment_arm WHERE experiment_arm.experiment = '${resource}' LIMIT 1001`, { maxRows: 1001 });
|
|
1173
|
+
if (armRows.length > 1e3) throw new AdportError7("INVALID_INPUT", "google: complete arm context exceeds the read bound");
|
|
1174
|
+
arms = armRows.map((value) => {
|
|
1175
|
+
const arm = object3(value.experimentArm);
|
|
1176
|
+
if (typeof arm.resourceName !== "string" || !new RegExp(`^customers/${selected2}/experimentArms/${input2.experiment_id}~[1-9]\\d*$`).test(arm.resourceName) || arm.experiment !== resource || typeof arm.name !== "string" || !/^\d+$/.test(String(arm.trafficSplit ?? "0")) || BigInt(String(arm.trafficSplit ?? "0")) > 100n) throw new AdportError7("PROVIDER_ERROR", "google: invalid experiment arm identity or traffic split");
|
|
1177
|
+
const campaigns = list(arm.campaigns).map((value2) => this.campaignName(value2, selected2)).sort(), drafts = list(arm.inDesignCampaigns).map((value2) => this.campaignName(value2, selected2)).sort();
|
|
1178
|
+
return { ...arm, resourceName: arm.resourceName, control: arm.control === true, campaigns, inDesignCampaigns: drafts };
|
|
1179
|
+
}).sort((a, b) => String(a.resourceName).localeCompare(String(b.resourceName)));
|
|
1180
|
+
if (new Set(arms.map((value) => value.resourceName)).size !== arms.length) throw new AdportError7("PROVIDER_ERROR", "google: duplicate experiment arms");
|
|
1181
|
+
related = await this.campaigns(selected2, arms.flatMap((arm) => [...list(arm.campaigns), ...list(arm.inDesignCampaigns)]).map(String));
|
|
1182
|
+
}
|
|
1183
|
+
const base2 = input2.base_campaign_id ? (await this.campaigns(selected2, [`customers/${selected2}/campaigns/${id6.parse(input2.base_campaign_id)}`]))[0] : void 0;
|
|
1184
|
+
let budget;
|
|
1185
|
+
if (input2.campaign_budget_id) {
|
|
1186
|
+
const resource = `customers/${selected2}/campaignBudgets/${id6.parse(input2.campaign_budget_id)}`, rows = await this.client.search(selected2, `SELECT ${budgetFields} FROM campaign_budget WHERE campaign_budget.resource_name = '${resource}' LIMIT 2`, { maxRows: 2 });
|
|
1187
|
+
budget = object3(rows[0]?.campaignBudget);
|
|
1188
|
+
if (rows.length !== 1 || budget.resourceName !== resource || budget.period !== "DAILY") throw new AdportError7("INVALID_INPUT", "google: graduation daily budget was not available in the selected account");
|
|
1189
|
+
micros(budget.amountMicros ?? "0");
|
|
1190
|
+
}
|
|
1191
|
+
return { account: customer, ...experiment ? { experiment, arms, campaigns: related, experiment_snapshot_hash: digest3({ customer, experiment, arms, campaigns: related }) } : {}, ...base2 ? { base_campaign: base2, base_snapshot_hash: digest3({ customer, base: base2 }) } : {}, ...budget ? { graduation_budget: budget, budget_snapshot_hash: digest3({ customer, budget }) } : {}, note: "Snapshots cover the returned experiment/arms, campaign status/bidding and budget configuration; they do not freeze all underlying ads, keywords or targeting, and Google provides no atomic compare-and-set. Dates use the account timezone. Intra-campaign, asset-optimization and campaign-mix creation require separate native workflows." };
|
|
1192
|
+
}
|
|
1193
|
+
async checked(accountId, value) {
|
|
1194
|
+
const context = await this.context({ account_id: accountId, experiment_id: value.experiment_id, ..."campaign_budget_id" in value ? { campaign_budget_id: value.campaign_budget_id } : {} });
|
|
1195
|
+
if (context.experiment_snapshot_hash !== value.expected_experiment_hash) throw new AdportError7("PENDING_MISMATCH", "google: experiment, arms or campaign/budget context changed; read it again");
|
|
1196
|
+
if (context.experiment.status === "REMOVED") throw new AdportError7("INVALID_INPUT", "google: removed experiment cannot be changed");
|
|
1197
|
+
return context;
|
|
1198
|
+
}
|
|
1199
|
+
fields(value) {
|
|
1200
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).map(([key2, item]) => [camel2(key2), item]));
|
|
1201
|
+
}
|
|
1202
|
+
mutation(selected2, service, operations, summary, changes, expected) {
|
|
1203
|
+
return { summary, changes, coercions: [], budgetDeltas: [], notes: ["Native validateOnly previews make no changes. Experiment removal/arm removal may also remove their draft or treatment copies; control campaigns are preserved.", "Metadata and draft setup are separate from serving. Native type/state/date restrictions remain authoritative."], execute: async (validateOnly) => {
|
|
1204
|
+
const result2 = await this.client.mutate(selected2, service, operations, { validateOnly });
|
|
1205
|
+
if (validateOnly) return [];
|
|
1206
|
+
const ids2 = result2.results?.map((value) => value.resourceName);
|
|
1207
|
+
if (!ids2 || ids2.length !== operations.length || ids2.some((value, index) => {
|
|
1208
|
+
const operation = operations[index], target4 = expected?.[index] ?? object3(operation.update).resourceName ?? operation.remove;
|
|
1209
|
+
const armExperiment = String(object3(operation.create).experiment ?? "").split("/").at(-1);
|
|
1210
|
+
const pattern = service === "experiments" ? `^customers/${selected2}/experiments/[1-9]\\d*$` : `^customers/${selected2}/experimentArms/${target4 ? "[1-9]\\d*" : armExperiment}~[1-9]\\d*$`;
|
|
1211
|
+
return typeof value !== "string" || !new RegExp(pattern).test(value) || target4 !== void 0 && value !== target4;
|
|
1212
|
+
})) throw new AdportError7("PROVIDER_ERROR", "google: experiment mutation receipt was not confirmed; reconcile before retrying", { resource_ids: ids2?.filter((value) => typeof value === "string") ?? [] });
|
|
1213
|
+
return ids2;
|
|
1214
|
+
} };
|
|
1215
|
+
}
|
|
1216
|
+
armInput(experiment, controlName, controlSplit, base2, treatments) {
|
|
1217
|
+
return [{ name: controlName, control: true, trafficSplit: String(controlSplit), campaigns: [base2], experiment }, ...treatments.map((value) => ({ name: value.name, control: false, trafficSplit: String(value.traffic_split_percent), experiment, ...value.performance_max ? { performanceMaxExperimentArmInfo: { experimentalPerformanceMaxCampaignSettings: Object.fromEntries(Object.entries(value.performance_max).map(([key2, item]) => [camel2(key2), /_micros$/.test(key2) ? String(item) : item])) } } : {} }))];
|
|
1218
|
+
}
|
|
1219
|
+
async pauseDrafts(selected2, experimentId, createdArms, base2, treatmentBounds, forcePaused) {
|
|
1220
|
+
const context = await this.context({ account_id: selected2, experiment_id: experimentId }), fresh = createdArms.map((resource) => context.arms.find((value) => value.resourceName === resource)), treatments = fresh.filter((value) => Boolean(value) && !value.control), drafts = treatments.flatMap((value) => list(value.inDesignCampaigns).map(String));
|
|
1221
|
+
if (context.experiment.status !== "SETUP" || fresh.some((value) => !value) || fresh.some((value) => value?.control && (list(value.campaigns).length !== 1 || list(value.campaigns)[0] !== base2.campaign.resourceName)) || treatments.length !== treatmentBounds.length || treatments.some((value) => list(value.inDesignCampaigns).length !== 1 || list(value.campaigns).length > 0) || drafts.length !== treatments.length || new Set(drafts).size !== drafts.length || drafts.includes(String(base2.campaign.resourceName))) throw new AdportError7("PROVIDER_ERROR", "google: generated treatment drafts were not confirmed; inspect the SETUP experiment before retrying", { resource_ids: [String(context.experiment.resourceName), ...createdArms] });
|
|
1222
|
+
const copies = context.campaigns.filter((value) => drafts.includes(String(value.campaign.resourceName)));
|
|
1223
|
+
if (copies.length !== drafts.length || copies.some((value) => value.campaign.experimentType !== "DRAFT" || value.campaign.baseCampaign && value.campaign.baseCampaign !== base2.campaign.resourceName)) throw new AdportError7("PROVIDER_ERROR", "google: native generated campaign ownership/type mismatch; SETUP was not scheduled", { resource_ids: [...createdArms, ...drafts] });
|
|
1224
|
+
if (forcePaused) {
|
|
1225
|
+
const operations = copies.filter((value) => value.campaign.status !== "PAUSED").map((value) => ({ update: { resourceName: value.campaign.resourceName, status: "PAUSED" }, updateMask: "status" }));
|
|
1226
|
+
if (operations.length) {
|
|
1227
|
+
await this.client.mutate(selected2, "campaigns", operations, { validateOnly: true });
|
|
1228
|
+
const result2 = await this.client.mutate(selected2, "campaigns", operations, { validateOnly: false }), names = result2.results?.map((value) => value.resourceName);
|
|
1229
|
+
if (!names || names.length !== operations.length || names.some((value, index) => value !== operations[index].update.resourceName)) throw new AdportError7("PROVIDER_ERROR", "google: draft pause was not confirmed; inspect these SETUP drafts before retrying", { resource_ids: drafts });
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
const after = await this.campaigns(selected2, drafts);
|
|
1233
|
+
if (after.some((value) => forcePaused && value.campaign.status !== "PAUSED" || value.budget_micros > treatmentBounds[drafts.indexOf(String(value.campaign.resourceName))])) throw new AdportError7("PROVIDER_ERROR", "google: copied draft status or budget exceeds the approved plan; the experiment remains unscheduled", { resource_ids: drafts });
|
|
1234
|
+
return drafts;
|
|
1235
|
+
}
|
|
1236
|
+
async plan(op, guard) {
|
|
1237
|
+
if (!GOOGLE_EXPERIMENT_WRITES.has(op.tool) || op.provider !== "google" || op.kind !== kinds[op.tool]) throw new AdportError7("INVALID_INPUT", "google: invalid experiment operation kind");
|
|
1238
|
+
const selected2 = normalizeCustomerId(op.accountId);
|
|
1239
|
+
if (op.tool === "google_create_experiment") return this.create(selected2, create2.parse(op.payload), guard);
|
|
1240
|
+
if (["google_add_experiment_arms", "google_update_experiment_arms", "google_remove_experiment_arms"].includes(op.tool)) return this.changeArms(selected2, op, guard);
|
|
1241
|
+
const input2 = op.tool === "google_update_experiment" ? update2.parse(op.payload) : op.tool === "google_graduate_experiment" ? graduate.parse(op.payload) : ["google_schedule_experiment", "google_promote_experiment"].includes(op.tool) ? action.parse(op.payload) : z6.object(experimentRef).strict().parse(op.payload);
|
|
1242
|
+
const context = await this.checked(selected2, input2), experiment = context.experiment, resource = String(experiment.resourceName);
|
|
1243
|
+
if (op.tool === "google_remove_experiment") return this.mutation(selected2, "experiments", [{ remove: resource }], `Remove Google experiment \u201C${String(experiment.name)}\u201D`, [`- ${resource}; arms ${context.arms.map((value) => value.resourceName).join(", ")}. Native removal may also remove its draft/treatment copies; base campaigns are retained.`], [resource]);
|
|
1244
|
+
if (op.tool === "google_update_experiment") {
|
|
1245
|
+
const { experiment_id: _id, expected_experiment_hash: _hash, ...settings2 } = update2.parse(input2), fields5 = this.fields(settings2), masks = Object.keys(settings2).filter((key2) => settings2[key2] !== void 0);
|
|
1246
|
+
const start = fields5.startDate ?? experiment.startDate, end = fields5.endDate ?? experiment.endDate;
|
|
1247
|
+
if (typeof start === "string" && typeof end === "string" && start > end) throw new AdportError7("INVALID_INPUT", "google: end date precedes start date");
|
|
1248
|
+
const plan = this.mutation(selected2, "experiments", [{ update: { resourceName: resource, ...fields5 }, updateMask: masks.join(",") }], `Update Google experiment \u201C${String(experiment.name)}\u201D`, masks.map((key2) => `~ ${key2}: ${JSON.stringify(experiment[camel2(key2)] ?? null)} \u2192 ${JSON.stringify(fields5[camel2(key2)])}`), [resource]);
|
|
1249
|
+
return { ...plan, fieldChanges: masks.map((key2) => ({ field: key2, before: JSON.stringify(experiment[camel2(key2)] ?? null), after: JSON.stringify(fields5[camel2(key2)]) })) };
|
|
1250
|
+
}
|
|
1251
|
+
if (op.tool === "google_schedule_experiment" && guard.forcePausedCreation) throw new AdportError7("POLICY_VIOLATION", "google: ScheduleExperiment can materialize serving campaigns and exposes no paused-creation flag. paused_creation blocks this native active workflow; no schedule request was sent.");
|
|
1252
|
+
const methods = { google_schedule_experiment: "scheduleExperiment", google_end_experiment: "endExperiment", google_promote_experiment: "promoteExperiment", google_graduate_experiment: "graduateExperiment" };
|
|
1253
|
+
const method = methods[op.tool];
|
|
1254
|
+
if (!method) throw new AdportError7("INVALID_INPUT", "google: unsupported experiment lifecycle action");
|
|
1255
|
+
let payload = {}, deltas = [];
|
|
1256
|
+
if (op.tool === "google_graduate_experiment") {
|
|
1257
|
+
const value = graduate.parse(input2), target4 = `customers/${selected2}/campaigns/${value.campaign_id}`, campaign = context.campaigns.find((value2) => value2.campaign.resourceName === target4), treatmentNames = context.arms.filter((value2) => !value2.control).flatMap((value2) => list(value2.campaigns));
|
|
1258
|
+
const budget = context.graduation_budget;
|
|
1259
|
+
if (!campaign || !treatmentNames.includes(target4) || campaign.campaign.experimentType !== "EXPERIMENT" || context.budget_snapshot_hash !== value.expected_budget_hash) throw new AdportError7("PENDING_MISMATCH", "google: graduation campaign or budget does not match the current treatment and budget snapshot");
|
|
1260
|
+
if (budget.status !== "ENABLED" || budget.explicitlyShared === true || BigInt(String(budget.referenceCount ?? "0")) > (campaign.campaign.campaignBudget === budget.resourceName ? 1n : 0n)) throw new AdportError7("INVALID_INPUT", "google: graduation needs an available non-shared budget unused by other campaigns");
|
|
1261
|
+
deltas = [{ target: `graduated campaign ${value.campaign_id} daily budget`, fromMicros: campaign.budget_micros, toMicros: micros(budget.amountMicros ?? "0") }];
|
|
1262
|
+
payload = { campaignBudgetMappings: [{ experimentCampaign: target4, campaignBudget: budget.resourceName }] };
|
|
1263
|
+
} else if (op.tool !== "google_end_experiment") {
|
|
1264
|
+
const maximum = Math.max(0, ...context.campaigns.map((value) => value.budget_micros));
|
|
1265
|
+
deltas = context.campaigns.map((value) => ({ target: `${String(value.campaign.name)} native lifecycle daily budget ceiling`, fromMicros: value.budget_micros, toMicros: maximum }));
|
|
1266
|
+
}
|
|
1267
|
+
let details;
|
|
1268
|
+
return { summary: `${method.replace("Experiment", "")} Google experiment \u201C${String(experiment.name)}\u201D`, changes: [`~ ${resource}: ${method}.`, ...method === "endExperiment" ? ["Ends native experiment serving immediately; treatment campaigns are not deleted."] : ["This native action can change serving, bidding, campaign configuration or budget allocation. Explicit serving confirmation was supplied.", "Scheduling/promotion applies native behavior, including changes below campaign level; the snapshot is not a complete immutable copy of all ads, keywords or targeting."], ...Object.keys(payload).length ? [`~ ${JSON.stringify(payload)}`] : []], notes: ["Dates use the customer timezone. Native validation does not promise future eligibility or successful asynchronous processing.", "Budget deltas use a conservative configured daily ceiling for lifecycle effects; native traffic splitting is not an additional independent spend guarantee.", "No automatic retry. Check experiment context, the current long-running operation and asynchronous errors after submission."], coercions: [], budgetDeltas: deltas, resultDetails: () => details, execute: async (validateOnly) => {
|
|
1269
|
+
const result2 = await this.client.experimentAction(selected2, String(experiment.experimentId), method, payload, validateOnly);
|
|
1270
|
+
if (validateOnly) return [];
|
|
1271
|
+
if (method === "scheduleExperiment" || method === "promoteExperiment") {
|
|
1272
|
+
const operation = result2.name;
|
|
1273
|
+
if (typeof operation !== "string" || !new RegExp(`^customers/${selected2}/operations/[^\\s/\\\\?#%]{1,512}$`).test(operation) || [".", ".."].includes(operation.split("/").at(-1)) || object3(result2.metadata).experiment !== void 0 && object3(result2.metadata).experiment !== resource) throw new AdportError7("PROVIDER_ERROR", "google: experiment operation acknowledgement was not confirmed; inspect native state before retrying", { resource_ids: [resource] });
|
|
1274
|
+
details = { status: "ACCEPTED_FOR_PROCESSING", processed: false, operation_name: operation, experiment_id: experiment.experimentId, next_tool: "google_experiment_operation", note: "Only native submission is confirmed. Poll the operation and inspect experiment async errors; do not resubmit automatically." };
|
|
1275
|
+
} else details = { status: "NATIVE_ACTION_ACCEPTED", experiment_id: experiment.experimentId, next_tool: "google_experiment_context", note: "The synchronous native command returned successfully. Read current experiment/campaign state before further changes." };
|
|
1276
|
+
return [resource];
|
|
1277
|
+
} };
|
|
1278
|
+
}
|
|
1279
|
+
async create(selected2, input2, guard) {
|
|
1280
|
+
const context = await this.context({ account_id: selected2, base_campaign_id: input2.base_campaign_id }), base2 = context.base_campaign;
|
|
1281
|
+
if (context.base_snapshot_hash !== input2.expected_base_hash) throw new AdportError7("PENDING_MISMATCH", "google: experiment base campaign or budget changed; read its context again");
|
|
1282
|
+
const channels = { SEARCH_CUSTOM: ["SEARCH"], DISPLAY_CUSTOM: ["DISPLAY"], HOTEL_CUSTOM: ["HOTEL"], YOUTUBE_CUSTOM: ["VIDEO", "DEMAND_GEN"], PMAX_REPLACEMENT_SHOPPING: ["SHOPPING"] };
|
|
1283
|
+
if (base2.campaign.experimentType !== "BASE" || !["ENABLED", "PAUSED"].includes(String(base2.campaign.status)) || !channels[input2.type].includes(String(base2.campaign.advertisingChannelType)) || base2.budget.explicitlyShared === true || base2.budget.status !== "ENABLED") throw new AdportError7("INVALID_INPUT", "google: system-managed experiment needs an available base campaign of the matching channel with a non-shared enabled daily budget");
|
|
1284
|
+
const temporary = `customers/${selected2}/experiments/-1`;
|
|
1285
|
+
const metadata2 = { resourceName: temporary, name: input2.name, type: input2.type, status: "SETUP", suffix: input2.suffix, ...this.fields({ description: input2.description, start_date: input2.start_date, end_date: input2.end_date, goals: input2.goals, sync_enabled: input2.sync_enabled }), ...input2.video_experiment_subtype ? { videoExperiment: { videoExperimentSubtype: input2.video_experiment_subtype } } : {} };
|
|
1286
|
+
const arms = this.armInput(temporary, input2.control_name, input2.control_traffic_split_percent, String(base2.campaign.resourceName), input2.treatments), operations = [{ experimentOperation: { create: metadata2 } }, ...arms.map((value) => ({ experimentArmOperation: { create: value } }))];
|
|
1287
|
+
const bounds = input2.treatments.map((value) => value.performance_max?.budget_amount_micros ?? base2.budget_micros);
|
|
1288
|
+
let details;
|
|
1289
|
+
return { summary: `Create Google ${input2.type} experiment \u201C${input2.name}\u201D in SETUP`, changes: [`+ Experiment, one control arm and ${input2.treatments.length} treatment arm(s) in one atomic native transaction. Base ${String(base2.campaign.name)} (${input2.base_campaign_id}) stays ${String(base2.campaign.status)}.`, `+ Control traffic ${input2.control_traffic_split_percent}%; treatments ${input2.treatments.map((value) => `${value.name}: ${value.traffic_split_percent}%`).join(", ")}.`, "Native treatment arms generate in-design draft campaigns. SETUP is unscheduled and cannot serve experiment traffic. Scheduling is a separate guarded operation."], coercions: guard.forcePausedCreation ? ["Generated treatment campaign status is coerced to PAUSED after native creation, while the experiment remains SETUP (paused_creation)."] : [], budgetDeltas: bounds.map((value, index) => ({ target: `new treatment \u201C${input2.treatments[index].name}\u201D daily configuration upper bound`, fromMicros: 0, toMicros: value })), serverValidated: !guard.forcePausedCreation, notes: ["Native validateOnly checks the atomic experiment/arm creation. Generated draft IDs do not exist in a preview, so a required follow-up pause cannot be server-validated until apply; serverValidated=false reports that limit.", "Apply confirms the created identities, validates/applies any required pause, and verifies the draft status and configured daily budget bound. A partial follow-up failure returns resource IDs for reconciliation and never schedules or retries the experiment.", "Configured draft budget bounds are conservative policy inputs; native experiment traffic/budget sharing is not a promise of independent additional spend. Dates use the customer timezone."], resultDetails: () => details, execute: async (validateOnly) => {
|
|
1290
|
+
const result2 = await this.client.googleAdsMutate(selected2, operations, { validateOnly, responseContentType: "MUTABLE_RESOURCE" });
|
|
1291
|
+
if (validateOnly) return [];
|
|
1292
|
+
const response = result2.mutateOperationResponses, experiment = object3(response?.[0]?.experimentResult), resource = experiment.resourceName;
|
|
1293
|
+
const created = response?.slice(1).map((value) => object3(value.experimentArmResult).resourceName);
|
|
1294
|
+
if (!response || response.length !== operations.length || typeof resource !== "string" || !new RegExp(`^customers/${selected2}/experiments/[1-9]\\d*$`).test(resource) || !created || created.some((value) => typeof value !== "string" || !new RegExp(`^customers/${selected2}/experimentArms/${resource.split("/").at(-1)}~[1-9]\\d*$`).test(value)) || new Set(created).size !== created.length) throw new AdportError7("PROVIDER_ERROR", "google: atomic experiment creation receipt was not confirmed; find this experiment before another create", { resource_ids: [resource, ...created ?? []].filter((value) => typeof value === "string") });
|
|
1295
|
+
const experimentId = resource.split("/").at(-1), ids2 = created;
|
|
1296
|
+
try {
|
|
1297
|
+
const current = await this.context({ account_id: selected2, experiment_id: experimentId });
|
|
1298
|
+
if (current.experiment.name !== input2.name || current.experiment.type !== input2.type || current.experiment.status !== "SETUP" || ids2.some((value, index) => {
|
|
1299
|
+
const arm = current.arms.find((arm2) => arm2.resourceName === value), wanted = arms[index];
|
|
1300
|
+
return !arm || arm.name !== wanted.name || arm.control !== wanted.control || arm.trafficSplit !== wanted.trafficSplit;
|
|
1301
|
+
})) throw new AdportError7("PROVIDER_ERROR", "google: experiment creation readback differs from the approved setup");
|
|
1302
|
+
const drafts = await this.pauseDrafts(selected2, experimentId, ids2, base2, bounds, guard.forcePausedCreation);
|
|
1303
|
+
details = { status: "SETUP", experiment_id: experimentId, arm_ids: ids2, draft_campaign_ids: drafts, paused_by_policy: guard.forcePausedCreation, scheduled: false, next_tool: "google_experiment_context" };
|
|
1304
|
+
return [resource, ...ids2, ...drafts];
|
|
1305
|
+
} catch (error) {
|
|
1306
|
+
throw new AdportError7("PROVIDER_ERROR", `${error instanceof Error ? error.message : "google: setup follow-up was not confirmed"}. Creation was acknowledged but not retried; inspect this unscheduled experiment and its drafts.`, { resource_ids: [resource, ...ids2] });
|
|
1307
|
+
}
|
|
1308
|
+
} };
|
|
1309
|
+
}
|
|
1310
|
+
patchedArms(selected2, experimentId, current, patches) {
|
|
1311
|
+
if (new Set(patches.map((value) => value.arm_id)).size !== patches.length) throw new AdportError7("INVALID_INPUT", "google: duplicate arm IDs");
|
|
1312
|
+
const operations = [], after = current.map((value) => ({ ...value }));
|
|
1313
|
+
for (const patch of patches) {
|
|
1314
|
+
const resource = `customers/${selected2}/experimentArms/${experimentId}~${patch.arm_id}`, arm = after.find((value) => value.resourceName === resource);
|
|
1315
|
+
if (!arm) throw new AdportError7("INVALID_INPUT", "google: arm does not belong to this experiment");
|
|
1316
|
+
const values = { ...patch.name !== void 0 ? { name: patch.name } : {}, ...patch.traffic_split_percent !== void 0 ? { trafficSplit: String(patch.traffic_split_percent) } : {} };
|
|
1317
|
+
if (!Object.keys(values).length) continue;
|
|
1318
|
+
Object.assign(arm, values);
|
|
1319
|
+
operations.push({ update: { resourceName: resource, ...values }, updateMask: Object.keys(values).map((key2) => key2 === "trafficSplit" ? "traffic_split" : key2).join(",") });
|
|
1320
|
+
}
|
|
1321
|
+
return { operations, after };
|
|
1322
|
+
}
|
|
1323
|
+
validArms(arms) {
|
|
1324
|
+
if (arms.length && (arms.filter((value) => value.control).length !== 1 || arms.reduce((sum, value) => sum + Number(value.trafficSplit), 0) !== 100 || new Set(arms.map((value) => value.name)).size !== arms.length)) throw new AdportError7("INVALID_INPUT", "google: final arm set must have one control, unique names and traffic totaling 100");
|
|
1325
|
+
}
|
|
1326
|
+
async changeArms(selected2, op, guard) {
|
|
1327
|
+
const input2 = op.tool === "google_add_experiment_arms" ? addArms.parse(op.payload) : op.tool === "google_remove_experiment_arms" ? removeArms.parse(op.payload) : patchArms.parse(op.payload), context = await this.checked(selected2, input2), experiment = context.experiment, arms = context.arms;
|
|
1328
|
+
if (experiment.status !== "SETUP" || !systemType.safeParse(experiment.type).success) throw new AdportError7("INVALID_INPUT", "google: arm setup tools require an unscheduled system-managed SETUP experiment");
|
|
1329
|
+
const patches = "existing_arms" in input2 ? input2.existing_arms : "remaining_arms" in input2 ? input2.remaining_arms : input2.arms;
|
|
1330
|
+
const patched = this.patchedArms(selected2, input2.experiment_id, arms, patches);
|
|
1331
|
+
let operations = patched.operations, bounds = [], newArms = [], base2;
|
|
1332
|
+
if ("treatments" in input2) {
|
|
1333
|
+
const controls = arms.filter((value) => value.control), names = controls.flatMap((value) => list(value.campaigns));
|
|
1334
|
+
if (controls.length !== 1 || names.length !== 1) throw new AdportError7("INVALID_INPUT", "google: treatment creation requires one verified control campaign");
|
|
1335
|
+
base2 = context.campaigns.find((value) => value.campaign.resourceName === names[0]);
|
|
1336
|
+
if (!base2 || base2.campaign.experimentType !== "BASE" || base2.budget.explicitlyShared === true) throw new AdportError7("INVALID_INPUT", "google: base campaign or non-shared budget was not available");
|
|
1337
|
+
if (experiment.type !== "PMAX_REPLACEMENT_SHOPPING" && input2.treatments.some((value) => value.performance_max)) throw new AdportError7("INVALID_INPUT", "google: Performance Max settings do not match this experiment type");
|
|
1338
|
+
newArms = this.armInput(String(experiment.resourceName), "", 0, "", input2.treatments).slice(1);
|
|
1339
|
+
bounds = input2.treatments.map((value) => value.performance_max?.budget_amount_micros ?? base2.budget_micros);
|
|
1340
|
+
this.validArms([...patched.after, ...newArms]);
|
|
1341
|
+
operations = [...operations, ...newArms.map((value) => ({ create: value }))];
|
|
1342
|
+
} else if ("arm_ids" in input2) {
|
|
1343
|
+
if (new Set(input2.arm_ids).size !== input2.arm_ids.length) throw new AdportError7("INVALID_INPUT", "google: duplicate removed arm IDs");
|
|
1344
|
+
const removed = input2.arm_ids.map((value) => `customers/${selected2}/experimentArms/${input2.experiment_id}~${value}`);
|
|
1345
|
+
if (removed.some((value) => !arms.some((arm) => arm.resourceName === value)) || patches.some((value) => input2.arm_ids.includes(value.arm_id))) throw new AdportError7("INVALID_INPUT", "google: removed arms must belong to this experiment and cannot also be updated");
|
|
1346
|
+
this.validArms(patched.after.filter((value) => !removed.includes(String(value.resourceName))));
|
|
1347
|
+
operations = [...operations, ...removed.map((resource) => ({ remove: resource }))];
|
|
1348
|
+
} else {
|
|
1349
|
+
this.validArms(patched.after);
|
|
1350
|
+
if (!operations.length) throw new AdportError7("INVALID_INPUT", "google: supply arm names or traffic shares to update");
|
|
1351
|
+
}
|
|
1352
|
+
const plan = this.mutation(selected2, "experimentArms", operations, `${op.tool === "google_add_experiment_arms" ? "Add" : op.tool === "google_remove_experiment_arms" ? "Remove" : "Update"} Google experiment arms`, operations.map((value) => `~ ${JSON.stringify(value)}`));
|
|
1353
|
+
if (!newArms.length) return plan;
|
|
1354
|
+
let details;
|
|
1355
|
+
return { ...plan, serverValidated: !guard.forcePausedCreation, coercions: guard.forcePausedCreation ? ["New generated treatment draft campaigns are coerced to PAUSED while SETUP remains unscheduled (paused_creation)."] : [], budgetDeltas: bounds.map((value, index) => ({ target: `new treatment \u201C${String(newArms[index].name)}\u201D daily configuration upper bound`, fromMicros: 0, toMicros: value })), notes: [...plan.notes ?? [], "The generated draft pause can only be native-validated after the server assigns draft IDs; serverValidated=false reports this deferred policy follow-up. Partial creation is never retried or scheduled automatically."], resultDetails: () => details, execute: async (validateOnly) => {
|
|
1356
|
+
const ids2 = await plan.execute(validateOnly);
|
|
1357
|
+
if (validateOnly) return [];
|
|
1358
|
+
const created = ids2.slice(ids2.length - newArms.length);
|
|
1359
|
+
try {
|
|
1360
|
+
const drafts = await this.pauseDrafts(selected2, input2.experiment_id, created, base2, bounds, guard.forcePausedCreation);
|
|
1361
|
+
details = { status: "SETUP", experiment_id: input2.experiment_id, arm_ids: created, draft_campaign_ids: drafts, paused_by_policy: guard.forcePausedCreation, scheduled: false, next_tool: "google_experiment_context" };
|
|
1362
|
+
return [...ids2, ...drafts];
|
|
1363
|
+
} catch (error) {
|
|
1364
|
+
throw new AdportError7("PROVIDER_ERROR", `${error instanceof Error ? error.message : "google: arm follow-up was not confirmed"}. The native arm request was acknowledged; inspect SETUP before retrying.`, { resource_ids: [String(experiment.resourceName), ...ids2] });
|
|
1365
|
+
}
|
|
1366
|
+
} };
|
|
1367
|
+
}
|
|
1368
|
+
async asyncErrors(input2) {
|
|
1369
|
+
const context = await this.context(input2), result2 = await this.client.experimentAsyncErrors(input2.account_id, input2.experiment_id, input2.page_size, input2.page_token);
|
|
1370
|
+
if (result2.errors !== void 0 && !Array.isArray(result2.errors) || result2.nextPageToken !== void 0 && (typeof result2.nextPageToken !== "string" || !result2.nextPageToken || result2.nextPageToken === input2.page_token)) throw new AdportError7("PROVIDER_ERROR", "google: invalid experiment async error page or nonadvancing cursor");
|
|
1371
|
+
return { experiment_id: input2.experiment_id, status: context.experiment.status, errors: list(result2.errors).map(statusError), truncated: Boolean(result2.nextPageToken), ...typeof result2.nextPageToken === "string" ? { next_page_token: result2.nextPageToken } : {} };
|
|
1372
|
+
}
|
|
1373
|
+
async operation(input2) {
|
|
1374
|
+
const context = await this.context(input2), experiment = context.experiment, current = experiment.longRunningOperation;
|
|
1375
|
+
if (typeof current !== "string" || !current) return { experiment_id: input2.experiment_id, experiment_status: experiment.status, state: "NO_OPERATION_REPORTED", note: "The experiment has no current long-running operation. This is not proof of successful scheduling or promotion." };
|
|
1376
|
+
const result2 = await this.client.experimentOperation(input2.account_id, current), metadata2 = object3(result2.metadata);
|
|
1377
|
+
if (result2.name !== current || metadata2.experiment !== void 0 && metadata2.experiment !== experiment.resourceName || result2.done !== void 0 && typeof result2.done !== "boolean" || result2.done !== true && (result2.error !== void 0 || result2.response !== void 0) || result2.error !== void 0 && result2.response !== void 0) throw new AdportError7("PROVIDER_ERROR", "google: experiment operation identity or completion result mismatch");
|
|
1378
|
+
const done = result2.done === true, error = result2.error !== void 0 ? statusError(result2.error) : void 0;
|
|
1379
|
+
return { experiment_id: input2.experiment_id, operation_name: current, experiment_status: experiment.status, state: !done ? "PROCESSING" : error ? "FAILED" : result2.response !== void 0 ? "SUCCEEDED" : "UNKNOWN", done, ...error ? { error } : {}, note: "Inspect native asynchronous experiment errors even after a completed operation. Operation completion alone does not guarantee campaign serving or experiment performance." };
|
|
1380
|
+
}
|
|
1381
|
+
};
|
|
1382
|
+
function googleExperimentTools(provider) {
|
|
1383
|
+
const ref = z6.object(experimentRef).strict();
|
|
1384
|
+
return [
|
|
1385
|
+
defineTool6({ name: "google_experiments", namespace: "google", description: "List account-owned experiment configuration, lifecycle and latest operation. Continue next_cursor as after_experiment_id. No campaigns are created or scheduled.", input: z6.object({ account_id: z6.string(), limit: z6.number().int().positive().max(100).default(25), after_experiment_id: id6.optional(), include_removed: z6.boolean().default(false) }), annotations: { readOnly: true }, pagination: { cursorInput: "after_experiment_id" }, handler: (input2) => provider.experiments.list(input2) }),
|
|
1386
|
+
defineTool6({ name: "google_experiment_context", namespace: "google", description: "Read experiment/arms and their scoped base/draft/trial campaigns, daily budgets, currency/timezone and snapshot hashes. Supply base_campaign_id before create, experiment_id before edits/actions, and campaign_budget_id for graduation. Hashes cover returned configuration, not every underlying ad/keyword/target.", input: z6.object({ account_id: z6.string(), experiment_id: id6.optional(), base_campaign_id: id6.optional(), campaign_budget_id: id6.optional() }), annotations: { readOnly: true }, handler: (input2) => provider.experiments.context(input2) }),
|
|
1387
|
+
defineTool6({ name: "google_experiment_async_errors", namespace: "google", description: "Read the selected experiment\u2019s native scheduling/promotion errors. Returns enum/field diagnostics without sensitive native value echoes; continue next_page_token with identical selection.", input: z6.object({ account_id: z6.string(), experiment_id: id6, page_size: z6.number().int().positive().max(1e3).default(100), page_token: z6.string().min(1).max(16384).optional() }), annotations: { readOnly: true }, pagination: { cursorInput: "page_token" }, handler: (input2) => provider.experiments.asyncErrors(input2) }),
|
|
1388
|
+
defineTool6({ name: "google_experiment_operation", namespace: "google", description: "Read only the current account-scoped operation named by this verified experiment. Distinguishes PROCESSING, SUCCEEDED, FAILED and UNKNOWN; no scheduling, cancellation or retry.", input: z6.object({ account_id: z6.string(), experiment_id: id6 }), annotations: { readOnly: true }, handler: (input2) => provider.experiments.operation(input2) }),
|
|
1389
|
+
...[
|
|
1390
|
+
["google_create_experiment", "Create an unscheduled system-managed experiment with control/treatment arms in one native atomic request. Native draft copies are verified and paused by policy before success; no base pause, scheduling or serving. Requires expected_base_hash. Budget bounds use micros. Deferred draft pausing is reported as not fully server-validated.", create2],
|
|
1391
|
+
["google_update_experiment", "Edit supplied experiment name/description/dates/goals through exact masks and expected_experiment_hash. Type and sync choice stay immutable; lifecycle transitions use their named actions.", update2],
|
|
1392
|
+
["google_add_experiment_arms", "Add generated treatment draft arms to SETUP and atomically rebalance supplied existing arm shares. Final traffic totals 100. New draft copies are checked/paused under policy, with explicit deferred validation and budget bounds.", addArms],
|
|
1393
|
+
["google_update_experiment_arms", "Atomically edit owned SETUP arm names/traffic while preserving control roles and campaign references. Final arm set needs one control and 100% total traffic.", patchArms],
|
|
1394
|
+
["google_remove_experiment_arms", "Remove owned SETUP arms and atomically rebalance remaining traffic. Native removal may delete their draft copies. Control campaigns are retained; removing the control requires removing the full arm set.", removeArms],
|
|
1395
|
+
["google_remove_experiment", "Remove the verified experiment through native mutate. Preview lists associated arms/campaign copies; native type/state constraints and protected-account policy still apply.", ref],
|
|
1396
|
+
["google_schedule_experiment", "Materialize and schedule a SETUP experiment with explicit serving confirmation and expected_experiment_hash. Native action can start serving campaigns and has no paused-creation flag, so paused_creation blocks it. Otherwise native validateOnly previews, then apply returns an asynchronous operation.", action],
|
|
1397
|
+
["google_end_experiment", "Immediately end the verified experiment through native EndExperiment, with validateOnly preview. Treatment campaigns stop serving but are retained; no campaign is promoted or graduated.", ref],
|
|
1398
|
+
["google_promote_experiment", "Apply the current treatment configuration to its base through native promotion. Explicit serving confirmation and expected_experiment_hash required. Preview includes conservative daily budget ceilings; async submission is separate from completion.", action],
|
|
1399
|
+
["google_graduate_experiment", "Graduate one verified treatment campaign to an independent campaign using an owned, unused non-shared daily budget. Requires current experiment/budget hashes and explicit serving confirmation; reports the budget delta in micros.", graduate]
|
|
1400
|
+
].map(([tool, description, payload]) => guardedWriteTool6({ name: tool, namespace: "google", provider: "google", kind: kinds[tool], description, payload, ...tool === "google_create_experiment" ? { destructive: false } : {} }))
|
|
1401
|
+
];
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
// src/pmax.ts
|
|
1405
|
+
import { createHash as createHash5 } from "crypto";
|
|
1406
|
+
import { AdportError as AdportError8, creativeStatusAction, creativesOutput as creativesOutput2, defineTool as defineTool7, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
|
|
1407
|
+
import { z as z7 } from "zod";
|
|
1408
|
+
var row = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1409
|
+
var array = (value) => Array.isArray(value) ? value : [];
|
|
1410
|
+
var id7 = z7.string().regex(/^[1-9]\d*$/);
|
|
1411
|
+
var hash5 = z7.string().regex(/^[a-f0-9]{64}$/);
|
|
1412
|
+
var name4 = z7.string().trim().min(1).max(128);
|
|
1413
|
+
var url2 = z7.string().url().refine((value) => {
|
|
1414
|
+
const u = new URL(value);
|
|
1415
|
+
return ["https:", "http:"].includes(u.protocol) && !u.username && !u.password;
|
|
1416
|
+
});
|
|
1417
|
+
var fieldType = z7.enum(["HEADLINE", "LONG_HEADLINE", "DESCRIPTION", "BUSINESS_NAME", "MARKETING_IMAGE", "SQUARE_MARKETING_IMAGE", "PORTRAIT_MARKETING_IMAGE", "LOGO", "LANDSCAPE_LOGO", "YOUTUBE_VIDEO"]);
|
|
1418
|
+
var textType = z7.enum(["HEADLINE", "LONG_HEADLINE", "DESCRIPTION", "BUSINESS_NAME"]);
|
|
1419
|
+
var asset = z7.union([z7.object({ field_type: fieldType, asset_id: id7 }).strict(), z7.object({ field_type: textType, text: z7.string().min(1).max(2048) }).strict()]);
|
|
1420
|
+
var assetKey = z7.object({ field_type: fieldType, asset_id: id7 }).strict();
|
|
1421
|
+
var level = z7.enum(["LEVEL1", "LEVEL2", "LEVEL3", "LEVEL4", "LEVEL5"]);
|
|
1422
|
+
var dimension = z7.discriminatedUnion("dimension", [
|
|
1423
|
+
z7.object({ dimension: z7.literal("product_brand"), value: z7.string().max(1e3).optional() }).strict(),
|
|
1424
|
+
z7.object({ dimension: z7.literal("product_item_id"), value: z7.string().max(1e3).optional() }).strict(),
|
|
1425
|
+
z7.object({ dimension: z7.literal("product_category"), category_id: id7.optional(), level }).strict(),
|
|
1426
|
+
z7.object({ dimension: z7.literal("product_type"), value: z7.string().max(1e3).optional(), level }).strict(),
|
|
1427
|
+
z7.object({ dimension: z7.literal("product_custom_attribute"), value: z7.string().max(1e3).optional(), index: z7.enum(["INDEX0", "INDEX1", "INDEX2", "INDEX3", "INDEX4"]) }).strict(),
|
|
1428
|
+
z7.object({ dimension: z7.literal("product_channel"), channel: z7.enum(["ONLINE", "LOCAL"]).optional() }).strict(),
|
|
1429
|
+
z7.object({ dimension: z7.literal("product_condition"), condition: z7.enum(["NEW", "USED", "REFURBISHED"]).optional() }).strict()
|
|
1430
|
+
]);
|
|
1431
|
+
var filterNode = z7.object({ key: z7.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,39}$/), parent_key: z7.string().optional(), type: z7.enum(["SUBDIVISION", "UNIT_INCLUDED", "UNIT_EXCLUDED"]), case_value: dimension.optional() }).strict();
|
|
1432
|
+
var signal = z7.discriminatedUnion("type", [z7.object({ type: z7.literal("AUDIENCE"), audience_id: id7 }).strict(), z7.object({ type: z7.literal("SEARCH_THEME"), text: z7.string().trim().min(1).max(2e3) }).strict()]);
|
|
1433
|
+
var groupSettings = { name: name4.optional(), final_urls: z7.array(url2).max(10).optional(), final_mobile_urls: z7.array(url2).max(10).optional(), path1: z7.string().max(15).optional(), path2: z7.string().max(15).optional(), tracking_url_template: z7.string().max(2048).optional(), final_url_suffix: z7.string().max(2048).optional(), url_custom_parameters: z7.array(z7.object({ key: z7.string().min(1).max(16), value: z7.string().max(200) }).strict()).max(8).optional() };
|
|
1434
|
+
var groupCreate = z7.object({ ...groupSettings, name: name4, status: z7.enum(["PAUSED", "ENABLED"]).default("PAUSED"), assets: z7.array(asset).max(120), signals: z7.array(signal).max(100).default([]), listing_filters: z7.array(filterNode).min(1).max(1e3).optional() }).strict();
|
|
1435
|
+
var campaignCreate = z7.object({ name: name4, daily_budget_micros: z7.number().int().positive().safe(), status: z7.enum(["PAUSED", "ENABLED"]).default("PAUSED"), bidding: z7.discriminatedUnion("strategy", [z7.object({ strategy: z7.literal("MAXIMIZE_CONVERSIONS"), target_cpa_micros: z7.number().int().positive().safe().optional() }).strict(), z7.object({ strategy: z7.literal("MAXIMIZE_CONVERSION_VALUE"), target_roas: z7.number().finite().positive().optional() }).strict()]), merchant: z7.object({ merchant_id: id7, feed_label: z7.string().min(1).max(100).optional() }).strict().optional(), brand_guidelines: z7.object({ main_color: z7.string().regex(/^#[a-fA-F0-9]{6}$/), accent_color: z7.string().regex(/^#[a-fA-F0-9]{6}$/), predefined_font_family: z7.enum(["Open Sans", "Roboto", "Montserrat", "Poppins", "Lato", "Oswald", "Playfair Display", "Roboto Slab"]).optional() }).strict().optional(), allow_final_url_expansion: z7.boolean().default(false), location_ids: z7.array(id7).max(100).default([]), language_ids: z7.array(id7).max(100).default([]), contains_eu_political_advertising: z7.enum(["CONTAINS_EU_POLITICAL_ADVERTISING", "DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING"]).default("DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING"), asset_group: groupCreate }).strict();
|
|
1436
|
+
var groupRef = { asset_group_id: id7, expected_group_hash: hash5 };
|
|
1437
|
+
var groupUpdate = z7.object({ ...groupRef, ...groupSettings }).strict().refine((value) => Object.entries(value).some(([key2, item]) => !["asset_group_id", "expected_group_hash"].includes(key2) && item !== void 0), "Supply asset-group metadata to update");
|
|
1438
|
+
var copyUpdate = z7.object({ asset_group_id: id7, expected_assets_hash: hash5, headlines: z7.array(z7.string().min(1).max(2048)).min(3).max(15).optional(), long_headlines: z7.array(z7.string().min(1).max(2048)).min(1).max(5).optional(), descriptions: z7.array(z7.string().min(1).max(2048)).min(2).max(5).optional() }).strict().refine((value) => value.headlines || value.long_headlines || value.descriptions, "Supply text copy to replace");
|
|
1439
|
+
var assetsUpdate = z7.object({ asset_group_id: id7, expected_assets_hash: hash5, add: z7.array(asset).max(120).default([]), remove: z7.array(assetKey).max(120).default([]) }).strict().refine((value) => value.add.length + value.remove.length > 0, "Supply asset links to add or remove");
|
|
1440
|
+
var brandUpdate = z7.object({ campaign_id: id7, expected_campaign_hash: hash5, add: z7.array(asset).max(30).default([]), remove: z7.array(assetKey).max(30).default([]) }).strict().refine((value) => value.add.length + value.remove.length > 0 && [...value.add, ...value.remove].every((value2) => ["BUSINESS_NAME", "LOGO", "LANDSCAPE_LOGO"].includes(value2.field_type)), "Supply campaign brand placements to add or remove");
|
|
1441
|
+
var signalsAdd = z7.object({ asset_group_id: id7, expected_signals_hash: hash5, signals: z7.array(signal).min(1).max(100) }).strict();
|
|
1442
|
+
var signalsRemove = z7.object({ asset_group_id: id7, expected_signals_hash: hash5, signal_ids: z7.array(id7).min(1).max(100) }).strict();
|
|
1443
|
+
var listingReplace = z7.object({ asset_group_id: id7, expected_listing_hash: hash5, listing_filters: z7.array(filterNode).min(1).max(1e3) }).strict();
|
|
1444
|
+
var campaignFields2 = "campaign.resource_name, campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign.advertising_channel_sub_type, campaign.brand_guidelines_enabled, campaign.shopping_setting.merchant_id, campaign.shopping_setting.feed_label, campaign.asset_automation_settings, campaign.campaign_budget, campaign.bidding_strategy_type, campaign.maximize_conversions.target_cpa_micros, campaign.maximize_conversion_value.target_roas, campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.explicitly_shared";
|
|
1445
|
+
var groupFields = "asset_group.resource_name, asset_group.id, asset_group.campaign, asset_group.name, asset_group.status, asset_group.final_urls, asset_group.final_mobile_urls, asset_group.path1, asset_group.path2, asset_group.primary_status, asset_group.primary_status_reasons, asset_group.ad_strength, asset_group.tracking_url_template, asset_group.final_url_suffix, asset_group.url_custom_parameters";
|
|
1446
|
+
var assetFields = "asset.resource_name, asset.id, asset.type, asset.name, asset.text_asset.text, asset.image_asset.full_size.url, asset.image_asset.full_size.width_pixels, asset.image_asset.full_size.height_pixels, asset.youtube_video_asset.youtube_video_id";
|
|
1447
|
+
var linkFields = "asset_group_asset.resource_name, asset_group_asset.asset_group, asset_group_asset.asset, asset_group_asset.field_type, asset_group_asset.status, asset_group_asset.primary_status, asset_group_asset.policy_summary.approval_status";
|
|
1448
|
+
var signalFields = "asset_group_signal.resource_name, asset_group_signal.asset_group, asset_group_signal.audience.audience, asset_group_signal.search_theme.text, asset_group_signal.approval_status, asset_group_signal.disapproval_reasons";
|
|
1449
|
+
var filterFields = "asset_group_listing_group_filter.resource_name, asset_group_listing_group_filter.id, asset_group_listing_group_filter.asset_group, asset_group_listing_group_filter.type, asset_group_listing_group_filter.listing_source, asset_group_listing_group_filter.parent_listing_group_filter, " + ["product_category.category_id", "product_category.level", "product_brand.value", "product_channel.channel", "product_condition.condition", "product_custom_attribute.value", "product_custom_attribute.index", "product_item_id.value", "product_type.value", "product_type.level", "webpage.conditions", "retail_filter_bundle.shared_set"].map((value) => `asset_group_listing_group_filter.case_value.${value}`).join(", ");
|
|
1450
|
+
var camel3 = (key2) => key2.replace(/_([a-z])/g, (_match, c) => c.toUpperCase());
|
|
1451
|
+
var fields3 = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).map(([key2, item]) => [camel3(key2), item]));
|
|
1452
|
+
function sorted(value) {
|
|
1453
|
+
return Array.isArray(value) ? value.map(sorted) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, sorted(item)])) : value;
|
|
1454
|
+
}
|
|
1455
|
+
var digest4 = (value) => createHash5("sha256").update(JSON.stringify(sorted(value))).digest("hex");
|
|
1456
|
+
var kinds2 = { google_create_performance_max_campaign: "create", google_create_asset_group: "create", google_update_asset_group: "update", google_set_asset_group_status: "update", google_remove_asset_group: "remove", google_update_asset_group_assets: "update", google_update_asset_group_copy: "update", google_update_performance_max_brand_assets: "update", google_add_asset_group_signals: "create", google_remove_asset_group_signals: "remove", google_replace_asset_group_listing_filters: "update" };
|
|
1457
|
+
var GOOGLE_PMAX_WRITES = new Set(Object.keys(kinds2));
|
|
1458
|
+
var brandTypes = /* @__PURE__ */ new Set(["BUSINESS_NAME", "LOGO", "LANDSCAPE_LOGO"]);
|
|
1459
|
+
var GooglePerformanceMaxService = class {
|
|
1460
|
+
constructor(client) {
|
|
1461
|
+
this.client = client;
|
|
1462
|
+
}
|
|
1463
|
+
client;
|
|
1464
|
+
resource(account2, service, value) {
|
|
1465
|
+
return `customers/${account2}/${service}/${id7.parse(value)}`;
|
|
1466
|
+
}
|
|
1467
|
+
async customer(account2) {
|
|
1468
|
+
const rows = await this.client.search(account2, "SELECT customer.resource_name, customer.id, customer.currency_code, customer.time_zone FROM customer LIMIT 2", { maxRows: 2 }), value = row(rows[0]?.customer);
|
|
1469
|
+
if (rows.length !== 1 || value.id !== account2 || value.resourceName !== `customers/${account2}` || typeof value.currencyCode !== "string" || !/^[A-Z]{3}$/.test(value.currencyCode) || typeof value.timeZone !== "string") throw new AdportError8("PROVIDER_ERROR", "google: invalid Performance Max customer context");
|
|
1470
|
+
return value;
|
|
1471
|
+
}
|
|
1472
|
+
group(value, account2) {
|
|
1473
|
+
const group = row(value);
|
|
1474
|
+
if (!id7.safeParse(group.id).success || group.resourceName !== this.resource(account2, "assetGroups", String(group.id)) || typeof group.campaign !== "string" || !new RegExp(`^customers/${account2}/campaigns/[1-9]\\d*$`).test(group.campaign) || typeof group.name !== "string" || !["PAUSED", "ENABLED", "REMOVED"].includes(String(group.status))) throw new AdportError8("PROVIDER_ERROR", "google: invalid asset-group identity or status");
|
|
1475
|
+
return group;
|
|
1476
|
+
}
|
|
1477
|
+
async campaignContext(input2) {
|
|
1478
|
+
const account2 = normalizeCustomerId(input2.account_id), customer = await this.customer(account2), resource = this.resource(account2, "campaigns", input2.campaign_id);
|
|
1479
|
+
const rows = await this.client.search(account2, `SELECT ${campaignFields2} FROM campaign WHERE campaign.resource_name = '${resource}' LIMIT 2`, { maxRows: 2, includeDrafts: true }), campaign = row(rows[0]?.campaign), budget = row(rows[0]?.campaignBudget);
|
|
1480
|
+
if (rows.length !== 1 || campaign.resourceName !== resource || campaign.id !== input2.campaign_id || campaign.advertisingChannelType !== "PERFORMANCE_MAX" || campaign.status === "REMOVED" || campaign.campaignBudget !== budget.resourceName || !new RegExp(`^customers/${account2}/campaignBudgets/[1-9]\\d*$`).test(String(budget.resourceName))) throw new AdportError8("INVALID_INPUT", "google: an available Performance Max campaign with an owned budget is required");
|
|
1481
|
+
const brands = await this.client.search(account2, `SELECT campaign.id, campaign_asset.resource_name, campaign_asset.campaign, campaign_asset.asset, campaign_asset.field_type, campaign_asset.status, ${assetFields} FROM campaign_asset WHERE campaign_asset.campaign = '${resource}' AND campaign_asset.field_type IN ('BUSINESS_NAME','LOGO','LANDSCAPE_LOGO') AND campaign_asset.status != 'REMOVED' LIMIT 101`, { maxRows: 101, includeDrafts: true });
|
|
1482
|
+
if (brands.length > 100) throw new AdportError8("PROVIDER_ERROR", "google: complete campaign brand context exceeds the read bound");
|
|
1483
|
+
const brandAssets = brands.map((value) => {
|
|
1484
|
+
const link = row(value.campaignAsset), asset2 = row(value.asset);
|
|
1485
|
+
this.assetIdentity(asset2, account2);
|
|
1486
|
+
if (link.campaign !== resource || link.asset !== asset2.resourceName || !brandTypes.has(String(link.fieldType)) || link.resourceName !== `customers/${account2}/campaignAssets/${input2.campaign_id}~${asset2.id}~${link.fieldType}`) throw new AdportError8("PROVIDER_ERROR", "google: campaign brand asset ownership mismatch");
|
|
1487
|
+
return { link, asset: asset2 };
|
|
1488
|
+
}).sort((a, b) => String(a.link.resourceName).localeCompare(String(b.link.resourceName)));
|
|
1489
|
+
return { account: customer, campaign, budget, brand_assets: brandAssets, campaign_snapshot_hash: digest4({ customer, campaign, budget, brandAssets }), note: "Hashes cover returned campaign/group configuration, not performance or every campaign criterion. Native validation remains authoritative; Google has no atomic compare-and-set. Existing media assets are reused without downloading their bytes." };
|
|
1490
|
+
}
|
|
1491
|
+
assetIdentity(asset2, account2) {
|
|
1492
|
+
if (!id7.safeParse(asset2.id).success || asset2.resourceName !== this.resource(account2, "assets", String(asset2.id)) || typeof asset2.type !== "string") throw new AdportError8("PROVIDER_ERROR", "google: asset ownership or identity mismatch");
|
|
1493
|
+
}
|
|
1494
|
+
async list(input2) {
|
|
1495
|
+
const account2 = normalizeCustomerId(input2.account_id), campaign = this.resource(account2, "campaigns", input2.campaign_id), predicates = [`asset_group.campaign = '${campaign}'`, ...!input2.include_removed ? ["asset_group.status != 'REMOVED'"] : [], ...input2.after_asset_group_id ? [`asset_group.id > ${id7.parse(input2.after_asset_group_id)}`] : []];
|
|
1496
|
+
const rows = await this.client.search(account2, `SELECT ${groupFields} FROM asset_group WHERE ${predicates.join(" AND ")} ORDER BY asset_group.id ASC LIMIT ${input2.limit + 1}`, { maxRows: input2.limit + 1, includeDrafts: true }), groups = rows.map((value) => this.group(value.assetGroup, account2));
|
|
1497
|
+
if (groups.some((value, index) => value.campaign !== campaign || BigInt(String(value.id)) <= BigInt(index ? String(groups[index - 1].id) : input2.after_asset_group_id ?? "0"))) throw new AdportError8("PROVIDER_ERROR", "google: asset-group continuation or campaign scope mismatch");
|
|
1498
|
+
return { asset_groups: groups.slice(0, input2.limit), truncated: groups.length > input2.limit, ...groups.length > input2.limit ? { next_cursor: String(groups[input2.limit - 1].id) } : {} };
|
|
1499
|
+
}
|
|
1500
|
+
async context(input2) {
|
|
1501
|
+
const account2 = normalizeCustomerId(input2.account_id), resource = this.resource(account2, "assetGroups", input2.asset_group_id), rows = await this.client.search(account2, `SELECT ${groupFields} FROM asset_group WHERE asset_group.resource_name = '${resource}' LIMIT 2`, { maxRows: 2, includeDrafts: true });
|
|
1502
|
+
if (rows.length !== 1) throw new AdportError8("INVALID_INPUT", "google: asset group was not available in this account");
|
|
1503
|
+
const group = this.group(rows[0]?.assetGroup, account2);
|
|
1504
|
+
if (group.resourceName !== resource) throw new AdportError8("PROVIDER_ERROR", "google: asset-group selection mismatch");
|
|
1505
|
+
const campaign = await this.campaignContext({ account_id: account2, campaign_id: String(group.campaign).split("/").at(-1) });
|
|
1506
|
+
const [links, signals, filters] = await Promise.all([
|
|
1507
|
+
this.client.search(account2, `SELECT ${linkFields}, ${assetFields} FROM asset_group_asset WHERE asset_group_asset.asset_group = '${resource}' AND asset_group_asset.status != 'REMOVED' LIMIT 501`, { maxRows: 501, includeDrafts: true }),
|
|
1508
|
+
this.client.search(account2, `SELECT ${signalFields} FROM asset_group_signal WHERE asset_group_signal.asset_group = '${resource}' LIMIT 1001`, { maxRows: 1001, includeDrafts: true }),
|
|
1509
|
+
this.client.search(account2, `SELECT ${filterFields} FROM asset_group_listing_group_filter WHERE asset_group_listing_group_filter.asset_group = '${resource}' LIMIT 1001`, { maxRows: 1001, includeDrafts: true })
|
|
1510
|
+
]);
|
|
1511
|
+
if (links.length > 500 || signals.length > 1e3 || filters.length > 1e3) throw new AdportError8("INVALID_INPUT", "google: complete asset-group context exceeds the read bound");
|
|
1512
|
+
const assets = links.map((value) => {
|
|
1513
|
+
const link = row(value.assetGroupAsset), asset2 = row(value.asset);
|
|
1514
|
+
this.assetIdentity(asset2, account2);
|
|
1515
|
+
if (link.assetGroup !== resource || link.asset !== asset2.resourceName || link.resourceName !== `customers/${account2}/assetGroupAssets/${input2.asset_group_id}~${asset2.id}~${link.fieldType}` || !["ENABLED", "PAUSED"].includes(String(link.status))) throw new AdportError8("PROVIDER_ERROR", "google: asset-group link identity or status mismatch");
|
|
1516
|
+
return { link, asset: asset2 };
|
|
1517
|
+
}).sort((a, b) => String(a.link.resourceName).localeCompare(String(b.link.resourceName)));
|
|
1518
|
+
const owned = (values, key2, service) => values.map((value) => {
|
|
1519
|
+
const item = row(value[key2]);
|
|
1520
|
+
if (item.assetGroup !== resource || !new RegExp(`^customers/${account2}/${service}/${input2.asset_group_id}~[1-9]\\d*$`).test(String(item.resourceName))) throw new AdportError8("PROVIDER_ERROR", "google: signal/filter ownership mismatch");
|
|
1521
|
+
return item;
|
|
1522
|
+
}).sort((a, b) => String(a.resourceName).localeCompare(String(b.resourceName)));
|
|
1523
|
+
const nativeSignals = owned(signals, "assetGroupSignal", "assetGroupSignals"), listing = owned(filters, "assetGroupListingGroupFilter", "assetGroupListingGroupFilters"), groupHash = digest4({ parent: campaign.campaign_snapshot_hash, group });
|
|
1524
|
+
if (new Set(assets.map((value) => value.link.resourceName)).size !== assets.length || new Set(nativeSignals.map((value) => value.resourceName)).size !== nativeSignals.length || new Set(listing.map((value) => value.resourceName)).size !== listing.length) throw new AdportError8("PROVIDER_ERROR", "google: duplicate asset-group configuration rows");
|
|
1525
|
+
return { ...campaign, asset_group: group, assets, signals: nativeSignals, listing_filters: listing, group_snapshot_hash: groupHash, assets_snapshot_hash: digest4({ groupHash, assets }), signals_snapshot_hash: digest4({ groupHash, signals: nativeSignals }), listing_snapshot_hash: digest4({ groupHash, filters: listing }) };
|
|
1526
|
+
}
|
|
1527
|
+
async creatives(input2) {
|
|
1528
|
+
const context = await this.context(input2), group = context.asset_group, account2 = normalizeCustomerId(input2.account_id);
|
|
1529
|
+
const texts = (type) => context.assets.filter((value) => value.link.fieldType === type).map((value) => row(value.asset.textAsset).text).filter((value) => typeof value === "string");
|
|
1530
|
+
const media = context.assets.flatMap((value) => {
|
|
1531
|
+
const image = row(row(value.asset.imageAsset).fullSize), candidate = image.url;
|
|
1532
|
+
if (typeof candidate !== "string") return [];
|
|
1533
|
+
try {
|
|
1534
|
+
const u = new URL(candidate);
|
|
1535
|
+
return u.protocol === "https:" && !u.username && !u.password && (u.hostname === "tpc.googlesyndication.com" || u.hostname.endsWith(".googleusercontent.com")) ? [{ type: "image", url: candidate }] : [];
|
|
1536
|
+
} catch {
|
|
1537
|
+
return [];
|
|
1538
|
+
}
|
|
1539
|
+
});
|
|
1540
|
+
return creativesOutput2.parse({ truncated: false, creatives: [{ id: input2.asset_group_id, provider: "google", account_id: account2, campaign_id: String(context.campaign.id), name: String(group.name), type: "PERFORMANCE_MAX_ASSET_GROUP", status: String(group.status), headlines: texts("HEADLINE"), descriptions: [...texts("LONG_HEADLINE"), ...texts("DESCRIPTION")], landing_urls: array(group.finalUrls).filter((value) => url2.safeParse(value).success), media, actions: group.status === "REMOVED" ? [] : [creativeStatusAction("google_set_asset_group_status", { account_id: account2, asset_group_id: input2.asset_group_id, expected_group_hash: context.group_snapshot_hash }, String(group.status), ["ENABLED", "PAUSED"]), { label: "Edit group copy", tool: "google_update_asset_group_copy", arguments: { account_id: account2, asset_group_id: input2.asset_group_id, expected_assets_hash: context.assets_snapshot_hash }, fields: [{ key: "headlines", label: "Headlines (one per line)", type: "text_list", value: texts("HEADLINE") }, { key: "long_headlines", label: "Long headlines (one per line)", type: "text_list", value: texts("LONG_HEADLINE") }, { key: "descriptions", label: "Descriptions (one per line)", type: "text_list", value: texts("DESCRIPTION") }] }] }] });
|
|
1541
|
+
}
|
|
1542
|
+
atomic(account2, operations, summary, changes, coercions = [], budgetDeltas = []) {
|
|
1543
|
+
return { summary, changes, coercions, budgetDeltas, notes: ["Native validateOnly checks the entire atomic request. Google checks placement eligibility, language-aware text lengths, image ratios, asset minimums and product-feed access.", "Existing assets and links are re-read at preview/apply. Hashes are not an atomic native lock. No request is automatically retried; reconcile acknowledged IDs if a response is incomplete.", "Asset association/content changes can affect serving creative combinations. Existing campaign/group statuses and budgets are preserved unless explicitly included in this operation."], execute: async (validateOnly) => {
|
|
1544
|
+
const result2 = await this.client.googleAdsMutate(account2, operations, { validateOnly });
|
|
1545
|
+
if (validateOnly) return [];
|
|
1546
|
+
const responses = result2.mutateOperationResponses;
|
|
1547
|
+
const resources = responses?.map((value) => Object.values(value).map((value2) => value2.resourceName));
|
|
1548
|
+
const services = { assetOperation: "assets", campaignBudgetOperation: "campaignBudgets", campaignOperation: "campaigns", campaignAssetOperation: "campaignAssets", campaignCriterionOperation: "campaignCriteria", assetGroupOperation: "assetGroups", assetGroupAssetOperation: "assetGroupAssets", assetGroupSignalOperation: "assetGroupSignals", assetGroupListingGroupFilterOperation: "assetGroupListingGroupFilters" };
|
|
1549
|
+
if (!resources || resources.length !== operations.length || resources.some((values, index) => {
|
|
1550
|
+
const [type, raw] = Object.entries(operations[index])[0], operation = row(raw), target4 = row(operation.update).resourceName ?? operation.remove, service = services[type];
|
|
1551
|
+
return values.length !== 1 || typeof values[0] !== "string" || !service || !new RegExp(`^customers/${account2}/${service}/[1-9]\\d*(?:~[1-9]\\d*)?(?:~[A-Z_]+)?$`).test(values[0]) || target4 !== void 0 && target4 !== values[0];
|
|
1552
|
+
})) throw new AdportError8("PROVIDER_ERROR", "google: Performance Max atomic acknowledgement was not confirmed; reconcile before another mutation", { resource_ids: resources?.flat().filter((value) => typeof value === "string") ?? [] });
|
|
1553
|
+
return resources.flat();
|
|
1554
|
+
} };
|
|
1555
|
+
}
|
|
1556
|
+
async resolveAssets(account2, input2) {
|
|
1557
|
+
const ids2 = [...new Set(input2.flatMap((value) => "asset_id" in value ? [value.asset_id] : []))], native = /* @__PURE__ */ new Map();
|
|
1558
|
+
if (ids2.length) {
|
|
1559
|
+
const rows = await this.client.search(account2, `SELECT ${assetFields} FROM asset WHERE asset.id IN (${ids2.join(",")}) LIMIT ${ids2.length + 1}`, { maxRows: ids2.length + 1 });
|
|
1560
|
+
for (const value of rows) {
|
|
1561
|
+
const item = row(value.asset);
|
|
1562
|
+
this.assetIdentity(item, account2);
|
|
1563
|
+
if (!ids2.includes(String(item.id)) || native.has(String(item.id))) throw new AdportError8("PROVIDER_ERROR", "google: asset selection returned unexpected or duplicate IDs");
|
|
1564
|
+
native.set(String(item.id), item);
|
|
1565
|
+
}
|
|
1566
|
+
if (native.size !== ids2.length) throw new AdportError8("INVALID_INPUT", "google: all supplied assets must be available in the selected account");
|
|
1567
|
+
}
|
|
1568
|
+
const operations = [], textResources = /* @__PURE__ */ new Map();
|
|
1569
|
+
const assets = input2.map((value) => {
|
|
1570
|
+
let item;
|
|
1571
|
+
if ("asset_id" in value) item = native.get(value.asset_id);
|
|
1572
|
+
else {
|
|
1573
|
+
let resource = textResources.get(value.text);
|
|
1574
|
+
if (!resource) {
|
|
1575
|
+
resource = `customers/${account2}/assets/-${textResources.size + 1}`;
|
|
1576
|
+
textResources.set(value.text, resource);
|
|
1577
|
+
operations.push({ assetOperation: { create: { resourceName: resource, textAsset: { text: value.text } } } });
|
|
1578
|
+
}
|
|
1579
|
+
item = { resourceName: resource, type: "TEXT", textAsset: { text: value.text } };
|
|
1580
|
+
}
|
|
1581
|
+
const expectedType = textType.safeParse(value.field_type).success ? "TEXT" : value.field_type === "YOUTUBE_VIDEO" ? "YOUTUBE_VIDEO" : "IMAGE";
|
|
1582
|
+
if (item.type !== expectedType) throw new AdportError8("INVALID_INPUT", `google: ${value.field_type} requires ${expectedType}, not the selected asset type`);
|
|
1583
|
+
return { link: { fieldType: value.field_type, asset: item.resourceName, status: "ENABLED" }, asset: item };
|
|
1584
|
+
});
|
|
1585
|
+
if (new Set(assets.map((value) => `${value.link.fieldType}:${value.link.asset}`)).size !== assets.length) throw new AdportError8("INVALID_INPUT", "google: duplicate asset and placement");
|
|
1586
|
+
return { assets, operations };
|
|
1587
|
+
}
|
|
1588
|
+
requirements(groupAssets, brands, brandGuidelines, retail, finalUrls) {
|
|
1589
|
+
if (retail && groupAssets.every((value) => value.asset.type === "MEDIA_BUNDLE")) return;
|
|
1590
|
+
if (!array(finalUrls).length) throw new AdportError8("INVALID_INPUT", "google: custom asset groups need at least one final URL, including retail campaigns");
|
|
1591
|
+
const count2 = (values, type) => values.filter((value) => value.link.fieldType === type).length;
|
|
1592
|
+
for (const [type, min, max] of [["HEADLINE", 3, 15], ["LONG_HEADLINE", 1, 5], ["DESCRIPTION", 2, 5], ["MARKETING_IMAGE", 1, 20], ["SQUARE_MARKETING_IMAGE", 1, 20], ["PORTRAIT_MARKETING_IMAGE", 0, 20], ["YOUTUBE_VIDEO", 0, 5]]) {
|
|
1593
|
+
const size = count2(groupAssets, type);
|
|
1594
|
+
if (size < min || size > max) throw new AdportError8("INVALID_INPUT", `google: ${type} needs ${min}\u2013${max} linked assets in the final atomic set`);
|
|
1595
|
+
}
|
|
1596
|
+
const branding = brandGuidelines ? brands : groupAssets;
|
|
1597
|
+
if (count2(branding, "BUSINESS_NAME") !== 1 || count2(branding, "LOGO") < 1 || count2(branding, "LOGO") > 5) throw new AdportError8("INVALID_INPUT", `google: exactly one BUSINESS_NAME and one to five LOGO assets are required at ${brandGuidelines ? "campaign" : "asset-group"} level`);
|
|
1598
|
+
if (brandGuidelines && groupAssets.some((value) => brandTypes.has(String(value.link.fieldType)))) throw new AdportError8("INVALID_INPUT", "google: brand-guidelines campaigns require brand assets at campaign level");
|
|
1599
|
+
}
|
|
1600
|
+
groupWire(value) {
|
|
1601
|
+
const result2 = fields3(value), path1 = result2.path1, path2 = result2.path2;
|
|
1602
|
+
if (path2 && !path1) throw new AdportError8("INVALID_INPUT", "google: path2 requires path1");
|
|
1603
|
+
if (Array.isArray(value.url_custom_parameters)) result2.urlCustomParameters = value.url_custom_parameters;
|
|
1604
|
+
return result2;
|
|
1605
|
+
}
|
|
1606
|
+
async signalOperations(account2, group, values) {
|
|
1607
|
+
if (new Set(values.map((value) => JSON.stringify(value))).size !== values.length) throw new AdportError8("INVALID_INPUT", "google: duplicate signals");
|
|
1608
|
+
for (const audienceId of new Set(values.flatMap((value) => value.type === "AUDIENCE" ? [value.audience_id] : []))) {
|
|
1609
|
+
const resource = this.resource(account2, "audiences", audienceId), rows = await this.client.search(account2, `SELECT audience.resource_name, audience.status FROM audience WHERE audience.resource_name = '${resource}' LIMIT 2`, { maxRows: 2 });
|
|
1610
|
+
if (rows.length !== 1 || row(rows[0]?.audience).resourceName !== resource || row(rows[0]?.audience).status !== "ENABLED") throw new AdportError8("INVALID_INPUT", "google: signal audience must be an available account-owned audience");
|
|
1611
|
+
}
|
|
1612
|
+
return values.map((value) => ({ assetGroupSignalOperation: { create: { assetGroup: group, ...value.type === "AUDIENCE" ? { audience: { audience: this.resource(account2, "audiences", value.audience_id) } } : { searchTheme: { text: value.text } } } } }));
|
|
1613
|
+
}
|
|
1614
|
+
listingOperations(account2, group, values) {
|
|
1615
|
+
const byKey = new Map(values.map((value) => [value.key, value]));
|
|
1616
|
+
if (byKey.size !== values.length || values.filter((value) => !value.parent_key).length !== 1) throw new AdportError8("INVALID_INPUT", "google: shopping listing tree requires unique keys and one root");
|
|
1617
|
+
const ordered = [], visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
|
|
1618
|
+
const visit = (node) => {
|
|
1619
|
+
if (visiting.has(node.key)) throw new AdportError8("INVALID_INPUT", "google: cycle in listing filters");
|
|
1620
|
+
if (visited.has(node.key)) return;
|
|
1621
|
+
visiting.add(node.key);
|
|
1622
|
+
if (node.parent_key) {
|
|
1623
|
+
const parent = byKey.get(node.parent_key);
|
|
1624
|
+
if (!parent || parent.type !== "SUBDIVISION" || !node.case_value) throw new AdportError8("INVALID_INPUT", "google: child listing filter requires a subdivision parent and case value");
|
|
1625
|
+
visit(parent);
|
|
1626
|
+
} else if (node.case_value) throw new AdportError8("INVALID_INPUT", "google: shopping root has no case value");
|
|
1627
|
+
visiting.delete(node.key);
|
|
1628
|
+
visited.add(node.key);
|
|
1629
|
+
ordered.push(node);
|
|
1630
|
+
};
|
|
1631
|
+
for (const value of values) visit(value);
|
|
1632
|
+
for (const value of values) {
|
|
1633
|
+
const children = values.filter((child) => child.parent_key === value.key);
|
|
1634
|
+
if (value.type !== "SUBDIVISION" && children.length || value.type === "SUBDIVISION" && children.length < 2) throw new AdportError8("INVALID_INPUT", "google: subdivision needs explicit and other children; units cannot have children");
|
|
1635
|
+
if (!children.length) continue;
|
|
1636
|
+
const dimensions = children.map((child) => {
|
|
1637
|
+
const c = child.case_value;
|
|
1638
|
+
return JSON.stringify([c.dimension, "level" in c ? c.level : null, "index" in c ? c.index : null]);
|
|
1639
|
+
});
|
|
1640
|
+
const cases = children.map((child) => JSON.stringify(sorted(child.case_value)));
|
|
1641
|
+
const other = children.filter((child) => {
|
|
1642
|
+
const c = child.case_value;
|
|
1643
|
+
return !Object.keys(c).some((key2) => ["value", "category_id", "channel", "condition"].includes(key2));
|
|
1644
|
+
});
|
|
1645
|
+
if (new Set(dimensions).size !== 1 || new Set(cases).size !== cases.length || other.length !== 1) throw new AdportError8("INVALID_INPUT", "google: siblings require one dimension/level, distinct cases and exactly one other case");
|
|
1646
|
+
}
|
|
1647
|
+
const groupId = group.split("/").at(-1), names = new Map(ordered.map((value, index) => [value.key, `customers/${account2}/assetGroupListingGroupFilters/${groupId}~-${2e4 + index}`]));
|
|
1648
|
+
return ordered.map((value) => {
|
|
1649
|
+
const c = value.case_value, nativeCase = c ? { [camel3(c.dimension)]: fields3(Object.fromEntries(Object.entries(c).filter(([key2]) => key2 !== "dimension"))) } : void 0;
|
|
1650
|
+
return { assetGroupListingGroupFilterOperation: { create: { resourceName: names.get(value.key), assetGroup: group, type: value.type, listingSource: "SHOPPING", ...value.parent_key ? { parentListingGroupFilter: names.get(value.parent_key) } : {}, ...nativeCase ? { caseValue: nativeCase } : {} } } };
|
|
1651
|
+
});
|
|
1652
|
+
}
|
|
1653
|
+
groupOperations(account2, group, campaign, input2, assets, status) {
|
|
1654
|
+
const { assets: _assets, signals: _signals, listing_filters: _filters, status: _status, ...settings2 } = input2;
|
|
1655
|
+
return [{ assetGroupOperation: { create: { resourceName: group, campaign, ...this.groupWire(settings2), status } } }, ...assets.map((value) => ({ assetGroupAssetOperation: { create: { assetGroup: group, asset: value.link.asset, fieldType: value.link.fieldType, status: "ENABLED" } } }))];
|
|
1656
|
+
}
|
|
1657
|
+
createdStatus(value, guard, target4, coercions) {
|
|
1658
|
+
if (guard.forcePausedCreation && value !== "PAUSED") {
|
|
1659
|
+
coercions.push(`${target4} status coerced to PAUSED by policy (paused_creation)`);
|
|
1660
|
+
return "PAUSED";
|
|
1661
|
+
}
|
|
1662
|
+
return value;
|
|
1663
|
+
}
|
|
1664
|
+
verifyCreation(plan, account2, expectedName, groupName, groupStatus, expectedCampaign, campaignStatus) {
|
|
1665
|
+
return { ...plan, execute: async (validateOnly) => {
|
|
1666
|
+
const ids2 = await plan.execute(validateOnly);
|
|
1667
|
+
if (validateOnly) return [];
|
|
1668
|
+
const group = ids2.find((value) => new RegExp(`^customers/${account2}/assetGroups/[1-9]\\d*$`).test(value));
|
|
1669
|
+
const campaign = expectedCampaign ?? ids2.find((value) => new RegExp(`^customers/${account2}/campaigns/[1-9]\\d*$`).test(value));
|
|
1670
|
+
try {
|
|
1671
|
+
if (!group || !campaign) throw new Error("missing campaign/group receipt");
|
|
1672
|
+
const current = await this.context({ account_id: account2, asset_group_id: group.split("/").at(-1) });
|
|
1673
|
+
if (current.asset_group.resourceName !== group || current.asset_group.campaign !== campaign || current.asset_group.name !== groupName || current.asset_group.status !== groupStatus || current.campaign.name !== expectedName || campaignStatus && current.campaign.status !== campaignStatus) throw new Error("created group/parent state differs from the approved plan");
|
|
1674
|
+
} catch {
|
|
1675
|
+
throw new AdportError8("PROVIDER_ERROR", "google: creation was acknowledged but readback could not confirm the approved campaign/group. Reconcile these IDs before another create; nothing was automatically retried.", { resource_ids: ids2 });
|
|
1676
|
+
}
|
|
1677
|
+
return ids2;
|
|
1678
|
+
} };
|
|
1679
|
+
}
|
|
1680
|
+
async createCampaign(account2, input2, guard) {
|
|
1681
|
+
const customer = await this.customer(account2), resolved = await this.resolveAssets(account2, input2.asset_group.assets), brandAssets = resolved.assets.filter((value) => brandTypes.has(String(value.link.fieldType))), groupAssets = resolved.assets.filter((value) => !brandTypes.has(String(value.link.fieldType))), retail = Boolean(input2.merchant);
|
|
1682
|
+
this.requirements(groupAssets, brandAssets, true, retail, input2.asset_group.final_urls);
|
|
1683
|
+
if (Boolean(input2.asset_group.listing_filters) !== retail) throw new AdportError8("INVALID_INPUT", "google: retail campaigns require a SHOPPING product listing tree; non-retail campaigns must omit it");
|
|
1684
|
+
const budget = `customers/${account2}/campaignBudgets/-10001`, campaign = `customers/${account2}/campaigns/-10002`, group = `customers/${account2}/assetGroups/-10003`, coercions = [];
|
|
1685
|
+
const status = this.createdStatus(input2.status, guard, "Campaign", coercions), groupStatus = this.createdStatus(input2.asset_group.status, guard, "Asset group", coercions);
|
|
1686
|
+
const bidding = input2.bidding.strategy === "MAXIMIZE_CONVERSIONS" ? { maximizeConversions: { ...input2.bidding.target_cpa_micros !== void 0 ? { targetCpaMicros: String(input2.bidding.target_cpa_micros) } : {} } } : { maximizeConversionValue: { ...input2.bidding.target_roas !== void 0 ? { targetRoas: input2.bidding.target_roas } : {} } };
|
|
1687
|
+
const operations = [
|
|
1688
|
+
...resolved.operations,
|
|
1689
|
+
{ campaignBudgetOperation: { create: { resourceName: budget, name: `Budget for ${input2.name}`, amountMicros: String(input2.daily_budget_micros), explicitlyShared: false, deliveryMethod: "STANDARD" } } },
|
|
1690
|
+
{ campaignOperation: { create: { resourceName: campaign, name: input2.name, advertisingChannelType: "PERFORMANCE_MAX", status, campaignBudget: budget, containsEuPoliticalAdvertising: input2.contains_eu_political_advertising, brandGuidelinesEnabled: true, ...input2.brand_guidelines ? { brandGuidelines: fields3(input2.brand_guidelines) } : {}, ...input2.merchant ? { shoppingSetting: { merchantId: input2.merchant.merchant_id, ...input2.merchant.feed_label ? { feedLabel: input2.merchant.feed_label } : {} } } : {}, assetAutomationSettings: [{ assetAutomationType: "FINAL_URL_EXPANSION_TEXT_ASSET_AUTOMATION", assetAutomationStatus: input2.allow_final_url_expansion ? "OPTED_IN" : "OPTED_OUT" }], ...input2.location_ids.length ? { geoTargetTypeSetting: { positiveGeoTargetType: "PRESENCE" } } : {}, ...bidding } } },
|
|
1691
|
+
...brandAssets.map((value) => ({ campaignAssetOperation: { create: { campaign, asset: value.link.asset, fieldType: value.link.fieldType, status: "ENABLED" } } })),
|
|
1692
|
+
...this.groupOperations(account2, group, campaign, input2.asset_group, groupAssets, groupStatus),
|
|
1693
|
+
...await this.signalOperations(account2, group, input2.asset_group.signals),
|
|
1694
|
+
...input2.asset_group.listing_filters ? this.listingOperations(account2, group, input2.asset_group.listing_filters) : [],
|
|
1695
|
+
...[...new Set(input2.location_ids)].map((value) => ({ campaignCriterionOperation: { create: { campaign, location: { geoTargetConstant: `geoTargetConstants/${value}` } } } })),
|
|
1696
|
+
...[...new Set(input2.language_ids)].map((value) => ({ campaignCriterionOperation: { create: { campaign, language: { languageConstant: `languageConstants/${value}` } } } }))
|
|
1697
|
+
];
|
|
1698
|
+
const plan = this.atomic(account2, operations, `Create Performance Max campaign \u201C${input2.name}\u201D and complete ${retail ? "retail" : "standard"} asset group (${status})`, [`+ Non-shared budget ${input2.daily_budget_micros} micros/day in ${String(customer.currencyCode)}; bidding ${input2.bidding.strategy}.`, `+ Campaign ${status}; group \u201C${input2.asset_group.name}\u201D ${groupStatus}; ${groupAssets.length} group assets, ${brandAssets.length} campaign brand assets.`, `+ ${input2.asset_group.signals.length} signals; ${input2.asset_group.listing_filters?.length ?? 0} SHOPPING filters.`, `+ Final URL expansion ${input2.allow_final_url_expansion ? "OPTED_IN (Google can select/generate other landing pages and text)" : "OPTED_OUT"}; other native asset-automation defaults remain in effect.`, `+ Locations ${input2.location_ids.join(", ") || "unrestricted"}; languages ${input2.language_ids.join(", ") || "unrestricted"}. Native geo/language eligibility and Merchant Center links are checked by Google.`, "All text assets precede associations, campaign brand links immediately follow the campaign, and group asset links are consecutive. This is one atomic request, not an incomplete channel-only campaign."], coercions, [{ target: `new Performance Max campaign \u201C${input2.name}\u201D daily budget`, fromMicros: 0, toMicros: input2.daily_budget_micros }]);
|
|
1699
|
+
return this.verifyCreation(plan, account2, input2.name, input2.asset_group.name, groupStatus, void 0, status);
|
|
1700
|
+
}
|
|
1701
|
+
async createGroup(account2, payload, guard) {
|
|
1702
|
+
const input2 = groupCreate.safeExtend({ campaign_id: id7, expected_campaign_hash: hash5 }).parse(payload), context = await this.campaignContext({ account_id: account2, campaign_id: input2.campaign_id });
|
|
1703
|
+
if (context.campaign_snapshot_hash !== input2.expected_campaign_hash) throw new AdportError8("PENDING_MISMATCH", "google: campaign, budget or brand assets changed; read Performance Max context again");
|
|
1704
|
+
const { campaign_id: _campaign, expected_campaign_hash: _hash, ...settings2 } = input2, resolved = await this.resolveAssets(account2, input2.assets), brands = context.campaign.brandGuidelinesEnabled === true, retail = Boolean(row(context.campaign.shoppingSetting).merchantId);
|
|
1705
|
+
if (brands && resolved.assets.some((value) => brandTypes.has(String(value.link.fieldType)))) throw new AdportError8("INVALID_INPUT", "google: use google_update_performance_max_brand_assets for campaign-level brand changes before creating a group");
|
|
1706
|
+
this.requirements(resolved.assets, context.brand_assets, brands, retail, input2.final_urls);
|
|
1707
|
+
if (Boolean(input2.listing_filters) !== retail) throw new AdportError8("INVALID_INPUT", "google: only retail groups require a SHOPPING product tree");
|
|
1708
|
+
const group = `customers/${account2}/assetGroups/-10003`, coercions = [], status = this.createdStatus(input2.status, guard, "Asset group", coercions);
|
|
1709
|
+
const operations = [...resolved.operations, ...this.groupOperations(account2, group, String(context.campaign.resourceName), settings2, resolved.assets, status), ...await this.signalOperations(account2, group, input2.signals), ...input2.listing_filters ? this.listingOperations(account2, group, input2.listing_filters) : []];
|
|
1710
|
+
const plan = this.atomic(account2, operations, `Create Performance Max asset group \u201C${input2.name}\u201D (${status})`, [`+ Group in campaign ${input2.campaign_id}, with ${resolved.assets.length} atomic creative links, ${input2.signals.length} signals and ${input2.listing_filters?.length ?? 0} product filters.`, "Campaign status, budget and campaign-level brand links are preserved. Child links are enabled within the new group; a paused group cannot serve."], coercions);
|
|
1711
|
+
return this.verifyCreation(plan, account2, String(context.campaign.name), input2.name, status, String(context.campaign.resourceName));
|
|
1712
|
+
}
|
|
1713
|
+
async updateAssets(account2, input2, context) {
|
|
1714
|
+
if (context.assets_snapshot_hash !== input2.expected_assets_hash) throw new AdportError8("PENDING_MISMATCH", "google: group, parent, assets or brand configuration changed; read context again");
|
|
1715
|
+
const remove2 = input2.remove.map((value) => `customers/${account2}/assetGroupAssets/${input2.asset_group_id}~${value.asset_id}~${value.field_type}`);
|
|
1716
|
+
if (new Set(remove2).size !== remove2.length || remove2.some((value) => !context.assets.some((item) => item.link.resourceName === value))) throw new AdportError8("INVALID_INPUT", "google: every removed asset association must belong to this group exactly once");
|
|
1717
|
+
const resolved = await this.resolveAssets(account2, input2.add), remain = context.assets.filter((value) => !remove2.includes(String(value.link.resourceName))), after = [...remain, ...resolved.assets];
|
|
1718
|
+
if (new Set(after.map((value) => `${value.link.asset}:${value.link.fieldType}`)).size !== after.length) throw new AdportError8("INVALID_INPUT", "google: final asset set contains duplicate links");
|
|
1719
|
+
this.requirements(after, context.brand_assets, context.campaign.brandGuidelinesEnabled === true, Boolean(row(context.campaign.shoppingSetting).merchantId), context.asset_group.finalUrls);
|
|
1720
|
+
const operations = [...resolved.operations, ...remove2.map((resource) => ({ assetGroupAssetOperation: { remove: resource } })), ...resolved.assets.map((value) => ({ assetGroupAssetOperation: { create: { assetGroup: context.asset_group.resourceName, asset: value.link.asset, fieldType: value.link.fieldType, status: "ENABLED" } } }))];
|
|
1721
|
+
return this.atomic(account2, operations, `Update creative assets in group \u201C${String(context.asset_group.name)}\u201D`, [`- ${remove2.length} exact associations; + ${resolved.assets.length} associations in one atomic set. Shared source assets are retained.`, `Group stays ${String(context.asset_group.status)}; parent campaign stays ${String(context.campaign.status)}. New links are enabled as part of this explicit creative edit and can affect serving combinations.`, ...resolved.assets.map((value) => `+ ${String(value.link.fieldType)} ${String(row(value.asset.textAsset).text ?? value.link.asset)}`)]);
|
|
1722
|
+
}
|
|
1723
|
+
async plan(op, guard) {
|
|
1724
|
+
if (op.provider !== "google" || !GOOGLE_PMAX_WRITES.has(op.tool) || op.kind !== kinds2[op.tool]) throw new AdportError8("INVALID_INPUT", "google: invalid Performance Max operation kind");
|
|
1725
|
+
const account2 = normalizeCustomerId(op.accountId);
|
|
1726
|
+
if (op.tool === "google_create_performance_max_campaign") return this.createCampaign(account2, campaignCreate.parse(op.payload), guard);
|
|
1727
|
+
if (op.tool === "google_create_asset_group") return this.createGroup(account2, op.payload, guard);
|
|
1728
|
+
if (op.tool === "google_update_performance_max_brand_assets") return this.updateBrandAssets(account2, op.payload);
|
|
1729
|
+
const payload = row(op.payload), groupId = id7.parse(payload.asset_group_id), context = await this.context({ account_id: account2, asset_group_id: groupId }), group = context.asset_group, resource = String(group.resourceName);
|
|
1730
|
+
if (group.status === "REMOVED") throw new AdportError8("INVALID_INPUT", "google: removed asset group cannot be changed");
|
|
1731
|
+
if (op.tool === "google_update_asset_group_assets") return this.updateAssets(account2, assetsUpdate.parse(payload), context);
|
|
1732
|
+
if (op.tool === "google_update_asset_group_copy") {
|
|
1733
|
+
const input3 = copyUpdate.parse(payload), changes = { asset_group_id: groupId, expected_assets_hash: input3.expected_assets_hash, add: [], remove: [] };
|
|
1734
|
+
for (const [key2, type] of [["headlines", "HEADLINE"], ["long_headlines", "LONG_HEADLINE"], ["descriptions", "DESCRIPTION"]]) {
|
|
1735
|
+
const wanted = input3[key2];
|
|
1736
|
+
if (!wanted) continue;
|
|
1737
|
+
if (new Set(wanted).size !== wanted.length) throw new AdportError8("INVALID_INPUT", "google: duplicate copy within a placement");
|
|
1738
|
+
const current = context.assets.filter((value) => value.link.fieldType === type), existing = current.map((value) => row(value.asset.textAsset).text);
|
|
1739
|
+
changes.add.push(...wanted.filter((value) => !existing.includes(value)).map((text2) => ({ field_type: type, text: text2 })));
|
|
1740
|
+
changes.remove.push(...current.filter((value) => !wanted.includes(String(row(value.asset.textAsset).text))).map((value) => ({ asset_id: String(value.asset.id), field_type: type })));
|
|
1741
|
+
}
|
|
1742
|
+
if (!changes.add.length && !changes.remove.length) throw new AdportError8("INVALID_INPUT", "google: supplied copy already matches this group");
|
|
1743
|
+
return this.updateAssets(account2, changes, context);
|
|
1744
|
+
}
|
|
1745
|
+
if (op.tool === "google_add_asset_group_signals" || op.tool === "google_remove_asset_group_signals") return this.changeSignals(account2, op, context);
|
|
1746
|
+
if (op.tool === "google_replace_asset_group_listing_filters") return this.replaceFilters(account2, payload, context);
|
|
1747
|
+
const input2 = op.tool === "google_update_asset_group" ? groupUpdate.parse(payload) : op.tool === "google_set_asset_group_status" ? z7.object({ ...groupRef, status: z7.enum(["ENABLED", "PAUSED"]) }).strict().parse(payload) : z7.object(groupRef).strict().parse(payload);
|
|
1748
|
+
if (context.group_snapshot_hash !== input2.expected_group_hash) throw new AdportError8("PENDING_MISMATCH", "google: asset-group or parent configuration changed; read context again");
|
|
1749
|
+
if (op.tool === "google_remove_asset_group") return this.atomic(account2, [{ assetGroupOperation: { remove: resource } }], `Remove asset group \u201C${String(group.name)}\u201D`, [`- ${resource}; its associations, signals and listing filters may also be removed. Shared assets, parent campaign and budget are retained.`]);
|
|
1750
|
+
const { asset_group_id: _id, expected_group_hash: _hash, ...settings2 } = input2, merged = { ...group, ...fields3(settings2) };
|
|
1751
|
+
const pausing = op.tool === "google_set_asset_group_status" && "status" in input2 && input2.status === "PAUSED";
|
|
1752
|
+
if (!pausing) {
|
|
1753
|
+
this.groupWire({ path1: merged.path1, path2: merged.path2 });
|
|
1754
|
+
this.requirements(context.assets, context.brand_assets, context.campaign.brandGuidelinesEnabled === true, Boolean(row(context.campaign.shoppingSetting).merchantId), merged.finalUrls);
|
|
1755
|
+
}
|
|
1756
|
+
return this.atomic(account2, [{ assetGroupOperation: { update: { resourceName: resource, ...fields3(settings2) }, updateMask: Object.keys(settings2).filter((key2) => settings2[key2] !== void 0).join(",") } }], `Update asset group \u201C${String(group.name)}\u201D`, Object.entries(fields3(settings2)).map(([key2, value]) => `~ ${key2}: ${JSON.stringify(group[key2] ?? null)} \u2192 ${JSON.stringify(value)}`));
|
|
1757
|
+
}
|
|
1758
|
+
async updateBrandAssets(account2, payload) {
|
|
1759
|
+
const input2 = brandUpdate.parse(payload), context = await this.campaignContext({ account_id: account2, campaign_id: input2.campaign_id });
|
|
1760
|
+
if (context.campaign_snapshot_hash !== input2.expected_campaign_hash) throw new AdportError8("PENDING_MISMATCH", "google: campaign, budget or brand assets changed; read context again");
|
|
1761
|
+
if (context.campaign.brandGuidelinesEnabled !== true) throw new AdportError8("INVALID_INPUT", "google: campaign brand edits require native brand guidelines enabled; disabled campaigns keep branding on each group");
|
|
1762
|
+
const remove2 = input2.remove.map((value) => `customers/${account2}/campaignAssets/${input2.campaign_id}~${value.asset_id}~${value.field_type}`);
|
|
1763
|
+
if (new Set(remove2).size !== remove2.length || remove2.some((value) => !context.brand_assets.some((item) => item.link.resourceName === value))) throw new AdportError8("INVALID_INPUT", "google: every removed brand link must belong to this campaign exactly once");
|
|
1764
|
+
const resolved = await this.resolveAssets(account2, input2.add), after = [...context.brand_assets.filter((value) => !remove2.includes(String(value.link.resourceName))), ...resolved.assets];
|
|
1765
|
+
if (new Set(after.map((value) => `${value.link.fieldType}:${value.link.asset}`)).size !== after.length || after.filter((value) => value.link.fieldType === "BUSINESS_NAME").length !== 1 || after.filter((value) => value.link.fieldType === "LOGO").length < 1 || after.filter((value) => value.link.fieldType === "LOGO").length > 5) throw new AdportError8("INVALID_INPUT", "google: final campaign branding requires distinct links, one business name and one to five logos");
|
|
1766
|
+
return this.atomic(account2, [...resolved.operations, ...remove2.map((resource) => ({ campaignAssetOperation: { remove: resource } })), ...resolved.assets.map((value) => ({ campaignAssetOperation: { create: { campaign: context.campaign.resourceName, asset: value.link.asset, fieldType: value.link.fieldType, status: "ENABLED" } } }))], `Update shared Performance Max branding for campaign \u201C${String(context.campaign.name)}\u201D`, [`- ${remove2.length} exact brand links; + ${resolved.assets.length} links atomically. Source assets are retained.`, "Brand changes affect every asset group in this campaign, including serving creative combinations. Campaign/group statuses and budget are preserved."]);
|
|
1767
|
+
}
|
|
1768
|
+
async changeSignals(account2, op, context) {
|
|
1769
|
+
const input2 = op.tool === "google_add_asset_group_signals" ? signalsAdd.parse(op.payload) : signalsRemove.parse(op.payload);
|
|
1770
|
+
if (context.signals_snapshot_hash !== input2.expected_signals_hash) throw new AdportError8("PENDING_MISMATCH", "google: group, parent or signals changed; read context again");
|
|
1771
|
+
let operations;
|
|
1772
|
+
if ("signals" in input2) {
|
|
1773
|
+
const key2 = (value) => value.audience ? `audience:${String(row(value.audience).audience)}` : `theme:${String(row(value.searchTheme).text)}`;
|
|
1774
|
+
operations = await this.signalOperations(account2, String(context.asset_group.resourceName), input2.signals);
|
|
1775
|
+
if (operations.some((value) => context.signals.some((existing) => key2(existing) === key2(row(row(value.assetGroupSignalOperation).create))))) throw new AdportError8("INVALID_INPUT", "google: a supplied audience or search theme is already linked");
|
|
1776
|
+
} else {
|
|
1777
|
+
const names = input2.signal_ids.map((value) => `customers/${account2}/assetGroupSignals/${input2.asset_group_id}~${value}`);
|
|
1778
|
+
if (new Set(names).size !== names.length || names.some((value) => !context.signals.some((existing) => existing.resourceName === value))) throw new AdportError8("INVALID_INPUT", "google: every removed signal must belong to this group exactly once");
|
|
1779
|
+
operations = names.map((resource) => ({ assetGroupSignalOperation: { remove: resource } }));
|
|
1780
|
+
}
|
|
1781
|
+
return this.atomic(account2, operations, `${"signals" in input2 ? "Add" : "Remove"} ${operations.length} Performance Max signals`, ["Signals guide optimization and can change delivery, but audiences/search themes do not restrict targeting to only these users or queries.", "This workflow does not upload customer records, create an audience or change campaign/group status or budget."]);
|
|
1782
|
+
}
|
|
1783
|
+
replaceFilters(account2, payload, context) {
|
|
1784
|
+
const input2 = listingReplace.parse(payload);
|
|
1785
|
+
if (context.listing_snapshot_hash !== input2.expected_listing_hash) throw new AdportError8("PENDING_MISMATCH", "google: group, parent or listing filters changed; read context again");
|
|
1786
|
+
if (!row(context.campaign.shoppingSetting).merchantId || context.listing_filters.some((value) => value.listingSource !== "SHOPPING")) throw new AdportError8("INVALID_INPUT", "google: this workflow replaces only SHOPPING product filters in an existing retail campaign; webpage/retail-bundle filters are separate native workflows");
|
|
1787
|
+
const byName = new Map(context.listing_filters.map((value) => [String(value.resourceName), value]));
|
|
1788
|
+
const depth = (value, seen = /* @__PURE__ */ new Set()) => {
|
|
1789
|
+
const resource = String(value.resourceName);
|
|
1790
|
+
if (seen.has(resource)) throw new AdportError8("PROVIDER_ERROR", "google: cycle in current native listing tree");
|
|
1791
|
+
seen.add(resource);
|
|
1792
|
+
if (!value.parentListingGroupFilter) return 0;
|
|
1793
|
+
const parent = byName.get(String(value.parentListingGroupFilter));
|
|
1794
|
+
if (!parent) throw new AdportError8("PROVIDER_ERROR", "google: current native listing tree has an unavailable parent");
|
|
1795
|
+
return 1 + depth(parent, seen);
|
|
1796
|
+
};
|
|
1797
|
+
const remove2 = [...context.listing_filters].sort((a, b) => depth(b) - depth(a)).map((value) => ({ assetGroupListingGroupFilterOperation: { remove: value.resourceName } }));
|
|
1798
|
+
return this.atomic(account2, [...remove2, ...this.listingOperations(account2, String(context.asset_group.resourceName), input2.listing_filters)], `Replace product listing tree for group \u201C${String(context.asset_group.name)}\u201D`, [`- ${remove2.length} old tree nodes, children first; + ${input2.listing_filters.length} new nodes, parents first, in one atomic request.`, "Included/excluded products can change immediately in serving groups. Shared feeds, Merchant Center records, media assets, campaign/group statuses and budgets are preserved."]);
|
|
1799
|
+
}
|
|
1800
|
+
};
|
|
1801
|
+
function googlePerformanceMaxTools(provider) {
|
|
1802
|
+
const ref = z7.object({ account_id: z7.string(), asset_group_id: id7 });
|
|
1803
|
+
return [
|
|
1804
|
+
defineTool7({ name: "google_performance_max_context", namespace: "google", description: "Read an owned Performance Max campaign, budget, brand-guidelines state, automation settings and campaign brand links. Supply campaign_snapshot_hash to guarded group/brand changes. Does not enable a campaign or access Merchant Center records.", input: z7.object({ account_id: z7.string(), campaign_id: id7 }), annotations: { readOnly: true }, handler: (input2) => provider.performanceMax.campaignContext(input2) }),
|
|
1805
|
+
defineTool7({ name: "google_asset_groups", namespace: "google", description: "List owned Performance Max asset groups in one campaign with status, actual landing URLs and native eligibility/ad-strength reasons. Continue next_cursor as after_asset_group_id; use context/creatives for one group.", input: z7.object({ account_id: z7.string(), campaign_id: id7, limit: z7.number().int().positive().max(100).default(25), after_asset_group_id: id7.optional(), include_removed: z7.boolean().default(false) }), annotations: { readOnly: true }, pagination: { cursorInput: "after_asset_group_id" }, handler: (input2) => provider.performanceMax.list(input2) }),
|
|
1806
|
+
defineTool7({ name: "google_asset_group_context", namespace: "google", description: "Read one owned group, complete scoped creative/brand associations, signals and listing filters with separate group/assets/signals/listing snapshot hashes. Includes draft groups. Fails if a complete context exceeds its bounded read.", input: ref, annotations: { readOnly: true }, handler: (input2) => provider.performanceMax.context(input2) }),
|
|
1807
|
+
defineTool7({ name: "google_asset_group_creatives", namespace: "google", description: "View actual Performance Max group copy, owned image previews and landing URLs, with guarded status/copy-edit actions. The group generates creative combinations; it is not one fixed rendered ad. Previews omit unsupported media origins.", input: ref, output: creativesOutput2, presentation: "creatives", annotations: { readOnly: true }, handler: (input2) => provider.performanceMax.creatives(input2) }),
|
|
1808
|
+
...[
|
|
1809
|
+
["google_create_performance_max_campaign", "Create a complete standard/retail Performance Max campaign, non-shared budget, group, native text assets/associations and optional signals/product tree in one atomic request. Existing image/YouTube assets are account-verified. New brand guidelines use campaign-level business name/logos. Campaign/group creation obeys paused policy; previews use validateOnly. Final URL expansion defaults opted out.", campaignCreate],
|
|
1810
|
+
["google_create_asset_group", "Create a complete owned-campaign Performance Max group with atomic creative links, optional audience/search-theme signals and a retail product tree. Requires expected_campaign_hash. New group obeys paused policy; enabled child links cannot serve inside a paused group. Brand-guidelines campaigns need existing campaign-level branding.", groupCreate.safeExtend({ campaign_id: id7, expected_campaign_hash: hash5 })],
|
|
1811
|
+
["google_update_asset_group", "Edit only supplied group name, URLs, display paths and tracking fields with exact masks and expected_group_hash. Omission preserves values. Existing statuses, creative sources, campaign budget and parent are retained.", groupUpdate],
|
|
1812
|
+
["google_set_asset_group_status", "Enable or pause a verified owned asset group with expected_group_hash. Enabling can serve its generated combinations if the parent campaign is enabled. Does not change campaign status or budget.", z7.object({ ...groupRef, status: z7.enum(["ENABLED", "PAUSED"]) }).strict()],
|
|
1813
|
+
["google_remove_asset_group", "Remove a verified asset group and its native child associations/signals/filter tree, using expected_group_hash. Parent campaign, budget and shared source assets are retained. Native constraints still apply.", z7.object(groupRef).strict()],
|
|
1814
|
+
["google_update_asset_group_assets", "Atomically add supplied creative placements/text assets and remove exact owned associations, using expected_assets_hash. Preserves source assets and parent/group status. New links are enabled as an explicit creative edit; serving combinations can change. Final set must meet native minimums; retail can unlink all custom assets to return to feed-only.", assetsUpdate],
|
|
1815
|
+
["google_update_asset_group_copy", "Replace supplied headline/long-headline/description sets atomically with expected_assets_hash. Retains matching existing text and all unsupplied placements. New immutable text assets precede consecutive association changes; shared old sources are retained. Can affect serving combinations.", copyUpdate],
|
|
1816
|
+
["google_update_performance_max_brand_assets", "Atomically change campaign-level BUSINESS_NAME/LOGO/LANDSCAPE_LOGO links for brand-guidelines campaigns with expected_campaign_hash. Affects every group in the campaign, including serving creative combinations. Preserves sources/status/budget and native minimum branding.", brandUpdate],
|
|
1817
|
+
["google_add_asset_group_signals", "Add account-owned audience references or search themes with expected_signals_hash. These guide optimization rather than restrict targeting. No records are uploaded, audiences created or serving statuses changed.", signalsAdd],
|
|
1818
|
+
["google_remove_asset_group_signals", "Remove exact owned signal IDs from the selected group with expected_signals_hash. Does not delete audiences or upload customer records. Native minimum-signal rules remain authoritative.", signalsRemove],
|
|
1819
|
+
["google_replace_asset_group_listing_filters", "Replace a retail SHOPPING product tree atomically with expected_listing_hash. Typed brand/category/product type/custom-label/item/channel/condition nodes require unique keys, one root and complete subdivisions. Old children are removed first; new parents created first. Can alter eligible products in serving groups; feeds/status/budgets are retained.", listingReplace]
|
|
1820
|
+
].map(([tool, description, payload]) => guardedWriteTool7({ name: tool, namespace: "google", provider: "google", kind: kinds2[tool], description, payload }))
|
|
1821
|
+
];
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
// src/targeting.ts
|
|
1825
|
+
import { createHash as createHash6 } from "crypto";
|
|
1826
|
+
import { AdportError as AdportError9, defineTool as defineTool8, guardedWriteTool as guardedWriteTool8 } from "@adport/core";
|
|
1827
|
+
import { z as z9 } from "zod";
|
|
1828
|
+
|
|
1829
|
+
// src/targeting-schemas.ts
|
|
1830
|
+
import { z as z8 } from "zod";
|
|
1831
|
+
var targetingId = z8.string().regex(/^[1-9]\d*$/).max(30);
|
|
1832
|
+
var unique = (values) => new Set(values).size === values.length;
|
|
1833
|
+
var ids = z8.array(targetingId).max(1e3).refine(unique, "Use unique IDs");
|
|
1834
|
+
var delta = z8.object({ add_ids: ids.default([]), remove_ids: ids.default([]) }).strict().refine((value) => value.add_ids.length + value.remove_ids.length > 0, "Supply additions or removals").refine((value) => !value.add_ids.some((id8) => value.remove_ids.includes(id8)), "An ID cannot be added and removed together");
|
|
1835
|
+
var locationChanges = z8.object({ include: delta.optional(), exclude: delta.optional() }).strict().refine((value) => value.include !== void 0 || value.exclude !== void 0, "Supply included or excluded location changes");
|
|
1836
|
+
var targetingDevice = z8.enum(["DESKTOP", "MOBILE", "TABLET", "CONNECTED_TV", "OTHER"]);
|
|
1837
|
+
var bidMultiplier = z8.number().finite().min(0.1).max(10);
|
|
1838
|
+
var scheduleDay = z8.enum(["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]);
|
|
1839
|
+
var minute = z8.union([z8.literal(0), z8.literal(15), z8.literal(30), z8.literal(45)]);
|
|
1840
|
+
var adSchedule = z8.object({ day: scheduleDay, start_hour: z8.number().int().min(0).max(23), start_minute: minute, end_hour: z8.number().int().min(0).max(24), end_minute: minute, bid_modifier: bidMultiplier.optional() }).strict().refine((value) => value.end_hour !== 24 || value.end_minute === 0, "24:00 must end at minute0").refine((value) => value.end_hour * 60 + value.end_minute > value.start_hour * 60 + value.start_minute, "End must follow start within the same account-local day; split overnight schedules");
|
|
1841
|
+
var schedules = z8.array(adSchedule).max(42).superRefine((values, ctx) => {
|
|
1842
|
+
for (const day of scheduleDay.options) {
|
|
1843
|
+
const rows = values.filter((value) => value.day === day).sort((a, b) => a.start_hour * 60 + a.start_minute - b.start_hour * 60 - b.start_minute);
|
|
1844
|
+
if (rows.length > 6) ctx.addIssue({ code: "custom", message: "Native maximum: six schedules per day" });
|
|
1845
|
+
if (rows.some((value, index) => index && value.start_hour * 60 + value.start_minute < rows[index - 1].end_hour * 60 + rows[index - 1].end_minute)) ctx.addIssue({ code: "custom", message: "Schedules on a day must not overlap" });
|
|
1846
|
+
}
|
|
1847
|
+
});
|
|
1848
|
+
var targetingUpdate = z8.object({
|
|
1849
|
+
campaign_id: targetingId,
|
|
1850
|
+
expected_snapshot_hash: z8.string().regex(/^[a-f0-9]{64}$/),
|
|
1851
|
+
acknowledge_delivery_effects: z8.literal(true),
|
|
1852
|
+
locations: locationChanges.optional(),
|
|
1853
|
+
languages: delta.optional(),
|
|
1854
|
+
ad_schedules: schedules.optional().describe("Replaces weekly schedule; [] removes its time restrictions. Account timezone; omitted intervals retain their existing modifier only when unchanged."),
|
|
1855
|
+
device_bid_modifiers: z8.array(z8.object({ device: targetingDevice, bid_modifier: z8.union([z8.literal(0), bidMultiplier]) }).strict()).min(1).max(5).refine((values) => unique(values.map((value) => value.device)), "Use unique device types").optional(),
|
|
1856
|
+
positive_geo_target_type: z8.enum(["PRESENCE", "PRESENCE_OR_INTEREST", "SEARCH_INTEREST"]).optional(),
|
|
1857
|
+
negative_geo_target_type: z8.enum(["PRESENCE", "PRESENCE_OR_INTEREST"]).optional()
|
|
1858
|
+
}).strict().refine((value) => ["locations", "languages", "ad_schedules", "device_bid_modifiers", "positive_geo_target_type", "negative_geo_target_type"].some((key2) => value[key2] !== void 0), "Supply a targeting change");
|
|
1859
|
+
var targetingList = z8.object({ account_id: z8.string(), campaign_id: targetingId, page_size: z8.number().int().positive().max(200).default(50), cursor: z8.string().min(1).max(1024).regex(/^[A-Za-z0-9_-]+$/).optional() }).strict();
|
|
1860
|
+
var nativeSchedule = z8.object({ dayOfWeek: scheduleDay, startHour: z8.number().int().min(0).max(23), startMinute: z8.enum(["ZERO", "FIFTEEN", "THIRTY", "FORTY_FIVE"]), endHour: z8.number().int().min(0).max(24), endMinute: z8.enum(["ZERO", "FIFTEEN", "THIRTY", "FORTY_FIVE"]) }).strict();
|
|
1861
|
+
var nativeTargetingCriterion = z8.object({ resourceName: z8.string(), criterionId: targetingId, campaign: z8.string(), type: z8.enum(["LOCATION", "LANGUAGE", "DEVICE", "AD_SCHEDULE", "LOCATION_GROUP", "PROXIMITY"]), status: z8.enum(["ENABLED", "PAUSED"]), negative: z8.boolean().default(false), bidModifier: z8.number().finite().optional(), location: z8.object({ geoTargetConstant: z8.string().regex(/^geoTargetConstants\/[1-9]\d*$/) }).optional(), language: z8.object({ languageConstant: z8.string().regex(/^languageConstants\/[1-9]\d*$/) }).optional(), device: z8.object({ type: z8.string() }).optional(), adSchedule: nativeSchedule.optional() }).strict();
|
|
1862
|
+
|
|
1863
|
+
// src/targeting.ts
|
|
1864
|
+
var BOUND = 2e4;
|
|
1865
|
+
var fields4 = ["resource_name", "criterion_id", "campaign", "type", "status", "negative", "bid_modifier", "location.geo_target_constant", "language.language_constant", "device.type", "ad_schedule.day_of_week", "ad_schedule.start_hour", "ad_schedule.start_minute", "ad_schedule.end_hour", "ad_schedule.end_minute"].map((field3) => `campaign_criterion.${field3}`);
|
|
1866
|
+
var types = ["LOCATION", "LANGUAGE", "DEVICE", "AD_SCHEDULE", "LOCATION_GROUP", "PROXIMITY"];
|
|
1867
|
+
var infoFields = { LOCATION: "location", LANGUAGE: "language", DEVICE: "device", AD_SCHEDULE: "adSchedule" };
|
|
1868
|
+
var minuteWire = ["ZERO", "FIFTEEN", "THIRTY", "FORTY_FIVE"];
|
|
1869
|
+
var object4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1870
|
+
var canonical4 = (value) => Array.isArray(value) ? value.map(canonical4) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key2, item]) => [key2, canonical4(item)])) : value;
|
|
1871
|
+
var digest5 = (value) => createHash6("sha256").update(JSON.stringify(canonical4(value))).digest("hex");
|
|
1872
|
+
var equal = (a, b) => digest5(a) === digest5(b);
|
|
1873
|
+
var float = (value) => typeof value === "number" ? Math.fround(value) : value;
|
|
1874
|
+
var comparable = (value) => ({ ...value, ...value.bidModifier !== void 0 ? { bidModifier: float(value.bidModifier) } : {} });
|
|
1875
|
+
var key = (value) => `${value.type}:${value.negative}:${value.location?.geoTargetConstant ?? value.language?.languageConstant ?? value.device?.type ?? (value.adSchedule ? digest5(value.adSchedule) : value.criterionId)}`;
|
|
1876
|
+
var scheduleWire = (value) => ({ dayOfWeek: value.day, startHour: value.start_hour, startMinute: minuteWire[value.start_minute / 15], endHour: value.end_hour, endMinute: minuteWire[value.end_minute / 15] });
|
|
1877
|
+
var scheduleText = (value) => `${value.dayOfWeek} ${String(value.startHour).padStart(2, "0")}:${String(minuteWire.indexOf(value.startMinute) * 15).padStart(2, "0")}\u2013${String(value.endHour).padStart(2, "0")}:${String(minuteWire.indexOf(value.endMinute) * 15).padStart(2, "0")}`;
|
|
1878
|
+
var multiplierText = (value) => value === void 0 ? "Not reported" : `${Number(value.toPrecision(7))}\xD7`;
|
|
1879
|
+
var notes = ["Changes can affect delivery immediately on an enabled campaign. Campaign/ad statuses and monetary budgets are preserved; new targeting criteria are enabled within that existing campaign.", "Bid modifiers are multipliers, not currency micros or monetary ceilings. Native eligibility and bidding strategy determine whether they affect bids.", "Snapshots cover the returned six criterion types and selected parent/budget/timezone configuration, not performance or every other targeting dimension. Google has no atomic compare-and-set."];
|
|
1880
|
+
var GoogleTargetingService = class {
|
|
1881
|
+
constructor(client) {
|
|
1882
|
+
this.client = client;
|
|
1883
|
+
}
|
|
1884
|
+
client;
|
|
1885
|
+
async context(accountId, campaignId) {
|
|
1886
|
+
const account2 = normalizeCustomerId(accountId), campaignResource = `customers/${account2}/campaigns/${campaignId}`;
|
|
1887
|
+
const customerRows = await this.client.search(account2, "SELECT customer.resource_name, customer.id, customer.currency_code, customer.time_zone FROM customer LIMIT 2", { maxRows: 2 });
|
|
1888
|
+
const customer = object4(customerRows[0]?.customer);
|
|
1889
|
+
if (customerRows.length !== 1 || customer.id !== account2 || customer.resourceName !== `customers/${account2}` || typeof customer.timeZone !== "string" || typeof customer.currencyCode !== "string") throw new AdportError9("PROVIDER_ERROR", "google: exact customer currency/timezone context was not returned");
|
|
1890
|
+
const rows = await this.client.search(account2, `SELECT campaign.resource_name, campaign.id, campaign.name, campaign.status, campaign.advertising_channel_type, campaign.advertising_channel_sub_type, campaign.bidding_strategy_type, campaign.campaign_budget, campaign.geo_target_type_setting.positive_geo_target_type, campaign.geo_target_type_setting.negative_geo_target_type, campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.total_amount_micros, campaign_budget.period, campaign_budget.explicitly_shared FROM campaign WHERE campaign.id = ${campaignId} LIMIT 2`, { maxRows: 2, includeDrafts: true });
|
|
1891
|
+
const campaign = object4(rows[0]?.campaign), budget = object4(rows[0]?.campaignBudget);
|
|
1892
|
+
if (rows.length !== 1 || campaign.id !== campaignId || campaign.resourceName !== campaignResource || !["ENABLED", "PAUSED"].includes(String(campaign.status)) || typeof campaign.advertisingChannelType !== "string" || campaign.campaignBudget !== budget.resourceName || !new RegExp(`^customers/${account2}/campaignBudgets/[1-9]\\d*$`).test(String(budget.resourceName))) throw new AdportError9("INVALID_INPUT", "google: available campaign and owned budget configuration are required");
|
|
1893
|
+
const native = await this.client.search(account2, `SELECT campaign.id, ${fields4.join(", ")} FROM campaign_criterion WHERE campaign.id = ${campaignId} AND campaign_criterion.status != 'REMOVED' AND campaign_criterion.type IN (${types.map((type) => `'${type}'`).join(",")}) ORDER BY campaign_criterion.criterion_id ASC LIMIT ${BOUND + 1}`, { maxRows: BOUND + 1, includeDrafts: true });
|
|
1894
|
+
if (native.length > BOUND) throw new AdportError9("PROVIDER_ERROR", "google: complete targeting context exceeds the20,000 criterion safety bound");
|
|
1895
|
+
const seen = /* @__PURE__ */ new Set(), selections = /* @__PURE__ */ new Set(), criteria = native.map((value) => {
|
|
1896
|
+
const parsed = nativeTargetingCriterion.safeParse(value.campaignCriterion);
|
|
1897
|
+
if (!parsed.success) throw new AdportError9("PROVIDER_ERROR", "google: targeting criterion configuration is incomplete or unsupported");
|
|
1898
|
+
const row2 = parsed.data, info = infoFields[row2.type];
|
|
1899
|
+
if (object4(value.campaign).id !== campaignId || row2.campaign !== campaignResource || row2.resourceName !== `customers/${account2}/campaignCriteria/${campaignId}~${row2.criterionId}` || seen.has(row2.criterionId) || info && !row2[info] || ["location", "language", "device", "adSchedule"].filter((field3) => row2[field3] !== void 0).length !== (info ? 1 : 0) || row2.negative && ["LANGUAGE", "DEVICE", "AD_SCHEDULE", "PROXIMITY", "LOCATION_GROUP"].includes(row2.type)) throw new AdportError9("PROVIDER_ERROR", "google: criterion identity, hierarchy, type or polarity mismatch");
|
|
1900
|
+
if (selections.has(key(row2))) throw new AdportError9("PROVIDER_ERROR", "google: duplicate semantic targeting criteria prevent a reliable update");
|
|
1901
|
+
seen.add(row2.criterionId);
|
|
1902
|
+
selections.add(key(row2));
|
|
1903
|
+
return row2;
|
|
1904
|
+
}).sort((a, b) => BigInt(a.criterionId) < BigInt(b.criterionId) ? -1 : 1);
|
|
1905
|
+
const snapshot = { account_id: account2, customer, campaign, budget, criteria };
|
|
1906
|
+
return { ...snapshot, snapshot_hash: digest5(snapshot) };
|
|
1907
|
+
}
|
|
1908
|
+
async constants(account2, ids2, kind, required) {
|
|
1909
|
+
const values = [...new Set(ids2)], found = /* @__PURE__ */ new Map(), resource = kind === "LOCATION" ? "geo_target_constant" : "language_constant", property = kind === "LOCATION" ? "geoTargetConstant" : "languageConstant";
|
|
1910
|
+
for (let index = 0; index < values.length; index += 100) {
|
|
1911
|
+
const batch = values.slice(index, index + 100), selected2 = kind === "LOCATION" ? "geo_target_constant.resource_name, geo_target_constant.id, geo_target_constant.name, geo_target_constant.country_code, geo_target_constant.target_type, geo_target_constant.status" : "language_constant.resource_name, language_constant.id, language_constant.name, language_constant.code, language_constant.targetable";
|
|
1912
|
+
const rows = await this.client.search(account2, `SELECT ${selected2} FROM ${resource} WHERE ${resource}.id IN (${batch.join(",")}) LIMIT ${batch.length + 1}`, { maxRows: batch.length + 1 });
|
|
1913
|
+
for (const raw of rows) {
|
|
1914
|
+
const value = object4(raw[property]), id8 = String(value.id ?? "");
|
|
1915
|
+
if (!batch.includes(id8) || value.resourceName !== `${kind === "LOCATION" ? "geoTargetConstants" : "languageConstants"}/${id8}` || found.has(id8) || required && (kind === "LOCATION" ? value.status !== "ENABLED" : value.targetable !== true)) throw new AdportError9("INVALID_INPUT", "google: referenced targeting constant is unverified, duplicated or not currently targetable");
|
|
1916
|
+
found.set(id8, value);
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
if (required && values.some((id8) => !found.has(id8))) throw new AdportError9("INVALID_INPUT", "google: not every requested targeting constant was returned");
|
|
1920
|
+
return found;
|
|
1921
|
+
}
|
|
1922
|
+
async list(raw) {
|
|
1923
|
+
const input2 = targetingList.parse(raw), context = await this.context(input2.account_id, input2.campaign_id);
|
|
1924
|
+
let offset = 0;
|
|
1925
|
+
if (input2.cursor) {
|
|
1926
|
+
try {
|
|
1927
|
+
const parsed = z9.object({ account: z9.string(), campaign: z9.string(), hash: z9.string(), offset: z9.number().int().positive(), size: z9.number().int().positive() }).strict().parse(JSON.parse(Buffer.from(input2.cursor, "base64url").toString("utf8")));
|
|
1928
|
+
if (parsed.account !== context.account_id || parsed.campaign !== input2.campaign_id || parsed.hash !== context.snapshot_hash || parsed.size !== input2.page_size || parsed.offset >= context.criteria.length || parsed.offset % parsed.size) throw new Error("stale cursor");
|
|
1929
|
+
offset = parsed.offset;
|
|
1930
|
+
} catch {
|
|
1931
|
+
throw new AdportError9("INVALID_INPUT", "google: targeting continuation changed or belongs to another selection; refresh the first page");
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
const page = context.criteria.slice(offset, offset + input2.page_size), warnings2 = [], labels = /* @__PURE__ */ new Map();
|
|
1935
|
+
for (const kind of ["LOCATION", "LANGUAGE"]) {
|
|
1936
|
+
const ids2 = page.filter((row2) => row2.type === kind).map((row2) => (kind === "LOCATION" ? row2.location.geoTargetConstant : row2.language.languageConstant).split("/").at(-1));
|
|
1937
|
+
try {
|
|
1938
|
+
for (const [id8, value] of await this.constants(context.account_id, ids2, kind, false)) if (typeof value.name === "string") labels.set(`${kind}:${id8}`, value.name);
|
|
1939
|
+
} catch {
|
|
1940
|
+
warnings2.push(`${kind} names were not resolved; native IDs and configuration remain available.`);
|
|
1941
|
+
}
|
|
1942
|
+
}
|
|
1943
|
+
const languageNote = context.campaign.advertisingChannelType === "SEARCH" ? "Search manual language targets are legacy and do not control serving. Only their removal is supported." : context.campaign.advertisingChannelType === "PERFORMANCE_MAX" ? "Performance Max language criteria apply outside Google Search; Search matching is automatic." : "Language criterion eligibility remains native campaign-specific.";
|
|
1944
|
+
const records = page.map((row2) => {
|
|
1945
|
+
const id8 = (row2.location?.geoTargetConstant ?? row2.language?.languageConstant)?.split("/").at(-1), name5 = id8 ? labels.get(`${row2.type}:${id8}`) ?? id8 : row2.device?.type ?? (row2.adSchedule ? scheduleText(row2.adSchedule) : `Retained ${row2.type}`);
|
|
1946
|
+
return { id: row2.criterionId, name: name5, kind: row2.type, scope: row2.negative ? "Excluded" : "Targeted", status: row2.status, ...row2.type === "DEVICE" || row2.type === "AD_SCHEDULE" ? { bid_multiplier: multiplierText(row2.bidModifier) } : {}, ...row2.type === "LANGUAGE" && context.campaign.advertisingChannelType === "SEARCH" ? { serving: "Legacy \xB7 not used by Search" } : {} };
|
|
1947
|
+
});
|
|
1948
|
+
const end = offset + page.length;
|
|
1949
|
+
return { account_id: context.account_id, campaign_id: input2.campaign_id, campaign: context.campaign, customer: context.customer, budget: context.budget, snapshot_hash: context.snapshot_hash, records, criteria: page, total_criteria: context.criteria.length, truncated: end < context.criteria.length, ...end < context.criteria.length ? { next_cursor: Buffer.from(JSON.stringify({ account: context.account_id, campaign: input2.campaign_id, hash: context.snapshot_hash, offset: end, size: input2.page_size })).toString("base64url") } : {}, notes: [languageNote, "LOCATION_GROUP and PROXIMITY references are retained and are not edited by this tool. A location-ID list is not the entire geographic targeting model.", ...notes], warnings: warnings2 };
|
|
1950
|
+
}
|
|
1951
|
+
async plan(op) {
|
|
1952
|
+
if (op.provider !== "google" || op.kind !== "update" || op.tool !== "google_update_targeting") throw new AdportError9("INVALID_INPUT", "google: targeting operation provider/kind mismatch");
|
|
1953
|
+
const input2 = targetingUpdate.parse(op.payload), before = await this.context(op.accountId, input2.campaign_id);
|
|
1954
|
+
if (before.snapshot_hash !== input2.expected_snapshot_hash) throw new AdportError9("PENDING_MISMATCH", "google: targeting, parent or budget configuration changed; read and preview it again");
|
|
1955
|
+
const campaign = String(before.campaign.resourceName), removals = /* @__PURE__ */ new Set(), updates = /* @__PURE__ */ new Map(), creates = [], reviewFields = [{ label: "Campaign", after: before.campaign.name }, { label: "Campaign status", after: before.campaign.status }, { label: "Account timezone", after: before.customer.timeZone }];
|
|
1956
|
+
const patch = (row2, fields5) => updates.set(row2.resourceName, { ...updates.get(row2.resourceName), ...fields5 });
|
|
1957
|
+
const changeIds = async (kind, negative, delta2) => {
|
|
1958
|
+
if (!delta2) return;
|
|
1959
|
+
if (kind === "LANGUAGE" && before.campaign.advertisingChannelType === "SEARCH" && delta2.add_ids.length) throw new AdportError9("INVALID_INPUT", "google: Search manual language creation/update is no longer supported; only legacy criterion removal is available");
|
|
1960
|
+
const current = before.criteria.filter((row2) => row2.type === kind && row2.negative === negative), idOf = (row2) => (kind === "LOCATION" ? row2.location.geoTargetConstant : row2.language.languageConstant).split("/").at(-1);
|
|
1961
|
+
if (delta2.add_ids.some((id8) => current.some((row2) => idOf(row2) === id8)) || delta2.remove_ids.some((id8) => !current.some((row2) => idOf(row2) === id8))) throw new AdportError9("INVALID_INPUT", "google: targeting additions already exist or removals were not found; no mutation submitted");
|
|
1962
|
+
const constants = await this.constants(before.account_id, delta2.add_ids, kind, true);
|
|
1963
|
+
for (const id8 of delta2.remove_ids) removals.add(current.find((row2) => idOf(row2) === id8).resourceName);
|
|
1964
|
+
for (const id8 of delta2.add_ids) creates.push({ campaign, status: "ENABLED", negative, ...kind === "LOCATION" ? { location: { geoTargetConstant: `geoTargetConstants/${id8}` } } : { language: { languageConstant: `languageConstants/${id8}` } } });
|
|
1965
|
+
if (delta2.add_ids.length) reviewFields.push({ label: `Add ${negative ? "excluded" : "targeted"} ${kind.toLowerCase()}`, after: delta2.add_ids.map((id8) => `${constants.get(id8)?.name ?? id8} [${id8}]`) });
|
|
1966
|
+
if (delta2.remove_ids.length) reviewFields.push({ label: `Remove ${negative ? "excluded" : "targeted"} ${kind.toLowerCase()}`, after: delta2.remove_ids });
|
|
1967
|
+
};
|
|
1968
|
+
await changeIds("LOCATION", false, input2.locations?.include);
|
|
1969
|
+
await changeIds("LOCATION", true, input2.locations?.exclude);
|
|
1970
|
+
await changeIds("LANGUAGE", false, input2.languages);
|
|
1971
|
+
if (input2.locations) {
|
|
1972
|
+
const retained = before.criteria.filter((row2) => row2.type === "LOCATION" && !removals.has(row2.resourceName));
|
|
1973
|
+
const included = /* @__PURE__ */ new Set([...retained.filter((row2) => !row2.negative).map((row2) => row2.location.geoTargetConstant), ...creates.filter((row2) => !row2.negative && row2.location).map((row2) => String(object4(row2.location).geoTargetConstant))]);
|
|
1974
|
+
const excluded = /* @__PURE__ */ new Set([...retained.filter((row2) => row2.negative).map((row2) => row2.location.geoTargetConstant), ...creates.filter((row2) => row2.negative && row2.location).map((row2) => String(object4(row2.location).geoTargetConstant))]);
|
|
1975
|
+
if ([...included].some((value) => excluded.has(value))) throw new AdportError9("INVALID_INPUT", "google: the same location cannot be both explicitly included and excluded");
|
|
1976
|
+
if (!included.size) reviewFields.push({ label: "Remaining included location IDs", after: "None. Other radius/group criteria and exclusions are retained; without other positive geography, reach is unrestricted by included locations." });
|
|
1977
|
+
}
|
|
1978
|
+
if (input2.ad_schedules !== void 0) {
|
|
1979
|
+
const current = before.criteria.filter((row2) => row2.type === "AD_SCHEDULE"), wanted = new Set(input2.ad_schedules.map((value) => digest5(scheduleWire(value))));
|
|
1980
|
+
for (const row2 of current) if (!wanted.has(digest5(row2.adSchedule))) removals.add(row2.resourceName);
|
|
1981
|
+
for (const value of input2.ad_schedules) {
|
|
1982
|
+
const wire3 = scheduleWire(value), existing = current.find((row2) => equal(row2.adSchedule, wire3));
|
|
1983
|
+
if (!existing) creates.push({ campaign, status: "ENABLED", negative: false, adSchedule: wire3, ...value.bid_modifier !== void 0 ? { bidModifier: value.bid_modifier } : {} });
|
|
1984
|
+
else if (value.bid_modifier !== void 0 && float(existing.bidModifier) !== float(value.bid_modifier)) patch(existing, { bidModifier: value.bid_modifier });
|
|
1985
|
+
}
|
|
1986
|
+
reviewFields.push({ label: "Weekly schedule", before: current.map((row2) => `${scheduleText(row2.adSchedule)} \xB7 ${multiplierText(row2.bidModifier)}`), after: input2.ad_schedules.length ? input2.ad_schedules.map((value) => `${scheduleText(scheduleWire(value))} \xB7 ${value.bid_modifier === void 0 ? "preserve matching interval modifier; native default for new intervals" : multiplierText(value.bid_modifier)}`) : "No ad-schedule time restriction \xB7 all day" });
|
|
1987
|
+
}
|
|
1988
|
+
for (const value of input2.device_bid_modifiers ?? []) {
|
|
1989
|
+
const current = before.criteria.filter((row3) => row3.type === "DEVICE" && row3.device?.type === value.device);
|
|
1990
|
+
if (current.length !== 1) throw new AdportError9("INVALID_INPUT", "google: device bid changes require an existing exact device criterion; device types are not created or removed here");
|
|
1991
|
+
const row2 = current[0];
|
|
1992
|
+
if (float(row2.bidModifier) !== float(value.bid_modifier)) {
|
|
1993
|
+
patch(row2, { bidModifier: value.bid_modifier });
|
|
1994
|
+
reviewFields.push({ label: `${value.device} bid multiplier`, before: multiplierText(row2.bidModifier), after: value.bid_modifier === 0 ? "0\xD7 \xB7 device excluded" : multiplierText(value.bid_modifier) });
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
const geo = {}, geoMask = [], existingGeo = object4(before.campaign.geoTargetTypeSetting);
|
|
1998
|
+
if (before.campaign.advertisingChannelType === "SEARCH" && (input2.positive_geo_target_type === "SEARCH_INTEREST" || input2.negative_geo_target_type === "PRESENCE_OR_INTEREST")) throw new AdportError9("INVALID_INPUT", "google: Search supports PRESENCE/PRESENCE_OR_INTEREST positive intent and PRESENCE exclusion intent; native validation rejected the selected combination");
|
|
1999
|
+
for (const [inputKey, nativeKey] of [["positive_geo_target_type", "positiveGeoTargetType"], ["negative_geo_target_type", "negativeGeoTargetType"]]) if (input2[inputKey] !== void 0 && input2[inputKey] !== existingGeo[nativeKey]) {
|
|
2000
|
+
geo[nativeKey] = input2[inputKey];
|
|
2001
|
+
geoMask.push(`geo_target_type_setting.${inputKey}`);
|
|
2002
|
+
reviewFields.push({ label: inputKey === "positive_geo_target_type" ? "Location inclusion intent" : "Location exclusion intent", before: existingGeo[nativeKey] ?? "Not reported", after: input2[inputKey] });
|
|
2003
|
+
}
|
|
2004
|
+
const operations = [...removals].map((resource) => ({ campaignCriterionOperation: { remove: resource } }));
|
|
2005
|
+
for (const [resourceName, changes] of updates) {
|
|
2006
|
+
const current = before.criteria.find((row2) => row2.resourceName === resourceName);
|
|
2007
|
+
if (removals.has(resourceName)) throw new AdportError9("INVALID_INPUT", "google: cannot edit and remove the same criterion");
|
|
2008
|
+
const info = Object.fromEntries(["location", "language", "device", "adSchedule"].filter((key2) => current[key2] !== void 0).map((key2) => [key2, current[key2]]));
|
|
2009
|
+
operations.push({ campaignCriterionOperation: { update: { resourceName, ...info, ...changes }, updateMask: Object.keys(changes).map((key2) => key2 === "bidModifier" ? "bid_modifier" : key2).join(",") } });
|
|
2010
|
+
}
|
|
2011
|
+
operations.push(...creates.map((create3) => ({ campaignCriterionOperation: { create: create3 } })));
|
|
2012
|
+
if (geoMask.length) operations.push({ campaignOperation: { update: { resourceName: campaign, geoTargetTypeSetting: geo }, updateMask: geoMask.join(",") } });
|
|
2013
|
+
if (!operations.length) throw new AdportError9("INVALID_INPUT", "google: no targeting configuration change remains after comparing current values");
|
|
2014
|
+
if (operations.length > 5e3) throw new AdportError9("INVALID_INPUT", "google: targeting edits exceed the5,000-operation tool bound; use smaller changes");
|
|
2015
|
+
const reviewNotes = [...notes, before.campaign.advertisingChannelType === "SEARCH" ? "Search legacy language criteria are not used in serving; removal is cleanup, not a new language restriction." : before.campaign.advertisingChannelType === "PERFORMANCE_MAX" ? "Performance Max language settings apply only outside Google Search." : "Google validates criterion/campaign compatibility before approval.", "Schedules use the account timezone, with exclusive end times. [] removes time restrictions. Location/language add/remove lists preserve every unmentioned criterion."];
|
|
2016
|
+
let details;
|
|
2017
|
+
return {
|
|
2018
|
+
summary: `Update Google campaign targeting \xB7 ${before.campaign.name}`,
|
|
2019
|
+
changes: reviewFields.map((field3) => `${field3.label}: ${JSON.stringify(field3.after)}`),
|
|
2020
|
+
coercions: [],
|
|
2021
|
+
budgetDeltas: [],
|
|
2022
|
+
notes: reviewNotes,
|
|
2023
|
+
review: { provider: "google", accountId: before.account_id, kind: "update", title: "Update campaign targeting", fields: reviewFields, notices: reviewNotes },
|
|
2024
|
+
resultDetails: () => details,
|
|
2025
|
+
execute: async (validateOnly) => {
|
|
2026
|
+
const known = /* @__PURE__ */ new Set([...removals, ...updates.keys(), ...geoMask.length ? [campaign] : []]);
|
|
2027
|
+
try {
|
|
2028
|
+
const result2 = await this.client.googleAdsMutate(before.account_id, operations, { validateOnly });
|
|
2029
|
+
if (!result2 || typeof result2 !== "object" || Array.isArray(result2)) throw new AdportError9("PROVIDER_ERROR", "google: targeting mutate response envelope could not be verified");
|
|
2030
|
+
const responses = result2.mutateOperationResponses;
|
|
2031
|
+
if (Array.isArray(responses)) {
|
|
2032
|
+
for (const response of responses) for (const value of Object.values(object4(response))) if (typeof object4(value).resourceName === "string") known.add(String(object4(value).resourceName));
|
|
2033
|
+
}
|
|
2034
|
+
if ("partialFailureError" in result2) throw new Error("unexpected partial failure");
|
|
2035
|
+
if (validateOnly) return [];
|
|
2036
|
+
if (!Array.isArray(responses) || responses.length !== operations.length) throw new Error("mutation receipt count mismatch");
|
|
2037
|
+
const created = [];
|
|
2038
|
+
for (let index = 0; index < operations.length; index++) {
|
|
2039
|
+
const operation = operations[index], criterionOp = object4(operation.campaignCriterionOperation), campaignOp = object4(operation.campaignOperation), expectedKey = operation.campaignCriterionOperation ? "campaignCriterionResult" : "campaignResult", response = responses[index];
|
|
2040
|
+
if (Object.keys(response).length !== 1 || !response[expectedKey]) throw new Error("mutation receipt type mismatch");
|
|
2041
|
+
const resource = response[expectedKey].resourceName;
|
|
2042
|
+
if (criterionOp.create) {
|
|
2043
|
+
if (typeof resource !== "string" || !new RegExp(`^customers/${before.account_id}/campaignCriteria/${input2.campaign_id}~[1-9]\\d*$`).test(resource) || before.criteria.some((row2) => row2.resourceName === resource) || created.some((row2) => row2.id === resource)) throw new Error("created criterion identity mismatch");
|
|
2044
|
+
created.push({ id: resource, value: object4(criterionOp.create) });
|
|
2045
|
+
} else if (resource !== (criterionOp.remove ?? object4(criterionOp.update).resourceName ?? campaignOp.remove ?? object4(campaignOp.update).resourceName)) throw new Error("mutation receipt scope mismatch");
|
|
2046
|
+
}
|
|
2047
|
+
const after = await this.context(before.account_id, input2.campaign_id), expectedCampaign = { ...before.campaign, ...geoMask.length ? { geoTargetTypeSetting: { ...existingGeo, ...geo } } : {} };
|
|
2048
|
+
if (!equal(after.customer, before.customer) || !equal(after.budget, before.budget) || !equal(after.campaign, expectedCampaign)) throw new Error("parent preservation mismatch");
|
|
2049
|
+
const expectedIds = new Set(created.map((row2) => row2.id));
|
|
2050
|
+
for (const previous of before.criteria) {
|
|
2051
|
+
const observed = after.criteria.find((row2) => row2.resourceName === previous.resourceName);
|
|
2052
|
+
if (removals.has(previous.resourceName)) {
|
|
2053
|
+
if (observed) throw new Error("removed criterion remains");
|
|
2054
|
+
continue;
|
|
2055
|
+
}
|
|
2056
|
+
expectedIds.add(previous.resourceName);
|
|
2057
|
+
const expected = { ...previous, ...updates.get(previous.resourceName) };
|
|
2058
|
+
if (!observed || !equal(comparable(observed), comparable(expected))) throw new Error("criterion preservation mismatch");
|
|
2059
|
+
}
|
|
2060
|
+
for (const item of created) {
|
|
2061
|
+
const observed = after.criteria.find((row2) => row2.resourceName === item.id);
|
|
2062
|
+
if (!observed || Object.entries(item.value).some(([field3, expected]) => field3 === "bidModifier" ? float(observed.bidModifier) !== float(expected) : !equal(observed[field3], expected))) throw new Error("created criterion readback mismatch");
|
|
2063
|
+
}
|
|
2064
|
+
if (after.criteria.some((row2) => !expectedIds.has(row2.resourceName))) throw new Error("unexpected criterion appeared");
|
|
2065
|
+
details = { snapshot_hash: after.snapshot_hash, created_criteria: created.map((row2) => row2.id), removed_criteria: [...removals], updated_criteria: [...updates.keys()], independent_scoped_readback_verified: true, other_criterion_types_submitted: false };
|
|
2066
|
+
return [...known];
|
|
2067
|
+
} catch (error) {
|
|
2068
|
+
if (validateOnly) throw error;
|
|
2069
|
+
throw new AdportError9("PROVIDER_ERROR", "google: targeting mutation outcome was not confirmed. Reconcile acknowledged IDs and current targeting before another change; no write was retried.", { resourceIds: [...known] });
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
};
|
|
2073
|
+
}
|
|
2074
|
+
};
|
|
2075
|
+
function googleTargetingTools(provider) {
|
|
2076
|
+
const catalog = { category: "audiences", exposure: "specialist" };
|
|
2077
|
+
return [
|
|
2078
|
+
defineTool8({ name: "google_campaign_targeting", namespace: "google", catalog, description: "Read scoped campaign location/language/device/schedule configuration and snapshot_hash. Native statuses, omitted bid multipliers and retained radius/group references remain explicit. Stable snapshot paging supports Load more. Search language criteria are legacy, not serving restrictions.", input: targetingList, presentation: "records", pagination: { cursorInput: "cursor" }, annotations: { readOnly: true }, handler: (input2) => provider.targeting.list(input2) }),
|
|
2079
|
+
guardedWriteTool8({ name: "google_update_targeting", namespace: "google", provider: "google", catalog, kind: "update", description: "Edit existing campaign targeting with snapshot_hash and delivery-effects acknowledgement. Location/language additions/removals preserve unmentioned criteria; schedules replace weekly intervals; device multipliers edit existing types. Exact native masks, atomic validateOnly and independent readback. Search languages can only be removed.", payload: targetingUpdate })
|
|
2080
|
+
];
|
|
2081
|
+
}
|
|
2082
|
+
|
|
2083
|
+
// src/provider.ts
|
|
150
2084
|
var LEVEL_RESOURCE = {
|
|
151
2085
|
account: "customer",
|
|
152
2086
|
campaign: "campaign",
|
|
@@ -161,12 +2095,91 @@ var BASE_METRIC_FIELDS = {
|
|
|
161
2095
|
conversion_value: "metrics.conversions_value"
|
|
162
2096
|
};
|
|
163
2097
|
var GoogleAdsProvider = class {
|
|
164
|
-
constructor(client) {
|
|
2098
|
+
constructor(client, media) {
|
|
165
2099
|
this.client = client;
|
|
2100
|
+
this.assets = new GoogleAssetService(client, media);
|
|
2101
|
+
this.assetLinks = new GoogleAssetLinks(client, this.assets);
|
|
2102
|
+
this.labels = new GoogleLabelService(client);
|
|
2103
|
+
this.conversions = new GoogleConversionService(client);
|
|
2104
|
+
this.dataManager = new GoogleDataManagerService(client, this.conversions);
|
|
2105
|
+
this.experiments = new GoogleExperimentService(client);
|
|
2106
|
+
this.performanceMax = new GooglePerformanceMaxService(client);
|
|
2107
|
+
this.targeting = new GoogleTargetingService(client);
|
|
166
2108
|
}
|
|
167
2109
|
client;
|
|
168
2110
|
id = "google";
|
|
169
2111
|
discoveredLoginCustomerIds = /* @__PURE__ */ new Map();
|
|
2112
|
+
assets;
|
|
2113
|
+
assetLinks;
|
|
2114
|
+
labels;
|
|
2115
|
+
conversions;
|
|
2116
|
+
dataManager;
|
|
2117
|
+
experiments;
|
|
2118
|
+
performanceMax;
|
|
2119
|
+
targeting;
|
|
2120
|
+
keywordPlanning(customerId, method, body) {
|
|
2121
|
+
return this.client.keywordPlanning(customerId, method, body);
|
|
2122
|
+
}
|
|
2123
|
+
fieldMetadata(query, pageSize, pageToken) {
|
|
2124
|
+
return this.client.fieldMetadata(query, pageSize, pageToken);
|
|
2125
|
+
}
|
|
2126
|
+
async listAds(input2) {
|
|
2127
|
+
const cid = normalizeCustomerId(input2.account_id);
|
|
2128
|
+
const conditions = ["ad_group_ad.status != 'REMOVED'"];
|
|
2129
|
+
if (input2.campaign_id) conditions.push(`campaign.id = ${input2.campaign_id}`);
|
|
2130
|
+
if (input2.ad_group_id) conditions.push(`ad_group.id = ${input2.ad_group_id}`);
|
|
2131
|
+
const rows = await this.client.search(
|
|
2132
|
+
cid,
|
|
2133
|
+
`SELECT campaign.id, ad_group.id, ad_group_ad.ad.id, ad_group_ad.ad.name, ad_group_ad.ad.type, ad_group_ad.status, ad_group_ad.ad.final_urls, ad_group_ad.ad.responsive_search_ad.headlines, ad_group_ad.ad.responsive_search_ad.descriptions FROM ad_group_ad WHERE ${conditions.join(" AND ")} LIMIT ${input2.limit + 1}`,
|
|
2134
|
+
{ maxRows: input2.limit + 1, includeDrafts: input2.include_drafts }
|
|
2135
|
+
);
|
|
2136
|
+
const textAssets = (value) => Array.isArray(value) ? value.flatMap((item) => item && typeof item === "object" && "text" in item && typeof item.text === "string" ? [item.text] : []) : [];
|
|
2137
|
+
return creativesOutput3.parse({
|
|
2138
|
+
truncated: rows.length > input2.limit,
|
|
2139
|
+
creatives: rows.slice(0, input2.limit).map((row2) => {
|
|
2140
|
+
const groupAd = row2.adGroupAd;
|
|
2141
|
+
const ad = groupAd.ad;
|
|
2142
|
+
if (!ad?.id) throw new AdportError10("PROVIDER_ERROR", "google: ad response is missing its identifier");
|
|
2143
|
+
const adGroupId = String(row2.adGroup?.id ?? "");
|
|
2144
|
+
if (!/^\d+$/.test(adGroupId)) throw new AdportError10("PROVIDER_ERROR", "google: ad response is missing its ad-group identifier");
|
|
2145
|
+
const headlines = textAssets(ad.responsiveSearchAd?.headlines);
|
|
2146
|
+
return {
|
|
2147
|
+
id: ad.id,
|
|
2148
|
+
provider: this.id,
|
|
2149
|
+
account_id: cid,
|
|
2150
|
+
ad_group_id: adGroupId,
|
|
2151
|
+
campaign_id: String(row2.campaign?.id ?? ""),
|
|
2152
|
+
name: ad.name || headlines[0] || `Ad ${ad.id}`,
|
|
2153
|
+
type: ad.type ?? "UNKNOWN",
|
|
2154
|
+
status: groupAd.status,
|
|
2155
|
+
headlines,
|
|
2156
|
+
descriptions: textAssets(ad.responsiveSearchAd?.descriptions),
|
|
2157
|
+
landing_urls: (ad.finalUrls ?? []).filter((url4) => {
|
|
2158
|
+
try {
|
|
2159
|
+
const parsed = new URL(url4);
|
|
2160
|
+
return ["http:", "https:"].includes(parsed.protocol) && !parsed.username && !parsed.password;
|
|
2161
|
+
} catch {
|
|
2162
|
+
return false;
|
|
2163
|
+
}
|
|
2164
|
+
}),
|
|
2165
|
+
media: [],
|
|
2166
|
+
actions: ["ENABLED", "PAUSED"].includes(groupAd.status ?? "") ? [
|
|
2167
|
+
creativeStatusAction2("google_set_ad_status", { account_id: cid, ad_group_id: adGroupId, ad_id: ad.id }, groupAd.status, ["ENABLED", "PAUSED"]),
|
|
2168
|
+
...ad.type === "RESPONSIVE_SEARCH_AD" ? [{
|
|
2169
|
+
label: "Edit ad copy",
|
|
2170
|
+
tool: "google_update_responsive_search_ad",
|
|
2171
|
+
arguments: { account_id: cid, ad_group_id: adGroupId, ad_id: ad.id },
|
|
2172
|
+
fields: [
|
|
2173
|
+
{ key: "headlines", label: "Headlines (one per line)", type: "text_list", value: headlines },
|
|
2174
|
+
{ key: "descriptions", label: "Descriptions (one per line)", type: "text_list", value: textAssets(ad.responsiveSearchAd?.descriptions) },
|
|
2175
|
+
{ key: "final_urls", label: "Landing pages (one per line)", type: "url_list", value: ad.finalUrls ?? [] }
|
|
2176
|
+
]
|
|
2177
|
+
}] : []
|
|
2178
|
+
] : []
|
|
2179
|
+
};
|
|
2180
|
+
})
|
|
2181
|
+
});
|
|
2182
|
+
}
|
|
170
2183
|
capabilities() {
|
|
171
2184
|
return { serverDryRun: true };
|
|
172
2185
|
}
|
|
@@ -179,28 +2192,28 @@ var GoogleAdsProvider = class {
|
|
|
179
2192
|
};
|
|
180
2193
|
}
|
|
181
2194
|
async listAccounts() {
|
|
182
|
-
const
|
|
183
|
-
const directlyAccessible = new Set(
|
|
2195
|
+
const ids2 = await this.client.listAccessibleCustomers();
|
|
2196
|
+
const directlyAccessible = new Set(ids2);
|
|
184
2197
|
const accounts = /* @__PURE__ */ new Map();
|
|
185
2198
|
const managers = [];
|
|
186
|
-
for (const
|
|
2199
|
+
for (const id8 of ids2) {
|
|
187
2200
|
try {
|
|
188
2201
|
const rows = await this.client.search(
|
|
189
|
-
|
|
2202
|
+
id8,
|
|
190
2203
|
"SELECT customer.id, customer.descriptive_name, customer.currency_code, customer.status, customer.manager FROM customer LIMIT 1",
|
|
191
|
-
{ maxRows: 1, loginCustomerId:
|
|
2204
|
+
{ maxRows: 1, loginCustomerId: id8 }
|
|
192
2205
|
);
|
|
193
2206
|
const customer = rows[0]?.customer ?? {};
|
|
194
|
-
if (customer.manager) managers.push(
|
|
195
|
-
else accounts.set(
|
|
2207
|
+
if (customer.manager) managers.push(id8);
|
|
2208
|
+
else accounts.set(id8, {
|
|
196
2209
|
provider: this.id,
|
|
197
|
-
id,
|
|
198
|
-
name: customer.descriptiveName ?? `(account ${
|
|
2210
|
+
id: id8,
|
|
2211
|
+
name: customer.descriptiveName ?? `(account ${id8})`,
|
|
199
2212
|
currency: customer.currencyCode,
|
|
200
2213
|
status: customer.status
|
|
201
2214
|
});
|
|
202
2215
|
} catch {
|
|
203
|
-
accounts.set(
|
|
2216
|
+
accounts.set(id8, { provider: this.id, id: id8, name: "(details unavailable)", status: "UNKNOWN" });
|
|
204
2217
|
}
|
|
205
2218
|
}
|
|
206
2219
|
for (const rootManagerId of managers) {
|
|
@@ -215,8 +2228,8 @@ var GoogleAdsProvider = class {
|
|
|
215
2228
|
"SELECT customer_client.client_customer, customer_client.id, customer_client.level, customer_client.manager, customer_client.descriptive_name, customer_client.currency_code, customer_client.status FROM customer_client WHERE customer_client.level <= 1",
|
|
216
2229
|
{ maxRows: 1e4, loginCustomerId: rootManagerId }
|
|
217
2230
|
);
|
|
218
|
-
for (const
|
|
219
|
-
const customer =
|
|
2231
|
+
for (const row2 of rows) {
|
|
2232
|
+
const customer = row2.customerClient ?? {};
|
|
220
2233
|
if (Number(customer.level ?? 0) === 0) continue;
|
|
221
2234
|
const customerId = customer.clientCustomer?.replace("customers/", "") ?? String(customer.id ?? "");
|
|
222
2235
|
if (!/^\d{10}$/.test(customerId)) continue;
|
|
@@ -250,8 +2263,8 @@ var GoogleAdsProvider = class {
|
|
|
250
2263
|
const accountIds = query.accountIds ?? (await this.listAccounts()).filter((a) => !a.status?.includes("manager")).map((a) => a.id);
|
|
251
2264
|
const baseMetrics = /* @__PURE__ */ new Set();
|
|
252
2265
|
for (const metric of query.metrics) {
|
|
253
|
-
const
|
|
254
|
-
if (
|
|
2266
|
+
const field3 = BASE_METRIC_FIELDS[metric];
|
|
2267
|
+
if (field3) baseMetrics.add(field3);
|
|
255
2268
|
}
|
|
256
2269
|
const wants = (m) => query.metrics.includes(m);
|
|
257
2270
|
if (wants("ctr")) ["metrics.clicks", "metrics.impressions"].forEach((f) => baseMetrics.add(f));
|
|
@@ -270,15 +2283,15 @@ var GoogleAdsProvider = class {
|
|
|
270
2283
|
const rows = [];
|
|
271
2284
|
for (const accountId of accountIds) {
|
|
272
2285
|
const results = await this.client.search(accountId, gaql, { maxRows: query.limit ?? 1e3 });
|
|
273
|
-
for (const
|
|
274
|
-
rows.push(this.toReportRow(
|
|
2286
|
+
for (const row2 of results) {
|
|
2287
|
+
rows.push(this.toReportRow(row2, accountId, query));
|
|
275
2288
|
}
|
|
276
2289
|
}
|
|
277
2290
|
return { rows };
|
|
278
2291
|
}
|
|
279
|
-
toReportRow(
|
|
280
|
-
const metricsRaw =
|
|
281
|
-
const num = (
|
|
2292
|
+
toReportRow(row2, accountId, query) {
|
|
2293
|
+
const metricsRaw = row2.metrics ?? {};
|
|
2294
|
+
const num = (key2) => Number(metricsRaw[key2] ?? 0);
|
|
282
2295
|
const spend = num("costMicros") / 1e6;
|
|
283
2296
|
const impressions = num("impressions");
|
|
284
2297
|
const clicks = num("clicks");
|
|
@@ -299,22 +2312,22 @@ var GoogleAdsProvider = class {
|
|
|
299
2312
|
let entity;
|
|
300
2313
|
switch (query.level) {
|
|
301
2314
|
case "account": {
|
|
302
|
-
const customer =
|
|
2315
|
+
const customer = row2.customer ?? {};
|
|
303
2316
|
entity = { level: "account", id: String(customer.id ?? accountId), name: customer.descriptiveName ?? accountId, status: customer.status };
|
|
304
2317
|
break;
|
|
305
2318
|
}
|
|
306
2319
|
case "campaign": {
|
|
307
|
-
const campaign =
|
|
2320
|
+
const campaign = row2.campaign ?? {};
|
|
308
2321
|
entity = { level: "campaign", id: String(campaign.id ?? ""), name: campaign.name ?? "", status: campaign.status };
|
|
309
2322
|
break;
|
|
310
2323
|
}
|
|
311
2324
|
case "ad_group": {
|
|
312
|
-
const adGroup =
|
|
2325
|
+
const adGroup = row2.adGroup ?? {};
|
|
313
2326
|
entity = { level: "ad_group", id: String(adGroup.id ?? ""), name: adGroup.name ?? "", status: adGroup.status };
|
|
314
2327
|
break;
|
|
315
2328
|
}
|
|
316
2329
|
case "ad": {
|
|
317
|
-
const adGroupAd =
|
|
2330
|
+
const adGroupAd = row2.adGroupAd ?? {};
|
|
318
2331
|
entity = { level: "ad", id: String(adGroupAd.ad?.id ?? ""), name: `ad ${adGroupAd.ad?.id ?? "?"}`, status: adGroupAd.status };
|
|
319
2332
|
break;
|
|
320
2333
|
}
|
|
@@ -326,13 +2339,13 @@ var GoogleAdsProvider = class {
|
|
|
326
2339
|
metrics: Object.fromEntries(query.metrics.map((m) => [m, all[m]]))
|
|
327
2340
|
};
|
|
328
2341
|
}
|
|
329
|
-
async gaqlSearch(
|
|
330
|
-
const limit = Math.min(
|
|
331
|
-
let query = `SELECT ${
|
|
332
|
-
if (
|
|
333
|
-
if (
|
|
2342
|
+
async gaqlSearch(input2) {
|
|
2343
|
+
const limit = Math.min(input2.limit ?? 200, 1e4);
|
|
2344
|
+
let query = `SELECT ${input2.fields.join(", ")} FROM ${input2.resource}`;
|
|
2345
|
+
if (input2.conditions?.length) query += ` WHERE ${input2.conditions.join(" AND ")}`;
|
|
2346
|
+
if (input2.order_by?.length) query += ` ORDER BY ${input2.order_by.join(", ")}`;
|
|
334
2347
|
query += ` LIMIT ${limit} PARAMETERS omit_unselected_resource_names=true`;
|
|
335
|
-
return this.client.search(
|
|
2348
|
+
return this.client.search(input2.customer_id, query, { maxRows: limit, includeDrafts: input2.include_drafts });
|
|
336
2349
|
}
|
|
337
2350
|
async previewWrite(op, guard) {
|
|
338
2351
|
const plan = await this.plan(op, guard);
|
|
@@ -342,16 +2355,27 @@ var GoogleAdsProvider = class {
|
|
|
342
2355
|
changes: plan.changes,
|
|
343
2356
|
coercions: plan.coercions,
|
|
344
2357
|
budgetDeltas: plan.budgetDeltas,
|
|
345
|
-
|
|
2358
|
+
...plan.fieldChanges ? { fieldChanges: plan.fieldChanges } : {},
|
|
2359
|
+
...plan.notes ? { notes: plan.notes } : {},
|
|
2360
|
+
...plan.review ? { review: plan.review } : {},
|
|
2361
|
+
serverValidated: plan.serverValidated ?? true
|
|
346
2362
|
};
|
|
347
2363
|
}
|
|
348
2364
|
async applyWrite(op, guard) {
|
|
349
2365
|
const plan = await this.plan(op, guard);
|
|
350
2366
|
const resourceIds = await plan.execute(false);
|
|
351
|
-
return { applied: true, resourceIds };
|
|
2367
|
+
return { applied: true, resourceIds, ...plan.resultDetails ? { details: plan.resultDetails() } : {}, ...plan.resultWarnings ? { warnings: plan.resultWarnings() } : {} };
|
|
352
2368
|
}
|
|
353
2369
|
// ---- write planning ------------------------------------------------------
|
|
354
2370
|
async plan(op, guard) {
|
|
2371
|
+
if (GOOGLE_ASSET_WRITES.has(op.tool)) return this.assets.plan(op);
|
|
2372
|
+
if (GOOGLE_ASSET_LINK_WRITES.has(op.tool)) return this.assetLinks.plan(op, guard);
|
|
2373
|
+
if (GOOGLE_LABEL_WRITES.has(op.tool)) return this.labels.plan(op);
|
|
2374
|
+
if (GOOGLE_CONVERSION_WRITES.has(op.tool)) return this.conversions.plan(op);
|
|
2375
|
+
if (op.tool === "google_ingest_conversion_events") return this.dataManager.plan(op);
|
|
2376
|
+
if (GOOGLE_EXPERIMENT_WRITES.has(op.tool)) return this.experiments.plan(op, guard);
|
|
2377
|
+
if (GOOGLE_PMAX_WRITES.has(op.tool)) return this.performanceMax.plan(op, guard);
|
|
2378
|
+
if (op.tool === "google_update_targeting") return this.targeting.plan(op);
|
|
355
2379
|
const cid = normalizeCustomerId(op.accountId);
|
|
356
2380
|
const payload = op.payload;
|
|
357
2381
|
switch (op.tool) {
|
|
@@ -369,6 +2393,10 @@ var GoogleAdsProvider = class {
|
|
|
369
2393
|
return this.planAddKeywords(cid, payload);
|
|
370
2394
|
case "google_set_keyword_status":
|
|
371
2395
|
return this.planSetKeywordStatus(cid, payload);
|
|
2396
|
+
case "google_set_ad_status":
|
|
2397
|
+
return this.planSetAdStatus(cid, payload);
|
|
2398
|
+
case "google_update_responsive_search_ad":
|
|
2399
|
+
return this.planUpdateRsa(cid, payload);
|
|
372
2400
|
case "google_remove_keywords":
|
|
373
2401
|
return this.planRemoveKeywords(cid, payload);
|
|
374
2402
|
case "google_create_responsive_search_ad":
|
|
@@ -384,7 +2412,7 @@ var GoogleAdsProvider = class {
|
|
|
384
2412
|
case "google_api_remove":
|
|
385
2413
|
return this.planApiRemove(cid, payload);
|
|
386
2414
|
default:
|
|
387
|
-
throw new
|
|
2415
|
+
throw new AdportError10("PROVIDER_ERROR", `google: unsupported write tool ${op.tool}`);
|
|
388
2416
|
}
|
|
389
2417
|
}
|
|
390
2418
|
async planApiCreate(cid, payload, guard) {
|
|
@@ -392,31 +2420,31 @@ var GoogleAdsProvider = class {
|
|
|
392
2420
|
const creates = structuredClone(payload.creates);
|
|
393
2421
|
validateCustomerReferences(creates, cid);
|
|
394
2422
|
const coercions = [];
|
|
395
|
-
if (guard.forcePausedCreation &&
|
|
396
|
-
for (const [index,
|
|
397
|
-
if (
|
|
398
|
-
|
|
2423
|
+
if (guard.forcePausedCreation && ["campaigns", "adGroups", "adGroupAds", "assetGroups"].includes(service)) {
|
|
2424
|
+
for (const [index, create3] of creates.entries()) {
|
|
2425
|
+
if (create3.status !== "PAUSED") {
|
|
2426
|
+
create3.status = "PAUSED";
|
|
399
2427
|
coercions.push(`creates[${index}].status coerced to PAUSED by policy (paused_creation)`);
|
|
400
2428
|
}
|
|
401
2429
|
}
|
|
402
2430
|
}
|
|
403
2431
|
const budgetDeltas = service === "campaignBudgets" ? collectGoogleBudgetCreates(creates) : [];
|
|
404
|
-
const operations = creates.map((
|
|
2432
|
+
const operations = creates.map((create3) => ({ create: create3 }));
|
|
405
2433
|
return {
|
|
406
2434
|
summary: `Create ${creates.length} Google Ads ${service} resource(s)`,
|
|
407
|
-
changes: creates.map((
|
|
2435
|
+
changes: creates.map((create3) => `+ ${service} ${JSON.stringify(create3)}`),
|
|
408
2436
|
coercions,
|
|
409
2437
|
budgetDeltas,
|
|
410
2438
|
execute: async (validateOnly) => {
|
|
411
|
-
const
|
|
412
|
-
return (
|
|
2439
|
+
const result2 = await this.client.mutate(cid, service, operations, { validateOnly });
|
|
2440
|
+
return (result2.results ?? []).flatMap((item) => item.resourceName ? [item.resourceName] : []);
|
|
413
2441
|
}
|
|
414
2442
|
};
|
|
415
2443
|
}
|
|
416
2444
|
async planApiUpdate(cid, payload) {
|
|
417
2445
|
const service = validateGoogleService(payload.service);
|
|
418
2446
|
if (service === "campaignBudgets" || payload.updates.some((item) => /budget/i.test(item.update_mask))) {
|
|
419
|
-
throw new
|
|
2447
|
+
throw new AdportError10(
|
|
420
2448
|
"INVALID_INPUT",
|
|
421
2449
|
"google: budget updates require google_set_budget so the current and proposed values can be policy-checked"
|
|
422
2450
|
);
|
|
@@ -429,23 +2457,23 @@ var GoogleAdsProvider = class {
|
|
|
429
2457
|
coercions: [],
|
|
430
2458
|
budgetDeltas: [],
|
|
431
2459
|
execute: async (validateOnly) => {
|
|
432
|
-
const
|
|
433
|
-
return (
|
|
2460
|
+
const result2 = await this.client.mutate(cid, service, operations, { validateOnly });
|
|
2461
|
+
return (result2.results ?? []).flatMap((item) => item.resourceName ? [item.resourceName] : []);
|
|
434
2462
|
}
|
|
435
2463
|
};
|
|
436
2464
|
}
|
|
437
2465
|
async planApiRemove(cid, payload) {
|
|
438
2466
|
const service = validateGoogleService(payload.service);
|
|
439
2467
|
validateCustomerReferences(payload.resource_names, cid);
|
|
440
|
-
const operations = payload.resource_names.map((
|
|
2468
|
+
const operations = payload.resource_names.map((remove2) => ({ remove: remove2 }));
|
|
441
2469
|
return {
|
|
442
2470
|
summary: `Permanently remove ${operations.length} Google Ads ${service} resource(s)`,
|
|
443
|
-
changes: payload.resource_names.map((
|
|
2471
|
+
changes: payload.resource_names.map((name5) => `- ${name5}`),
|
|
444
2472
|
coercions: [],
|
|
445
2473
|
budgetDeltas: [],
|
|
446
2474
|
execute: async (validateOnly) => {
|
|
447
|
-
const
|
|
448
|
-
return (
|
|
2475
|
+
const result2 = await this.client.mutate(cid, service, operations, { validateOnly });
|
|
2476
|
+
return (result2.results ?? []).map((item, index) => item.resourceName ?? payload.resource_names[index]);
|
|
449
2477
|
}
|
|
450
2478
|
};
|
|
451
2479
|
}
|
|
@@ -457,8 +2485,10 @@ var GoogleAdsProvider = class {
|
|
|
457
2485
|
coercions.push("status coerced to PAUSED by policy (paused_creation)");
|
|
458
2486
|
}
|
|
459
2487
|
const channelType = payload.channel_type ?? "SEARCH";
|
|
2488
|
+
if (channelType === "SEARCH" && payload.language_ids?.length) throw new AdportError10("INVALID_INPUT", "google: Search no longer supports manual language criteria. Omit language_ids; matching uses creative/landing-page language and user preferences. Existing legacy language criteria can only be removed.");
|
|
2489
|
+
if (channelType === "PERFORMANCE_MAX") throw new AdportError10("INVALID_INPUT", "google: use google_create_performance_max_campaign to create the complete campaign, brand assets and asset-group hierarchy atomically");
|
|
460
2490
|
if (channelType !== "SEARCH" && (payload.search_partners !== void 0 || payload.display_expansion !== void 0)) {
|
|
461
|
-
throw new
|
|
2491
|
+
throw new AdportError10("INVALID_INPUT", "search_partners and display_expansion require a SEARCH campaign");
|
|
462
2492
|
}
|
|
463
2493
|
const strategy = payload.bidding_strategy ?? "MANUAL_CPC";
|
|
464
2494
|
const strategyField = { MANUAL_CPC: "manualCpc", MAXIMIZE_CLICKS: "targetSpend", MAXIMIZE_CONVERSIONS: "maximizeConversions", MAXIMIZE_CONVERSION_VALUE: "maximizeConversionValue" }[strategy];
|
|
@@ -581,20 +2611,20 @@ var GoogleAdsProvider = class {
|
|
|
581
2611
|
}
|
|
582
2612
|
async planCreateAdGroup(cid, payload) {
|
|
583
2613
|
const campaign = await this.lookupCampaign(cid, payload.campaign_id);
|
|
584
|
-
const
|
|
2614
|
+
const create3 = {
|
|
585
2615
|
name: payload.name,
|
|
586
2616
|
campaign: `customers/${cid}/campaigns/${payload.campaign_id}`,
|
|
587
2617
|
status: "ENABLED",
|
|
588
2618
|
type: "SEARCH_STANDARD"
|
|
589
2619
|
};
|
|
590
|
-
if (payload.cpc_bid_micros)
|
|
2620
|
+
if (payload.cpc_bid_micros) create3.cpcBidMicros = String(payload.cpc_bid_micros);
|
|
591
2621
|
return {
|
|
592
2622
|
summary: `Create ad group "${payload.name}" in campaign "${campaign.name}"`,
|
|
593
2623
|
changes: [`+ ad_group "${payload.name}" in campaign ${payload.campaign_id} (ENABLED \u2014 inherits campaign state)`],
|
|
594
2624
|
coercions: [],
|
|
595
2625
|
budgetDeltas: [],
|
|
596
2626
|
execute: async (validateOnly) => {
|
|
597
|
-
const res = await this.client.mutate(cid, "adGroups", [{ create }], { validateOnly });
|
|
2627
|
+
const res = await this.client.mutate(cid, "adGroups", [{ create: create3 }], { validateOnly });
|
|
598
2628
|
return (res.results ?? []).map((r) => r.resourceName ?? "");
|
|
599
2629
|
}
|
|
600
2630
|
};
|
|
@@ -658,7 +2688,7 @@ var GoogleAdsProvider = class {
|
|
|
658
2688
|
}
|
|
659
2689
|
async planRemoveKeywords(cid, payload) {
|
|
660
2690
|
const resourceNames = payload.criterion_ids.map(
|
|
661
|
-
(
|
|
2691
|
+
(id8) => `customers/${cid}/adGroupCriteria/${payload.ad_group_id}~${id8}`
|
|
662
2692
|
);
|
|
663
2693
|
return {
|
|
664
2694
|
summary: `PERMANENTLY remove ${resourceNames.length} keyword criteria from ad group ${payload.ad_group_id}`,
|
|
@@ -669,26 +2699,97 @@ var GoogleAdsProvider = class {
|
|
|
669
2699
|
const res = await this.client.mutate(
|
|
670
2700
|
cid,
|
|
671
2701
|
"adGroupCriteria",
|
|
672
|
-
resourceNames.map((
|
|
2702
|
+
resourceNames.map((remove2) => ({ remove: remove2 })),
|
|
673
2703
|
{ validateOnly }
|
|
674
2704
|
);
|
|
675
2705
|
return (res.results ?? []).map((r) => r.resourceName ?? "");
|
|
676
2706
|
}
|
|
677
2707
|
};
|
|
678
2708
|
}
|
|
2709
|
+
async planSetAdStatus(cid, payload) {
|
|
2710
|
+
const resourceName = `customers/${cid}/adGroupAds/${payload.ad_group_id}~${payload.ad_id}`;
|
|
2711
|
+
const rows = await this.client.search(
|
|
2712
|
+
cid,
|
|
2713
|
+
`SELECT ad_group_ad.resource_name, ad_group_ad.status FROM ad_group_ad WHERE ad_group.id = ${payload.ad_group_id} AND ad_group_ad.ad.id = ${payload.ad_id} LIMIT 2`,
|
|
2714
|
+
{ maxRows: 2, includeDrafts: true }
|
|
2715
|
+
);
|
|
2716
|
+
const current = rows[0]?.adGroupAd;
|
|
2717
|
+
if (rows.length !== 1 || current?.resourceName !== resourceName || current.status === "REMOVED") {
|
|
2718
|
+
throw new AdportError10("INVALID_INPUT", "google: ad was not found in the selected account and ad group, or has been removed");
|
|
2719
|
+
}
|
|
2720
|
+
return {
|
|
2721
|
+
summary: `Set ad ${payload.ad_id} status ${current.status ?? "unknown"} \u2192 ${payload.status}`,
|
|
2722
|
+
changes: [`~ ad ${payload.ad_id} status ${current.status ?? "unknown"} \u2192 ${payload.status}`],
|
|
2723
|
+
coercions: [],
|
|
2724
|
+
budgetDeltas: [],
|
|
2725
|
+
execute: async (validateOnly) => {
|
|
2726
|
+
const result2 = await this.client.mutate(cid, "adGroupAds", [
|
|
2727
|
+
{ update: { resourceName, status: payload.status }, updateMask: "status" }
|
|
2728
|
+
], { validateOnly });
|
|
2729
|
+
return (result2.results ?? []).map((item) => item.resourceName ?? resourceName);
|
|
2730
|
+
}
|
|
2731
|
+
};
|
|
2732
|
+
}
|
|
2733
|
+
async planUpdateRsa(cid, payload) {
|
|
2734
|
+
const rows = await this.client.search(
|
|
2735
|
+
cid,
|
|
2736
|
+
`SELECT ad_group_ad.resource_name, ad_group_ad.ad.id, ad_group_ad.ad.type, ad_group_ad.ad.final_urls, ad_group_ad.ad.responsive_search_ad.headlines, ad_group_ad.ad.responsive_search_ad.descriptions, ad_group_ad.ad.responsive_search_ad.path1, ad_group_ad.ad.responsive_search_ad.path2 FROM ad_group_ad WHERE ad_group.id = ${payload.ad_group_id} AND ad_group_ad.ad.id = ${payload.ad_id} AND ad_group_ad.status != 'REMOVED' LIMIT 2`,
|
|
2737
|
+
{ maxRows: 2, includeDrafts: true }
|
|
2738
|
+
);
|
|
2739
|
+
const groupAd = rows[0]?.adGroupAd;
|
|
2740
|
+
if (rows.length !== 1 || groupAd?.resourceName !== `customers/${cid}/adGroupAds/${payload.ad_group_id}~${payload.ad_id}` || groupAd.ad?.type !== "RESPONSIVE_SEARCH_AD") {
|
|
2741
|
+
throw new AdportError10("INVALID_INPUT", "google: responsive search ad was not found in the selected account and ad group");
|
|
2742
|
+
}
|
|
2743
|
+
const current = groupAd.ad;
|
|
2744
|
+
const update3 = { resourceName: `customers/${cid}/ads/${payload.ad_id}` };
|
|
2745
|
+
const responsiveSearchAd = {};
|
|
2746
|
+
const mask = [], changes = [];
|
|
2747
|
+
for (const key2 of ["headlines", "descriptions"]) {
|
|
2748
|
+
if (payload[key2] === void 0) continue;
|
|
2749
|
+
const existing = current.responsiveSearchAd?.[key2] ?? [];
|
|
2750
|
+
responsiveSearchAd[key2] = payload[key2].map((text2, index) => ({
|
|
2751
|
+
text: text2,
|
|
2752
|
+
...existing[index]?.pinnedField && existing[index].pinnedField !== "UNSPECIFIED" ? { pinnedField: existing[index].pinnedField } : {}
|
|
2753
|
+
}));
|
|
2754
|
+
mask.push(`responsive_search_ad.${key2}`);
|
|
2755
|
+
changes.push(`~ ad ${payload.ad_id} ${key2} ${JSON.stringify(existing.map((item) => item.text))} \u2192 ${JSON.stringify(payload[key2])}`);
|
|
2756
|
+
}
|
|
2757
|
+
for (const key2 of ["path1", "path2"]) {
|
|
2758
|
+
if (payload[key2] === void 0) continue;
|
|
2759
|
+
responsiveSearchAd[key2] = payload[key2];
|
|
2760
|
+
mask.push(`responsive_search_ad.${key2}`);
|
|
2761
|
+
changes.push(`~ ad ${payload.ad_id} ${key2} ${current.responsiveSearchAd?.[key2] ?? "(unset)"} \u2192 ${payload[key2] || "(cleared)"}`);
|
|
2762
|
+
}
|
|
2763
|
+
if (Object.keys(responsiveSearchAd).length) update3.responsiveSearchAd = responsiveSearchAd;
|
|
2764
|
+
if (payload.final_urls !== void 0) {
|
|
2765
|
+
update3.finalUrls = payload.final_urls;
|
|
2766
|
+
mask.push("final_urls");
|
|
2767
|
+
changes.push(`~ ad ${payload.ad_id} final URLs ${JSON.stringify(current.finalUrls ?? [])} \u2192 ${JSON.stringify(payload.final_urls)}`);
|
|
2768
|
+
}
|
|
2769
|
+
return {
|
|
2770
|
+
summary: `Update responsive search ad ${payload.ad_id} content`,
|
|
2771
|
+
changes,
|
|
2772
|
+
coercions: [],
|
|
2773
|
+
budgetDeltas: [],
|
|
2774
|
+
execute: async (validateOnly) => {
|
|
2775
|
+
const result2 = await this.client.mutate(cid, "ads", [{ update: update3, updateMask: mask.join(",") }], { validateOnly });
|
|
2776
|
+
return (result2.results ?? []).map((item) => item.resourceName ?? String(update3.resourceName));
|
|
2777
|
+
}
|
|
2778
|
+
};
|
|
2779
|
+
}
|
|
679
2780
|
async planCreateRsa(cid, payload, guard) {
|
|
680
2781
|
validateRsa(payload);
|
|
681
2782
|
const coercions = [];
|
|
682
2783
|
const status = guard.forcePausedCreation ? "PAUSED" : "ENABLED";
|
|
683
2784
|
if (guard.forcePausedCreation) coercions.push("ad created PAUSED by policy (paused_creation)");
|
|
684
|
-
const
|
|
2785
|
+
const create3 = {
|
|
685
2786
|
adGroup: `customers/${cid}/adGroups/${payload.ad_group_id}`,
|
|
686
2787
|
status,
|
|
687
2788
|
ad: {
|
|
688
2789
|
finalUrls: payload.final_urls,
|
|
689
2790
|
responsiveSearchAd: {
|
|
690
|
-
headlines: payload.headlines.map((
|
|
691
|
-
descriptions: payload.descriptions.map((
|
|
2791
|
+
headlines: payload.headlines.map((text2) => ({ text: text2 })),
|
|
2792
|
+
descriptions: payload.descriptions.map((text2) => ({ text: text2 })),
|
|
692
2793
|
...payload.path1 ? { path1: payload.path1 } : {},
|
|
693
2794
|
...payload.path2 ? { path2: payload.path2 } : {}
|
|
694
2795
|
}
|
|
@@ -700,7 +2801,7 @@ var GoogleAdsProvider = class {
|
|
|
700
2801
|
coercions,
|
|
701
2802
|
budgetDeltas: [],
|
|
702
2803
|
execute: async (validateOnly) => {
|
|
703
|
-
const res = await this.client.mutate(cid, "adGroupAds", [{ create }], { validateOnly });
|
|
2804
|
+
const res = await this.client.mutate(cid, "adGroupAds", [{ create: create3 }], { validateOnly });
|
|
704
2805
|
return (res.results ?? []).map((r) => r.resourceName ?? "");
|
|
705
2806
|
}
|
|
706
2807
|
};
|
|
@@ -709,19 +2810,19 @@ var GoogleAdsProvider = class {
|
|
|
709
2810
|
async planSetBidCeiling(cid, payload) {
|
|
710
2811
|
const current = await this.lookupCampaignBidding(cid, payload.campaign_id);
|
|
711
2812
|
const resourceName = `customers/${cid}/campaigns/${payload.campaign_id}`;
|
|
712
|
-
let
|
|
2813
|
+
let update3;
|
|
713
2814
|
let updateMask;
|
|
714
2815
|
if (current.strategyType === "TARGET_SPEND") {
|
|
715
|
-
|
|
2816
|
+
update3 = { resourceName, targetSpend: { cpcBidCeilingMicros: String(payload.cpc_bid_ceiling_micros) } };
|
|
716
2817
|
updateMask = "target_spend.cpc_bid_ceiling_micros";
|
|
717
2818
|
} else if (current.strategyType === "TARGET_IMPRESSION_SHARE") {
|
|
718
|
-
|
|
2819
|
+
update3 = {
|
|
719
2820
|
resourceName,
|
|
720
2821
|
targetImpressionShare: { cpcBidCeilingMicros: String(payload.cpc_bid_ceiling_micros) }
|
|
721
2822
|
};
|
|
722
2823
|
updateMask = "target_impression_share.cpc_bid_ceiling_micros";
|
|
723
2824
|
} else {
|
|
724
|
-
throw new
|
|
2825
|
+
throw new AdportError10(
|
|
725
2826
|
"PROVIDER_ERROR",
|
|
726
2827
|
`google: campaign "${current.name}" uses ${current.strategyType} bidding, which has no CPC bid ceiling. Use google_set_bidding_strategy to switch strategy (e.g. MAXIMIZE_CLICKS supports a ceiling).`
|
|
727
2828
|
);
|
|
@@ -734,20 +2835,20 @@ var GoogleAdsProvider = class {
|
|
|
734
2835
|
coercions: [],
|
|
735
2836
|
budgetDeltas: [],
|
|
736
2837
|
execute: async (validateOnly) => {
|
|
737
|
-
const res = await this.client.mutate(cid, "campaigns", [{ update, updateMask }], { validateOnly });
|
|
2838
|
+
const res = await this.client.mutate(cid, "campaigns", [{ update: update3, updateMask }], { validateOnly });
|
|
738
2839
|
return (res.results ?? []).map((r) => r.resourceName ?? resourceName);
|
|
739
2840
|
}
|
|
740
2841
|
};
|
|
741
2842
|
}
|
|
742
2843
|
async planSetBiddingStrategy(cid, payload) {
|
|
743
2844
|
if (payload.target_cpa_micros && payload.strategy !== "MAXIMIZE_CONVERSIONS") {
|
|
744
|
-
throw new
|
|
2845
|
+
throw new AdportError10("INVALID_INPUT", "target_cpa_micros only applies to MAXIMIZE_CONVERSIONS");
|
|
745
2846
|
}
|
|
746
2847
|
if (payload.target_roas && payload.strategy !== "MAXIMIZE_CONVERSION_VALUE") {
|
|
747
|
-
throw new
|
|
2848
|
+
throw new AdportError10("INVALID_INPUT", "target_roas only applies to MAXIMIZE_CONVERSION_VALUE");
|
|
748
2849
|
}
|
|
749
2850
|
if (payload.cpc_bid_ceiling_micros && payload.strategy !== "MAXIMIZE_CLICKS") {
|
|
750
|
-
throw new
|
|
2851
|
+
throw new AdportError10("INVALID_INPUT", "cpc_bid_ceiling_micros only applies to MAXIMIZE_CLICKS (target spend)");
|
|
751
2852
|
}
|
|
752
2853
|
const current = await this.lookupCampaignBidding(cid, payload.campaign_id);
|
|
753
2854
|
const resourceName = `customers/${cid}/campaigns/${payload.campaign_id}`;
|
|
@@ -798,16 +2899,17 @@ var GoogleAdsProvider = class {
|
|
|
798
2899
|
};
|
|
799
2900
|
}
|
|
800
2901
|
async lookupCampaignBidding(cid, campaignId) {
|
|
2902
|
+
if (!/^\d+$/.test(campaignId)) throw new AdportError10("INVALID_INPUT", "google: invalid campaign ID");
|
|
801
2903
|
const rows = await this.client.search(
|
|
802
2904
|
cid,
|
|
803
|
-
`SELECT campaign.name, campaign.bidding_strategy_type, campaign.target_spend.cpc_bid_ceiling_micros, campaign.target_impression_share.cpc_bid_ceiling_micros FROM campaign WHERE campaign.id = ${
|
|
804
|
-
{ maxRows: 1 }
|
|
2905
|
+
`SELECT campaign.name, campaign.bidding_strategy_type, campaign.target_spend.cpc_bid_ceiling_micros, campaign.target_impression_share.cpc_bid_ceiling_micros FROM campaign WHERE campaign.id = ${campaignId} LIMIT 1`,
|
|
2906
|
+
{ maxRows: 1, includeDrafts: true }
|
|
805
2907
|
);
|
|
806
|
-
const
|
|
807
|
-
if (!
|
|
808
|
-
throw new
|
|
2908
|
+
const row2 = rows[0];
|
|
2909
|
+
if (!row2) {
|
|
2910
|
+
throw new AdportError10("PROVIDER_ERROR", `google: campaign ${campaignId} not found in account ${cid}`);
|
|
809
2911
|
}
|
|
810
|
-
const campaign =
|
|
2912
|
+
const campaign = row2.campaign;
|
|
811
2913
|
const ceiling = campaign.targetSpend?.cpcBidCeilingMicros ?? campaign.targetImpressionShare?.cpcBidCeilingMicros;
|
|
812
2914
|
return {
|
|
813
2915
|
name: campaign.name ?? campaignId,
|
|
@@ -816,17 +2918,18 @@ var GoogleAdsProvider = class {
|
|
|
816
2918
|
};
|
|
817
2919
|
}
|
|
818
2920
|
async lookupCampaign(cid, campaignId) {
|
|
2921
|
+
if (!/^\d+$/.test(campaignId)) throw new AdportError10("INVALID_INPUT", "google: invalid campaign ID");
|
|
819
2922
|
const rows = await this.client.search(
|
|
820
2923
|
cid,
|
|
821
|
-
`SELECT campaign.name, campaign.status, campaign.campaign_budget, campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.explicitly_shared FROM campaign WHERE campaign.id = ${
|
|
822
|
-
{ maxRows: 1 }
|
|
2924
|
+
`SELECT campaign.name, campaign.status, campaign.campaign_budget, campaign_budget.resource_name, campaign_budget.amount_micros, campaign_budget.explicitly_shared FROM campaign WHERE campaign.id = ${campaignId} LIMIT 1`,
|
|
2925
|
+
{ maxRows: 1, includeDrafts: true }
|
|
823
2926
|
);
|
|
824
|
-
const
|
|
825
|
-
if (!
|
|
826
|
-
throw new
|
|
2927
|
+
const row2 = rows[0];
|
|
2928
|
+
if (!row2) {
|
|
2929
|
+
throw new AdportError10("PROVIDER_ERROR", `google: campaign ${campaignId} not found in account ${cid}`);
|
|
827
2930
|
}
|
|
828
|
-
const campaign =
|
|
829
|
-
const budget =
|
|
2931
|
+
const campaign = row2.campaign;
|
|
2932
|
+
const budget = row2.campaignBudget ?? {};
|
|
830
2933
|
return {
|
|
831
2934
|
name: campaign.name ?? campaignId,
|
|
832
2935
|
status: campaign.status ?? "UNKNOWN",
|
|
@@ -844,12 +2947,12 @@ function validateRsa(payload) {
|
|
|
844
2947
|
for (const h of payload.headlines) if (h.length > 30) problems.push(`headline over 30 chars: "${h}"`);
|
|
845
2948
|
for (const d of payload.descriptions) if (d.length > 90) problems.push(`description over 90 chars: "${d}"`);
|
|
846
2949
|
if (problems.length > 0) {
|
|
847
|
-
throw new
|
|
2950
|
+
throw new AdportError10("INVALID_INPUT", `Responsive search ad invalid: ${problems.join("; ")}`);
|
|
848
2951
|
}
|
|
849
2952
|
}
|
|
850
2953
|
function validateGoogleService(service) {
|
|
851
2954
|
if (!/^[a-z][A-Za-z0-9]{1,80}$/.test(service)) {
|
|
852
|
-
throw new
|
|
2955
|
+
throw new AdportError10("INVALID_INPUT", `google: invalid mutate service "${service}"`);
|
|
853
2956
|
}
|
|
854
2957
|
return service;
|
|
855
2958
|
}
|
|
@@ -862,7 +2965,7 @@ function validateCustomerReferences(value, customerId) {
|
|
|
862
2965
|
if (typeof value === "string") {
|
|
863
2966
|
const match = /^customers\/(\d+)/.exec(value);
|
|
864
2967
|
if (match && match[1] !== customerId) {
|
|
865
|
-
throw new
|
|
2968
|
+
throw new AdportError10("INVALID_INPUT", `google: resource reference belongs to customer ${match[1]}, not ${customerId}`);
|
|
866
2969
|
}
|
|
867
2970
|
}
|
|
868
2971
|
return;
|
|
@@ -870,15 +2973,15 @@ function validateCustomerReferences(value, customerId) {
|
|
|
870
2973
|
Object.values(value).forEach((item) => validateCustomerReferences(item, customerId));
|
|
871
2974
|
}
|
|
872
2975
|
function collectGoogleBudgetCreates(creates) {
|
|
873
|
-
return creates.map((
|
|
874
|
-
const amount = Number(
|
|
2976
|
+
return creates.map((create3, index) => {
|
|
2977
|
+
const amount = Number(create3.amountMicros);
|
|
875
2978
|
if (!Number.isSafeInteger(amount) || amount <= 0) {
|
|
876
|
-
throw new
|
|
2979
|
+
throw new AdportError10(
|
|
877
2980
|
"INVALID_INPUT",
|
|
878
2981
|
`google: campaignBudgets create ${index} must include a positive integer amountMicros for policy checks`
|
|
879
2982
|
);
|
|
880
2983
|
}
|
|
881
|
-
return { target: `new campaign budget ${String(
|
|
2984
|
+
return { target: `new campaign budget ${String(create3.name ?? index)}`, toMicros: amount };
|
|
882
2985
|
});
|
|
883
2986
|
}
|
|
884
2987
|
function round2(n) {
|
|
@@ -886,189 +2989,388 @@ function round2(n) {
|
|
|
886
2989
|
}
|
|
887
2990
|
|
|
888
2991
|
// src/tools.ts
|
|
889
|
-
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
890
|
-
import { z } from "zod";
|
|
891
|
-
|
|
892
|
-
|
|
2992
|
+
import { creativesOutput as creativesOutput4, defineTool as defineTool11, guardedWriteTool as guardedWriteTool9 } from "@adport/core";
|
|
2993
|
+
import { z as z12 } from "zod";
|
|
2994
|
+
|
|
2995
|
+
// src/planning.ts
|
|
2996
|
+
import { AdportError as AdportError11, defineTool as defineTool9 } from "@adport/core";
|
|
2997
|
+
import { z as z10 } from "zod";
|
|
2998
|
+
var identifier2 = z10.string().regex(/^\d+$/);
|
|
2999
|
+
var keywords = z10.array(z10.string().trim().min(1).max(500));
|
|
3000
|
+
var url3 = z10.string().url().refine((value) => {
|
|
3001
|
+
const parsed = new URL(value);
|
|
3002
|
+
return ["https:", "http:"].includes(parsed.protocol) && !parsed.username && !parsed.password;
|
|
3003
|
+
}, "Use an HTTP(S) URL without credentials");
|
|
3004
|
+
var targeting = {
|
|
3005
|
+
account_id: z10.string(),
|
|
3006
|
+
language_id: identifier2.optional(),
|
|
3007
|
+
location_ids: z10.array(identifier2).max(10).default([]),
|
|
3008
|
+
network: z10.enum(["GOOGLE_SEARCH", "GOOGLE_SEARCH_AND_PARTNERS"]).default("GOOGLE_SEARCH"),
|
|
3009
|
+
include_adult_keywords: z10.boolean().default(false),
|
|
3010
|
+
include_average_cpc: z10.boolean().default(false)
|
|
3011
|
+
};
|
|
3012
|
+
var nativeResult = z10.record(z10.string(), z10.unknown());
|
|
3013
|
+
var output = z10.object({
|
|
3014
|
+
results: z10.array(nativeResult),
|
|
3015
|
+
aggregate_metric_results: nativeResult.optional(),
|
|
3016
|
+
next_page_token: z10.string().optional(),
|
|
3017
|
+
total_size: z10.string().regex(/^\d+$/).optional(),
|
|
3018
|
+
truncated: z10.boolean()
|
|
3019
|
+
});
|
|
3020
|
+
var ideasInput = z10.object({
|
|
3021
|
+
...targeting,
|
|
3022
|
+
seed: z10.discriminatedUnion("type", [
|
|
3023
|
+
z10.object({ type: z10.literal("keywords"), keywords: keywords.min(1).max(20) }),
|
|
3024
|
+
z10.object({ type: z10.literal("url"), url: url3 }),
|
|
3025
|
+
z10.object({ type: z10.literal("keywords_and_url"), keywords: keywords.min(1).max(20), url: url3 }),
|
|
3026
|
+
z10.object({ type: z10.literal("site"), url: url3 })
|
|
3027
|
+
]),
|
|
3028
|
+
page_size: z10.number().int().positive().max(1e4).default(100),
|
|
3029
|
+
page_token: z10.string().min(1).max(1e4).optional()
|
|
3030
|
+
});
|
|
3031
|
+
var historicalInput = z10.object({ ...targeting, keywords: keywords.min(1).max(1e4) });
|
|
3032
|
+
function target3(input2) {
|
|
3033
|
+
return {
|
|
3034
|
+
...input2.language_id ? { language: `languageConstants/${input2.language_id}` } : {},
|
|
3035
|
+
geoTargetConstants: input2.location_ids.map((value) => `geoTargetConstants/${value}`),
|
|
3036
|
+
keywordPlanNetwork: input2.network,
|
|
3037
|
+
includeAdultKeywords: input2.include_adult_keywords,
|
|
3038
|
+
historicalMetricsOptions: { includeAverageCpc: input2.include_average_cpc }
|
|
3039
|
+
};
|
|
3040
|
+
}
|
|
3041
|
+
function result(data) {
|
|
3042
|
+
const rows = data.results ?? [];
|
|
3043
|
+
const token = data.nextPageToken;
|
|
3044
|
+
const total = data.totalSize;
|
|
3045
|
+
const parsed = output.safeParse({
|
|
3046
|
+
results: rows,
|
|
3047
|
+
...data.aggregateMetricResults === void 0 ? {} : { aggregate_metric_results: data.aggregateMetricResults },
|
|
3048
|
+
...token === void 0 || token === "" ? {} : { next_page_token: token },
|
|
3049
|
+
...total === void 0 ? {} : { total_size: total },
|
|
3050
|
+
truncated: typeof token === "string" && token.length > 0
|
|
3051
|
+
});
|
|
3052
|
+
if (!parsed.success) throw new AdportError11("PROVIDER_ERROR", "Google keyword planning returned an invalid response shape");
|
|
3053
|
+
return parsed.data;
|
|
3054
|
+
}
|
|
3055
|
+
function googlePlanningTools(provider) {
|
|
3056
|
+
return [
|
|
3057
|
+
defineTool9({
|
|
3058
|
+
name: "google_keyword_ideas",
|
|
3059
|
+
namespace: "google",
|
|
3060
|
+
description: "Discover keyword ideas from keywords, a URL, both, or a site. Reads one native page; pass next_page_token as page_token with identical targeting and seed. Metrics are historical estimates, not a forecast. No keyword plan or campaign is created.",
|
|
3061
|
+
input: ideasInput,
|
|
3062
|
+
output,
|
|
3063
|
+
annotations: { readOnly: true },
|
|
3064
|
+
async handler(input2) {
|
|
3065
|
+
const seed = input2.seed;
|
|
3066
|
+
const body = {
|
|
3067
|
+
...target3(input2),
|
|
3068
|
+
pageSize: input2.page_size,
|
|
3069
|
+
...input2.page_token ? { pageToken: input2.page_token } : {},
|
|
3070
|
+
...seed.type === "keywords" ? { keywordSeed: { keywords: seed.keywords } } : seed.type === "url" ? { urlSeed: { url: seed.url } } : seed.type === "keywords_and_url" ? { keywordAndUrlSeed: { keywords: seed.keywords, url: seed.url } } : { siteSeed: { site: seed.url } }
|
|
3071
|
+
};
|
|
3072
|
+
return result(await provider.keywordPlanning(normalizeCustomerId(input2.account_id), "generateKeywordIdeas", body));
|
|
3073
|
+
}
|
|
3074
|
+
}),
|
|
3075
|
+
defineTool9({
|
|
3076
|
+
name: "google_keyword_historical_metrics",
|
|
3077
|
+
namespace: "google",
|
|
3078
|
+
description: "Read native historical search volume, competition and bid estimates for up to 10,000 keywords. Google merges close variants; missing values stay unavailable and monetary int64 values remain native micros strings. Does not create a keyword plan or campaign.",
|
|
3079
|
+
input: historicalInput,
|
|
3080
|
+
output,
|
|
3081
|
+
annotations: { readOnly: true },
|
|
3082
|
+
handler: async (input2) => result(await provider.keywordPlanning(normalizeCustomerId(input2.account_id), "generateKeywordHistoricalMetrics", { ...target3(input2), keywords: input2.keywords }))
|
|
3083
|
+
})
|
|
3084
|
+
];
|
|
3085
|
+
}
|
|
3086
|
+
|
|
3087
|
+
// src/field-metadata.ts
|
|
3088
|
+
import { AdportError as AdportError12, defineTool as defineTool10 } from "@adport/core";
|
|
3089
|
+
import { z as z11 } from "zod";
|
|
3090
|
+
var fieldName = z11.string().regex(/^[a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)*$/).max(200);
|
|
3091
|
+
var input = z11.object({
|
|
3092
|
+
account_id: z11.string(),
|
|
3093
|
+
field_names: z11.array(fieldName).min(1).max(20).refine((values) => new Set(values).size === values.length, "Field names must be unique"),
|
|
3094
|
+
include_compatibility: z11.boolean().default(false),
|
|
3095
|
+
page_token: z11.string().min(1).max(16384).optional()
|
|
3096
|
+
});
|
|
3097
|
+
var field2 = z11.object({
|
|
3098
|
+
name: fieldName,
|
|
3099
|
+
resourceName: z11.string().optional(),
|
|
3100
|
+
category: z11.string().min(1),
|
|
3101
|
+
dataType: z11.string().min(1).optional(),
|
|
3102
|
+
typeUrl: z11.string().optional(),
|
|
3103
|
+
selectable: z11.boolean().optional(),
|
|
3104
|
+
filterable: z11.boolean().optional(),
|
|
3105
|
+
sortable: z11.boolean().optional(),
|
|
3106
|
+
isRepeated: z11.boolean().optional(),
|
|
3107
|
+
enumValues: z11.array(z11.string()).optional(),
|
|
3108
|
+
selectableWith: z11.array(z11.string()).optional(),
|
|
3109
|
+
attributeResources: z11.array(z11.string()).optional(),
|
|
3110
|
+
metrics: z11.array(z11.string()).optional(),
|
|
3111
|
+
segments: z11.array(z11.string()).optional()
|
|
3112
|
+
}).passthrough();
|
|
3113
|
+
var nativeOutput = z11.object({ results: z11.array(field2).default([]), nextPageToken: z11.string().optional(), totalResultsCount: z11.string().regex(/^\d+$/).optional() });
|
|
3114
|
+
var output2 = z11.object({ api_version: z11.string(), results: z11.array(field2), truncated: z11.boolean(), next_page_token: z11.string().optional(), total_results_count: z11.string().optional() });
|
|
3115
|
+
function googleFieldMetadataTools(provider) {
|
|
3116
|
+
return [defineTool10({
|
|
3117
|
+
name: "google_field_metadata",
|
|
3118
|
+
namespace: "google",
|
|
3119
|
+
description: "Look up up to 20 exact GAQL resource or field names in the connected API version. Returns native types, enums and queryability; optional compatibility lists can be large. API-wide metadata, not account performance. Continue next_page_token with identical names/options.",
|
|
3120
|
+
input,
|
|
3121
|
+
output: output2,
|
|
3122
|
+
annotations: { readOnly: true },
|
|
3123
|
+
pagination: { cursorInput: "page_token" },
|
|
3124
|
+
async handler(raw) {
|
|
3125
|
+
normalizeCustomerId(raw.account_id);
|
|
3126
|
+
const fields5 = ["name", "category", "data_type", "type_url", "is_repeated", "selectable", "filterable", "sortable", "enum_values", ...raw.include_compatibility ? ["selectable_with", "attribute_resources", "metrics", "segments"] : []];
|
|
3127
|
+
const query = `SELECT ${fields5.join(", ")} WHERE name IN (${raw.field_names.map((name5) => `'${name5}'`).join(", ")})`;
|
|
3128
|
+
const { apiVersion, response } = await provider.fieldMetadata(query, raw.field_names.length, raw.page_token), parsed = nativeOutput.safeParse(response);
|
|
3129
|
+
if (!parsed.success) throw new AdportError12("PROVIDER_ERROR", "google: invalid field metadata response");
|
|
3130
|
+
const result2 = parsed.data;
|
|
3131
|
+
if (result2.results.length > raw.field_names.length || new Set(result2.results.map((value) => value.name)).size !== result2.results.length || result2.results.some((value) => !raw.field_names.includes(value.name) || value.resourceName !== void 0 && value.resourceName !== `googleAdsFields/${value.name}`)) throw new AdportError12("PROVIDER_ERROR", "google: field metadata identity or requested selection mismatch");
|
|
3132
|
+
return { api_version: apiVersion, results: result2.results, truncated: Boolean(result2.nextPageToken), ...result2.nextPageToken ? { next_page_token: result2.nextPageToken } : {}, ...result2.totalResultsCount !== void 0 ? { total_results_count: result2.totalResultsCount } : {} };
|
|
3133
|
+
}
|
|
3134
|
+
})];
|
|
3135
|
+
}
|
|
3136
|
+
|
|
3137
|
+
// src/tools.ts
|
|
3138
|
+
var statusSchema = z12.enum(["ENABLED", "PAUSED"]);
|
|
3139
|
+
var matchTypeSchema = z12.enum(["EXACT", "PHRASE", "BROAD"]);
|
|
893
3140
|
function googleTools(provider) {
|
|
894
3141
|
return [
|
|
895
|
-
|
|
3142
|
+
...googlePlanningTools(provider),
|
|
3143
|
+
...googleAssetTools(provider),
|
|
3144
|
+
...googleAssetLinkTools(provider),
|
|
3145
|
+
...googleLabelTools(provider),
|
|
3146
|
+
...googleFieldMetadataTools(provider),
|
|
3147
|
+
...googleConversionTools(provider),
|
|
3148
|
+
...googleDataManagerTools(provider),
|
|
3149
|
+
...googleExperimentTools(provider),
|
|
3150
|
+
...googlePerformanceMaxTools(provider),
|
|
3151
|
+
...googleTargetingTools(provider),
|
|
3152
|
+
defineTool11({
|
|
3153
|
+
name: "google_ads",
|
|
3154
|
+
namespace: "google",
|
|
3155
|
+
description: "Browse Google Ads with their actual text, final URLs, serving status and creative actions. Filter by campaign or ad group. Changes requested from the creative viewer return a preview before approval.",
|
|
3156
|
+
input: z12.object({
|
|
3157
|
+
account_id: z12.string(),
|
|
3158
|
+
campaign_id: z12.string().regex(/^\d+$/).optional(),
|
|
3159
|
+
ad_group_id: z12.string().regex(/^\d+$/).optional(),
|
|
3160
|
+
include_drafts: z12.boolean().optional().describe("Include in-design experiment draft ads; off by default"),
|
|
3161
|
+
limit: z12.number().int().positive().max(200).default(50)
|
|
3162
|
+
}),
|
|
3163
|
+
output: creativesOutput4,
|
|
3164
|
+
presentation: "creatives",
|
|
3165
|
+
annotations: { readOnly: true },
|
|
3166
|
+
handler: (input2) => provider.listAds(input2)
|
|
3167
|
+
}),
|
|
3168
|
+
defineTool11({
|
|
896
3169
|
name: "google_gaql",
|
|
897
3170
|
namespace: "google",
|
|
898
3171
|
description: `Run a structured Google Ads (GAQL) query: pick a resource (campaign, ad_group, keyword_view, change_event, ...), fields (e.g. campaign.name, metrics.clicks, segments.date), optional conditions and ordering. Conditions are raw GAQL predicates, e.g. "segments.date DURING LAST_7_DAYS" or "campaign.status = 'ENABLED'".`,
|
|
899
|
-
input:
|
|
900
|
-
customer_id:
|
|
901
|
-
resource:
|
|
902
|
-
fields:
|
|
903
|
-
conditions:
|
|
904
|
-
order_by:
|
|
905
|
-
|
|
3172
|
+
input: z12.object({
|
|
3173
|
+
customer_id: z12.string().describe("10-digit account id, dashes ok"),
|
|
3174
|
+
resource: z12.string().min(1),
|
|
3175
|
+
fields: z12.array(z12.string()).min(1),
|
|
3176
|
+
conditions: z12.array(z12.string()).optional(),
|
|
3177
|
+
order_by: z12.array(z12.string()).optional(),
|
|
3178
|
+
include_drafts: z12.boolean().optional().describe("Include in-design experiment draft campaigns and children; off by default"),
|
|
3179
|
+
limit: z12.number().int().positive().max(1e4).default(200)
|
|
906
3180
|
}),
|
|
907
3181
|
annotations: { readOnly: true },
|
|
908
|
-
async handler(
|
|
909
|
-
const rows = await provider.gaqlSearch(
|
|
3182
|
+
async handler(input2) {
|
|
3183
|
+
const rows = await provider.gaqlSearch(input2);
|
|
910
3184
|
return { rows, row_count: rows.length };
|
|
911
3185
|
}
|
|
912
3186
|
}),
|
|
913
|
-
|
|
3187
|
+
guardedWriteTool9({
|
|
914
3188
|
name: "google_create_campaign",
|
|
915
3189
|
namespace: "google",
|
|
916
3190
|
description: "Create a campaign and non-shared budget atomically, with bidding and optional location/language targeting. Search defaults to Google Search only (no partners or Display expansion). Use google_gaql to resolve geo_target_constant and language_constant IDs. Ad groups, keywords and responsive search ads have separate explicit tools. Creation remains subject to paused-creation policy.",
|
|
917
3191
|
provider: "google",
|
|
918
3192
|
kind: "create",
|
|
919
|
-
payload:
|
|
920
|
-
name:
|
|
921
|
-
daily_budget_micros:
|
|
922
|
-
channel_type:
|
|
3193
|
+
payload: z12.object({
|
|
3194
|
+
name: z12.string().min(1),
|
|
3195
|
+
daily_budget_micros: z12.number().int().positive().describe("1 currency unit = 1,000,000 micros"),
|
|
3196
|
+
channel_type: z12.enum(["SEARCH", "DISPLAY", "SHOPPING", "VIDEO", "PERFORMANCE_MAX"]).default("SEARCH"),
|
|
923
3197
|
status: statusSchema.optional(),
|
|
924
|
-
bidding_strategy:
|
|
925
|
-
search_partners:
|
|
926
|
-
display_expansion:
|
|
927
|
-
location_ids:
|
|
928
|
-
language_ids:
|
|
929
|
-
location_presence_only:
|
|
3198
|
+
bidding_strategy: z12.enum(["MANUAL_CPC", "MAXIMIZE_CLICKS", "MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE"]).default("MANUAL_CPC"),
|
|
3199
|
+
search_partners: z12.boolean().optional().describe("SEARCH only; defaults false"),
|
|
3200
|
+
display_expansion: z12.boolean().optional().describe("SEARCH only; defaults false"),
|
|
3201
|
+
location_ids: z12.array(z12.string().regex(/^\d+$/)).min(1).max(100).optional().describe("Google geo target constant IDs; omitted means unrestricted locations"),
|
|
3202
|
+
language_ids: z12.array(z12.string().regex(/^\d+$/)).min(1).max(100).optional().describe("Eligible non-Search campaigns only. Search language matching is automatic; omit this field for Search."),
|
|
3203
|
+
location_presence_only: z12.boolean().optional().describe("Target people in locations rather than people interested in them; defaults true when locations are specified")
|
|
930
3204
|
})
|
|
931
3205
|
}),
|
|
932
|
-
|
|
3206
|
+
guardedWriteTool9({
|
|
933
3207
|
name: "google_set_campaign_status",
|
|
934
3208
|
namespace: "google",
|
|
935
3209
|
description: "Enable or pause a campaign.",
|
|
936
3210
|
provider: "google",
|
|
937
3211
|
kind: "update",
|
|
938
|
-
payload:
|
|
3212
|
+
payload: z12.object({ campaign_id: z12.string(), status: statusSchema })
|
|
939
3213
|
}),
|
|
940
|
-
|
|
3214
|
+
guardedWriteTool9({
|
|
941
3215
|
name: "google_set_budget",
|
|
942
3216
|
namespace: "google",
|
|
943
3217
|
description: "Change a campaign's daily budget. The preview warns when the budget is shared across campaigns.",
|
|
944
3218
|
provider: "google",
|
|
945
3219
|
kind: "update",
|
|
946
|
-
payload:
|
|
3220
|
+
payload: z12.object({ campaign_id: z12.string(), daily_budget_micros: z12.number().int().positive() })
|
|
947
3221
|
}),
|
|
948
|
-
|
|
3222
|
+
guardedWriteTool9({
|
|
949
3223
|
name: "google_set_bid_ceiling",
|
|
950
3224
|
namespace: "google",
|
|
951
3225
|
description: "Set a campaign's max CPC bid ceiling (micros). Works for MAXIMIZE_CLICKS (target spend) and TARGET_IMPRESSION_SHARE strategies; fails with guidance for others.",
|
|
952
3226
|
provider: "google",
|
|
953
3227
|
kind: "update",
|
|
954
|
-
payload:
|
|
955
|
-
campaign_id:
|
|
956
|
-
cpc_bid_ceiling_micros:
|
|
3228
|
+
payload: z12.object({
|
|
3229
|
+
campaign_id: z12.string(),
|
|
3230
|
+
cpc_bid_ceiling_micros: z12.number().int().positive().describe("1 currency unit = 1,000,000 micros")
|
|
957
3231
|
})
|
|
958
3232
|
}),
|
|
959
|
-
|
|
3233
|
+
guardedWriteTool9({
|
|
960
3234
|
name: "google_set_bidding_strategy",
|
|
961
3235
|
namespace: "google",
|
|
962
3236
|
description: "Switch a campaign's bidding strategy: MANUAL_CPC, MAXIMIZE_CLICKS (optional cpc_bid_ceiling_micros), MAXIMIZE_CONVERSIONS (optional target_cpa_micros), MAXIMIZE_CONVERSION_VALUE (optional target_roas). Also updates the target of the current strategy when the strategy stays the same.",
|
|
963
3237
|
provider: "google",
|
|
964
3238
|
kind: "update",
|
|
965
|
-
payload:
|
|
966
|
-
campaign_id:
|
|
967
|
-
strategy:
|
|
968
|
-
target_cpa_micros:
|
|
969
|
-
target_roas:
|
|
970
|
-
cpc_bid_ceiling_micros:
|
|
3239
|
+
payload: z12.object({
|
|
3240
|
+
campaign_id: z12.string(),
|
|
3241
|
+
strategy: z12.enum(["MANUAL_CPC", "MAXIMIZE_CLICKS", "MAXIMIZE_CONVERSIONS", "MAXIMIZE_CONVERSION_VALUE"]),
|
|
3242
|
+
target_cpa_micros: z12.number().int().positive().optional(),
|
|
3243
|
+
target_roas: z12.number().positive().optional().describe("e.g. 3.5 = 350% return on ad spend"),
|
|
3244
|
+
cpc_bid_ceiling_micros: z12.number().int().positive().optional()
|
|
971
3245
|
})
|
|
972
3246
|
}),
|
|
973
|
-
|
|
3247
|
+
guardedWriteTool9({
|
|
974
3248
|
name: "google_create_ad_group",
|
|
975
3249
|
namespace: "google",
|
|
976
3250
|
description: "Create a SEARCH_STANDARD ad group in a campaign.",
|
|
977
3251
|
provider: "google",
|
|
978
3252
|
kind: "create",
|
|
979
|
-
payload:
|
|
980
|
-
campaign_id:
|
|
981
|
-
name:
|
|
982
|
-
cpc_bid_micros:
|
|
3253
|
+
payload: z12.object({
|
|
3254
|
+
campaign_id: z12.string(),
|
|
3255
|
+
name: z12.string().min(1),
|
|
3256
|
+
cpc_bid_micros: z12.number().int().positive().optional()
|
|
983
3257
|
})
|
|
984
3258
|
}),
|
|
985
|
-
|
|
3259
|
+
guardedWriteTool9({
|
|
986
3260
|
name: "google_set_ad_group_status",
|
|
987
3261
|
namespace: "google",
|
|
988
3262
|
description: "Enable or pause an ad group.",
|
|
989
3263
|
provider: "google",
|
|
990
3264
|
kind: "update",
|
|
991
|
-
payload:
|
|
3265
|
+
payload: z12.object({ ad_group_id: z12.string(), status: statusSchema })
|
|
992
3266
|
}),
|
|
993
|
-
|
|
3267
|
+
guardedWriteTool9({
|
|
994
3268
|
name: "google_add_keywords",
|
|
995
3269
|
namespace: "google",
|
|
996
3270
|
description: "Add keywords (or negative keywords) to an ad group.",
|
|
997
3271
|
provider: "google",
|
|
998
3272
|
kind: "create",
|
|
999
|
-
payload:
|
|
1000
|
-
ad_group_id:
|
|
1001
|
-
keywords:
|
|
1002
|
-
negative:
|
|
3273
|
+
payload: z12.object({
|
|
3274
|
+
ad_group_id: z12.string(),
|
|
3275
|
+
keywords: z12.array(z12.object({ text: z12.string().min(1), match_type: matchTypeSchema })).min(1),
|
|
3276
|
+
negative: z12.boolean().default(false)
|
|
1003
3277
|
})
|
|
1004
3278
|
}),
|
|
1005
|
-
|
|
3279
|
+
guardedWriteTool9({
|
|
1006
3280
|
name: "google_set_keyword_status",
|
|
1007
3281
|
namespace: "google",
|
|
1008
3282
|
description: "Enable or pause a keyword criterion.",
|
|
1009
3283
|
provider: "google",
|
|
1010
3284
|
kind: "update",
|
|
1011
|
-
payload:
|
|
3285
|
+
payload: z12.object({ ad_group_id: z12.string(), criterion_id: z12.string(), status: statusSchema })
|
|
1012
3286
|
}),
|
|
1013
|
-
|
|
3287
|
+
guardedWriteTool9({
|
|
1014
3288
|
name: "google_remove_keywords",
|
|
1015
3289
|
namespace: "google",
|
|
1016
3290
|
description: "PERMANENTLY remove keyword criteria from an ad group. Prefer google_set_keyword_status to pause.",
|
|
1017
3291
|
provider: "google",
|
|
1018
3292
|
kind: "remove",
|
|
1019
3293
|
destructive: true,
|
|
1020
|
-
payload:
|
|
3294
|
+
payload: z12.object({ ad_group_id: z12.string(), criterion_ids: z12.array(z12.string()).min(1) })
|
|
3295
|
+
}),
|
|
3296
|
+
guardedWriteTool9({
|
|
3297
|
+
name: "google_set_ad_status",
|
|
3298
|
+
namespace: "google",
|
|
3299
|
+
description: "Enable or pause an existing ad in its ad group. Enabling an ad does not change its campaign or ad-group status.",
|
|
3300
|
+
provider: "google",
|
|
3301
|
+
kind: "update",
|
|
3302
|
+
payload: z12.object({
|
|
3303
|
+
ad_group_id: z12.string().regex(/^\d+$/),
|
|
3304
|
+
ad_id: z12.string().regex(/^\d+$/),
|
|
3305
|
+
status: statusSchema
|
|
3306
|
+
})
|
|
3307
|
+
}),
|
|
3308
|
+
guardedWriteTool9({
|
|
3309
|
+
name: "google_update_responsive_search_ad",
|
|
3310
|
+
namespace: "google",
|
|
3311
|
+
description: "Edit an existing responsive search ad\u2019s headlines, descriptions, final URLs or display paths. Omitted fields remain unchanged. Existing headline and description pinning is retained by position. Serving status does not change.",
|
|
3312
|
+
provider: "google",
|
|
3313
|
+
kind: "update",
|
|
3314
|
+
payload: z12.object({
|
|
3315
|
+
ad_group_id: z12.string().regex(/^\d+$/),
|
|
3316
|
+
ad_id: z12.string().regex(/^\d+$/),
|
|
3317
|
+
headlines: z12.array(z12.string().min(1).max(30)).min(3).max(15).optional(),
|
|
3318
|
+
descriptions: z12.array(z12.string().min(1).max(90)).min(2).max(4).optional(),
|
|
3319
|
+
final_urls: z12.array(z12.string().url()).min(1).max(10).optional(),
|
|
3320
|
+
path1: z12.string().max(15).optional(),
|
|
3321
|
+
path2: z12.string().max(15).optional()
|
|
3322
|
+
}).refine((input2) => ["headlines", "descriptions", "final_urls", "path1", "path2"].some((key2) => input2[key2] !== void 0), "Provide at least one content field")
|
|
1021
3323
|
}),
|
|
1022
|
-
|
|
3324
|
+
guardedWriteTool9({
|
|
1023
3325
|
name: "google_create_responsive_search_ad",
|
|
1024
3326
|
namespace: "google",
|
|
1025
3327
|
description: "Create a responsive search ad (3\u201315 headlines \u226430 chars, 2\u20134 descriptions \u226490 chars).",
|
|
1026
3328
|
provider: "google",
|
|
1027
3329
|
kind: "create",
|
|
1028
|
-
payload:
|
|
1029
|
-
ad_group_id:
|
|
1030
|
-
headlines:
|
|
1031
|
-
descriptions:
|
|
1032
|
-
final_urls:
|
|
1033
|
-
path1:
|
|
1034
|
-
path2:
|
|
3330
|
+
payload: z12.object({
|
|
3331
|
+
ad_group_id: z12.string(),
|
|
3332
|
+
headlines: z12.array(z12.string()).min(3).max(15),
|
|
3333
|
+
descriptions: z12.array(z12.string()).min(2).max(4),
|
|
3334
|
+
final_urls: z12.array(z12.string().url()).min(1),
|
|
3335
|
+
path1: z12.string().max(15).optional(),
|
|
3336
|
+
path2: z12.string().max(15).optional()
|
|
1035
3337
|
})
|
|
1036
3338
|
}),
|
|
1037
|
-
|
|
3339
|
+
guardedWriteTool9({
|
|
1038
3340
|
name: "google_api_create",
|
|
1039
3341
|
namespace: "google",
|
|
1040
3342
|
description: "Create resources through any Google Ads v25 mutate service using API-shaped create objects. Campaign status is forced to PAUSED and campaign-budget amounts are policy-checked.",
|
|
1041
3343
|
provider: "google",
|
|
1042
3344
|
kind: "create",
|
|
1043
|
-
payload:
|
|
1044
|
-
service:
|
|
1045
|
-
creates:
|
|
3345
|
+
payload: z12.object({
|
|
3346
|
+
service: z12.string().min(2).describe("REST mutate service, e.g. adGroupAds, assets, campaignCriteria"),
|
|
3347
|
+
creates: z12.array(z12.record(z12.string(), z12.unknown())).min(1).max(100)
|
|
1046
3348
|
})
|
|
1047
3349
|
}),
|
|
1048
|
-
|
|
3350
|
+
guardedWriteTool9({
|
|
1049
3351
|
name: "google_api_update",
|
|
1050
3352
|
namespace: "google",
|
|
1051
3353
|
description: "Update non-budget resources through any Google Ads v25 mutate service. Budget updates must use google_set_budget.",
|
|
1052
3354
|
provider: "google",
|
|
1053
3355
|
kind: "update",
|
|
1054
|
-
payload:
|
|
1055
|
-
service:
|
|
1056
|
-
updates:
|
|
1057
|
-
update:
|
|
1058
|
-
update_mask:
|
|
3356
|
+
payload: z12.object({
|
|
3357
|
+
service: z12.string().min(2),
|
|
3358
|
+
updates: z12.array(z12.object({
|
|
3359
|
+
update: z12.record(z12.string(), z12.unknown()),
|
|
3360
|
+
update_mask: z12.string().min(1)
|
|
1059
3361
|
})).min(1).max(100)
|
|
1060
3362
|
})
|
|
1061
3363
|
}),
|
|
1062
|
-
|
|
3364
|
+
guardedWriteTool9({
|
|
1063
3365
|
name: "google_api_remove",
|
|
1064
3366
|
namespace: "google",
|
|
1065
3367
|
description: "Permanently remove resources through any Google Ads v25 mutate service.",
|
|
1066
3368
|
provider: "google",
|
|
1067
3369
|
kind: "remove",
|
|
1068
3370
|
destructive: true,
|
|
1069
|
-
payload:
|
|
1070
|
-
service:
|
|
1071
|
-
resource_names:
|
|
3371
|
+
payload: z12.object({
|
|
3372
|
+
service: z12.string().min(2),
|
|
3373
|
+
resource_names: z12.array(z12.string().min(1)).min(1).max(100)
|
|
1072
3374
|
})
|
|
1073
3375
|
})
|
|
1074
3376
|
];
|
|
@@ -1076,9 +3378,9 @@ function googleTools(provider) {
|
|
|
1076
3378
|
|
|
1077
3379
|
// src/index.ts
|
|
1078
3380
|
async function resolveGoogleCredentials(store) {
|
|
1079
|
-
const
|
|
1080
|
-
if (
|
|
1081
|
-
const { client_id, client_secret, refresh_token, login_customer_id } =
|
|
3381
|
+
const record4 = await store.get("google");
|
|
3382
|
+
if (record4) {
|
|
3383
|
+
const { client_id, client_secret, refresh_token, login_customer_id } = record4.data;
|
|
1082
3384
|
if (client_id && client_secret && refresh_token) {
|
|
1083
3385
|
return {
|
|
1084
3386
|
clientId: client_id,
|
|
@@ -1107,6 +3409,7 @@ async function createGoogleModule(store) {
|
|
|
1107
3409
|
}
|
|
1108
3410
|
export {
|
|
1109
3411
|
DEFAULT_API_VERSION,
|
|
3412
|
+
GOOGLE_DATA_MANAGER_SCOPE,
|
|
1110
3413
|
GoogleAdsProvider,
|
|
1111
3414
|
GoogleAdsRestClient,
|
|
1112
3415
|
createGoogleModule,
|