@adport/provider-pinterest 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 +1941 -28
- package/dist/index.js +2905 -81
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,35 +1,44 @@
|
|
|
1
1
|
// src/client.ts
|
|
2
2
|
import { AdportError } from "@adport/core";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
4
5
|
var PINTEREST_API_BASE = "https://api.pinterest.com/v5/";
|
|
5
6
|
var PINTEREST_TOKEN_URL = `${PINTEREST_API_BASE}oauth/token`;
|
|
7
|
+
var PINTEREST_ADS_SCOPES = ["ads:read", "ads:write"];
|
|
8
|
+
var PINTEREST_PIN_SCOPES = [...PINTEREST_ADS_SCOPES, "boards:read", "boards:write", "pins:read", "pins:write", "user_accounts:read"];
|
|
9
|
+
var PINTEREST_SECRET_PIN_SCOPES = [...PINTEREST_PIN_SCOPES, "boards:read_secret", "boards:write_secret", "pins:read_secret", "pins:write_secret"];
|
|
10
|
+
var PINTEREST_CATALOG_SCOPES = ["catalogs:read", "catalogs:write"];
|
|
11
|
+
function pinterestAuthorizationScopes(options = {}) {
|
|
12
|
+
return [...options.secretPins ? PINTEREST_SECRET_PIN_SCOPES : options.pinManagement ? PINTEREST_PIN_SCOPES : PINTEREST_ADS_SCOPES, ...options.catalogManagement ? PINTEREST_CATALOG_SCOPES : []];
|
|
13
|
+
}
|
|
6
14
|
var tokenSchema = z.object({
|
|
7
15
|
access_token: z.string().min(1),
|
|
8
16
|
expires_in: z.number().positive(),
|
|
9
|
-
refresh_token: z.string().min(1).optional()
|
|
17
|
+
refresh_token: z.string().min(1).optional(),
|
|
18
|
+
scope: z.string().optional()
|
|
10
19
|
});
|
|
11
|
-
function buildPinterestAuthUrl(clientId, redirectUri,
|
|
20
|
+
function buildPinterestAuthUrl(clientId, redirectUri, state2, options = {}) {
|
|
12
21
|
return `https://www.pinterest.com/oauth/?${new URLSearchParams({
|
|
13
22
|
client_id: clientId,
|
|
14
23
|
response_type: "code",
|
|
15
24
|
redirect_uri: redirectUri,
|
|
16
|
-
state,
|
|
17
|
-
scope: "
|
|
25
|
+
state: state2,
|
|
26
|
+
scope: pinterestAuthorizationScopes(options).join(",")
|
|
18
27
|
})}`;
|
|
19
28
|
}
|
|
20
|
-
async function tokenRequest(
|
|
21
|
-
const
|
|
29
|
+
async function tokenRequest(credentials2, body, fetchImpl) {
|
|
30
|
+
const response2 = await fetchImpl(PINTEREST_TOKEN_URL, {
|
|
22
31
|
method: "POST",
|
|
23
32
|
headers: {
|
|
24
|
-
authorization: `Basic ${Buffer.from(`${
|
|
33
|
+
authorization: `Basic ${Buffer.from(`${credentials2.clientId}:${credentials2.clientSecret}`).toString("base64")}`,
|
|
25
34
|
"content-type": "application/x-www-form-urlencoded"
|
|
26
35
|
},
|
|
27
36
|
body,
|
|
28
37
|
redirect: "error",
|
|
29
38
|
signal: AbortSignal.timeout(3e4)
|
|
30
39
|
});
|
|
31
|
-
if (!
|
|
32
|
-
const parsed = tokenSchema.safeParse(await
|
|
40
|
+
if (!response2.ok) throw new AdportError("PROVIDER_ERROR", `pinterest: OAuth ${body.get("grant_type")} failed (HTTP ${response2.status})`);
|
|
41
|
+
const parsed = tokenSchema.safeParse(await response2.json());
|
|
33
42
|
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "pinterest: malformed OAuth response");
|
|
34
43
|
return parsed.data;
|
|
35
44
|
}
|
|
@@ -41,47 +50,98 @@ async function exchangePinterestCode(input, fetchImpl = fetch) {
|
|
|
41
50
|
continuous_refresh: "true"
|
|
42
51
|
}), fetchImpl);
|
|
43
52
|
if (!token.refresh_token) throw new AdportError("PROVIDER_ERROR", "pinterest: OAuth exchange did not return a refresh token");
|
|
53
|
+
if (input.pinManagement || input.secretPins || input.catalogManagement) {
|
|
54
|
+
const granted = new Set(token.scope?.split(/[\s,]+/).filter(Boolean));
|
|
55
|
+
const requested = pinterestAuthorizationScopes(input);
|
|
56
|
+
if (requested.some((scope) => !granted.has(scope))) throw new AdportError("PROVIDER_ERROR", input.catalogManagement ? "pinterest: requested Ads, catalog and existing Pin management permissions were not all confirmed. The previous connection was preserved." : `pinterest: Ads and ${input.secretPins ? "secret " : ""}Pin management permissions were not all confirmed. The previous connection was preserved.`);
|
|
57
|
+
}
|
|
44
58
|
return token.refresh_token;
|
|
45
59
|
}
|
|
46
60
|
var PinterestAdsClient = class {
|
|
47
|
-
constructor(
|
|
48
|
-
this.credentials =
|
|
61
|
+
constructor(credentials2, fetchImpl = fetch) {
|
|
62
|
+
this.credentials = credentials2;
|
|
49
63
|
this.fetchImpl = fetchImpl;
|
|
50
|
-
this.refreshToken =
|
|
64
|
+
this.refreshToken = credentials2.refreshToken;
|
|
51
65
|
}
|
|
52
66
|
credentials;
|
|
53
67
|
fetchImpl;
|
|
54
68
|
token;
|
|
55
69
|
refreshToken;
|
|
56
70
|
refreshing;
|
|
71
|
+
catalogBatchReceipt(value) {
|
|
72
|
+
const encoded = Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
73
|
+
if (encoded.length > 15e5) throw new AdportError("INVALID_INPUT", "Catalog batch proof exceeds its bound; split this batch before previewing.");
|
|
74
|
+
return encoded + "." + createHmac("sha256", this.credentials.clientSecret).update("pinterest_catalog_batch_v1:" + this.credentials.clientId + ":" + encoded).digest("hex");
|
|
75
|
+
}
|
|
76
|
+
verifyCatalogBatchReceipt(value) {
|
|
77
|
+
const [encoded, signature, extra] = value.split(".");
|
|
78
|
+
if (extra !== void 0 || !encoded || encoded.length > 15e5 || !/^[a-f0-9]{64}$/.test(signature ?? "")) throw new AdportError("INVALID_INPUT", "Invalid catalog batch receipt.");
|
|
79
|
+
const expected = createHmac("sha256", this.credentials.clientSecret).update("pinterest_catalog_batch_v1:" + this.credentials.clientId + ":" + encoded).digest();
|
|
80
|
+
if (!timingSafeEqual(expected, Buffer.from(signature, "hex"))) throw new AdportError("INVALID_INPUT", "Catalog batch receipt belongs to another application or was changed.");
|
|
81
|
+
try {
|
|
82
|
+
return JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
|
|
83
|
+
} catch {
|
|
84
|
+
throw new AdportError("INVALID_INPUT", "Invalid catalog batch receipt.");
|
|
85
|
+
}
|
|
86
|
+
}
|
|
57
87
|
async get(path, schema, params = new URLSearchParams()) {
|
|
58
88
|
return this.request(path, "GET", schema, void 0, params);
|
|
59
89
|
}
|
|
60
|
-
async mutate(path, method, body, schema) {
|
|
61
|
-
return this.request(path, method, schema, body);
|
|
90
|
+
async mutate(path, method, body, schema, params = new URLSearchParams()) {
|
|
91
|
+
return this.request(path, method, schema, body, params);
|
|
92
|
+
}
|
|
93
|
+
async uploadVideo(url2, parameters, bytes, name3) {
|
|
94
|
+
const destination = new URL(url2);
|
|
95
|
+
if (destination.origin !== "https://pinterest-media-upload.s3-accelerate.amazonaws.com" || destination.pathname !== "/" || destination.search || destination.hash || destination.username || destination.password) throw new AdportError("PROVIDER_ERROR", "pinterest: unrecognized native upload destination; no bytes sent");
|
|
96
|
+
const required = ["Content-Type", "key", "policy", "x-amz-algorithm", "x-amz-credential", "x-amz-date", "x-amz-security-token", "x-amz-signature"];
|
|
97
|
+
if (Object.keys(parameters).length !== required.length || required.some((key) => !parameters[key] || parameters[key].length > 32768) || parameters["Content-Type"] !== "multipart/form-data" || parameters["x-amz-algorithm"] !== "AWS4-HMAC-SHA256" || !parameters.key.startsWith("uploads/")) throw new AdportError("PROVIDER_ERROR", "pinterest: invalid native multipart instructions; no bytes sent");
|
|
98
|
+
const body = new FormData();
|
|
99
|
+
for (const key of required) body.set(key, parameters[key]);
|
|
100
|
+
body.set("file", new Blob([bytes], { type: "video/mp4" }), name3);
|
|
101
|
+
const response2 = await this.fetchImpl(destination.href, { method: "POST", body, redirect: "error", signal: AbortSignal.timeout(12e4) });
|
|
102
|
+
if (response2.status !== 204) throw new AdportError("PROVIDER_ERROR", "pinterest: video transfer was not confirmed");
|
|
62
103
|
}
|
|
63
104
|
async request(path, method, schema, body, params = new URLSearchParams(), retry = true) {
|
|
64
105
|
if (!/^[a-z_]+(?:\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError("INVALID_INPUT", "pinterest: invalid API resource path");
|
|
65
|
-
const
|
|
66
|
-
|
|
106
|
+
const url2 = new URL(path, PINTEREST_API_BASE);
|
|
107
|
+
url2.search = params.toString();
|
|
67
108
|
const token = await this.accessToken();
|
|
68
|
-
const
|
|
109
|
+
const missingCatalogScope = method === "GET" && (path === "catalogs" || path.startsWith("catalogs/")) && this.token?.value === token && this.token.scopes !== void 0 && !this.token.scopes.has("catalogs:read");
|
|
110
|
+
const response2 = await this.fetchImpl(url2.href, {
|
|
69
111
|
method,
|
|
70
112
|
headers: { authorization: `Bearer ${token}`, ...body !== void 0 ? { "content-type": "application/json" } : {} },
|
|
71
113
|
...body !== void 0 ? { body: JSON.stringify(body) } : {},
|
|
72
114
|
redirect: "error",
|
|
73
115
|
signal: AbortSignal.timeout(3e4)
|
|
74
116
|
});
|
|
75
|
-
if (
|
|
117
|
+
if (response2.status === 401 && method === "GET" && retry && !missingCatalogScope) {
|
|
76
118
|
if (this.token?.value === token) this.token = void 0;
|
|
77
119
|
return this.request(path, method, schema, body, params, false);
|
|
78
120
|
}
|
|
79
|
-
if (!
|
|
80
|
-
const advice =
|
|
81
|
-
|
|
121
|
+
if (!response2.ok) {
|
|
122
|
+
const advice = response2.status === 401 && missingCatalogScope ? " The current token is missing catalogs:read. Ask the connection owner to review catalog access; refreshing the same grant cannot add permissions." : response2.status === 403 ? " Check app Trial/Standard access, endpoint-specific scopes and ad-account permissions; reauthorization alone may not help." : "";
|
|
123
|
+
const details = { http_status: response2.status };
|
|
124
|
+
if (response2.status === 401 && missingCatalogScope) details.missing_scopes = ["catalogs:read"];
|
|
125
|
+
if ([400, 404, 409, 422].includes(response2.status)) {
|
|
126
|
+
const error = z.object({ code: z.union([z.string(), z.number()]).optional(), message: z.string().max(2e3).optional() }).safeParse(await response2.json().catch(() => void 0));
|
|
127
|
+
if (error.success) {
|
|
128
|
+
if (error.data.code !== void 0) details.api_code = error.data.code;
|
|
129
|
+
const payload = body && typeof body === "object" && !Array.isArray(body) ? body : {};
|
|
130
|
+
const auth = payload.credentials && typeof payload.credentials === "object" ? payload.credentials : {};
|
|
131
|
+
const sourceSecrets = path.startsWith("catalogs/") ? [payload.location, auth.username, auth.password].filter((value) => typeof value === "string" && value.length > 0) : [];
|
|
132
|
+
if (error.data.message) details.api_message = [...sourceSecrets, this.credentials.clientId, this.credentials.clientSecret, this.credentials.refreshToken, this.refreshToken, token].reduce((text4, secret) => secret ? text4.replaceAll(secret, "[redacted]") : text4, error.data.message);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
throw new AdportError("PROVIDER_ERROR", `pinterest: HTTP ${response2.status}.${advice}${details.api_message ? ` ${details.api_message}` : ""}`, details);
|
|
136
|
+
}
|
|
137
|
+
const raw = response2.status === 204 ? void 0 : await response2.json();
|
|
138
|
+
const parsed = schema.safeParse(raw);
|
|
139
|
+
if (!parsed.success) {
|
|
140
|
+
const value = raw && typeof raw === "object" ? raw : {};
|
|
141
|
+
const resourceIds = [value.id, value.media_id].filter((id4) => typeof id4 === "string" && /^\d{1,30}$/.test(id4));
|
|
142
|
+
if ((path === "catalogs/items/batch" || /^catalogs\/\d{1,30}\/local_inventory_items\/batch$/.test(path)) && typeof value.batch_id === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(value.batch_id)) resourceIds.push(value.batch_id);
|
|
143
|
+
throw new AdportError("PROVIDER_ERROR", "pinterest: malformed API response", { api_path: path, response_issues: parsed.error.issues.map((issue) => ({ path: issue.path, code: issue.code })), ...method !== "GET" && resourceIds.length ? { resource_ids: [...new Set(resourceIds)] } : {} });
|
|
82
144
|
}
|
|
83
|
-
const parsed = schema.safeParse(await response.json());
|
|
84
|
-
if (!parsed.success) throw new AdportError("PROVIDER_ERROR", "pinterest: malformed API response");
|
|
85
145
|
return parsed.data;
|
|
86
146
|
}
|
|
87
147
|
async accessToken() {
|
|
@@ -97,18 +157,31 @@ var PinterestAdsClient = class {
|
|
|
97
157
|
this.refreshToken = token.refresh_token;
|
|
98
158
|
await this.credentials.onRefreshToken?.(token.refresh_token);
|
|
99
159
|
}
|
|
100
|
-
this.token = {
|
|
160
|
+
this.token = {
|
|
161
|
+
value: token.access_token,
|
|
162
|
+
expiresAt: Date.now() + token.expires_in * 1e3,
|
|
163
|
+
...token.scope?.trim() ? { scopes: new Set(token.scope.split(/[\s,]+/).filter(Boolean)) } : {}
|
|
164
|
+
};
|
|
101
165
|
return token.access_token;
|
|
102
166
|
}
|
|
103
167
|
};
|
|
104
168
|
|
|
105
169
|
// src/provider.ts
|
|
106
|
-
import { z as
|
|
170
|
+
import { z as z19 } from "zod";
|
|
107
171
|
import {
|
|
108
|
-
AdportError as
|
|
172
|
+
AdportError as AdportError14,
|
|
173
|
+
LocalMediaResolver as LocalMediaResolver2,
|
|
109
174
|
resolveDateRange
|
|
110
175
|
} from "@adport/core";
|
|
111
176
|
|
|
177
|
+
// src/creatives.ts
|
|
178
|
+
import { AdportError as AdportError2, creativeStatusAction } from "@adport/core";
|
|
179
|
+
import { z as z4 } from "zod";
|
|
180
|
+
|
|
181
|
+
// src/creative-tools.ts
|
|
182
|
+
import { creativesOutput, defineTool, guardedWriteTool } from "@adport/core";
|
|
183
|
+
import { z as z3 } from "zod";
|
|
184
|
+
|
|
112
185
|
// src/schemas.ts
|
|
113
186
|
import { z as z2 } from "zod";
|
|
114
187
|
var pinterestId = z2.string().regex(/^\d+$/).max(18);
|
|
@@ -131,12 +204,15 @@ var createCampaignSchema = z2.object({
|
|
|
131
204
|
objective_type: z2.enum(["AWARENESS", "CONSIDERATION", "WEB_CONVERSION", "CATALOG_SALES", "VIDEO_COMPLETION", "APP_INSTALL", "SALES", "LEADS", "CTV_CONSIDERATION"]),
|
|
132
205
|
status: z2.enum(["PAUSED", "ACTIVE"]).default("PAUSED"),
|
|
133
206
|
budget_type: z2.enum(["DAILY", "LIFETIME"]).default("DAILY"),
|
|
207
|
+
daily_budget_mode: z2.enum(["FIXED", "AVERAGE"]).default("FIXED"),
|
|
208
|
+
acknowledge_variable_daily_spend: z2.literal(true).optional(),
|
|
134
209
|
budget_micros: micros.positive(),
|
|
135
210
|
start_time: z2.number().int().positive().safe().optional(),
|
|
136
211
|
end_time: z2.number().int().positive().safe().optional(),
|
|
137
212
|
app_id: z2.string().min(1).optional(),
|
|
138
213
|
app_platform: z2.enum(["IOS", "ANDROID"]).optional()
|
|
139
214
|
}).superRefine((value, ctx) => {
|
|
215
|
+
if (value.daily_budget_mode === "AVERAGE" && (value.budget_type !== "DAILY" || !value.acknowledge_variable_daily_spend)) ctx.addIssue({ code: "custom", path: ["daily_budget_mode"], message: "AVERAGE requires DAILY and acknowledge_variable_daily_spend: true." });
|
|
140
216
|
if (value.budget_type === "LIFETIME" && !value.end_time) ctx.addIssue({ code: "custom", path: ["end_time"], message: "Lifetime campaign budgets require an end time." });
|
|
141
217
|
if (value.start_time && value.end_time && value.end_time <= value.start_time) ctx.addIssue({ code: "custom", path: ["end_time"], message: "End time must be after start time." });
|
|
142
218
|
if (value.objective_type === "APP_INSTALL" && (!value.app_id || !value.app_platform)) ctx.addIssue({ code: "custom", path: ["app_id"], message: "APP_INSTALL requires app_id and app_platform and Pinterest beta access." });
|
|
@@ -144,6 +220,2643 @@ var createCampaignSchema = z2.object({
|
|
|
144
220
|
var setStatusSchema = z2.object({ campaign_id: pinterestId, status: z2.enum(["PAUSED", "ACTIVE"]) });
|
|
145
221
|
var setBudgetSchema = z2.object({ campaign_id: pinterestId, budget_micros: micros.positive() });
|
|
146
222
|
|
|
223
|
+
// src/creative-tools.ts
|
|
224
|
+
var id = pinterestId;
|
|
225
|
+
var pinId = z3.string().regex(/^\d+$/).max(30);
|
|
226
|
+
var money = z3.number().int().positive().safe();
|
|
227
|
+
var strings = z3.array(z3.string().min(1)).max(1e3);
|
|
228
|
+
var url = z3.string().url().refine((value) => {
|
|
229
|
+
const u = new URL(value);
|
|
230
|
+
return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password;
|
|
231
|
+
}, "Use an HTTP(S) URL without embedded credentials");
|
|
232
|
+
var microsString = z3.string().regex(/^\d+$/).refine((value) => Number.isSafeInteger(Number(value)), "Micro amount must be a safe integer");
|
|
233
|
+
var targeting = z3.object({ AGE_BUCKET: strings.optional(), APPTYPE: strings.optional(), AUDIENCE_EXCLUDE: z3.array(id).optional(), AUDIENCE_INCLUDE: z3.array(id).optional(), GENDER: z3.array(z3.enum(["unknown", "male", "female"])).optional(), GEO: strings.optional(), GEO_EXCLUDE: strings.optional(), INTEREST: strings.optional(), LOCALE: strings.optional(), LOCATION: strings.optional(), LOCATION_EXCLUDE: strings.optional(), MINIMUM_AGE: z3.string().regex(/^\d+$/).optional(), MAXIMUM_AGE: z3.string().regex(/^\d+\+?$/).optional(), TARGETING_STRATEGY: strings.optional() }).strict();
|
|
234
|
+
var optimization = z3.object({ conversion_tag_v3_goal_metadata: z3.object({ conversion_tag_id: id.optional(), conversion_event: z3.string().min(1).optional(), cpa_goal_value_in_micro_currency: microsString.optional(), is_roas_optimized: z3.boolean().optional(), reporting_event: z3.string().optional() }).strict().optional(), frequency_goal_metadata: z3.object({ frequency: z3.number().int().min(2).max(20), timerange: z3.enum(["THIRTY_DAY", "DAY", "SEVEN_DAY", "TWENTY_MINUTE", "TEN_MINUTE", "TWENTY_FOUR_HOUR"]) }).strict().optional(), scrollup_goal_metadata: z3.object({ scrollup_goal_value_in_micro_currency: microsString }).strict().optional() }).strict();
|
|
235
|
+
var bidStrategy = z3.enum(["AUTOMATIC_BID", "MAX_BID", "TARGET_AVG"]);
|
|
236
|
+
var groupFields = { name: z3.string().trim().min(1).max(255).optional(), targeting_spec: targeting.optional(), auto_targeting_enabled: z3.boolean().optional(), placement_group: z3.enum(["ALL", "SEARCH", "BROWSE", "OTHER"]).optional(), start_time: z3.number().int().positive().safe().optional(), end_time: z3.number().int().positive().safe().optional(), lifetime_frequency_cap: z3.number().int().positive().optional(), optimization_goal_metadata: optimization.optional() };
|
|
237
|
+
var createGroup = z3.object({ ...groupFields, name: z3.string().trim().min(1).max(255), targeting_spec: targeting, auto_targeting_enabled: z3.boolean().default(false), campaign_id: id, billable_event: z3.enum(["CLICKTHROUGH", "IMPRESSION", "VIDEO_V_50_MRC"]), bid_strategy_type: bidStrategy, bid_in_micro_currency: money.optional(), budget_in_micro_currency: money.optional(), budget_type: z3.enum(["DAILY", "LIFETIME"]).optional(), pacing_delivery_type: z3.enum(["STANDARD", "ACCELERATED"]).default("STANDARD"), status: z3.enum(["PAUSED", "ACTIVE"]).default("PAUSED") }).refine((v) => !v.end_time || !v.start_time || v.end_time > v.start_time, "End must follow start").refine((v) => v.bid_strategy_type !== "MAX_BID" || Boolean(v.bid_in_micro_currency), "MAX_BID requires a bid");
|
|
238
|
+
var updateGroup = z3.object({ ad_group_id: id, ...groupFields }).refine((v) => Object.keys(v).length > 1, "Provide an ad-group field");
|
|
239
|
+
var createAd = z3.object({ ad_group_id: id, pin_id: pinId, creative_type: z3.enum(["REGULAR", "VIDEO", "SHOPPING", "CAROUSEL", "MAX_VIDEO", "COLLECTION", "IDEA", "SHOWCASE", "QUIZ", "COLLAGE", "MAX_WIDTH_REGULAR_COLLECTION", "MAX_WIDTH_VIDEO_COLLECTION", "APP"]), name: z3.string().min(1).max(255), destination_url: url.optional(), click_tracking_url: url.optional(), view_tracking_url: url.optional(), status: z3.enum(["PAUSED", "ACTIVE"]).default("PAUSED") });
|
|
240
|
+
var updateAd = z3.object({ ad_id: id, name: z3.string().min(1).max(255).optional(), destination_url: url.optional(), click_tracking_url: url.optional(), view_tracking_url: url.optional(), pin_id: pinId.optional() }).refine((v) => Object.keys(v).length > 1, "Provide an ad field");
|
|
241
|
+
var page = { page_size: z3.number().int().positive().max(250).default(50), bookmark: z3.string().min(1).optional() };
|
|
242
|
+
var account = { account_id: id };
|
|
243
|
+
var ids = z3.array(id).min(1).max(250);
|
|
244
|
+
function pinterestCreativeTools(provider) {
|
|
245
|
+
const read = (name3, description2, input, handler) => defineTool({ name: name3, namespace: "pinterest", description: description2, input, annotations: { readOnly: true }, handler });
|
|
246
|
+
const write2 = (name3, description2, payload, kind = "update") => guardedWriteTool({ name: name3, namespace: "pinterest", provider: "pinterest", description: description2, payload, kind });
|
|
247
|
+
return [
|
|
248
|
+
read("pinterest_get_entity", "Read a campaign, ad group or ad by ID through the native resource endpoint, verifying advertiser and parent ownership.", z3.object({ ...account, entity: z3.enum(["campaigns", "ad_groups", "ads"]), resource_id: id }), (input) => provider.creatives.getEntity(input.account_id, input.entity, input.resource_id)),
|
|
249
|
+
read("pinterest_ad_groups", "Read advertiser ad-group targeting, budgets, bids and schedules with native bookmark pagination.", z3.object({ ...account, campaign_ids: ids.optional(), ad_group_ids: ids.optional(), entity_statuses: z3.array(entityStatus).optional(), ...page }), (input) => provider.creatives.page(input, "ad_groups")),
|
|
250
|
+
defineTool({ name: "pinterest_ads", namespace: "pinterest", description: "View advertiser ad settings and referenced Pin copy/media, with bound name/destination/status edit actions. Pin previews require existing boards/pins read permissions; original Pins remain unchanged.", input: z3.object({ ...account, campaign_ids: ids.optional(), ad_group_ids: ids.optional(), ad_ids: ids.optional(), entity_statuses: z3.array(entityStatus).optional(), include_pin_details: z3.boolean().default(true), ...page }).refine((input) => !input.include_pin_details || input.page_size <= 50, "Pin preview pages are limited to50; disable include_pin_details for larger configuration pages"), output: creativesOutput.passthrough(), presentation: "creatives", pagination: { cursorInput: "bookmark" }, annotations: { readOnly: true }, handler: (input) => provider.creatives.ads(input) }),
|
|
251
|
+
read("pinterest_targeting_options", "Read native targeting resources for the selected advertiser; returns provider codes and labels.", z3.object({ ...account, targeting_type: z3.enum(["APPTYPE", "GENDER", "LOCALE", "AGE_BUCKET", "LOCATION", "GEO", "INTEREST", "KEYWORD", "AUDIENCE_INCLUDE", "AUDIENCE_EXCLUDE"]) }), (input) => provider.creatives.targetingOptions(input.account_id, input.targeting_type)),
|
|
252
|
+
read("pinterest_audience_estimate", "Get a native non-binding audience-size estimate via read-only POST. No targeting or delivery changes.", z3.object({ ...account, targeting_spec: targeting, auto_targeting_enabled: z3.boolean(), placement_group: z3.enum(["ALL", "SEARCH", "BROWSE", "OTHER"]).default("ALL") }), (input) => provider.creatives.estimate(input)),
|
|
253
|
+
write2("pinterest_create_ad_group", "Create a verified campaign\u2019s ad group, paused by policy. Budgets/bids are integer account-currency micros; non-CBO campaigns require an ad-group budget.", createGroup, "create"),
|
|
254
|
+
write2("pinterest_update_ad_group", "Patch supplied ad-group name, schedule, targeting or optimization fields. Omitted targeting dimensions remain unchanged; supplied arrays replace their previous values.", updateGroup),
|
|
255
|
+
write2("pinterest_create_ad", "Create a paused advertiser ad using an existing eligible Pin. This does not edit or publish an organic Pin.", createAd, "create"),
|
|
256
|
+
write2("pinterest_update_ad", "Patch the verified advertiser ad\u2019s name/destination/tracking fields. Pin replacement is allowed only for DRAFT ads; existing Pins remain unchanged.", updateAd),
|
|
257
|
+
...["ad_group", "ad"].map((entity) => write2(`pinterest_set_${entity}_status`, "Pause or activate an account-owned child entity after checking its parent hierarchy.", z3.object({ [entity === "ad" ? "ad_id" : "ad_group_id"]: id, status: z3.enum(["PAUSED", "ACTIVE"]) }))),
|
|
258
|
+
write2("pinterest_set_ad_group_budget", "Set an existing non-CBO ad-group budget in integer micros, preserving DAILY/LIFETIME type and enforcing current-value policy checks.", z3.object({ ad_group_id: id, budget_micros: money })),
|
|
259
|
+
write2("pinterest_set_ad_group_bidding", "Set advertiser ad-group bids/strategy with current-value micro policy checks. TARGET_AVG is a monetary bid target, not a currency ratio.", z3.object({ ad_group_id: id, bid_strategy_type: bidStrategy.optional(), bid_micros: money.optional() }).refine((v) => Boolean(v.bid_strategy_type || v.bid_micros), "Provide a bidding field")),
|
|
260
|
+
write2("pinterest_archive_entity", "Archive a verified advertiser campaign, ad group or ad through native batch PATCH. This does not delete an original Pin.", z3.object({ entity: z3.enum(["campaigns", "ad_groups", "ads"]), resource_id: id }))
|
|
261
|
+
];
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// src/creatives.ts
|
|
265
|
+
var object = z4.record(z4.string(), z4.unknown());
|
|
266
|
+
var response = z4.looseObject({ id: pinterestId, ad_account_id: pinterestId.optional() });
|
|
267
|
+
function record(value) {
|
|
268
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
269
|
+
}
|
|
270
|
+
function query(input) {
|
|
271
|
+
const params = new URLSearchParams();
|
|
272
|
+
for (const [key, value] of Object.entries(input)) if (value !== void 0) params.set(key, Array.isArray(value) ? value.map(String).join(",") : String(value));
|
|
273
|
+
return params;
|
|
274
|
+
}
|
|
275
|
+
function safeUrl(value) {
|
|
276
|
+
if (typeof value !== "string") return [];
|
|
277
|
+
try {
|
|
278
|
+
const u = new URL(value);
|
|
279
|
+
return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password ? [value] : [];
|
|
280
|
+
} catch {
|
|
281
|
+
return [];
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
var PinterestCreativeService = class {
|
|
285
|
+
constructor(client, campaign) {
|
|
286
|
+
this.client = client;
|
|
287
|
+
this.campaign = campaign;
|
|
288
|
+
}
|
|
289
|
+
client;
|
|
290
|
+
campaign;
|
|
291
|
+
base(account3) {
|
|
292
|
+
return `ad_accounts/${pinterestId.parse(account3)}`;
|
|
293
|
+
}
|
|
294
|
+
async read(account3, path) {
|
|
295
|
+
return this.client.get(`${this.base(account3)}/${path}`, object);
|
|
296
|
+
}
|
|
297
|
+
async getEntity(account3, entity, id4) {
|
|
298
|
+
return this.owned(account3, entity, id4);
|
|
299
|
+
}
|
|
300
|
+
async page(input, collection) {
|
|
301
|
+
const { account_id, ...params } = input;
|
|
302
|
+
const data = await this.client.get(`${this.base(account_id)}/${collection}`, z4.looseObject({ items: z4.array(response), bookmark: z4.string().nullable().optional() }), query({ ...params, ...collection !== "audiences" && !params.entity_statuses ? { entity_statuses: ["ACTIVE", "PAUSED", "ARCHIVED", "DRAFT", "DELETED_DRAFT"] } : {} }));
|
|
303
|
+
if (data.items.some((row) => row.ad_account_id !== void 0 && row.ad_account_id !== account_id)) throw new AdportError2("PROVIDER_ERROR", "pinterest: collection returned a foreign account");
|
|
304
|
+
if (data.bookmark && data.bookmark === input.bookmark) throw new AdportError2("PROVIDER_ERROR", "pinterest: pagination repeated a bookmark");
|
|
305
|
+
return { ...data, truncated: Boolean(data.bookmark), ...data.bookmark ? { next_cursor: data.bookmark } : {} };
|
|
306
|
+
}
|
|
307
|
+
async ads(input) {
|
|
308
|
+
const { include_pin_details, ...filters } = input;
|
|
309
|
+
const data = await this.page(filters, "ads");
|
|
310
|
+
const pins = /* @__PURE__ */ new Map(), warnings = [];
|
|
311
|
+
if (include_pin_details) {
|
|
312
|
+
const ids3 = [...new Set(data.items.map((ad) => typeof ad.pin_id === "string" && /^\d{1,30}$/.test(ad.pin_id) ? ad.pin_id : "").filter(Boolean))];
|
|
313
|
+
let cursor3 = 0, denied = false;
|
|
314
|
+
await Promise.all(Array.from({ length: Math.min(4, ids3.length) }, async () => {
|
|
315
|
+
while (cursor3 < ids3.length && !denied) {
|
|
316
|
+
const id4 = ids3[cursor3++];
|
|
317
|
+
try {
|
|
318
|
+
const pin = await this.client.get(`pins/${id4}`, z4.looseObject({ id: z4.string().regex(/^\d+$/) }), query({ ad_account_id: input.account_id }));
|
|
319
|
+
if (pin.id !== id4) throw new AdportError2("PROVIDER_ERROR", "pinterest: referenced Pin response ID mismatch");
|
|
320
|
+
pins.set(id4, pin);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
const forbidden = error instanceof AdportError2 && record(error.details).http_status === 403;
|
|
323
|
+
if (forbidden) denied = true;
|
|
324
|
+
const message = forbidden ? "Pinterest denied a Pin preview. Check boards:read, pins:read and access to the referenced Pin." : `Pin preview unavailable: ${error instanceof Error ? error.message : "Pinterest read failed"}`;
|
|
325
|
+
if (!warnings.some((warning) => warning.message === message)) warnings.push({ provider: "pinterest", message });
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}));
|
|
329
|
+
}
|
|
330
|
+
const creatives = data.items.map((ad) => {
|
|
331
|
+
const status = typeof ad.status === "string" ? ad.status : "", args = { account_id: input.account_id, ad_id: ad.id };
|
|
332
|
+
const pin = pins.get(String(ad.pin_id));
|
|
333
|
+
return { id: ad.id, provider: "pinterest", account_id: input.account_id, name: String(ad.name ?? ad.id), type: String(ad.creative_type ?? "PIN_AD"), ...status ? { status } : {}, ...typeof ad.campaign_id === "string" ? { campaign_id: ad.campaign_id } : {}, ...typeof ad.ad_group_id === "string" ? { ad_group_id: ad.ad_group_id } : {}, headlines: typeof pin?.title === "string" ? [pin.title] : [], descriptions: typeof pin?.description === "string" ? [pin.description] : [], landing_urls: safeUrl(ad.destination_url).length ? safeUrl(ad.destination_url) : safeUrl(pin?.link), media: pinMedia(pin?.media), actions: ["ARCHIVED", "DELETED_DRAFT"].includes(status) ? [] : [
|
|
334
|
+
...["ACTIVE", "PAUSED"].includes(status) ? [creativeStatusAction("pinterest_set_ad_status", args, status, ["ACTIVE", "PAUSED"])] : [],
|
|
335
|
+
{ label: "Edit ad settings", tool: "pinterest_update_ad", arguments: args, fields: [{ key: "name", label: "Ad name", type: "text", value: String(ad.name ?? ""), max_length: 255 }, ...typeof ad.destination_url === "string" ? [{ key: "destination_url", label: "Destination URL", type: "text", value: ad.destination_url, max_length: 2048 }] : []] }
|
|
336
|
+
] };
|
|
337
|
+
});
|
|
338
|
+
return { ...data, creatives, warnings };
|
|
339
|
+
}
|
|
340
|
+
async targetingOptions(account3, type2) {
|
|
341
|
+
return this.client.get(`resources/targeting/${type2}`, z4.array(object), query({ ad_account_id: pinterestId.parse(account3) }));
|
|
342
|
+
}
|
|
343
|
+
async estimate(input) {
|
|
344
|
+
const { account_id, ...body } = input;
|
|
345
|
+
return this.client.mutate(`${this.base(account_id)}/ad_groups/audience_sizing`, "POST", body, object);
|
|
346
|
+
}
|
|
347
|
+
async owned(account3, collection, id4) {
|
|
348
|
+
if (collection === "campaigns") return this.campaign(account3, id4);
|
|
349
|
+
const row = await this.client.get(`${this.base(account3)}/${collection}/${pinterestId.parse(id4)}`, response);
|
|
350
|
+
if (row.id !== id4 || row.ad_account_id !== void 0 && row.ad_account_id !== account3) throw new AdportError2("PROVIDER_ERROR", "pinterest: resource ID/account mismatch");
|
|
351
|
+
if (collection === "ad_groups") await this.campaign(account3, pinterestId.parse(row.campaign_id));
|
|
352
|
+
else {
|
|
353
|
+
const parent2 = await this.owned(account3, "ad_groups", pinterestId.parse(row.ad_group_id));
|
|
354
|
+
if (row.campaign_id !== void 0 && row.campaign_id !== parent2.campaign_id) throw new AdportError2("PROVIDER_ERROR", "pinterest: ad campaign hierarchy mismatch");
|
|
355
|
+
}
|
|
356
|
+
return row;
|
|
357
|
+
}
|
|
358
|
+
async batch(account3, collection, method, body) {
|
|
359
|
+
const data = await this.client.mutate(`${this.base(account3)}/${collection}`, method, [body], z4.object({ items: z4.array(z4.object({ data: object.nullable().optional(), exceptions: z4.array(z4.unknown()).optional() })) }));
|
|
360
|
+
const item = data.items[0], parsed = response.safeParse(item?.data);
|
|
361
|
+
const ids3 = parsed.success ? [parsed.data.id] : [];
|
|
362
|
+
if (data.items.length !== 1 || !parsed.success || item?.exceptions?.length) throw new AdportError2("PROVIDER_ERROR", "pinterest: native batch item failed or returned incomplete data; reconcile before retrying", { resource_ids: ids3 });
|
|
363
|
+
if (parsed.data.ad_account_id !== void 0 && parsed.data.ad_account_id !== account3 || body.id && parsed.data.id !== body.id || body.status !== void 0 && parsed.data.status !== body.status) throw new AdportError2("PROVIDER_ERROR", "pinterest: mutation receipt ID/account/status mismatch; reconcile before retrying", { resource_ids: ids3 });
|
|
364
|
+
if (["campaign_id", "ad_group_id", "budget_in_micro_currency", "bid_in_micro_currency"].some((key) => body[key] !== void 0 && parsed.data[key] !== body[key])) throw new AdportError2("PROVIDER_ERROR", "pinterest: mutation receipt parent/money mismatch; read configuration before retrying", { resource_ids: ids3 });
|
|
365
|
+
const goals = record(body.optimization_goal_metadata), returnedGoals = record(parsed.data.optimization_goal_metadata);
|
|
366
|
+
for (const [key, field] of [["conversion_tag_v3_goal_metadata", "cpa_goal_value_in_micro_currency"], ["scrollup_goal_metadata", "scrollup_goal_value_in_micro_currency"]]) {
|
|
367
|
+
const expected = record(goals[key])[field], returned = record(returnedGoals[key])[field];
|
|
368
|
+
if (expected !== void 0 && (returned == null || !/^\d+$/.test(String(returned)) || Number(returned) !== Number(expected))) throw new AdportError2("PROVIDER_ERROR", "pinterest: monetary optimization receipt mismatch; read configuration before retrying", { resource_ids: ids3 });
|
|
369
|
+
}
|
|
370
|
+
return ids3;
|
|
371
|
+
}
|
|
372
|
+
async verifyOptimization(account3, input) {
|
|
373
|
+
const tag2 = record(record(input).conversion_tag_v3_goal_metadata).conversion_tag_id;
|
|
374
|
+
if (tag2 === void 0) return;
|
|
375
|
+
const result = await this.client.get(`${this.base(account3)}/conversion_tags/${pinterestId.parse(tag2)}`, z4.looseObject({ id: pinterestId, ad_account_id: pinterestId }));
|
|
376
|
+
if (result.id !== tag2 || result.ad_account_id !== account3) throw new AdportError2("INVALID_INPUT", "pinterest: conversion tag is not owned by the selected advertiser");
|
|
377
|
+
}
|
|
378
|
+
async plan(op, guard) {
|
|
379
|
+
const p = op.payload, account3 = op.accountId, coercions = [], budgetDeltas = [];
|
|
380
|
+
let collection, body, method = "PATCH";
|
|
381
|
+
const paused = (status) => {
|
|
382
|
+
if (guard.forcePausedCreation && status !== "PAUSED") {
|
|
383
|
+
coercions.push("status coerced to PAUSED by policy (paused_creation)");
|
|
384
|
+
return "PAUSED";
|
|
385
|
+
}
|
|
386
|
+
return status;
|
|
387
|
+
};
|
|
388
|
+
switch (op.tool) {
|
|
389
|
+
case "pinterest_create_ad_group": {
|
|
390
|
+
const input = createGroup.parse(p), parent2 = await this.campaign(account3, input.campaign_id);
|
|
391
|
+
if (typeof parent2.is_campaign_budget_optimization !== "boolean") throw new AdportError2("INVALID_INPUT", "pinterest: campaign CBO mode is unavailable; cannot determine budget ownership");
|
|
392
|
+
if (parent2.is_campaign_budget_optimization && input.budget_in_micro_currency !== void 0) throw new AdportError2("INVALID_INPUT", "pinterest: CBO campaigns own the budget; omit an ad-group budget");
|
|
393
|
+
if (!parent2.is_campaign_budget_optimization && input.budget_in_micro_currency === void 0) throw new AdportError2("INVALID_INPUT", "pinterest: non-CBO campaigns require an ad-group budget");
|
|
394
|
+
if (parent2.is_campaign_budget_optimization && input.pacing_delivery_type !== "STANDARD") throw new AdportError2("INVALID_INPUT", "pinterest: CBO permits only STANDARD pacing");
|
|
395
|
+
if (input.budget_type === "LIFETIME" && !input.end_time) throw new AdportError2("INVALID_INPUT", "pinterest: lifetime budgets require end_time");
|
|
396
|
+
if (input.lifetime_frequency_cap && !input.end_time) throw new AdportError2("INVALID_INPUT", "pinterest: a frequency cap requires end_time");
|
|
397
|
+
checkTargeting(input.targeting_spec);
|
|
398
|
+
await this.verifyOptimization(account3, input.optimization_goal_metadata);
|
|
399
|
+
body = { ...input, status: paused(input.status), ...input.budget_in_micro_currency !== void 0 ? { budget_type: input.budget_type ?? "DAILY" } : {} };
|
|
400
|
+
collection = "ad_groups";
|
|
401
|
+
method = "POST";
|
|
402
|
+
moneyDeltas(body, {}, `new ad group ${input.name}`, budgetDeltas);
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
case "pinterest_create_ad": {
|
|
406
|
+
const input = createAd.parse(p);
|
|
407
|
+
await this.owned(account3, "ad_groups", input.ad_group_id);
|
|
408
|
+
collection = "ads";
|
|
409
|
+
method = "POST";
|
|
410
|
+
body = { ...input, status: paused(input.status) };
|
|
411
|
+
break;
|
|
412
|
+
}
|
|
413
|
+
case "pinterest_update_ad_group": {
|
|
414
|
+
const input = updateGroup.parse(p), { ad_group_id, ...fields2 } = input, current = await this.owned(account3, "ad_groups", ad_group_id);
|
|
415
|
+
body = { id: ad_group_id, ...fields2 };
|
|
416
|
+
if (fields2.targeting_spec) {
|
|
417
|
+
body.targeting_spec = { ...record(current.targeting_spec), ...fields2.targeting_spec };
|
|
418
|
+
checkTargeting(body.targeting_spec);
|
|
419
|
+
}
|
|
420
|
+
if (fields2.optimization_goal_metadata) {
|
|
421
|
+
await this.verifyOptimization(account3, fields2.optimization_goal_metadata);
|
|
422
|
+
const previous = record(current.optimization_goal_metadata), merged = { ...previous, ...fields2.optimization_goal_metadata };
|
|
423
|
+
for (const [key, value] of Object.entries(fields2.optimization_goal_metadata)) merged[key] = { ...record(previous[key]), ...record(value) };
|
|
424
|
+
body.optimization_goal_metadata = merged;
|
|
425
|
+
}
|
|
426
|
+
const effective = { ...current, ...body };
|
|
427
|
+
if (effective.start_time && effective.end_time && Number(effective.end_time) <= Number(effective.start_time)) throw new AdportError2("INVALID_INPUT", "pinterest: end_time must follow start_time");
|
|
428
|
+
moneyDeltas(body, current, `ad group ${ad_group_id}`, budgetDeltas);
|
|
429
|
+
collection = "ad_groups";
|
|
430
|
+
break;
|
|
431
|
+
}
|
|
432
|
+
case "pinterest_update_ad": {
|
|
433
|
+
const input = updateAd.parse(p), { ad_id, ...fields2 } = input, current = await this.owned(account3, "ads", ad_id);
|
|
434
|
+
if (input.pin_id !== void 0 && current.status !== "DRAFT") throw new AdportError2("INVALID_INPUT", "pinterest: pin_id can only be replaced on DRAFT ads. Create a new paused ad for a different Pin.");
|
|
435
|
+
collection = "ads";
|
|
436
|
+
body = { id: ad_id, ...fields2 };
|
|
437
|
+
break;
|
|
438
|
+
}
|
|
439
|
+
case "pinterest_set_ad_status":
|
|
440
|
+
case "pinterest_set_ad_group_status": {
|
|
441
|
+
collection = op.tool === "pinterest_set_ad_status" ? "ads" : "ad_groups";
|
|
442
|
+
const id4 = pinterestId.parse(p[collection === "ads" ? "ad_id" : "ad_group_id"]);
|
|
443
|
+
await this.owned(account3, collection, id4);
|
|
444
|
+
body = { id: id4, status: z4.enum(["ACTIVE", "PAUSED"]).parse(p.status) };
|
|
445
|
+
break;
|
|
446
|
+
}
|
|
447
|
+
case "pinterest_set_ad_group_budget": {
|
|
448
|
+
const id4 = pinterestId.parse(p.ad_group_id), current = await this.owned(account3, "ad_groups", id4), parent2 = await this.campaign(account3, String(current.campaign_id));
|
|
449
|
+
if (parent2.is_campaign_budget_optimization) throw new AdportError2("INVALID_INPUT", "pinterest: this ad group uses the campaign\u2019s CBO budget");
|
|
450
|
+
if (!["DAILY", "LIFETIME"].includes(String(current.budget_type)) || typeof current.budget_in_micro_currency !== "number") throw new AdportError2("INVALID_INPUT", "pinterest: current ad-group budget/type is unavailable");
|
|
451
|
+
collection = "ad_groups";
|
|
452
|
+
body = { id: id4, budget_in_micro_currency: z4.number().int().positive().safe().parse(p.budget_micros) };
|
|
453
|
+
moneyDeltas(body, current, `ad group ${id4}`, budgetDeltas);
|
|
454
|
+
break;
|
|
455
|
+
}
|
|
456
|
+
case "pinterest_set_ad_group_bidding": {
|
|
457
|
+
const id4 = pinterestId.parse(p.ad_group_id), current = await this.owned(account3, "ad_groups", id4);
|
|
458
|
+
body = { id: id4, ...p.bid_strategy_type !== void 0 ? { bid_strategy_type: p.bid_strategy_type } : {}, ...p.bid_micros !== void 0 ? { bid_in_micro_currency: p.bid_micros } : {} };
|
|
459
|
+
if ((body.bid_strategy_type ?? current.bid_strategy_type) === "MAX_BID" && !(body.bid_in_micro_currency ?? current.bid_in_micro_currency)) throw new AdportError2("INVALID_INPUT", "pinterest: MAX_BID requires a monetary bid");
|
|
460
|
+
moneyDeltas(body, current, `ad group ${id4}`, budgetDeltas);
|
|
461
|
+
collection = "ad_groups";
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
case "pinterest_archive_entity": {
|
|
465
|
+
collection = z4.enum(["campaigns", "ad_groups", "ads"]).parse(p.entity);
|
|
466
|
+
const id4 = pinterestId.parse(p.resource_id);
|
|
467
|
+
await this.owned(account3, collection, id4);
|
|
468
|
+
body = { id: id4, status: "ARCHIVED" };
|
|
469
|
+
break;
|
|
470
|
+
}
|
|
471
|
+
default:
|
|
472
|
+
throw new AdportError2("INVALID_INPUT", `pinterest: unsupported write ${op.tool}`);
|
|
473
|
+
}
|
|
474
|
+
return { summary: `Pinterest ${op.tool.replace(/^pinterest_/, "").replaceAll("_", " ")}`, changes: [`${method} ${collection}: ${JSON.stringify(body)}`], coercions, budgetDeltas, execute: () => this.batch(account3, collection, method, body) };
|
|
475
|
+
}
|
|
476
|
+
};
|
|
477
|
+
function checkTargeting(input) {
|
|
478
|
+
if (!input) return;
|
|
479
|
+
const target = record(input);
|
|
480
|
+
if (!(Array.isArray(target.GEO) && target.GEO.length) && !(Array.isArray(target.LOCATION) && target.LOCATION.length)) throw new AdportError2("INVALID_INPUT", "pinterest: targeting requires GEO or LOCATION");
|
|
481
|
+
if (Array.isArray(target.AGE_BUCKET) && target.AGE_BUCKET.length && (target.MINIMUM_AGE || target.MAXIMUM_AGE)) throw new AdportError2("INVALID_INPUT", "pinterest: choose AGE_BUCKET or minimum/maximum age");
|
|
482
|
+
if (Boolean(target.MINIMUM_AGE) !== Boolean(target.MAXIMUM_AGE) || target.MINIMUM_AGE && Number.parseInt(String(target.MINIMUM_AGE)) > Number.parseInt(String(target.MAXIMUM_AGE))) throw new AdportError2("INVALID_INPUT", "pinterest: minimum and maximum age must be supplied together and ordered");
|
|
483
|
+
}
|
|
484
|
+
function pinMedia(input, depth = 0) {
|
|
485
|
+
if (depth > 2) return [];
|
|
486
|
+
const media = record(input), result = [];
|
|
487
|
+
const variants = (value) => Object.values(record(value)).map(record).sort((a, b) => Number(b.width ?? 0) * Number(b.height ?? 0) - Number(a.width ?? 0) * Number(a.height ?? 0));
|
|
488
|
+
const video = variants(media.video_list).find((item) => safeUrl(item.url).some((url2) => url2.startsWith("https:")));
|
|
489
|
+
if (video) result.push({ type: "video", url: String(video.url) });
|
|
490
|
+
else {
|
|
491
|
+
const image = variants(media.images).find((item) => safeUrl(item.url).some((url2) => url2.startsWith("https:")));
|
|
492
|
+
if (image) result.push({ type: "image", url: String(image.url) });
|
|
493
|
+
}
|
|
494
|
+
for (const item of (Array.isArray(media.items) ? media.items : []).slice(0, 10)) result.push(...pinMedia(item, depth + 1));
|
|
495
|
+
return result.slice(0, 10);
|
|
496
|
+
}
|
|
497
|
+
function moneyDeltas(next, current, target, deltas) {
|
|
498
|
+
const amount = (label, value, old) => {
|
|
499
|
+
const parse = (input) => {
|
|
500
|
+
const n = typeof input === "number" ? input : typeof input === "string" && /^\d+$/.test(input) ? Number(input) : NaN;
|
|
501
|
+
if (!Number.isSafeInteger(n) || n < 0) throw new AdportError2("PROVIDER_ERROR", `pinterest: invalid ${label} money value`);
|
|
502
|
+
return n;
|
|
503
|
+
};
|
|
504
|
+
const to = parse(value);
|
|
505
|
+
if (old !== void 0 && old !== null) deltas.push({ target: `${target} ${label}`, fromMicros: parse(old), toMicros: to });
|
|
506
|
+
else deltas.push({ target: `${target} ${label}`, toMicros: to });
|
|
507
|
+
};
|
|
508
|
+
for (const key of ["budget_in_micro_currency", "bid_in_micro_currency"]) if (next[key] !== void 0) amount(key, next[key], current[key]);
|
|
509
|
+
const goals = record(next.optimization_goal_metadata), previous = record(current.optimization_goal_metadata);
|
|
510
|
+
for (const [key, field] of [["conversion_tag_v3_goal_metadata", "cpa_goal_value_in_micro_currency"], ["scrollup_goal_metadata", "scrollup_goal_value_in_micro_currency"]]) if (record(goals[key])[field] !== void 0) amount(field, record(goals[key])[field], record(previous[key])[field]);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// src/assets.ts
|
|
514
|
+
import { createHash } from "crypto";
|
|
515
|
+
import { AdportError as AdportError3, LocalMediaResolver, creativesOutput as creativesOutput2, defineTool as defineTool2, guardedWriteTool as guardedWriteTool2, mediaSourceFields } from "@adport/core";
|
|
516
|
+
import { z as z5 } from "zod";
|
|
517
|
+
var id2 = z5.string().regex(/^\d+$/).max(30);
|
|
518
|
+
var hash = z5.string().regex(/^[a-f0-9]{64}$/);
|
|
519
|
+
var privacy = z5.enum(["PUBLIC", "PROTECTED", "SECRET"]);
|
|
520
|
+
var username = z5.string().min(1);
|
|
521
|
+
var owner = z5.object({ username });
|
|
522
|
+
var boardSchema = z5.looseObject({ id: id2, name: z5.string(), description: z5.string().nullable().optional(), privacy, owner, is_ads_only: z5.boolean().optional(), pin_count: z5.number().int().nonnegative().optional(), collaborator_count: z5.number().int().nonnegative().optional(), follower_count: z5.number().int().nonnegative().optional() });
|
|
523
|
+
var pinSchema = z5.looseObject({ id: id2, board_id: id2, title: z5.string().nullable().optional(), description: z5.string().nullable().optional(), alt_text: z5.string().nullable().optional(), link: z5.string().nullable().optional(), is_owner: z5.boolean().optional(), has_been_promoted: z5.boolean().optional() });
|
|
524
|
+
var mediaSchema = z5.object({ media_id: id2, media_type: z5.literal("video"), status: z5.enum(["registered", "processing", "succeeded", "failed"]) });
|
|
525
|
+
var source = z5.object(mediaSourceFields).refine((v) => Boolean(v.media_id) !== Boolean(v.file_path), "Choose project media_id or local file_path");
|
|
526
|
+
var link = z5.string().max(2048).url().refine((value) => {
|
|
527
|
+
const url2 = new URL(value);
|
|
528
|
+
return ["http:", "https:"].includes(url2.protocol) && !url2.username && !url2.password;
|
|
529
|
+
}, "Use an HTTP(S) destination without credentials");
|
|
530
|
+
var copy = { title: z5.string().max(100).nullable().optional(), description: z5.string().max(800).nullable().optional(), alt_text: z5.string().max(500).nullable().optional(), link: link.nullable().optional() };
|
|
531
|
+
var pinCreation = { board_id: id2, expected_board_privacy: privacy, original_content: z5.literal(true), confirm_publication: z5.boolean().default(false), ...copy };
|
|
532
|
+
var createImage = source.safeExtend(pinCreation);
|
|
533
|
+
var createVideo = z5.object({ ...pinCreation, native_media_id: id2, cover_image_key_frame_time: z5.number().int().nonnegative().safe().default(0) });
|
|
534
|
+
var createBoard = z5.object({ name: z5.string().trim().min(1).max(180), description: z5.string().max(500).optional(), privacy: privacy.default("SECRET"), confirm_publication: z5.boolean().default(false) });
|
|
535
|
+
var boardReference = { board_id: id2, expected_snapshot_hash: hash };
|
|
536
|
+
var updateBoard = z5.object({ ...boardReference, name: z5.string().trim().min(1).max(180).optional(), description: z5.string().max(500).nullable().optional() }).strict().refine((v) => v.name !== void 0 || v.description !== void 0, "Provide a board name or description");
|
|
537
|
+
var deleteEmptyBoard = z5.object({ ...boardReference, confirm_permanent_deletion: z5.literal(true) }).strict();
|
|
538
|
+
var updatePin = z5.object({ pin_id: id2, expected_snapshot_hash: hash, ...copy }).strict().refine((v) => Object.keys(copy).some((key) => v[key] !== void 0), "Provide Pin copy to update");
|
|
539
|
+
var deletePin = z5.object({ pin_id: id2, expected_snapshot_hash: hash }).strict();
|
|
540
|
+
var kinds = { pinterest_create_board: "create", pinterest_update_board: "update", pinterest_delete_empty_board: "remove", pinterest_create_image_pin: "create", pinterest_upload_video: "create", pinterest_create_video_pin: "create", pinterest_update_pin: "update", pinterest_delete_pin: "remove" };
|
|
541
|
+
var PINTEREST_ASSET_WRITES = new Set(Object.keys(kinds));
|
|
542
|
+
function boardSnapshot(board) {
|
|
543
|
+
return createHash("sha256").update(JSON.stringify({ id: board.id, name: board.name, description: board.description ?? null, privacy: board.privacy, owner: board.owner.username.toLowerCase(), is_ads_only: board.is_ads_only ?? null })).digest("hex");
|
|
544
|
+
}
|
|
545
|
+
function snapshot(pin, board) {
|
|
546
|
+
return createHash("sha256").update(JSON.stringify({ id: pin.id, board_id: pin.board_id, title: pin.title ?? null, description: pin.description ?? null, alt_text: pin.alt_text ?? null, link: pin.link ?? null, is_owner: pin.is_owner, has_been_promoted: pin.has_been_promoted, privacy: board.privacy, owner: board.owner.username, is_ads_only: board.is_ads_only ?? false })).digest("hex");
|
|
547
|
+
}
|
|
548
|
+
function copyFields(input) {
|
|
549
|
+
return Object.fromEntries(Object.keys(copy).filter((key) => input[key] !== void 0).map((key) => [key, input[key]]));
|
|
550
|
+
}
|
|
551
|
+
function plan(summary, changes, execute) {
|
|
552
|
+
return { summary, changes, coercions: [], budgetDeltas: [], notes: ["Preview is local. Pinterest permissions and app access are checked by the native API; there is no server dry-run."], execute };
|
|
553
|
+
}
|
|
554
|
+
var PinterestAssetService = class {
|
|
555
|
+
constructor(client, media = new LocalMediaResolver()) {
|
|
556
|
+
this.client = client;
|
|
557
|
+
this.media = media;
|
|
558
|
+
}
|
|
559
|
+
client;
|
|
560
|
+
media;
|
|
561
|
+
params(account3) {
|
|
562
|
+
return new URLSearchParams({ ad_account_id: pinterestId.parse(account3) });
|
|
563
|
+
}
|
|
564
|
+
async account(account3) {
|
|
565
|
+
const current = await this.client.get(`ad_accounts/${pinterestId.parse(account3)}`, z5.object({ id: pinterestId, owner }));
|
|
566
|
+
if (current.id !== account3) throw new AdportError3("PROVIDER_ERROR", "pinterest: advertiser response ID mismatch");
|
|
567
|
+
return current;
|
|
568
|
+
}
|
|
569
|
+
async ownedBoard(account3, boardId) {
|
|
570
|
+
const current = await this.account(account3);
|
|
571
|
+
const board = await this.client.get(`boards/${id2.parse(boardId)}`, boardSchema, this.params(account3));
|
|
572
|
+
if (board.id !== boardId || board.owner.username.toLowerCase() !== current.owner.username.toLowerCase()) throw new AdportError3("INVALID_INPUT", "pinterest: board is not owned by the selected advertiser; collaborator boards are not writable through this workflow");
|
|
573
|
+
return board;
|
|
574
|
+
}
|
|
575
|
+
async nativeOwner(account3) {
|
|
576
|
+
const current = await this.account(account3);
|
|
577
|
+
const tokenOwner = await this.client.get("user_account", z5.object({ username }));
|
|
578
|
+
if (current.owner.username.toLowerCase() !== tokenOwner.username.toLowerCase()) throw new AdportError3("INVALID_INPUT", "pinterest: native video uploads belong to the token user; the selected advertiser must have that same owner");
|
|
579
|
+
}
|
|
580
|
+
async page(path, schema, input, params) {
|
|
581
|
+
params.set("page_size", String(input.page_size));
|
|
582
|
+
if (input.bookmark) params.set("bookmark", input.bookmark);
|
|
583
|
+
const data = await this.client.get(path, z5.object({ items: z5.array(schema), bookmark: z5.string().nullable().optional() }), params);
|
|
584
|
+
if (data.items.length > input.page_size || data.bookmark && (data.bookmark === input.bookmark || !data.items.length)) throw new AdportError3("PROVIDER_ERROR", "pinterest: media pagination did not advance");
|
|
585
|
+
return { ...data, truncated: Boolean(data.bookmark), ...data.bookmark ? { next_cursor: data.bookmark } : {} };
|
|
586
|
+
}
|
|
587
|
+
async boards(input) {
|
|
588
|
+
const current = await this.account(input.account_id), params = this.params(input.account_id);
|
|
589
|
+
if (input.privacy) params.set("privacy", input.privacy);
|
|
590
|
+
const result = await this.page("boards", boardSchema, input, params);
|
|
591
|
+
return { ...result, items: result.items.map((board) => ({ ...board, owned_by_advertiser: board.owner.username.toLowerCase() === current.owner.username.toLowerCase() })) };
|
|
592
|
+
}
|
|
593
|
+
async getBoard(account3, boardId) {
|
|
594
|
+
const board = await this.ownedBoard(account3, boardId), snapshotHash = boardSnapshot(board);
|
|
595
|
+
const creative = { id: board.id, provider: "pinterest", account_id: account3, name: board.name, type: "PINTEREST_BOARD", status: board.privacy, headlines: [], descriptions: board.description ? [board.description] : [], landing_urls: [], media: [], actions: [{ label: "Edit board", tool: "pinterest_update_board", arguments: { account_id: account3, board_id: board.id, expected_snapshot_hash: snapshotHash }, fields: [...board.is_ads_only === true || board.privacy === "PROTECTED" ? [] : [{ key: "name", label: "Board name", type: "text", value: board.name, max_length: 180 }], { key: "description", label: "Description", type: "text", value: board.description ?? "", max_length: 500 }] }] };
|
|
596
|
+
return { board, snapshot_hash: snapshotHash, creatives: [creative], truncated: false, notes: ["Board copy and visibility are current native values. Copy edits preserve privacy, Pins, sections and ad delivery. Counts may change independently; they are not a deletion guarantee."] };
|
|
597
|
+
}
|
|
598
|
+
async requireEmptyBoard(account3, board) {
|
|
599
|
+
if (board.privacy !== "SECRET" || board.is_ads_only !== false || board.pin_count !== 0 || board.collaborator_count !== 0 || board.follower_count !== 0) throw new AdportError3("INVALID_INPUT", "pinterest: empty-board deletion requires an explicitly SECRET, non-ad-only board with known zero Pins, collaborators and followers");
|
|
600
|
+
const input = { account_id: account3, page_size: 1 };
|
|
601
|
+
const pins = await this.page(`boards/${board.id}/pins`, pinSchema, input, this.params(account3));
|
|
602
|
+
const sections = await this.page(`boards/${board.id}/sections`, z5.object({ id: id2.optional(), name: z5.string() }), input, this.params(account3));
|
|
603
|
+
if (pins.items.length || pins.truncated || sections.items.length || sections.truncated) throw new AdportError3("INVALID_INPUT", "pinterest: board still contains Pins or sections; empty-board deletion does not remove content");
|
|
604
|
+
}
|
|
605
|
+
async getPin(account3, pinId2) {
|
|
606
|
+
const pin = await this.client.get(`pins/${id2.parse(pinId2)}`, pinSchema, this.params(account3));
|
|
607
|
+
if (pin.id !== pinId2) throw new AdportError3("PROVIDER_ERROR", "pinterest: Pin response ID mismatch");
|
|
608
|
+
const board = await this.ownedBoard(account3, pin.board_id);
|
|
609
|
+
const snapshotHash = snapshot(pin, board);
|
|
610
|
+
const creative = { id: pin.id, provider: "pinterest", account_id: account3, name: pin.title || pin.id, type: "ORIGINAL_PIN", status: board.privacy, headlines: pin.title ? [pin.title] : [], descriptions: pin.description ? [pin.description] : [], landing_urls: pin.link && link.safeParse(pin.link).success ? [pin.link] : [], media: pinMedia(pin.media), actions: pin.is_owner === true && pin.has_been_promoted === false ? [{ label: "Edit original Pin copy", tool: "pinterest_update_pin", arguments: { account_id: account3, pin_id: pin.id, expected_snapshot_hash: snapshotHash }, fields: [{ key: "title", label: "Title", type: "text", value: pin.title ?? "", max_length: 100 }, { key: "description", label: "Description", type: "text", value: pin.description ?? "", max_length: 800 }, { key: "alt_text", label: "Alternative text", type: "text", value: pin.alt_text ?? "", max_length: 500 }, ...pin.link ? [{ key: "link", label: "Destination URL", type: "text", value: pin.link, max_length: 2048 }] : []] }] : [] };
|
|
611
|
+
return { pin, board, snapshot_hash: snapshotHash, creatives: [creative], truncated: false };
|
|
612
|
+
}
|
|
613
|
+
async pins(input) {
|
|
614
|
+
if (input.board_id) await this.ownedBoard(input.account_id, input.board_id);
|
|
615
|
+
else await this.account(input.account_id);
|
|
616
|
+
const data = await this.page(input.board_id ? `boards/${input.board_id}/pins` : "pins", pinSchema, input, this.params(input.account_id));
|
|
617
|
+
if (input.board_id && data.items.some((pin) => pin.board_id !== input.board_id)) throw new AdportError3("PROVIDER_ERROR", "pinterest: Pin collection returned another board");
|
|
618
|
+
const creatives = data.items.map((pin) => ({ id: pin.id, provider: "pinterest", account_id: input.account_id, name: pin.title || pin.id, type: "ORIGINAL_PIN", headlines: pin.title ? [pin.title] : [], descriptions: pin.description ? [pin.description] : [], landing_urls: pin.link && link.safeParse(pin.link).success ? [pin.link] : [], media: pinMedia(pin.media), actions: [] }));
|
|
619
|
+
return { ...data, creatives, notes: ["Original Pins are shared content. Read pinterest_get_pin for an exact snapshot before editing or deleting; promoted Pins require a new replacement Pin."] };
|
|
620
|
+
}
|
|
621
|
+
async getMedia(account3, mediaId) {
|
|
622
|
+
await this.nativeOwner(account3);
|
|
623
|
+
const current = await this.client.get(`media/${id2.parse(mediaId)}`, mediaSchema);
|
|
624
|
+
if (current.media_id !== mediaId) throw new AdportError3("PROVIDER_ERROR", "pinterest: media response ID mismatch");
|
|
625
|
+
return current;
|
|
626
|
+
}
|
|
627
|
+
checkPublication(board, expected, confirmed) {
|
|
628
|
+
if (board.privacy !== expected) throw new AdportError3("PENDING_MISMATCH", "pinterest: board privacy changed; read boards and prepare a new preview");
|
|
629
|
+
if (board.privacy === "PUBLIC" && !confirmed) throw new AdportError3("INVALID_INPUT", "pinterest: a public board publishes organic content; explicit confirm_publication is required");
|
|
630
|
+
}
|
|
631
|
+
checkPinReceipt(pin, boardId, fields2, pinId2) {
|
|
632
|
+
if (pinId2 && pin.id !== pinId2 || pin.board_id !== boardId || Object.entries(fields2).some(([key, value]) => (pin[key] ?? null) !== value)) throw new AdportError3("PROVIDER_ERROR", "pinterest: Pin write receipt differs from approved content; reconcile before retrying", { resource_ids: [pin.id] });
|
|
633
|
+
return [pin.id];
|
|
634
|
+
}
|
|
635
|
+
async plan(op) {
|
|
636
|
+
if (op.provider !== "pinterest" || !PINTEREST_ASSET_WRITES.has(op.tool) || op.kind !== kinds[op.tool]) throw new AdportError3("INVALID_INPUT", "pinterest: invalid asset operation kind");
|
|
637
|
+
const account3 = pinterestId.parse(op.accountId), params = this.params(account3);
|
|
638
|
+
if (op.tool === "pinterest_create_board") {
|
|
639
|
+
const input2 = createBoard.parse(op.payload), current2 = await this.account(account3);
|
|
640
|
+
this.checkPublication(input2, input2.privacy, input2.confirm_publication);
|
|
641
|
+
const { confirm_publication: _confirmed, ...body } = input2;
|
|
642
|
+
const native = { ...body, ...input2.privacy === "PROTECTED" ? { is_ads_only: true } : {} };
|
|
643
|
+
return plan(`Create Pinterest ${input2.privacy} board`, [JSON.stringify(native), input2.privacy === "PROTECTED" ? "Pinterest names ad-only boards \u201CAd-only Pins\u201D; they are protected, not secret." : `Board owned by ${current2.owner.username}; no Pin or ad is created.`], async () => {
|
|
644
|
+
const created = await this.client.mutate("boards", "POST", native, boardSchema, params);
|
|
645
|
+
if (created.owner.username.toLowerCase() !== current2.owner.username.toLowerCase() || created.privacy !== input2.privacy || input2.privacy !== "PROTECTED" && created.name !== input2.name || input2.privacy === "PROTECTED" && created.is_ads_only !== true) throw new AdportError3("PROVIDER_ERROR", "pinterest: created board owner/privacy/name mismatch; reconcile before retrying", { resource_ids: [created.id] });
|
|
646
|
+
return [created.id];
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
if (op.tool === "pinterest_update_board" || op.tool === "pinterest_delete_empty_board") {
|
|
650
|
+
const input2 = op.tool === "pinterest_update_board" ? updateBoard.parse(op.payload) : deleteEmptyBoard.parse(op.payload), board = await this.ownedBoard(account3, input2.board_id);
|
|
651
|
+
if (boardSnapshot(board) !== input2.expected_snapshot_hash) throw new AdportError3("PENDING_MISMATCH", "pinterest: board copy, privacy or ownership changed; read the board again");
|
|
652
|
+
if (op.tool === "pinterest_delete_empty_board") {
|
|
653
|
+
await this.requireEmptyBoard(account3, board);
|
|
654
|
+
return plan(`Permanently delete empty Pinterest board \u201C${board.name}\u201D`, [`Board ${board.id}; SECRET; native counts, Pins and sections checked empty.`, "No ad, Pin or project media is removed. Pinterest has no documented atomic empty-board conditional delete: stop other board writers until the operation completes."], async () => {
|
|
655
|
+
const fresh = await this.ownedBoard(account3, board.id);
|
|
656
|
+
if (boardSnapshot(fresh) !== input2.expected_snapshot_hash) throw new AdportError3("PENDING_MISMATCH", "pinterest: board changed before deletion; read it again");
|
|
657
|
+
await this.requireEmptyBoard(account3, fresh);
|
|
658
|
+
const receipt = await this.client.mutate(`boards/${board.id}`, "DELETE", void 0, boardSchema.optional(), params);
|
|
659
|
+
if (receipt && receipt.id !== board.id) throw new AdportError3("PROVIDER_ERROR", "pinterest: board deletion receipt ID mismatch; reconcile before retrying", { resource_ids: [board.id] });
|
|
660
|
+
return [board.id];
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
const patch = updateBoard.parse(input2);
|
|
664
|
+
if (patch.name !== void 0 && (board.is_ads_only === true || board.privacy === "PROTECTED")) throw new AdportError3("INVALID_INPUT", "pinterest: ad-only board names are assigned by Pinterest; edit only the description");
|
|
665
|
+
const fields3 = { ...patch.name !== void 0 ? { name: patch.name } : {}, ...patch.description !== void 0 ? { description: patch.description } : {} };
|
|
666
|
+
const edit = plan(`Edit Pinterest board \u201C${board.name}\u201D`, [`Board ${board.id}; visibility ${board.privacy} is preserved. Pins, sections and delivery are unchanged.`, ...Object.entries(fields3).map(([key, value]) => `${key}: ${JSON.stringify(board[key] ?? null)} \u2192 ${JSON.stringify(value)}`), "Pinterest provides no documented conditional-write version; the current snapshot is rechecked on apply, without claiming an atomic provider compare-and-swap."], async () => {
|
|
667
|
+
const receipt = await this.client.mutate(`boards/${board.id}`, "PATCH", fields3, boardSchema, params);
|
|
668
|
+
if (receipt.id !== board.id || receipt.privacy !== board.privacy || receipt.owner.username.toLowerCase() !== board.owner.username.toLowerCase() || receipt.is_ads_only !== board.is_ads_only || Object.entries(fields3).some(([key, value]) => (receipt[key] ?? null) !== value) || patch.name === void 0 && receipt.name !== board.name || patch.description === void 0 && (receipt.description ?? null) !== (board.description ?? null)) throw new AdportError3("PROVIDER_ERROR", "pinterest: board update receipt differs from approved copy or preserved visibility/ownership; reconcile before retrying", { resource_ids: [board.id] });
|
|
669
|
+
return [board.id];
|
|
670
|
+
});
|
|
671
|
+
return { ...edit, fieldChanges: Object.entries(fields3).filter(([key, value]) => (board[key] ?? null) !== value).map(([key, value]) => ({ field: key === "name" ? "Name" : "Description", before: String(board[key] ?? "(not set)"), after: String(value ?? "(cleared)") })) };
|
|
672
|
+
}
|
|
673
|
+
if (op.tool === "pinterest_upload_video") {
|
|
674
|
+
const input2 = source.parse(op.payload);
|
|
675
|
+
await this.nativeOwner(account3);
|
|
676
|
+
const file = await this.media.read(input2, { maxBytes: 50 * 1024 * 1024, contentTypes: ["video/mp4"] });
|
|
677
|
+
return plan("Upload Pinterest video source", [`+ ${file.name}; ${file.bytes.length} bytes; SHA-256 ${file.sha256}.`, "Native token-owner library; no Pin, post, ad or delivery change. Check pinterest_get_media_upload for processing; registered/upload-accepted does not mean succeeded."], async () => {
|
|
678
|
+
let mediaId;
|
|
679
|
+
try {
|
|
680
|
+
const result = await this.client.mutate("media", "POST", { media_type: "video" }, z5.object({ media_id: id2, media_type: z5.literal("video"), upload_url: z5.string().url().optional(), upload_parameters: z5.record(z5.string(), z5.string()).optional() }));
|
|
681
|
+
mediaId = result.media_id;
|
|
682
|
+
if (!result.upload_url || !result.upload_parameters) throw new Error("incomplete native upload instructions");
|
|
683
|
+
await this.client.uploadVideo(result.upload_url, result.upload_parameters, file.bytes, file.name);
|
|
684
|
+
} catch (error) {
|
|
685
|
+
const details = error instanceof AdportError3 && error.details && typeof error.details === "object" ? error.details : {};
|
|
686
|
+
const ids3 = mediaId ? [mediaId] : Array.isArray(details.resource_ids) ? details.resource_ids.filter((value) => typeof value === "string" && /^\d{1,30}$/.test(value)).slice(0, 2) : [];
|
|
687
|
+
throw new AdportError3("PROVIDER_ERROR", "pinterest: native video registration/transfer was not confirmed; reconcile before retrying. No mutation was retried.", { resource_ids: ids3 });
|
|
688
|
+
}
|
|
689
|
+
return [mediaId];
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
if (op.tool === "pinterest_create_image_pin" || op.tool === "pinterest_create_video_pin") {
|
|
693
|
+
const image = op.tool === "pinterest_create_image_pin" ? createImage.parse(op.payload) : void 0, video = image ? void 0 : createVideo.parse(op.payload), input2 = image ?? video;
|
|
694
|
+
const board = await this.ownedBoard(account3, input2.board_id);
|
|
695
|
+
this.checkPublication(board, input2.expected_board_privacy, input2.confirm_publication);
|
|
696
|
+
let mediaSource, mediaNote;
|
|
697
|
+
if (image) {
|
|
698
|
+
const file = await this.media.read(image, { maxBytes: 20 * 1024 * 1024, contentTypes: ["image/png", "image/jpeg"] });
|
|
699
|
+
mediaSource = { source_type: "image_base64", content_type: file.contentType, data: Buffer.from(file.bytes).toString("base64") };
|
|
700
|
+
mediaNote = `${file.name}; ${file.bytes.length} bytes; SHA-256 ${file.sha256}.`;
|
|
701
|
+
} else {
|
|
702
|
+
const native = await this.getMedia(account3, video.native_media_id);
|
|
703
|
+
if (native.status !== "succeeded") throw new AdportError3("INVALID_INPUT", `pinterest: video processing is ${native.status}; only succeeded media can create a Pin`);
|
|
704
|
+
mediaSource = { source_type: "video_id", media_id: native.media_id, cover_image_key_frame_time: video.cover_image_key_frame_time };
|
|
705
|
+
mediaNote = `Native video ${native.media_id}; cover keyframe ${video.cover_image_key_frame_time}s.`;
|
|
706
|
+
}
|
|
707
|
+
const fields3 = copyFields(input2), body = { board_id: board.id, ...fields3, media_source: mediaSource };
|
|
708
|
+
return plan(`Create Pinterest ${image ? "image" : "video"} Pin on ${board.privacy} board`, [mediaNote, `Board ${board.id} \u201C${board.name}\u201D; visibility ${board.privacy}.`, JSON.stringify(fields3), "Creates original content on Pinterest. PUBLIC boards publish organically; PROTECTED is ad-only, not secret. No ad is attached or enabled. Source media is immutable; replace it by creating another Pin."], async () => this.checkPinReceipt(await this.client.mutate("pins", "POST", body, pinSchema, params), board.id, fields3));
|
|
709
|
+
}
|
|
710
|
+
const input = op.tool === "pinterest_update_pin" ? updatePin.parse(op.payload) : deletePin.parse(op.payload), current = await this.getPin(account3, input.pin_id);
|
|
711
|
+
if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError3("PENDING_MISMATCH", "pinterest: Pin copy, ownership, promotion or board privacy changed; read the Pin again");
|
|
712
|
+
if (current.pin.is_owner !== true || current.pin.has_been_promoted !== false) throw new AdportError3("INVALID_INPUT", "pinterest: only an explicitly owned, never-promoted original Pin can be edited/deleted here. Create a replacement for promoted or unknown usage.");
|
|
713
|
+
if (op.tool === "pinterest_delete_pin") return plan(`Permanently delete Pinterest Pin ${input.pin_id}`, [`Remove the original ${current.board.privacy} Pin and its content. This cannot be undone; source project media is preserved.`], async () => {
|
|
714
|
+
const receipt = await this.client.mutate(`pins/${input.pin_id}`, "DELETE", void 0, pinSchema.optional(), params);
|
|
715
|
+
if (receipt && receipt.id !== input.pin_id) throw new AdportError3("PROVIDER_ERROR", "pinterest: deletion receipt ID mismatch; reconcile before retrying", { resource_ids: [input.pin_id] });
|
|
716
|
+
return [input.pin_id];
|
|
717
|
+
});
|
|
718
|
+
const fields2 = copyFields(input);
|
|
719
|
+
return plan(`Edit original Pinterest Pin ${input.pin_id}`, [`Board ${current.board.id}; visibility ${current.board.privacy}. Source media, board membership and ad delivery are preserved.`, ...Object.entries(fields2).map(([key, value]) => `${key}: ${JSON.stringify(current.pin[key] ?? null)} \u2192 ${JSON.stringify(value)}`), "Changes the shared original Pin, including its existing organic display. Native update is beta and may be denied for this app."], async () => this.checkPinReceipt(await this.client.mutate(`pins/${input.pin_id}`, "PATCH", fields2, pinSchema, params), current.board.id, fields2, input.pin_id));
|
|
720
|
+
}
|
|
721
|
+
};
|
|
722
|
+
function pinterestAssetTools(provider) {
|
|
723
|
+
const account3 = { account_id: pinterestId }, paging2 = { page_size: z5.number().int().min(1).max(250).default(25), bookmark: z5.string().min(1).optional() };
|
|
724
|
+
return [
|
|
725
|
+
defineTool2({ name: "pinterest_boards", namespace: "pinterest", description: "List selected advertiser-owner boards, privacy and ownership with native pagination. Public boards require boards:read; secret boards also require boards:read_secret. Collaborator boards are labeled, not treated as owned.", input: z5.object({ ...account3, ...paging2, privacy: z5.enum(["ALL", "PUBLIC", "PROTECTED", "SECRET", "PUBLIC_AND_SECRET"]).optional() }), annotations: { readOnly: true }, handler: (input) => provider.assets.boards(input) }),
|
|
726
|
+
defineTool2({ name: "pinterest_get_board", namespace: "pinterest", description: "Read one advertiser-owned board, native visibility/counts and copy snapshot with a guarded edit widget. Public boards require boards:read; secret boards also need boards:read_secret. No Pins are fetched or changed.", input: z5.object({ ...account3, board_id: id2 }), output: creativesOutput2.passthrough(), presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.assets.getBoard(input.account_id, input.board_id) }),
|
|
727
|
+
defineTool2({ name: "pinterest_pins", namespace: "pinterest", description: "View original Pinterest Pin copy/media for this advertiser owner or one owned board. Native bookmark pagination; public boards/Pins need boards:read and pins:read; secret content also needs their read_secret scopes. No dashboard.", input: z5.object({ ...account3, ...paging2, board_id: id2.optional() }), output: creativesOutput2.passthrough(), presentation: "creatives", pagination: { cursorInput: "bookmark" }, annotations: { readOnly: true }, handler: (input) => provider.assets.pins(input) }),
|
|
728
|
+
defineTool2({ name: "pinterest_get_pin", namespace: "pinterest", description: "View exact original Pin, owned board visibility and snapshot hash. Owned never-promoted Pins expose guarded copy-edit actions. This is separate from advertiser ad settings.", input: z5.object({ ...account3, pin_id: id2 }), output: creativesOutput2.passthrough(), presentation: "creatives", annotations: { readOnly: true }, handler: (input) => provider.assets.getPin(input.account_id, input.pin_id) }),
|
|
729
|
+
defineTool2({ name: "pinterest_get_media_upload", namespace: "pinterest", description: "Read native video upload processing. The credential-global media library must match the selected advertiser owner; requires pins:read and user_accounts:read. Never assumes an upload is ready.", input: z5.object({ ...account3, native_media_id: id2 }), annotations: { readOnly: true }, handler: (input) => provider.assets.getMedia(input.account_id, input.native_media_id) }),
|
|
730
|
+
guardedWriteTool2({ name: "pinterest_create_board", namespace: "pinterest", provider: "pinterest", kind: "create", destructive: false, payload: createBoard, description: "Create an advertiser-owned board, SECRET by default. PUBLIC requires confirm_publication; PROTECTED creates an ad-only board with Pinterest-assigned name. Public boards require boards read/write; SECRET also requires boards:read_secret and boards:write_secret." }),
|
|
731
|
+
guardedWriteTool2({ name: "pinterest_update_board", namespace: "pinterest", provider: "pinterest", kind: "update", payload: updateBoard, description: "Edit supplied board name/description after matching its copy/owner/privacy snapshot. Omitted fields, privacy, Pins, sections and delivery are preserved; null clears description. Ad-only names cannot be changed. Uses boards read/write and corresponding secret scopes for SECRET boards." }),
|
|
732
|
+
guardedWriteTool2({ name: "pinterest_delete_empty_board", namespace: "pinterest", provider: "pinterest", kind: "remove", payload: deleteEmptyBoard, description: "Permanently remove an owned SECRET non-ad-only board after snapshot and known-zero Pins/collaborators/followers plus empty native Pin/section checks. Rejects populated or unknown state; no cascade workflow. Confirm deletion and stop concurrent board writers; Pinterest has no atomic empty conditional delete." }),
|
|
733
|
+
guardedWriteTool2({ name: "pinterest_create_image_pin", namespace: "pinterest", provider: "pinterest", kind: "create", destructive: false, payload: createImage, description: "Upload exact SHA-bound PNG/JPEG bytes and create original Pin content on an owned board. Hosted media_id or local file_path; no dashboard. Explicit original_content and current board privacy required. PUBLIC needs confirm_publication; SECRET needs boards/pins read_secret and write_secret scopes. No ad or delivery change." }),
|
|
734
|
+
guardedWriteTool2({ name: "pinterest_upload_video", namespace: "pinterest", provider: "pinterest", kind: "create", destructive: false, payload: source, description: "Register and upload SHA-bound MP4 to Pinterest, without creating a Pin or ad. Native media is token-owner scoped, so advertiser owner must match; requires pins read/write and user_accounts:read. Read returned ID processing before create_video_pin. Unknown outcomes are not retried." }),
|
|
735
|
+
guardedWriteTool2({ name: "pinterest_create_video_pin", namespace: "pinterest", provider: "pinterest", kind: "create", destructive: false, payload: createVideo, description: "Create original Pin content from succeeded native video and an owned board; cover image uses explicit keyframe seconds. Requires boards/pins scopes, including read_secret/write_secret for SECRET content. Binds current visibility; PUBLIC requires confirm_publication. No advertiser ad is created." }),
|
|
736
|
+
guardedWriteTool2({ name: "pinterest_update_pin", namespace: "pinterest", provider: "pinterest", kind: "update", payload: updatePin, description: "Edit supplied title, description, alt text or link of an owned, never-promoted original Pin. Omitted copy, media and board are preserved; null clears a supplied field. Snapshot binds current copy/privacy/promotion. Changes existing organic content; SECRET needs boards/pins secret scopes. Native beta access required." }),
|
|
737
|
+
guardedWriteTool2({ name: "pinterest_delete_pin", namespace: "pinterest", provider: "pinterest", kind: "remove", payload: deletePin, description: "Permanently delete an owned, explicitly never-promoted original Pin after matching its current snapshot. Rejects promoted or unknown usage; does not delete project source media." })
|
|
738
|
+
];
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// src/keywords.ts
|
|
742
|
+
import { createHash as createHash2 } from "crypto";
|
|
743
|
+
import { AdportError as AdportError4, creativesOutput as creativesOutput3, defineTool as defineTool3, guardedWriteTool as guardedWriteTool3, planningViewSchema } from "@adport/core";
|
|
744
|
+
import { z as z6 } from "zod";
|
|
745
|
+
var hash2 = z6.string().regex(/^[a-f0-9]{64}$/);
|
|
746
|
+
var cursor = z6.string().min(1).max(4096);
|
|
747
|
+
var parent = z6.discriminatedUnion("type", [z6.object({ type: z6.literal("account") }).strict(), z6.object({ type: z6.literal("campaign"), campaign_id: pinterestId }).strict(), z6.object({ type: z6.literal("ad_group"), ad_group_id: pinterestId }).strict()]);
|
|
748
|
+
var match = z6.enum(["BROAD", "PHRASE", "EXACT", "EXACT_NEGATIVE", "PHRASE_NEGATIVE"]);
|
|
749
|
+
var metricsCountry = z6.enum(["CA", "GB", "US", "IE", "AU", "NZ"]);
|
|
750
|
+
var keyword = z6.looseObject({ id: pinterestId, parent_id: pinterestId, parent_type: z6.string().optional(), match_type: match.nullable(), value: z6.string(), archived: z6.boolean().optional(), bid: z6.number().int().nullable().optional() });
|
|
751
|
+
var reference = { parent, expected_parent_hash: hash2 };
|
|
752
|
+
var create = z6.object({ ...reference, keywords: z6.array(z6.object({ value: z6.string().trim().min(1).max(120), match_type: match }).strict()).min(1).max(100) }).strict().superRefine((v, ctx) => {
|
|
753
|
+
if (new Set(v.keywords.map((k) => `${k.match_type}:${k.value}`)).size !== v.keywords.length) ctx.addIssue({ code: "custom", message: "Use unique keyword/match-type pairs" });
|
|
754
|
+
if (v.parent.type !== "ad_group" && v.keywords.some((k) => !k.match_type.endsWith("_NEGATIVE"))) ctx.addIssue({ code: "custom", message: "Account and campaign parents accept only negative keywords" });
|
|
755
|
+
});
|
|
756
|
+
var archive = z6.object({ ...reference, keywords: z6.array(z6.object({ keyword_id: pinterestId, expected_snapshot_hash: hash2 }).strict()).min(1).max(100) }).strict().refine((v) => new Set(v.keywords.map((k) => k.keyword_id)).size === v.keywords.length, "Use unique keyword IDs");
|
|
757
|
+
var digest = (value) => createHash2("sha256").update(JSON.stringify(value)).digest("hex");
|
|
758
|
+
var snapshot2 = (value) => digest({ id: value.id, parent_id: value.parent_id, parent_type: value.parent_type ?? null, match_type: value.match_type, value: value.value, archived: value.archived ?? null });
|
|
759
|
+
var writes = /* @__PURE__ */ new Set(["pinterest_create_keywords", "pinterest_archive_keywords"]);
|
|
760
|
+
var PinterestKeywordService = class {
|
|
761
|
+
constructor(client, entity) {
|
|
762
|
+
this.client = client;
|
|
763
|
+
this.entity = entity;
|
|
764
|
+
}
|
|
765
|
+
client;
|
|
766
|
+
entity;
|
|
767
|
+
supports(tool) {
|
|
768
|
+
return writes.has(tool);
|
|
769
|
+
}
|
|
770
|
+
base(account3) {
|
|
771
|
+
return `ad_accounts/${pinterestId.parse(account3)}/keywords`;
|
|
772
|
+
}
|
|
773
|
+
async context(account3, selected3) {
|
|
774
|
+
const scope = parent.parse(selected3);
|
|
775
|
+
let entity, campaign;
|
|
776
|
+
if (scope.type === "account") {
|
|
777
|
+
entity = await this.client.get(`ad_accounts/${pinterestId.parse(account3)}`, z6.looseObject({ id: pinterestId }));
|
|
778
|
+
if (entity.id !== account3) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword account response mismatch");
|
|
779
|
+
} else if (scope.type === "campaign") entity = await this.entity(account3, "campaigns", scope.campaign_id);
|
|
780
|
+
else {
|
|
781
|
+
entity = await this.entity(account3, "ad_groups", scope.ad_group_id);
|
|
782
|
+
campaign = await this.entity(account3, "campaigns", pinterestId.parse(entity.campaign_id));
|
|
783
|
+
}
|
|
784
|
+
const parentId = pinterestId.parse(entity.id), configuration3 = { account_id: account3, parent: scope, parent_id: parentId, status: entity.status ?? null, ...campaign ? { campaign_id: campaign.id, campaign_status: campaign.status ?? null } : {} };
|
|
785
|
+
return { ...configuration3, entity, ...campaign ? { campaign } : {}, parent_snapshot_hash: digest(configuration3), notes: ["Account scope lists account-level negative keywords only. Campaign/ad-group keywords need their explicit parent.", "Keywords have no native pause flag. Keyword bids are deprecated and are not exposed as writable controls."] };
|
|
786
|
+
}
|
|
787
|
+
scoped(value, context) {
|
|
788
|
+
const types = context.parent.type === "account" ? ["advertiser", "account", "adaccount"] : context.parent.type === "campaign" ? ["campaign"] : ["adgroup"];
|
|
789
|
+
if (value.parent_id !== context.parent_id || value.parent_type && !types.includes(value.parent_type.toLowerCase().replaceAll("_", ""))) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword collection returned another parent");
|
|
790
|
+
return value;
|
|
791
|
+
}
|
|
792
|
+
async page(account3, context, size, bookmark, matches) {
|
|
793
|
+
const params = new URLSearchParams({ page_size: String(size) });
|
|
794
|
+
if (context.parent.type === "campaign") params.set("campaign_id", context.parent_id);
|
|
795
|
+
if (context.parent.type === "ad_group") params.set("ad_group_id", context.parent_id);
|
|
796
|
+
if (bookmark) params.set("bookmark", bookmark);
|
|
797
|
+
if (matches) params.set("match_types", matches.join(","));
|
|
798
|
+
const data = await this.client.get(this.base(account3), z6.object({ items: z6.array(keyword), bookmark: z6.string().nullable().optional() }), params);
|
|
799
|
+
if (data.items.length > size || new Set(data.items.map((v) => v.id)).size !== data.items.length || data.bookmark && (!data.items.length || data.bookmark === bookmark)) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword pagination did not advance or returned duplicate/oversized rows");
|
|
800
|
+
if (matches && data.items.some((v) => v.match_type === null || !matches.includes(v.match_type))) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword collection ignored the match-type selection");
|
|
801
|
+
return { ...data, items: data.items.map((v) => this.scoped(v, context)), truncated: Boolean(data.bookmark), ...data.bookmark ? { next_cursor: data.bookmark } : {} };
|
|
802
|
+
}
|
|
803
|
+
view(account3, scope, parentHash, item) {
|
|
804
|
+
return { id: item.id, provider: "pinterest", account_id: account3, name: item.value, type: `${item.match_type ?? "UNKNOWN"}_KEYWORD`, status: item.archived === true ? "ARCHIVED" : item.archived === false ? "UNARCHIVED" : "UNKNOWN", headlines: [item.value], descriptions: [], landing_urls: [], media: [], actions: item.archived === false ? [{ label: "Archive keyword", tool: "pinterest_archive_keywords", arguments: { account_id: account3, parent: scope, expected_parent_hash: parentHash, keywords: [{ keyword_id: item.id, expected_snapshot_hash: snapshot2(item) }] }, fields: [] }] : [] };
|
|
805
|
+
}
|
|
806
|
+
async list(input) {
|
|
807
|
+
const context = await this.context(input.account_id, input.parent), data = await this.page(input.account_id, context, input.page_size, input.bookmark, input.match_types);
|
|
808
|
+
return { ...data, parent: context.parent, parent_id: context.parent_id, parent_snapshot_hash: context.parent_snapshot_hash, items: data.items.map((value) => ({ ...value, snapshot_hash: snapshot2(value) })), creatives: data.items.map((value) => this.view(input.account_id, context.parent, context.parent_snapshot_hash, value)), notes: context.notes };
|
|
809
|
+
}
|
|
810
|
+
async find(account3, context, wanted) {
|
|
811
|
+
const found = /* @__PURE__ */ new Map(), cursors = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set();
|
|
812
|
+
let bookmark;
|
|
813
|
+
for (let page2 = 0; page2 < 40; page2++) {
|
|
814
|
+
const result = await this.page(account3, context, 250, bookmark);
|
|
815
|
+
for (const row of result.items) {
|
|
816
|
+
if (seen.has(row.id)) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword inventory repeated an ID");
|
|
817
|
+
seen.add(row.id);
|
|
818
|
+
if (wanted.has(row.id)) found.set(row.id, row);
|
|
819
|
+
}
|
|
820
|
+
if (found.size === wanted.size) return found;
|
|
821
|
+
if (!result.next_cursor) throw new AdportError4("INVALID_INPUT", "pinterest: requested keyword is not visible in this parent; archived keywords cannot be safely rediscovered/unarchived through this API");
|
|
822
|
+
if (cursors.has(result.next_cursor)) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword inventory repeated a cursor");
|
|
823
|
+
cursors.add(result.next_cursor);
|
|
824
|
+
bookmark = result.next_cursor;
|
|
825
|
+
}
|
|
826
|
+
throw new AdportError4("INVALID_INPUT", "pinterest: keyword ownership lookup exceeded 10,000 rows; no write was made");
|
|
827
|
+
}
|
|
828
|
+
async get(account3, scope, keywordId) {
|
|
829
|
+
const context = await this.context(account3, scope), found = (await this.find(account3, context, /* @__PURE__ */ new Set([keywordId]))).get(keywordId);
|
|
830
|
+
return { keyword: found, snapshot_hash: snapshot2(found), parent_snapshot_hash: context.parent_snapshot_hash, creatives: [this.view(account3, scope, context.parent_snapshot_hash, found)], truncated: false, notes: context.notes };
|
|
831
|
+
}
|
|
832
|
+
async metrics(input) {
|
|
833
|
+
metricsCountry.parse(input.country_code);
|
|
834
|
+
const data = await this.client.get(`${this.base(input.account_id)}/metrics`, z6.object({ data: z6.array(z6.looseObject({ keyword: z6.string(), metrics: z6.looseObject({ keyword_query_volume: z6.string().optional() }).optional() })) }), new URLSearchParams({ country_code: input.country_code, keywords: input.keywords.join(",") }));
|
|
835
|
+
const wanted = new Set(input.keywords), seen = /* @__PURE__ */ new Set();
|
|
836
|
+
for (const item of data.data) {
|
|
837
|
+
if (!wanted.has(item.keyword) || seen.has(item.keyword)) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword metrics returned another or repeated keyword");
|
|
838
|
+
seen.add(item.keyword);
|
|
839
|
+
}
|
|
840
|
+
return { ...data, country_code: input.country_code, truncated: false, planning: { title: "Pinterest keyword search frequency", columns: [{ key: "keyword", label: "Keyword" }, { key: "volume", label: "Native frequency" }], rows: input.keywords.map((value) => ({ keyword: value, volume: data.data.find((item) => item.keyword === value)?.metrics?.keyword_query_volume ?? null })), notes: ["Aggregated across Pinterest in the selected country, not account performance or campaign delivery.", "Native ranges such as 5M+ remain strings. Missing values remain unavailable; no counts are invented."] } };
|
|
841
|
+
}
|
|
842
|
+
async batch(account3, context, method, body, expected) {
|
|
843
|
+
const data = await this.client.mutate(this.base(account3), method, body, z6.object({ keywords: z6.array(z6.unknown()), errors: z6.array(z6.unknown()) }));
|
|
844
|
+
const ids3 = data.keywords.flatMap((value) => {
|
|
845
|
+
const parsed2 = z6.object({ id: pinterestId }).safeParse(value);
|
|
846
|
+
return parsed2.success ? [parsed2.data.id] : [];
|
|
847
|
+
});
|
|
848
|
+
const parsed = z6.array(keyword).safeParse(data.keywords);
|
|
849
|
+
if (data.errors.length || !parsed.success || parsed.data.length !== expected.length || new Set(ids3).size !== ids3.length) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword batch was partial or incomplete; reconcile returned IDs before retrying", { resource_ids: ids3 });
|
|
850
|
+
const unmatched = [...expected];
|
|
851
|
+
for (const row of parsed.data) {
|
|
852
|
+
try {
|
|
853
|
+
this.scoped(row, context);
|
|
854
|
+
} catch {
|
|
855
|
+
throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword receipt belongs to another parent; reconcile before retrying", { resource_ids: ids3 });
|
|
856
|
+
}
|
|
857
|
+
const index = unmatched.findIndex((item) => Object.entries(item).every(([key, value]) => row[key] === value));
|
|
858
|
+
if (index < 0) throw new AdportError4("PROVIDER_ERROR", "pinterest: keyword receipt differs from approved keywords; reconcile before retrying", { resource_ids: ids3 });
|
|
859
|
+
unmatched.splice(index, 1);
|
|
860
|
+
}
|
|
861
|
+
return ids3;
|
|
862
|
+
}
|
|
863
|
+
async plan(op, guard) {
|
|
864
|
+
if (op.provider !== "pinterest" || !this.supports(op.tool) || op.kind !== (op.tool === "pinterest_create_keywords" ? "create" : "update")) throw new AdportError4("INVALID_INPUT", "pinterest: invalid keyword operation");
|
|
865
|
+
const input = op.tool === "pinterest_create_keywords" ? create.parse(op.payload) : archive.parse(op.payload), context = await this.context(op.accountId, input.parent);
|
|
866
|
+
if (context.parent_snapshot_hash !== input.expected_parent_hash) throw new AdportError4("PENDING_MISMATCH", "pinterest: keyword parent state changed; read its context again");
|
|
867
|
+
const notes5 = ["Preview is local; Pinterest has no server dry-run for keyword writes.", ...context.notes];
|
|
868
|
+
if (op.tool === "pinterest_create_keywords") {
|
|
869
|
+
const value2 = create.parse(input), positive = value2.keywords.some((item) => !item.match_type.endsWith("_NEGATIVE"));
|
|
870
|
+
if (guard.forcePausedCreation && positive && context.entity.status !== "PAUSED" && context.campaign?.status !== "PAUSED") throw new AdportError4("POLICY_VIOLATION", "pinterest: positive keywords cannot be paused individually; paused_creation requires a paused parent ad group or campaign");
|
|
871
|
+
return { summary: `Create ${value2.keywords.length} Pinterest keywords`, changes: [`Parent ${context.parent.type} ${context.parent_id}.`, ...value2.keywords.map((item) => `${item.match_type}: ${item.value}`), "Keyword bids are omitted; existing ad-group bidding is preserved."], coercions: [], budgetDeltas: [], notes: notes5, execute: () => this.batch(op.accountId, context, "POST", { parent_id: context.parent_id, keywords: value2.keywords }, value2.keywords.map((item) => ({ ...item, archived: false }))) };
|
|
872
|
+
}
|
|
873
|
+
const value = archive.parse(input), current = await this.find(op.accountId, context, new Set(value.keywords.map((item) => item.keyword_id)));
|
|
874
|
+
for (const item of value.keywords) if (snapshot2(current.get(item.keyword_id)) !== item.expected_snapshot_hash || current.get(item.keyword_id).archived !== false) throw new AdportError4("PENDING_MISMATCH", "pinterest: keyword contents or archive state changed; read it again");
|
|
875
|
+
return { summary: `Archive ${value.keywords.length} Pinterest keywords`, changes: [...current.values()].map((item) => `${item.match_type}: ${item.value} (${item.id}) \u2192 archived`), coercions: [], budgetDeltas: [], notes: [...notes5, "Archiving removes keywords from native lists and metrics. Removing exclusions can broaden matching; this does not pause the parent or promise an undo path."], execute: () => this.batch(op.accountId, context, "PATCH", { keywords: value.keywords.map((item) => ({ id: item.keyword_id, archived: true })) }, value.keywords.map((item) => ({ id: item.keyword_id, value: current.get(item.keyword_id).value, match_type: current.get(item.keyword_id).match_type, archived: true }))) };
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
function pinterestKeywordTools(provider) {
|
|
879
|
+
const account3 = { account_id: pinterestId }, selected3 = { ...account3, parent: parent.default({ type: "account" }) };
|
|
880
|
+
return [
|
|
881
|
+
defineTool3({ name: "pinterest_keyword_context", namespace: "pinterest", description: "Read an explicit account/campaign/ad-group keyword parent and its snapshot. Account scope means account exclusions only, not all campaign/group keywords. Keywords have no pause flag; bids are deprecated.", input: z6.object(selected3), annotations: { readOnly: true }, handler: (v) => provider.keywords.context(v.account_id, v.parent) }),
|
|
882
|
+
defineTool3({ name: "pinterest_keywords", namespace: "pinterest", description: "List one verified parent\u2019s native keywords, copy snapshots and guarded archive actions. Native bookmark pagination; UNARCHIVED is keyword state, not delivery. Account scope excludes campaign/ad-group keywords.", input: z6.object({ ...selected3, page_size: z6.number().int().min(1).max(250).default(50), bookmark: cursor.optional(), match_types: z6.array(match).min(1).max(5).optional() }), output: creativesOutput3.passthrough(), presentation: "records", pagination: { cursorInput: "bookmark" }, annotations: { readOnly: true }, handler: (v) => provider.keywords.list(v) }),
|
|
883
|
+
defineTool3({ name: "pinterest_get_keyword", namespace: "pinterest", description: "Find an exact keyword in one owned parent, with a current snapshot. Native API has no GET-by-keyword-ID; lookup is bounded to 10,000 rows. Archived keywords disappear and cannot be safely unarchived here.", input: z6.object({ ...selected3, keyword_id: pinterestId }), output: creativesOutput3.passthrough(), presentation: "records", annotations: { readOnly: true }, handler: (v) => provider.keywords.get(v.account_id, v.parent, v.keyword_id) }),
|
|
884
|
+
defineTool3({ name: "pinterest_keyword_metrics", namespace: "pinterest", description: "Read native search-frequency ranges for up to 100 keywords in CA, GB, US, IE, AU or NZ. Other markets are unavailable. Keeps values such as 5M+ as strings; no account-performance, bid or delivery change.", input: z6.object({ ...account3, country_code: metricsCountry, keywords: z6.array(z6.string().trim().min(1).max(120).refine((v) => !v.includes(","), "Commas cannot be represented within the native CSV keyword query")).min(1).max(100).refine((v) => new Set(v).size === v.length, "Use unique keywords") }), output: z6.object({ planning: planningViewSchema }).passthrough(), presentation: "planning", annotations: { readOnly: true }, handler: (v) => provider.keywords.metrics(v) }),
|
|
885
|
+
guardedWriteTool3({ name: "pinterest_create_keywords", namespace: "pinterest", provider: "pinterest", kind: "create", description: "Create up to 100 keywords on a snapshot-bound owned parent. Accounts/campaigns accept only negatives; positive group keywords require a paused group or campaign under paused_creation. No keyword bid input: native bids are deprecated. Partial receipts retain IDs and are never retried.", payload: create }),
|
|
886
|
+
guardedWriteTool3({ name: "pinterest_archive_keywords", namespace: "pinterest", provider: "pinterest", kind: "update", description: "Archive exact snapshot-bound keywords in one owned parent. Native archive acts like deletion and removes metrics/list visibility; no guaranteed unarchive path. Removing exclusions can broaden matching. No parent status or bid changes.", payload: archive })
|
|
887
|
+
];
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// src/audiences.ts
|
|
891
|
+
import { createHash as createHash3 } from "crypto";
|
|
892
|
+
import { AdportError as AdportError5, creativesOutput as creativesOutput4, defineTool as defineTool4, guardedWriteTool as guardedWriteTool4 } from "@adport/core";
|
|
893
|
+
import { z as z7 } from "zod";
|
|
894
|
+
var hash3 = z7.string().regex(/^[a-f0-9]{64}$/);
|
|
895
|
+
var name = z7.string().trim().min(1).max(255);
|
|
896
|
+
var description = z7.string().max(1e3).nullable();
|
|
897
|
+
var ids2 = z7.array(pinterestId).min(1).max(100).refine((v) => new Set(v).size === v.length, "Use unique IDs");
|
|
898
|
+
var href = z7.string().url().max(2048).refine((value) => {
|
|
899
|
+
const u = new URL(value);
|
|
900
|
+
return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password;
|
|
901
|
+
}, "Use an HTTP(S) URL without credentials");
|
|
902
|
+
var domain = z7.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$/);
|
|
903
|
+
var customer = z7.object({ audience_type: z7.literal("CUSTOMER_LIST"), customer_list_id: pinterestId, expected_source_hash: hash3 }).strict();
|
|
904
|
+
var visitor = z7.object({ audience_type: z7.literal("VISITOR"), visitor_source_ids: ids2, retention_days: z7.number().int().min(1).max(540), prefill: z7.boolean(), event: z7.string().min(1).max(100).optional(), event_source: z7.array(z7.enum(["web", "mobile", "offline"])).min(1).max(3).optional(), ingestion_source: z7.array(z7.enum(["tag", "mmp", "file_upload", "conversions_api"])).min(1).max(4).optional(), url: z7.array(href).min(1).max(100).optional() }).strict();
|
|
905
|
+
var engagement = z7.object({ audience_type: z7.literal("ENGAGEMENT"), engagement_domains: z7.array(domain).min(1).max(10), engagement_type: z7.enum(["click", "save", "closeup", "comment", "like"]).optional(), engager_type: z7.number().int().min(1).max(2).optional(), retention_days: z7.number().int().min(1).max(540).optional(), campaign_ids: ids2.optional(), ad_ids: ids2.optional(), pin_ids: z7.array(z7.string().regex(/^\d{1,30}$/)).min(1).max(100).optional(), objective_types: z7.array(z7.enum(["AWARENESS", "CONSIDERATION", "WEB_CONVERSION", "CATALOG_SALES", "VIDEO_COMPLETION", "SALES"])).min(1).max(6).optional(), url: z7.array(href).min(1).max(100).optional() }).strict();
|
|
906
|
+
var actalike = z7.object({ audience_type: z7.literal("ACTALIKE"), seeds: z7.array(z7.object({ audience_id: pinterestId, expected_snapshot_hash: hash3 }).strict()).min(1).max(100).refine((v) => new Set(v.map((s) => s.audience_id)).size === v.length, "Use unique seeds"), country: z7.enum(["US", "CA", "GB"]), percentage: z7.number().int().min(1).max(10) }).strict();
|
|
907
|
+
var definition = z7.discriminatedUnion("audience_type", [customer, visitor, engagement, actalike]);
|
|
908
|
+
var audience = z7.looseObject({ id: pinterestId, ad_account_id: pinterestId.optional(), name: z7.string().optional(), description: z7.string().nullable().optional(), audience_type: z7.string().optional(), rule: z7.record(z7.string(), z7.unknown()).optional(), is_nca: z7.boolean().optional(), status: z7.string().optional() });
|
|
909
|
+
var customerList = z7.object({ id: pinterestId, name: z7.string(), ad_account_id: pinterestId.optional(), is_nca: z7.boolean().optional(), status: z7.string().optional(), created_time: z7.number().finite().optional(), updated_time: z7.number().finite().optional(), num_batches: z7.number().int().nonnegative().optional(), num_uploaded_user_records: z7.number().int().nonnegative().optional(), num_removed_user_records: z7.number().int().nonnegative().optional(), exceptions: z7.record(z7.string(), z7.unknown()).optional() });
|
|
910
|
+
var selected = { audience_id: pinterestId, expected_snapshot_hash: hash3 };
|
|
911
|
+
var createAudience = z7.object({ name, description: description.optional(), definition }).strict();
|
|
912
|
+
var updateAudience = z7.object({ ...selected, name: name.optional(), description: description.optional() }).strict().refine((v) => v.name !== void 0 || v.description !== void 0, "Supply audience copy");
|
|
913
|
+
var replaceRule = z7.object({ ...selected, expected_context_hash: hash3, definition }).strict();
|
|
914
|
+
var removeAudience = z7.object({ audience_id: pinterestId, expected_context_hash: hash3, confirm_permanent_removal: z7.literal(true) }).strict();
|
|
915
|
+
var records = z7.array(hash3).min(1).max(1e4).refine((v) => new Set(v).size === v.length, "Use unique SHA-256 records");
|
|
916
|
+
var createList = z7.object({ name, list_type: z7.enum(["EMAIL", "IDFA", "MAID"]).default("EMAIL"), is_nca: z7.boolean().default(false), records_sha256: records, confirm_data_rights: z7.literal(true) }).strict();
|
|
917
|
+
var updateRecords = z7.object({ customer_list_id: pinterestId, expected_snapshot_hash: hash3, operation_type: z7.enum(["ADD", "REMOVE"]), records_sha256: records, confirm_data_rights: z7.literal(true) }).strict();
|
|
918
|
+
var writes2 = /* @__PURE__ */ new Map([["pinterest_create_audience", "create"], ["pinterest_update_audience", "update"], ["pinterest_replace_audience_rule", "update"], ["pinterest_remove_audience", "remove"], ["pinterest_create_customer_list", "create"], ["pinterest_update_customer_list_records", "update"]]);
|
|
919
|
+
var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
920
|
+
function canonical(value) {
|
|
921
|
+
if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) throw new AdportError5("PROVIDER_ERROR", "pinterest: unsafe native identifier or counter in audience configuration");
|
|
922
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
923
|
+
return value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;
|
|
924
|
+
}
|
|
925
|
+
var digest2 = (value) => createHash3("sha256").update(JSON.stringify(canonical(value))).digest("hex");
|
|
926
|
+
var audienceSnapshot = (value) => digest2(Object.fromEntries(["id", "ad_account_id", "name", "description", "audience_type", "rule", "is_nca"].map((key) => [key, value[key] ?? null])));
|
|
927
|
+
var listSnapshot = (value) => digest2(Object.fromEntries(["id", "ad_account_id", "name", "is_nca", "updated_time", "num_batches", "num_uploaded_user_records", "num_removed_user_records"].map((key) => [key, value[key] ?? null])));
|
|
928
|
+
function normalizeRule(value) {
|
|
929
|
+
const rule = { ...object2(value) };
|
|
930
|
+
if (rule.percentage !== void 0) rule.percentage = String(rule.percentage);
|
|
931
|
+
if (typeof rule.visitor_source_id === "string") rule.visitor_source_id = [rule.visitor_source_id];
|
|
932
|
+
if (Array.isArray(rule.seed_id)) {
|
|
933
|
+
canonical(rule.seed_id);
|
|
934
|
+
rule.seed_id = rule.seed_id.map(String);
|
|
935
|
+
}
|
|
936
|
+
return rule;
|
|
937
|
+
}
|
|
938
|
+
function includesFields(actual, expected) {
|
|
939
|
+
if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => includesFields(actual[index], value));
|
|
940
|
+
if (expected !== null && typeof expected === "object") return Object.entries(object2(expected)).every(([key, value]) => includesFields(object2(actual)[key], value));
|
|
941
|
+
return actual === expected;
|
|
942
|
+
}
|
|
943
|
+
var PinterestAudienceService = class {
|
|
944
|
+
constructor(client, entity, pin) {
|
|
945
|
+
this.client = client;
|
|
946
|
+
this.entity = entity;
|
|
947
|
+
this.pin = pin;
|
|
948
|
+
}
|
|
949
|
+
client;
|
|
950
|
+
entity;
|
|
951
|
+
pin;
|
|
952
|
+
supports(tool) {
|
|
953
|
+
return writes2.has(tool);
|
|
954
|
+
}
|
|
955
|
+
base(account3) {
|
|
956
|
+
return `ad_accounts/${pinterestId.parse(account3)}`;
|
|
957
|
+
}
|
|
958
|
+
async page(account3, path, schema, size, bookmark, extra = {}) {
|
|
959
|
+
const data = await this.client.get(`${this.base(account3)}/${path}`, z7.object({ items: z7.array(schema), bookmark: z7.string().nullable().optional() }), new URLSearchParams({ ...extra, page_size: String(size), ...bookmark ? { bookmark } : {} }));
|
|
960
|
+
if (data.items.length > size || data.bookmark && (!data.items.length || data.bookmark === bookmark)) throw new AdportError5("PROVIDER_ERROR", "pinterest: audience pagination did not advance or exceeded page size");
|
|
961
|
+
return { ...data, truncated: Boolean(data.bookmark), ...data.bookmark ? { next_cursor: data.bookmark } : {} };
|
|
962
|
+
}
|
|
963
|
+
async list(input) {
|
|
964
|
+
const data = await this.page(input.account_id, "audiences", audience, input.page_size, input.bookmark, { ownership_type: input.ownership_type });
|
|
965
|
+
if (new Set(data.items.map((v) => v.id)).size !== data.items.length || input.ownership_type === "OWNED" && data.items.some((v) => v.ad_account_id !== void 0 && v.ad_account_id !== input.account_id)) throw new AdportError5("PROVIDER_ERROR", "pinterest: owned audience list returned foreign ownership or duplicate IDs");
|
|
966
|
+
return { ...data, items: data.items.map((v) => ({ ...v, owned_by_advertiser: v.ad_account_id === input.account_id, snapshot_hash: audienceSnapshot(v) })) };
|
|
967
|
+
}
|
|
968
|
+
async get(account3, audienceId) {
|
|
969
|
+
const current = await this.client.get(`${this.base(account3)}/audiences/${pinterestId.parse(audienceId)}`, audience);
|
|
970
|
+
if (current.id !== audienceId || current.ad_account_id !== account3) throw new AdportError5("INVALID_INPUT", "pinterest: audience ownership was not confirmed for this advertiser; received audiences are not writable");
|
|
971
|
+
const snapshotHash = audienceSnapshot(current);
|
|
972
|
+
const creative = { id: current.id, provider: "pinterest", account_id: account3, name: current.name ?? current.id, type: `${current.audience_type ?? "UNKNOWN"}_AUDIENCE`, ...current.status ? { status: current.status } : {}, headlines: [], descriptions: current.description ? [current.description] : [], landing_urls: [], media: [], actions: [{ label: "Edit audience", tool: "pinterest_update_audience", arguments: { account_id: account3, audience_id: current.id, expected_snapshot_hash: snapshotHash }, fields: [{ key: "name", label: "Audience name", type: "text", value: current.name ?? "", max_length: 255 }, { key: "description", label: "Description", type: "text", value: current.description ?? "", max_length: 1e3 }] }] };
|
|
973
|
+
return { audience: current, snapshot_hash: snapshotHash, creatives: [creative], truncated: false, notes: ["Processing status/size can change independently. Audiences have no pause flag; these are not ad-delivery statuses.", "The copy/configuration hash is current state, not a native monotonic version or atomic conditional-write token."] };
|
|
974
|
+
}
|
|
975
|
+
async getCustomerList(account3, resource) {
|
|
976
|
+
const current = await this.client.get(`${this.base(account3)}/customer_lists/${pinterestId.parse(resource)}`, customerList);
|
|
977
|
+
if (current.id !== resource || current.ad_account_id !== account3) throw new AdportError5("INVALID_INPUT", "pinterest: customer list is not explicitly owned by this advertiser");
|
|
978
|
+
const { exceptions: _exceptions, ...metadata } = current;
|
|
979
|
+
return { customer_list: metadata, snapshot_hash: listSnapshot(current), has_exceptions: Boolean(current.exceptions && Object.keys(object2(current.exceptions)).length), notes: ["Native processing and matching are asynchronous. Acceptance is not proof of matched users or serving eligibility.", "Customer identifiers and exception contents are not returned. Pinterest has no documented customer-list container delete endpoint here."] };
|
|
980
|
+
}
|
|
981
|
+
async customerLists(input) {
|
|
982
|
+
const data = await this.page(input.account_id, "customer_lists", customerList, input.page_size, input.bookmark);
|
|
983
|
+
if (data.items.some((v) => v.ad_account_id !== input.account_id) || new Set(data.items.map((v) => v.id)).size !== data.items.length) throw new AdportError5("PROVIDER_ERROR", "pinterest: customer list returned foreign/missing ownership or duplicate IDs");
|
|
984
|
+
return { ...data, items: data.items.map((value) => {
|
|
985
|
+
const { exceptions: _exceptions, ...metadata } = value;
|
|
986
|
+
return { ...metadata, snapshot_hash: listSnapshot(value) };
|
|
987
|
+
}) };
|
|
988
|
+
}
|
|
989
|
+
async sources(account3) {
|
|
990
|
+
const current = await this.client.get(this.base(account3), z7.object({ id: pinterestId, owner: z7.object({ username: z7.string() }) }));
|
|
991
|
+
if (current.id !== account3) throw new AdportError5("PROVIDER_ERROR", "pinterest: audience account ID mismatch");
|
|
992
|
+
const native = await this.client.get("user_account", z7.object({ username: z7.string() }));
|
|
993
|
+
if (native.username.toLowerCase() !== current.owner.username.toLowerCase()) return { token_owner_matches: false, websites: [], complete: false, notes: ["Website discovery is credential-global and cannot establish a delegated advertiser\u2019s domains. Account-scoped tag/list/seed workflows remain available."] };
|
|
994
|
+
const websites = [], seen = /* @__PURE__ */ new Set();
|
|
995
|
+
let bookmark;
|
|
996
|
+
for (let page2 = 0; page2 < 20; page2++) {
|
|
997
|
+
const data = await this.client.get("user_account/websites", z7.object({ items: z7.array(z7.object({ website: z7.string(), status: z7.string().optional(), verified_at: z7.string().optional() })), bookmark: z7.string().nullable().optional() }), new URLSearchParams({ page_size: "250", ...bookmark ? { bookmark } : {} }));
|
|
998
|
+
if (data.items.length > 250 || data.bookmark && (!data.items.length || seen.has(data.bookmark) || data.bookmark === bookmark)) throw new AdportError5("PROVIDER_ERROR", "pinterest: website pagination did not advance");
|
|
999
|
+
websites.push(...data.items);
|
|
1000
|
+
if (!data.bookmark) return { token_owner_matches: true, websites, complete: true, notes: ["Websites belong to the token user, whose owner matches the advertiser. Native statuses are preserved; listing alone does not certify engagement-audience eligibility. No website verification or claim is performed."] };
|
|
1001
|
+
seen.add(data.bookmark);
|
|
1002
|
+
bookmark = data.bookmark;
|
|
1003
|
+
}
|
|
1004
|
+
return { token_owner_matches: true, websites, complete: false, notes: ["Website inventory exceeded 5,000 entries; engagement-domain validation is blocked."] };
|
|
1005
|
+
}
|
|
1006
|
+
async rule(account3, value) {
|
|
1007
|
+
if (value.audience_type === "CUSTOMER_LIST") {
|
|
1008
|
+
const source2 = await this.getCustomerList(account3, value.customer_list_id);
|
|
1009
|
+
if (source2.snapshot_hash !== value.expected_source_hash) throw new AdportError5("PENDING_MISMATCH", "pinterest: customer-list source changed; read it again");
|
|
1010
|
+
return { customer_list_id: value.customer_list_id };
|
|
1011
|
+
}
|
|
1012
|
+
if (value.audience_type === "ACTALIKE") {
|
|
1013
|
+
for (const seed of value.seeds) {
|
|
1014
|
+
const source2 = await this.get(account3, seed.audience_id);
|
|
1015
|
+
if (source2.snapshot_hash !== seed.expected_snapshot_hash) throw new AdportError5("PENDING_MISMATCH", "pinterest: seed audience configuration changed; read it again");
|
|
1016
|
+
}
|
|
1017
|
+
return { seed_id: value.seeds.map((v) => v.audience_id), country: value.country, percentage: value.percentage };
|
|
1018
|
+
}
|
|
1019
|
+
if (value.audience_type === "VISITOR") {
|
|
1020
|
+
for (const source2 of value.visitor_source_ids) {
|
|
1021
|
+
const tag2 = await this.client.get(`${this.base(account3)}/conversion_tags/${source2}`, z7.object({ id: pinterestId, ad_account_id: pinterestId }));
|
|
1022
|
+
if (tag2.id !== source2 || tag2.ad_account_id !== account3) throw new AdportError5("INVALID_INPUT", "pinterest: visitor source tag is not owned by this advertiser");
|
|
1023
|
+
}
|
|
1024
|
+
return { visitor_source_id: value.visitor_source_ids, retention_days: value.retention_days, prefill: value.prefill, ...value.event ? { event: value.event } : {}, ...value.event_source ? { event_source: { "=": value.event_source } } : {}, ...value.ingestion_source ? { ingestion_source: { "=": value.ingestion_source } } : {}, ...value.url ? { url: value.url } : {} };
|
|
1025
|
+
}
|
|
1026
|
+
const available = await this.sources(account3);
|
|
1027
|
+
const hosts = new Set(available.websites.flatMap((v) => {
|
|
1028
|
+
try {
|
|
1029
|
+
return [new URL(v.website.includes("://") ? v.website : `https://${v.website}`).hostname];
|
|
1030
|
+
} catch {
|
|
1031
|
+
return [];
|
|
1032
|
+
}
|
|
1033
|
+
}));
|
|
1034
|
+
if (!available.complete || !available.token_owner_matches || value.engagement_domains.some((v) => !hosts.has(v))) throw new AdportError5("INVALID_INPUT", "pinterest: engagement domains are not present in the complete advertiser-owner website inventory");
|
|
1035
|
+
for (const campaign of value.campaign_ids ?? []) await this.entity(account3, "campaigns", campaign);
|
|
1036
|
+
for (const ad of value.ad_ids ?? []) await this.entity(account3, "ads", ad);
|
|
1037
|
+
for (const pin of value.pin_ids ?? []) if ((await this.pin(account3, pin)).pin.is_owner !== true) throw new AdportError5("INVALID_INPUT", "pinterest: engagement Pin is not explicitly owned");
|
|
1038
|
+
return { engagement_domain: value.engagement_domains, ...value.engagement_type ? { engagement_type: value.engagement_type } : {}, ...value.engager_type ? { engager_type: value.engager_type } : {}, ...value.retention_days ? { retention_days: value.retention_days } : {}, ...value.campaign_ids ? { campaign_id: value.campaign_ids } : {}, ...value.ad_ids ? { ad_id: value.ad_ids } : {}, ...value.pin_ids ? { pin_id: value.pin_ids } : {}, ...value.objective_types ? { objective_type: value.objective_types } : {}, ...value.url ? { url: value.url } : {} };
|
|
1039
|
+
}
|
|
1040
|
+
async inventory(account3, path, schema, extra = {}) {
|
|
1041
|
+
const items = [], cursors = /* @__PURE__ */ new Set();
|
|
1042
|
+
let bookmark;
|
|
1043
|
+
for (let page2 = 0; page2 < 50; page2++) {
|
|
1044
|
+
const data = await this.page(account3, path, schema, 100, bookmark, extra);
|
|
1045
|
+
items.push(...data.items);
|
|
1046
|
+
if (!data.next_cursor) return { items, complete: true };
|
|
1047
|
+
if (cursors.has(data.next_cursor)) throw new AdportError5("PROVIDER_ERROR", "pinterest: usage inventory repeated a cursor");
|
|
1048
|
+
cursors.add(data.next_cursor);
|
|
1049
|
+
bookmark = data.next_cursor;
|
|
1050
|
+
}
|
|
1051
|
+
return { items, complete: false };
|
|
1052
|
+
}
|
|
1053
|
+
async usage(account3, resource) {
|
|
1054
|
+
const current = await this.get(account3, resource);
|
|
1055
|
+
const groups = await this.inventory(account3, "ad_groups", z7.looseObject({ id: pinterestId, ad_account_id: pinterestId.optional(), status: z7.string().optional(), targeting_spec: z7.record(z7.string(), z7.unknown()).optional() }), { entity_statuses: "ACTIVE,PAUSED,ARCHIVED,DRAFT,DELETED_DRAFT" });
|
|
1056
|
+
const audiences = await this.inventory(account3, "audiences", audience, { ownership_type: "OWNED" });
|
|
1057
|
+
const sharing = [];
|
|
1058
|
+
for (const type2 of ["AD_ACCOUNT", "BUSINESS_ACCOUNT"]) {
|
|
1059
|
+
const data = await this.inventory(account3, "audiences/shared/accounts", z7.object({ account_id: pinterestId, account_type: z7.enum(["AD_ACCOUNT", "BUSINESS_ACCOUNT"]) }), { audience_id: resource, account_type: type2 });
|
|
1060
|
+
if (data.items.some((v) => v.account_type !== type2) || new Set(data.items.map((v) => v.account_id)).size !== data.items.length) throw new AdportError5("PROVIDER_ERROR", "pinterest: sharing returned the wrong account type or repeated accounts");
|
|
1061
|
+
sharing.push(data);
|
|
1062
|
+
}
|
|
1063
|
+
const seen = /* @__PURE__ */ new Set(), references = [];
|
|
1064
|
+
let configurationComplete = true;
|
|
1065
|
+
for (const group of groups.items) {
|
|
1066
|
+
if (seen.has(group.id) || group.ad_account_id !== void 0 && group.ad_account_id !== account3) throw new AdportError5("PROVIDER_ERROR", "pinterest: usage returned a foreign or repeated ad group");
|
|
1067
|
+
seen.add(group.id);
|
|
1068
|
+
if (!group.targeting_spec) configurationComplete = false;
|
|
1069
|
+
const targeting2 = group.targeting_spec ?? {};
|
|
1070
|
+
for (const key of ["AUDIENCE_INCLUDE", "AUDIENCE_EXCLUDE"]) if (targeting2[key] !== void 0 && !z7.array(pinterestId).safeParse(targeting2[key]).success) throw new AdportError5("PROVIDER_ERROR", "pinterest: audience targeting references could not be inspected");
|
|
1071
|
+
const dimensions = ["AUDIENCE_INCLUDE", "AUDIENCE_EXCLUDE"].filter((key) => Array.isArray(targeting2[key]) && targeting2[key].includes(resource));
|
|
1072
|
+
if (dimensions.length) references.push({ kind: "ad_group", id: group.id, ...typeof group.status === "string" ? { status: group.status } : {}, targeting_dimensions: dimensions });
|
|
1073
|
+
}
|
|
1074
|
+
seen.clear();
|
|
1075
|
+
for (const source2 of audiences.items) {
|
|
1076
|
+
if (seen.has(source2.id) || source2.ad_account_id !== account3) throw new AdportError5("PROVIDER_ERROR", "pinterest: usage returned a foreign or repeated owned audience");
|
|
1077
|
+
seen.add(source2.id);
|
|
1078
|
+
const seed = source2.rule?.seed_id;
|
|
1079
|
+
canonical(seed);
|
|
1080
|
+
if (!["CUSTOMER_LIST", "VISITOR", "ENGAGEMENT", "ACTALIKE"].includes(source2.audience_type ?? "") || source2.audience_type === "ACTALIKE" && !Array.isArray(seed)) configurationComplete = false;
|
|
1081
|
+
if (source2.id !== resource && Array.isArray(seed) && seed.some((v) => String(v) === resource)) references.push({ kind: "derived_audience", id: source2.id, snapshot_hash: audienceSnapshot(source2) });
|
|
1082
|
+
}
|
|
1083
|
+
const shared_accounts = sharing.flatMap((v) => v.items).filter((v) => v.account_type !== "AD_ACCOUNT" || v.account_id !== account3), scan_complete = configurationComplete && groups.complete && audiences.complete && sharing.every((v) => v.complete);
|
|
1084
|
+
references.sort((a, b) => `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`));
|
|
1085
|
+
shared_accounts.sort((a, b) => `${a.account_type}:${a.account_id}`.localeCompare(`${b.account_type}:${b.account_id}`));
|
|
1086
|
+
const context = { snapshot_hash: current.snapshot_hash, references, shared_accounts, scan_complete };
|
|
1087
|
+
return { ...current, ...context, context_hash: digest2(context), notes: ["Usage covers visible account ad groups, owned derived audiences and both native advertiser/business sharing edges, bounded to5,000 items per inventory.", "Pinterest has no documented atomic freeze or conditional-write version. Usage is re-read on apply; concurrent native changes remain possible."] };
|
|
1088
|
+
}
|
|
1089
|
+
planWrite(summary, changes, execute, fieldChanges) {
|
|
1090
|
+
return { summary, changes, coercions: [], budgetDeltas: [], ...fieldChanges ? { fieldChanges } : {}, notes: ["Local preview only; Pinterest has no server dry-run for these audience writes.", "Native source eligibility, processing and minimum matching sizes remain authoritative. No ad attachment, budget, delivery, tracking installation or event submission is performed."], execute };
|
|
1091
|
+
}
|
|
1092
|
+
async plan(op) {
|
|
1093
|
+
if (op.provider !== "pinterest" || writes2.get(op.tool) !== op.kind) throw new AdportError5("INVALID_INPUT", "pinterest: invalid audience operation");
|
|
1094
|
+
const account3 = pinterestId.parse(op.accountId);
|
|
1095
|
+
if (op.tool === "pinterest_create_customer_list" || op.tool === "pinterest_update_customer_list_records") {
|
|
1096
|
+
const create2 = op.tool === "pinterest_create_customer_list", input2 = create2 ? createList.parse(op.payload) : updateRecords.parse(op.payload);
|
|
1097
|
+
let resource;
|
|
1098
|
+
if ("customer_list_id" in input2) {
|
|
1099
|
+
resource = input2.customer_list_id;
|
|
1100
|
+
const current2 = await this.getCustomerList(account3, resource);
|
|
1101
|
+
if (current2.snapshot_hash !== input2.expected_snapshot_hash) throw new AdportError5("PENDING_MISMATCH", "pinterest: customer-list batches or metadata changed; read it again");
|
|
1102
|
+
}
|
|
1103
|
+
const recordsDigest = digest2(input2.records_sha256), body2 = create2 ? { name: createList.parse(input2).name, list_type: createList.parse(input2).list_type, is_nca: createList.parse(input2).is_nca, records: input2.records_sha256.join(",") } : { operation_type: updateRecords.parse(input2).operation_type, records: input2.records_sha256.join(",") };
|
|
1104
|
+
return this.planWrite(`${create2 ? "Create" : "Update"} Pinterest customer list`, [`${input2.records_sha256.length} unique SHA-256 identifiers; batch digest ${recordsDigest}. Identifiers are not included in this preview.`, create2 ? `New ${createList.parse(input2).list_type} list \u201C${createList.parse(input2).name}\u201D; expanded matching is_nca=${createList.parse(input2).is_nca}.` : `${updateRecords.parse(input2).operation_type} membership records on ${resource}.`, "Native processing is asynchronous. This does not confirm matched users; read customer-list status."], async () => {
|
|
1105
|
+
let result;
|
|
1106
|
+
try {
|
|
1107
|
+
result = await this.client.mutate(`${this.base(account3)}/customer_lists${resource ? `/${resource}` : ""}`, create2 ? "POST" : "PATCH", body2, customerList);
|
|
1108
|
+
} catch (error) {
|
|
1109
|
+
const details = error instanceof AdportError5 ? object2(error.details) : {}, ids3 = Array.isArray(details.resource_ids) ? details.resource_ids.filter((v) => pinterestId.safeParse(v).success) : resource ? [resource] : [];
|
|
1110
|
+
throw new AdportError5("PROVIDER_ERROR", "pinterest: customer-list write was not confirmed; reconcile before retrying. Identifiers/native error text are withheld.", { ...typeof details.http_status === "number" ? { http_status: details.http_status } : {}, ...typeof details.api_code === "number" || typeof details.api_code === "string" && /^[A-Z0-9_]{1,64}$/.test(details.api_code) ? { api_code: details.api_code } : {}, resource_ids: ids3 });
|
|
1111
|
+
}
|
|
1112
|
+
if (result.ad_account_id !== account3 || resource && result.id !== resource || create2 && (result.name !== createList.parse(input2).name || result.is_nca !== createList.parse(input2).is_nca)) throw new AdportError5("PROVIDER_ERROR", "pinterest: customer-list receipt ownership/name/matching mode mismatch; reconcile before retrying", { resource_ids: [result.id] });
|
|
1113
|
+
return [result.id];
|
|
1114
|
+
});
|
|
1115
|
+
}
|
|
1116
|
+
if (op.tool === "pinterest_create_audience") {
|
|
1117
|
+
const input2 = createAudience.parse(op.payload), rule = await this.rule(account3, input2.definition), body2 = { ad_account_id: account3, name: input2.name, ...input2.description !== void 0 ? { description: input2.description } : {}, audience_type: input2.definition.audience_type, rule };
|
|
1118
|
+
return this.planWrite(`Create Pinterest ${input2.definition.audience_type} audience \u201C${input2.name}\u201D`, [JSON.stringify(body2), "Audience is unattached; it has no pause state. Visitor prefill is an explicit choice. Website listing verifies owner association, not native engagement eligibility."], async () => this.receipt(account3, void 0, body2, await this.client.mutate(`${this.base(account3)}/audiences`, "POST", body2, audience)));
|
|
1119
|
+
}
|
|
1120
|
+
if (op.tool === "pinterest_remove_audience") {
|
|
1121
|
+
const input2 = removeAudience.parse(op.payload), current2 = await this.usage(account3, input2.audience_id);
|
|
1122
|
+
if (current2.context_hash !== input2.expected_context_hash || !current2.scan_complete) throw new AdportError5("PENDING_MISMATCH", "pinterest: audience usage changed or is incomplete; read it again");
|
|
1123
|
+
if (current2.references.length || current2.shared_accounts.length) throw new AdportError5("INVALID_INPUT", "pinterest: audience still has targeting, derived audiences or sharing references");
|
|
1124
|
+
return this.planWrite(`Remove Pinterest audience \u201C${current2.audience.name ?? input2.audience_id}\u201D`, [`Native operation_type REMOVE on ${input2.audience_id}; current visible usage/sharing is empty. This is a permanent audience operation, not a pause.`, "Customer-list containers and project media are preserved; native concurrent writes are not frozen."], async () => this.receipt(account3, input2.audience_id, {}, await this.client.mutate(`${this.base(account3)}/audiences/${input2.audience_id}`, "PATCH", { operation_type: "REMOVE" }, audience)));
|
|
1125
|
+
}
|
|
1126
|
+
const replacement = op.tool === "pinterest_replace_audience_rule", input = replacement ? replaceRule.parse(op.payload) : updateAudience.parse(op.payload), current = replacement ? await this.usage(account3, input.audience_id) : await this.get(account3, input.audience_id);
|
|
1127
|
+
if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError5("PENDING_MISMATCH", "pinterest: audience copy/configuration changed; read it again");
|
|
1128
|
+
const body = { operation_type: "UPDATE" }, changes = [];
|
|
1129
|
+
if (replacement) {
|
|
1130
|
+
const value = replaceRule.parse(input), context = current;
|
|
1131
|
+
if (context.context_hash !== value.expected_context_hash || !context.scan_complete) throw new AdportError5("PENDING_MISMATCH", "pinterest: audience usage changed or is incomplete; read it again");
|
|
1132
|
+
if (context.shared_accounts.length) throw new AdportError5("INVALID_INPUT", "pinterest: shared audience rules cannot be replaced through this workflow");
|
|
1133
|
+
if (value.definition.audience_type !== current.audience.audience_type) throw new AdportError5("INVALID_INPUT", "pinterest: rule replacement must preserve audience type");
|
|
1134
|
+
if (value.definition.audience_type === "ACTALIKE" && value.definition.seeds.some((seed) => seed.audience_id === input.audience_id || context.references.some((ref) => ref.kind === "derived_audience" && ref.id === seed.audience_id))) throw new AdportError5("INVALID_INPUT", "pinterest: an audience cannot use itself or a direct derived audience as a seed");
|
|
1135
|
+
body.rule = await this.rule(account3, value.definition);
|
|
1136
|
+
changes.push({ field: "Rule", before: JSON.stringify(current.audience.rule ?? null), after: JSON.stringify(body.rule) });
|
|
1137
|
+
} else {
|
|
1138
|
+
const value = updateAudience.parse(input);
|
|
1139
|
+
for (const key of ["name", "description"]) if (value[key] !== void 0) {
|
|
1140
|
+
body[key] = value[key];
|
|
1141
|
+
if ((current.audience[key] ?? null) !== value[key]) changes.push({ field: key === "name" ? "Name" : "Description", before: String(current.audience[key] ?? "(not set)"), after: String(value[key] ?? "(cleared)") });
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
return this.planWrite(`Edit Pinterest audience \u201C${current.audience.name ?? input.audience_id}\u201D`, [replacement ? "Replaces the complete definition and can affect every visible linked ad group. Usage is rechecked; source type and sharing are preserved." : "Only supplied copy fields change. Rules, membership sources and delivery are preserved.", JSON.stringify(body)], async () => this.receipt(account3, input.audience_id, body, await this.client.mutate(`${this.base(account3)}/audiences/${input.audience_id}`, "PATCH", body, audience), current.audience), changes);
|
|
1145
|
+
}
|
|
1146
|
+
receipt(account3, resource, expected, current, previous) {
|
|
1147
|
+
const fields2 = Object.entries(expected).filter(([key]) => key !== "operation_type");
|
|
1148
|
+
if (current.ad_account_id !== account3 || resource && current.id !== resource || fields2.some(([key, value]) => key === "rule" ? !includesFields(normalizeRule(current.rule), normalizeRule(value)) : digest2(current[key] ?? null) !== digest2(value)) || previous && ["name", "description", "rule", "audience_type", "is_nca"].some((key) => expected[key] === void 0 && digest2(current[key] ?? null) !== digest2(previous[key] ?? null))) throw new AdportError5("PROVIDER_ERROR", "pinterest: audience receipt differs from approved fields or preserved ownership/configuration; reconcile before retrying", { resource_ids: [current.id] });
|
|
1149
|
+
return [current.id];
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
function pinterestAudienceTools(provider) {
|
|
1153
|
+
const account3 = { account_id: pinterestId }, page2 = { page_size: z7.number().int().min(1).max(250).default(50), bookmark: z7.string().min(1).max(4096).optional() };
|
|
1154
|
+
const read = (name3, description2, input, handler) => defineTool4({ name: name3, namespace: "pinterest", description: description2, input, annotations: { readOnly: true }, handler });
|
|
1155
|
+
const write2 = (name3, description2, payload, kind) => guardedWriteTool4({ name: name3, namespace: "pinterest", provider: "pinterest", description: description2, payload, kind });
|
|
1156
|
+
return [
|
|
1157
|
+
read("pinterest_audiences", "List native OWNED or RECEIVED audiences with ownership labels and snapshots. Received audiences remain read-only. Uses native bookmark pagination; processing status is not ad delivery.", z7.object({ ...account3, ...page2, ownership_type: z7.enum(["OWNED", "RECEIVED"]).default("OWNED") }), (v) => provider.audiences.list(v)),
|
|
1158
|
+
defineTool4({ name: "pinterest_get_audience", namespace: "pinterest", description: "Read an owned audience, rule, native processing status and snapshot, with read-only record view. Size/status can change independently; ownership must be explicit.", input: z7.object({ ...account3, audience_id: pinterestId }), output: creativesOutput4.passthrough(), presentation: "records", annotations: { readOnly: true }, handler: (v) => provider.audiences.get(v.account_id, v.audience_id) }),
|
|
1159
|
+
read("pinterest_audience_usage", "Read owned audience targeting/derived references and both ad-account/business sharing edges. Bounded5,000 rows per inventory; incomplete or shared usage blocks removal. No native atomic freeze is claimed.", z7.object({ ...account3, audience_id: pinterestId }), (v) => provider.audiences.usage(v.account_id, v.audience_id)),
|
|
1160
|
+
read("pinterest_audience_sources", "Read the advertiser owner\u2019s native website inventory for engagement audience setup. Global websites require user_accounts:read and matching token owner. Does not claim/verify websites or certify audience eligibility.", z7.object(account3), (v) => provider.audiences.sources(v.account_id)),
|
|
1161
|
+
read("pinterest_customer_lists", "Read selected advertiser customer-list metadata, counts, processing status and snapshots with pagination. Never returns records or native exception contents.", z7.object({ ...account3, ...page2 }), (v) => provider.audiences.customerLists(v)),
|
|
1162
|
+
read("pinterest_get_customer_list", "Read an explicitly owned customer-list source and snapshot including batch counters. Matching is asynchronous; fewer than100 Pinterest accounts cannot serve. No source identifiers are returned.", z7.object({ ...account3, customer_list_id: pinterestId }), (v) => provider.audiences.getCustomerList(v.account_id, v.customer_list_id)),
|
|
1163
|
+
write2("pinterest_create_audience", "Create CUSTOMER_LIST, VISITOR, ENGAGEMENT or ACTALIKE audience from verified owned sources. Customer/seed snapshots are required; visitor prefill is explicit. No ad attachment, events or tracking installation. Native source eligibility remains authoritative.", createAudience, "create"),
|
|
1164
|
+
write2("pinterest_update_audience", "Edit supplied owned-audience name/description after matching its snapshot. Null clears description; omitted copy, rules, source type and membership remain unchanged. Shared audiences are rejected.", updateAudience, "update"),
|
|
1165
|
+
write2("pinterest_replace_audience_rule", "Replace a complete audience rule of the SAME type after matching configuration and complete usage context. Source ownership is reverified; shared rules are blocked. Existing linked ad groups can be affected.", replaceRule, "update"),
|
|
1166
|
+
write2("pinterest_remove_audience", "Request native permanent audience REMOVE only after snapshot-bound complete usage/sharing scans find no references. Requires confirm_permanent_removal; does not delete a customer-list container. No atomic provider usage freeze.", removeAudience, "remove"),
|
|
1167
|
+
write2("pinterest_create_customer_list", "Upload up to10,000 unique pre-normalized SHA-256 EMAIL/IDFA/MAID identifiers into a named list. Requires data rights confirmation; is_nca defaults false. Preview shows only count/digest. Acceptance is not matching success; native lists have no container-delete endpoint.", createList, "create"),
|
|
1168
|
+
write2("pinterest_update_customer_list_records", "ADD/REMOVE up to10,000 SHA-256 records on an owned, snapshot-bound customer list. Confirms data rights, preserves list type and matching mode, and previews count/digest only. Native errors cannot expose identifiers. No automatic retry.", updateRecords, "update")
|
|
1169
|
+
];
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
// src/measurement.ts
|
|
1173
|
+
import { createHash as createHash4 } from "crypto";
|
|
1174
|
+
import { isIP } from "net";
|
|
1175
|
+
import { AdportError as AdportError6, defineTool as defineTool5, guardedWriteTool as guardedWriteTool5 } from "@adport/core";
|
|
1176
|
+
import { z as z8 } from "zod";
|
|
1177
|
+
var canonical2 = (value) => Array.isArray(value) ? value.map(canonical2) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical2(item)])) : value;
|
|
1178
|
+
var digest3 = (value) => createHash4("sha256").update(JSON.stringify(canonical2(value))).digest("hex");
|
|
1179
|
+
var hash4 = z8.string().regex(/^[a-f0-9]{64}$/);
|
|
1180
|
+
var text = z8.string().min(1).max(4096);
|
|
1181
|
+
var decimal = z8.string().regex(/^\d+(?:\.\d+)?$/);
|
|
1182
|
+
var optionalText = text.nullable().optional();
|
|
1183
|
+
var integer = z8.number().int().nonnegative().safe();
|
|
1184
|
+
var aem = { aem_db_enabled: z8.boolean().default(false), aem_enabled: z8.boolean().default(false), aem_external_id_enabled: z8.boolean().default(false), aem_fnln_enabled: z8.boolean().default(false), aem_ge_enabled: z8.boolean().default(false), aem_loc_enabled: z8.boolean().default(false), aem_ph_enabled: z8.boolean().default(false) };
|
|
1185
|
+
var tag = z8.looseObject({ id: pinterestId.optional(), ad_account_id: pinterestId, name: z8.string(), status: z8.string().optional(), configs: z8.record(z8.string(), z8.unknown()).optional(), last_fired_time_ms: z8.number().nullable().optional() });
|
|
1186
|
+
var tagCreate = z8.object({ name: z8.string().trim().min(1).max(255), ...aem, md_frequency: z8.number().default(1), expected_context_hash: hash4, confirm_enhanced_match_consent: z8.boolean().default(false) }).strict().refine((value) => !Object.keys(aem).some((key) => value[key]) || value.confirm_enhanced_match_consent, "Enabling enhanced match requires explicit consent confirmation");
|
|
1187
|
+
var eventMetadata = z8.looseObject({ ad_account_id: pinterestId.optional(), conversion_tag_id: pinterestId.optional(), conversion_event: z8.string().optional(), created_time: z8.number().int().optional(), reporting_conversion_event: z8.string().optional() });
|
|
1188
|
+
var sourcePlatform = z8.enum(["WEB", "MOBILE", "MOBILE_ANDROID", "MOBILE_IOS", "OFFLINE", "PINTEREST_WEB", "PINTEREST_ANDROID", "PINTEREST_IOS", "POINT_OF_SALE"]);
|
|
1189
|
+
var ingestionSource = z8.enum(["TAG", "MMP", "FILE_UPLOAD", "CONVERSIONS_API", "NATIVE"]);
|
|
1190
|
+
var qualityInput = z8.object({ account_id: pinterestId, lookback_period: z8.enum(["1d", "14d"]), source_platform: sourcePlatform.optional(), ingestion_source: ingestionSource.optional() }).strict();
|
|
1191
|
+
var component = z8.looseObject({ coverage: z8.number(), overlap: z8.number().optional(), issues: z8.array(z8.looseObject({ id: z8.string(), name: z8.string(), reason: z8.string() })).optional() });
|
|
1192
|
+
var quality = z8.looseObject({ overall_status: z8.enum(["NEEDS_IMPROVEMENT", "FAIR", "GOOD"]), quality_components: z8.record(z8.string(), z8.record(z8.string(), component)), ingestion_source: ingestionSource, source_platform: sourcePlatform, lookback_period: z8.enum(["1d", "14d"]) });
|
|
1193
|
+
var hashedValues = z8.array(hash4).min(1).max(100);
|
|
1194
|
+
var userData = z8.object({ em: hashedValues.optional(), hashed_maids: hashedValues.optional(), ph: hashedValues.optional(), ge: hashedValues.optional(), db: hashedValues.optional(), ln: hashedValues.optional(), fn: hashedValues.optional(), ct: hashedValues.optional(), st: hashedValues.optional(), zp: hashedValues.optional(), country: hashedValues.optional(), external_id: hashedValues.optional(), client_ip_address: z8.string().refine((value) => isIP(value) !== 0 && !["0.0.0.0", "::"].includes(value), "Use a valid, non-unspecified IP address").optional(), client_user_agent: z8.string().min(1).max(16384).optional(), click_id: optionalText, partner_id: optionalText }).strict().refine((value) => Boolean(value.em?.length || value.hashed_maids?.length || value.client_ip_address && value.client_user_agent), "Provide SHA-256 email/MAID or both client IP address and user agent");
|
|
1195
|
+
var product = z8.object({ id: text.optional(), item_brand: text.optional(), item_brand_id: z8.string().max(64).optional(), item_category: text.optional(), item_name: text.optional(), item_price: decimal.optional(), quantity: integer.optional() }).strict();
|
|
1196
|
+
var customData = z8.object({ content_brand: optionalText, content_category: optionalText, content_ids: z8.array(text).max(1e3).optional(), content_name: optionalText, contents: z8.array(product).max(1e3).optional(), currency: z8.string().regex(/^[A-Z]{3}$/).nullable().optional(), external_measurement_id: optionalText, external_measurement_vendor_id: z8.number().int().safe().nullable().optional(), np: optionalText, num_items: integer.optional(), opt_out_type: optionalText, order_id: optionalText, predicted_ltv: decimal.nullable().optional(), search_string: optionalText, value: decimal.nullable().optional() }).strict().refine((value) => value.value == null && value.predicted_ltv == null || Boolean(value.currency), "Provide explicit ISO currency with monetary values");
|
|
1197
|
+
var appInfo = z8.object({ app_id: z8.string().max(200).optional(), app_name: z8.string().max(200).optional(), app_package_name: z8.string().max(200).optional(), app_store: z8.string().max(100).optional(), app_version: z8.string().max(100).optional(), install_time: integer.optional(), user_agent: z8.string().max(16384).optional(), window_height: integer.max(30720).optional(), window_width: integer.max(30720).optional() }).strict();
|
|
1198
|
+
var deviceInfo = z8.object({ battery_level: integer.max(100).optional(), brand: z8.string().max(100).optional(), carrier: z8.string().max(100).optional(), cpu_cores: integer.max(1152).optional(), external_storage_free_space: integer.max(1048576).optional(), external_storage_size: integer.max(1048576).optional(), form_factor: z8.enum(["desktop", "laptop", "cellphone", "tablet", "smartwatch", "tv", "vr", "console", "other"]).optional(), kernel_version: z8.string().max(100).optional(), languages: z8.array(z8.string()).max(100).optional(), locale: z8.string().max(35).optional(), model: z8.string().max(100).optional(), network_type: z8.enum(["wifi", "cellular_2g", "cellular_3g", "cellular_4g", "cellular_5g", "cellular_6g", "ethernet", "unknown"]).optional(), os_family: z8.enum(["ios", "android", "macos", "windows", "linux", "bsd", "other"]).optional(), os_name: z8.string().max(100).optional(), os_release_name: z8.string().max(100).optional(), os_version: z8.string().max(100).optional(), screen_density: integer.max(1e5).optional(), screen_height: integer.max(30720).optional(), screen_width: integer.max(30720).optional(), storage_free_space: integer.max(1048576).optional(), storage_size: integer.max(1048576).optional(), timezone: z8.string().max(40).optional(), timezone_abbr: z8.string().max(5).optional(), type: z8.string().max(100).optional() }).strict();
|
|
1199
|
+
var sourceUrl = z8.string().url().max(16384).refine((value) => {
|
|
1200
|
+
const url2 = new URL(value);
|
|
1201
|
+
return ["https:", "http:"].includes(url2.protocol) && !url2.username && !url2.password;
|
|
1202
|
+
}, "Use an HTTP(S) source URL without credentials");
|
|
1203
|
+
var event = z8.object({ action_source: z8.enum(["web", "app_android", "app_ios", "offline"]), event_id: z8.string().min(1).max(512), event_name: z8.string().regex(/^[A-Za-z0-9_-]{1,100}$/), event_time: integer.refine((value) => value <= Math.floor(Date.now() / 1e3) + 60, "Event time must be Unix seconds and not in the future"), user_data: userData, app_id: optionalText, app_info: appInfo.optional(), app_name: optionalText, app_version: optionalText, custom_data: customData.optional(), device_brand: optionalText, device_carrier: optionalText, device_info: deviceInfo.optional(), device_model: optionalText, device_type: optionalText, event_source_url: sourceUrl.nullable().optional(), language: optionalText, opt_out: z8.boolean().optional(), os_version: optionalText, partner_name: optionalText, wifi: z8.boolean().optional() }).strict();
|
|
1204
|
+
var sendEvents = z8.object({ expected_context_hash: hash4, test: z8.boolean().default(true), confirm_data_rights: z8.literal(true), confirm_live_events: z8.boolean().default(false), data: z8.array(event).min(1).max(1e3) }).strict().refine((value) => value.test || value.confirm_live_events, "Live event submission requires confirm_live_events").refine((value) => new Set(value.data.map((item) => item.event_id)).size === value.data.length, "Use unique stable event IDs within the batch");
|
|
1205
|
+
var eventResponse = z8.object({ num_events_received: integer, num_events_processed: integer, events: z8.array(z8.object({ status: z8.enum(["failed", "processed"]), error_message: z8.string().nullable().optional(), warning_message: z8.string().nullable().optional() })) });
|
|
1206
|
+
var writes3 = /* @__PURE__ */ new Set(["pinterest_create_conversion_tag", "pinterest_send_conversion_events"]);
|
|
1207
|
+
var PinterestMeasurementService = class {
|
|
1208
|
+
constructor(client) {
|
|
1209
|
+
this.client = client;
|
|
1210
|
+
}
|
|
1211
|
+
client;
|
|
1212
|
+
supports(tool) {
|
|
1213
|
+
return writes3.has(tool);
|
|
1214
|
+
}
|
|
1215
|
+
base(account3) {
|
|
1216
|
+
return `ad_accounts/${pinterestId.parse(account3)}`;
|
|
1217
|
+
}
|
|
1218
|
+
owned(account3, row) {
|
|
1219
|
+
if (row.ad_account_id !== void 0 && row.ad_account_id !== account3) throw new AdportError6("PROVIDER_ERROR", "pinterest: measurement response belongs to another advertiser");
|
|
1220
|
+
return row;
|
|
1221
|
+
}
|
|
1222
|
+
async tags(account3, filterDeleted = false) {
|
|
1223
|
+
const result = await this.client.get(`${this.base(account3)}/conversion_tags`, z8.object({ items: z8.array(tag) }), new URLSearchParams({ filter_deleted: String(filterDeleted) }));
|
|
1224
|
+
result.items.forEach((row) => this.owned(account3, row));
|
|
1225
|
+
const ids3 = result.items.flatMap((row) => row.id ? [row.id] : []);
|
|
1226
|
+
if (new Set(ids3).size !== ids3.length) throw new AdportError6("PROVIDER_ERROR", "pinterest: duplicate conversion-tag IDs");
|
|
1227
|
+
return { ...result, account_id: account3, truncated: false };
|
|
1228
|
+
}
|
|
1229
|
+
async context(account3) {
|
|
1230
|
+
const advertiser = await this.client.get(this.base(account3), z8.looseObject({ id: pinterestId, name: z8.string().optional(), currency: z8.string().optional() }));
|
|
1231
|
+
if (advertiser.id !== account3) throw new AdportError6("PROVIDER_ERROR", "pinterest: measurement account ID mismatch");
|
|
1232
|
+
const tags = await this.tags(account3);
|
|
1233
|
+
const configuration3 = tags.items.map((row) => ({ id: row.id ?? null, name: row.name, status: row.status ?? null, configs: row.configs ?? null })).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
|
|
1234
|
+
return { account_id: account3, advertiser, tags: tags.items, snapshot_hash: digest3({ account_id: account3, currency: advertiser.currency ?? null, tags: configuration3 }), notes: ["Tag creation does not install tracking. Event uploads are separate guarded operations and default to test mode.", "The native API exposes tag creation and reads; no tag edit/delete endpoint is exposed here."] };
|
|
1235
|
+
}
|
|
1236
|
+
async getTag(account3, tagId) {
|
|
1237
|
+
const row = await this.client.get(`${this.base(account3)}/conversion_tags/${pinterestId.parse(tagId)}`, tag);
|
|
1238
|
+
this.owned(account3, row);
|
|
1239
|
+
if (row.id !== tagId) throw new AdportError6("PROVIDER_ERROR", "pinterest: conversion-tag ID mismatch");
|
|
1240
|
+
return row;
|
|
1241
|
+
}
|
|
1242
|
+
async eligible(account3) {
|
|
1243
|
+
const result = await this.client.get(`${this.base(account3)}/conversion_tags/ocpm_eligible`, z8.record(z8.string(), z8.array(eventMetadata)));
|
|
1244
|
+
if (Object.keys(result).some((key) => key !== account3)) throw new AdportError6("PROVIDER_ERROR", "pinterest: eligible-event mapping belongs to another advertiser");
|
|
1245
|
+
return { account_id: account3, events: (result[account3] ?? []).map((row) => this.owned(account3, row)) };
|
|
1246
|
+
}
|
|
1247
|
+
async visits(input) {
|
|
1248
|
+
const params = new URLSearchParams({ page_size: String(input.page_size), order: input.order });
|
|
1249
|
+
if (input.bookmark) params.set("bookmark", input.bookmark);
|
|
1250
|
+
const result = await this.client.get(`${this.base(input.account_id)}/conversion_tags/page_visit`, z8.object({ items: z8.array(eventMetadata), bookmark: z8.string().nullable().optional() }), params);
|
|
1251
|
+
if (result.items.length > input.page_size || result.bookmark && (!result.items.length || result.bookmark === input.bookmark)) throw new AdportError6("PROVIDER_ERROR", "pinterest: page-visit pagination did not advance");
|
|
1252
|
+
result.items.forEach((row) => this.owned(input.account_id, row));
|
|
1253
|
+
return { ...result, account_id: input.account_id, truncated: Boolean(result.bookmark), ...result.bookmark ? { next_cursor: result.bookmark } : {} };
|
|
1254
|
+
}
|
|
1255
|
+
async quality(input) {
|
|
1256
|
+
const parsed = qualityInput.parse(input), params = new URLSearchParams({ lookback_period: parsed.lookback_period });
|
|
1257
|
+
if (parsed.source_platform) params.set("source_platform", parsed.source_platform);
|
|
1258
|
+
if (parsed.ingestion_source) params.set("ingestion_source", parsed.ingestion_source);
|
|
1259
|
+
const result = await this.client.get(`${this.base(parsed.account_id)}/conversion_eqs`, z8.array(quality), params);
|
|
1260
|
+
if (result.some((row) => row.lookback_period !== parsed.lookback_period || parsed.source_platform && row.source_platform !== parsed.source_platform || parsed.ingestion_source && row.ingestion_source !== parsed.ingestion_source)) throw new AdportError6("PROVIDER_ERROR", "pinterest: event-quality response ignored the selected filters");
|
|
1261
|
+
return { account_id: parsed.account_id, items: result };
|
|
1262
|
+
}
|
|
1263
|
+
async plan(op) {
|
|
1264
|
+
if (op.kind !== "create") throw new AdportError6("INVALID_INPUT", "pinterest: measurement writes require create kind");
|
|
1265
|
+
if (op.tool === "pinterest_create_conversion_tag") {
|
|
1266
|
+
const input2 = tagCreate.parse(op.payload), context2 = await this.context(op.accountId);
|
|
1267
|
+
this.checkContext(input2.expected_context_hash, context2.snapshot_hash);
|
|
1268
|
+
if (context2.tags.some((row) => !row.id) || context2.tags.some((row) => row.name.toLowerCase() === input2.name.toLowerCase())) throw new AdportError6("INVALID_INPUT", "pinterest: conversion tag already exists or tag identity is incomplete; inspect existing tags");
|
|
1269
|
+
const { expected_context_hash: _hash, confirm_enhanced_match_consent: _consent, ...body } = input2;
|
|
1270
|
+
return { summary: `Create Pinterest conversion tag "${input2.name}"`, changes: [`+ Conversion tag metadata for advertiser ${op.accountId}. Enhanced-match flags are explicitly supplied.`], notes: ["This creates tag metadata only. It does not install the returned code, send events or change ad delivery.", "No native tag delete endpoint is available. Inspect existing tags before creating another."], coercions: [], budgetDeltas: [], execute: async () => {
|
|
1271
|
+
const row = await this.client.mutate(`${this.base(op.accountId)}/conversion_tags`, "POST", body, tag);
|
|
1272
|
+
const resourceIds = row.id ? [row.id] : [];
|
|
1273
|
+
if (row.ad_account_id !== op.accountId || !row.id || row.name !== input2.name || row.configs && Object.entries(body).some(([key, value]) => key !== "name" && row.configs[key] !== void 0 && row.configs[key] !== value)) throw new AdportError6("PROVIDER_ERROR", "pinterest: conversion-tag creation not confirmed; inspect before any retry", { resource_ids: resourceIds });
|
|
1274
|
+
return resourceIds;
|
|
1275
|
+
} };
|
|
1276
|
+
}
|
|
1277
|
+
if (op.tool !== "pinterest_send_conversion_events") throw new AdportError6("INVALID_INPUT", "pinterest: unsupported measurement write");
|
|
1278
|
+
const input = sendEvents.parse(op.payload), context = await this.context(op.accountId);
|
|
1279
|
+
this.checkContext(input.expected_context_hash, context.snapshot_hash);
|
|
1280
|
+
const count2 = input.data.length, batchHash = digest3(input.data), mode = input.test ? "TEST" : "LIVE";
|
|
1281
|
+
let details, warnings = [];
|
|
1282
|
+
const notices = [input.test ? "Pinterest test mode: events are not recorded for reporting or ad optimization." : "Live events can affect attribution, reported revenue, audiences and automated bidding.", "Preview sends no event data. Applying sends this exact batch; event IDs must remain stable for deduplication.", "Customer data, source URLs, order IDs and device details are omitted from this review and receipts. Inspect per-row outcomes before any new submission; no automatic retry."];
|
|
1283
|
+
return { summary: `Send ${count2} Pinterest conversion events (${mode})`, changes: [`+ ${count2} events; batch SHA-256 ${batchHash}; mode ${mode}.`], notes: notices, coercions: [], budgetDeltas: [], review: { provider: "pinterest", accountId: op.accountId, kind: "create", title: "Send conversion events", fields: [{ label: "Mode", after: mode }, { label: "Events", after: count2 }, { label: "Batch SHA-256", after: batchHash }], notices }, resultDetails: () => details, resultWarnings: () => warnings, execute: async () => {
|
|
1284
|
+
let result;
|
|
1285
|
+
try {
|
|
1286
|
+
result = await this.client.mutate(`${this.base(op.accountId)}/events`, "POST", { data: input.data }, eventResponse, new URLSearchParams({ test: String(input.test) }));
|
|
1287
|
+
} catch (error) {
|
|
1288
|
+
const native = error instanceof AdportError6 && error.details && typeof error.details === "object" ? error.details : {};
|
|
1289
|
+
throw new AdportError6("PROVIDER_ERROR", "pinterest: conversion-event submission unconfirmed; inspect native diagnostics before any new submission. No automatic retry.", { status: "UNCONFIRMED", mode, batch_sha256: batchHash, record_count: count2, ...typeof native.http_status === "number" ? { http_status: native.http_status } : {}, ...typeof native.api_code === "number" || typeof native.api_code === "string" && /^-?\d{1,12}$/.test(native.api_code) ? { api_code: native.api_code } : {} });
|
|
1290
|
+
}
|
|
1291
|
+
const rows = result.events.map((row, index) => ({ index, status: row.status, has_error: Boolean(row.error_message), has_warning: Boolean(row.warning_message) }));
|
|
1292
|
+
const processed = rows.filter((row) => row.status === "processed").length;
|
|
1293
|
+
if (result.num_events_received !== count2 || result.events.length !== count2 || result.num_events_processed !== processed) throw new AdportError6("PROVIDER_ERROR", "pinterest: conversion-event receipt counts disagree; no automatic retry", { status: "UNCONFIRMED", mode, batch_sha256: batchHash, record_count: count2, num_events_received: result.num_events_received, num_events_processed: result.num_events_processed, rows });
|
|
1294
|
+
const complete = processed === count2 && rows.every((row) => !row.has_error);
|
|
1295
|
+
details = { status: complete ? "COMPLETE" : "PARTIAL_OR_UNCONFIRMED", mode, batch_sha256: batchHash, record_count: count2, num_events_received: result.num_events_received, num_events_processed: result.num_events_processed, failed_count: count2 - processed, rows };
|
|
1296
|
+
if (!processed) throw new AdportError6("PROVIDER_ERROR", "pinterest: no conversion events were processed; inspect row outcomes before any new submission", details);
|
|
1297
|
+
if (!complete || rows.some((row) => row.has_warning)) warnings.push(`${processed} of ${count2} events processed; ${count2 - processed} failed. Inspect result.details and native diagnostics before submitting again.`);
|
|
1298
|
+
if (input.test) warnings.push("Test-mode validation only; these events were not recorded for reporting or optimization.");
|
|
1299
|
+
return [];
|
|
1300
|
+
} };
|
|
1301
|
+
}
|
|
1302
|
+
checkContext(expected, actual) {
|
|
1303
|
+
if (expected !== actual) throw new AdportError6("INVALID_INPUT", "pinterest: measurement context changed; read it again before requesting a new preview");
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
function pinterestMeasurementTools(provider) {
|
|
1307
|
+
const read = (name3, description2, input, handler) => defineTool5({ name: name3, namespace: "pinterest", description: description2, input, annotations: { readOnly: true }, handler });
|
|
1308
|
+
return [
|
|
1309
|
+
read("pinterest_measurement_context", "Read advertiser identity, conversion tags and a stable snapshot_hash for guarded measurement writes.", z8.object({ account_id: pinterestId }), (input) => provider.measurement.context(input.account_id)),
|
|
1310
|
+
read("pinterest_conversion_tags", "Read advertiser-owned conversion tags and code snippets as data. Unpaged native collection; does not install tracking or send events.", z8.object({ account_id: pinterestId, filter_deleted: z8.boolean().default(false) }), (input) => provider.measurement.tags(input.account_id, input.filter_deleted)),
|
|
1311
|
+
read("pinterest_get_conversion_tag", "Read one advertiser-owned conversion tag by ID. Code snippets are returned as text only.", z8.object({ account_id: pinterestId, conversion_tag_id: pinterestId }), (input) => provider.measurement.getTag(input.account_id, input.conversion_tag_id)),
|
|
1312
|
+
read("pinterest_conversion_tag_eligible_events", "Read the advertiser\u2019s native OCPM-eligible conversion-tag events without changing optimization.", z8.object({ account_id: pinterestId }), (input) => provider.measurement.eligible(input.account_id)),
|
|
1313
|
+
defineTool5({ name: "pinterest_conversion_tag_page_visits", namespace: "pinterest", description: "Read native conversion-tag page-visit metadata with bookmark pagination.", input: z8.object({ account_id: pinterestId, page_size: z8.number().int().min(1).max(250).default(25), bookmark: z8.string().min(1).max(4096).optional(), order: z8.enum(["ASCENDING", "DESCENDING"]).default("ASCENDING") }), annotations: { readOnly: true }, pagination: { cursorInput: "bookmark" }, handler: (input) => provider.measurement.visits(input) }),
|
|
1314
|
+
read("pinterest_event_quality", "Read Pinterest\u2019s native conversion-event quality diagnostics for explicit lookback/source filters. No derived score or delivery change.", qualityInput, (input) => provider.measurement.quality(input)),
|
|
1315
|
+
guardedWriteTool5({ name: "pinterest_create_conversion_tag", namespace: "pinterest", provider: "pinterest", kind: "create", destructive: false, description: "Create conversion-tag metadata using expected_context_hash. Enhanced match defaults off and requires consent when enabled. Does not install code or send events; no native tag delete endpoint.", payload: tagCreate }),
|
|
1316
|
+
guardedWriteTool5({ name: "pinterest_send_conversion_events", namespace: "pinterest", provider: "pinterest", kind: "create", description: "Send 1\u20131000 conversion events using expected_context_hash. Defaults test=true; all applies send data. Requires data-rights confirmation; live requires confirm_live_events. Use stable event IDs, prehashed SHA-256 matching fields and explicit currency with decimal values. Per-index outcomes; no automatic retry.", payload: sendEvents })
|
|
1317
|
+
];
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
// src/catalogs.ts
|
|
1321
|
+
import { createHash as createHash5 } from "crypto";
|
|
1322
|
+
import { AdportError as AdportError7, defineTool as defineTool6, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
|
|
1323
|
+
import { z as z9 } from "zod";
|
|
1324
|
+
var id3 = z9.string().regex(/^\d{1,30}$/);
|
|
1325
|
+
var hash5 = z9.string().regex(/^[a-f0-9]{64}$/);
|
|
1326
|
+
var type = z9.enum(["RETAIL", "HOTEL", "CREATIVE_ASSETS"]);
|
|
1327
|
+
var format = z9.enum(["TSV", "CSV", "XML", "INTEGRATION"]);
|
|
1328
|
+
var state = z9.enum(["ACTIVE", "INACTIVE"]);
|
|
1329
|
+
var name2 = z9.string().trim().min(1).max(1024);
|
|
1330
|
+
var currency = z9.string().regex(/^[A-Z]{3}$/).nullable();
|
|
1331
|
+
var credentials = z9.object({ username: z9.string().min(1).max(4096), password: z9.string().min(1).max(8192) }).strict().nullable();
|
|
1332
|
+
var location = z9.string().url().max(16384).refine((value) => {
|
|
1333
|
+
const url2 = new URL(value);
|
|
1334
|
+
return ["http:", "https:", "ftp:", "sftp:"].includes(url2.protocol) && !url2.username && !url2.password && !url2.hash;
|
|
1335
|
+
}, "Use an HTTP(S), FTP or SFTP URL without inline credentials or fragments");
|
|
1336
|
+
var schedule = z9.object({ time: z9.string().regex(/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/), timezone: z9.string().min(1).max(100) }).strict().nullable();
|
|
1337
|
+
var availability = z9.enum(["IN_STOCK", "OUT_OF_STOCK", "PREORDER"]).nullable();
|
|
1338
|
+
var account2 = { account_id: pinterestId };
|
|
1339
|
+
var selected2 = { catalog_id: id3 };
|
|
1340
|
+
var reference2 = { ...selected2, feed_id: id3 };
|
|
1341
|
+
var bound = { ...reference2, expected_snapshot_hash: hash5 };
|
|
1342
|
+
var paging = { page_size: z9.number().int().min(1).max(250).default(25), bookmark: z9.string().min(1).max(4096).optional() };
|
|
1343
|
+
var catalog = z9.looseObject({ id: id3, name: z9.string(), catalog_type: type, created_at: z9.string(), updated_at: z9.string() });
|
|
1344
|
+
var feed = z9.looseObject({ id: id3, catalog_type: type, catalog_id: id3.nullable().optional(), name: z9.string().nullable(), status: z9.string(), format, default_locale: z9.string(), default_country: z9.string().optional(), default_currency: z9.string().nullable().optional(), default_availability: availability.optional(), preferred_processing_schedule: schedule.optional(), location: z9.string(), credentials: z9.unknown().optional(), created_at: z9.string(), updated_at: z9.string() });
|
|
1345
|
+
var common = { catalog_id: id3, name: name2, location, format, default_locale: z9.string().min(2).max(40), default_currency: currency.optional(), credentials: credentials.optional(), preferred_processing_schedule: schedule.optional(), status: state.default("INACTIVE") };
|
|
1346
|
+
var feedCreate = z9.discriminatedUnion("catalog_type", [
|
|
1347
|
+
z9.object({ ...common, catalog_type: z9.literal("RETAIL"), default_country: z9.string().regex(/^[A-Z]{2}$/), default_availability: availability.optional() }).strict(),
|
|
1348
|
+
z9.object({ ...common, catalog_type: z9.literal("HOTEL") }).strict(),
|
|
1349
|
+
z9.object({ ...common, catalog_type: z9.literal("CREATIVE_ASSETS"), default_country: z9.string().regex(/^[A-Z]{2}$/) }).strict()
|
|
1350
|
+
]);
|
|
1351
|
+
var feedChanges = z9.object({ name: name2.optional(), location: location.optional(), format: format.optional(), default_currency: currency.optional(), default_availability: availability.optional(), credentials: credentials.optional(), preferred_processing_schedule: schedule.optional(), status: state.optional() }).strict().refine((value) => Object.keys(value).length > 0, "Supply at least one feed setting");
|
|
1352
|
+
var createCatalog = z9.object({ expected_context_hash: hash5, name: name2, catalog_type: type }).strict();
|
|
1353
|
+
var createFeed = z9.object({ expected_context_hash: hash5, feed: feedCreate, confirm_source_access: z9.literal(true), confirm_publication: z9.boolean().default(false) }).strict();
|
|
1354
|
+
var updateFeed = z9.object({ ...bound, changes: feedChanges, confirm_source_access: z9.boolean().default(false), confirm_publication: z9.boolean().default(false) }).strict();
|
|
1355
|
+
var deleteFeed = z9.object({ ...bound, confirm_permanent_deletion: z9.literal(true) }).strict();
|
|
1356
|
+
var ingestFeed = z9.object({ ...bound, confirm_source_access: z9.literal(true), confirm_publication: z9.literal(true) }).strict();
|
|
1357
|
+
var processing = z9.looseObject({ id: id3, status: z9.enum(["COMPLETED", "FAILED", "PROCESSING"]), created_at: z9.string(), updated_at: z9.string(), ingestion_details: z9.record(z9.string(), z9.unknown()), product_counts: z9.record(z9.string(), z9.unknown()), validation_details: z9.record(z9.string(), z9.unknown()) });
|
|
1358
|
+
var ingestion = z9.object({ id: id3, feed_id: id3, status: z9.enum(["COMPLETED", "FAILED", "PROCESSING"]), created_at: z9.string() });
|
|
1359
|
+
var writeKinds = { pinterest_create_catalog: "create", pinterest_create_feed: "create", pinterest_update_feed: "update", pinterest_delete_feed: "remove", pinterest_ingest_feed: "update" };
|
|
1360
|
+
var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1361
|
+
var canonical3 = (value) => Array.isArray(value) ? value.map(canonical3) : isObject(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical3(item)])) : value;
|
|
1362
|
+
var digest4 = (value) => createHash5("sha256").update(JSON.stringify(canonical3(value)) ?? "undefined").digest("hex");
|
|
1363
|
+
var same = (a, b) => digest4(a) === digest4(b);
|
|
1364
|
+
function sourceOrigin(value) {
|
|
1365
|
+
try {
|
|
1366
|
+
const url2 = new URL(value);
|
|
1367
|
+
return `${url2.protocol}//${url2.host}`;
|
|
1368
|
+
} catch {
|
|
1369
|
+
return "Unavailable";
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
function privateValues(value) {
|
|
1373
|
+
const auth = isObject(value.credentials) ? value.credentials : {};
|
|
1374
|
+
return [value.location, auth.username, auth.password].filter((v) => typeof v === "string" && v.length > 0);
|
|
1375
|
+
}
|
|
1376
|
+
function redact(value, secrets) {
|
|
1377
|
+
if (typeof value === "string") return secrets.reduce((text4, secret) => text4.replaceAll(secret, "[redacted]"), value);
|
|
1378
|
+
if (Array.isArray(value)) return value.map((item) => redact(item, secrets));
|
|
1379
|
+
return isObject(value) ? Object.fromEntries(Object.entries(value).filter(([key]) => !/credential|password|authorization|access_token|refresh_token|download_url|^location$/i.test(key)).map(([key, item]) => [key, redact(item, secrets)])) : value;
|
|
1380
|
+
}
|
|
1381
|
+
function publicFeed(value) {
|
|
1382
|
+
const { location: location2, credentials: credentials2, ...rest } = value;
|
|
1383
|
+
const keys = ["id", "catalog_id", "catalog_type", "name", "status", "format", "default_locale", "default_country", "default_currency", "default_availability", "preferred_processing_schedule", "created_at", "updated_at"];
|
|
1384
|
+
const selected3 = Object.fromEntries(keys.filter((key) => Object.hasOwn(rest, key)).map((key) => [key, rest[key]]));
|
|
1385
|
+
const { created_at: _created, updated_at: _updated, ...settings } = selected3;
|
|
1386
|
+
const config = { ...settings, location: location2, credentials_configured: credentials2 != null };
|
|
1387
|
+
return { ...selected3, source_origin: sourceOrigin(location2), source_fingerprint: digest4(location2), credentials_configured: credentials2 != null, snapshot_hash: digest4(config) };
|
|
1388
|
+
}
|
|
1389
|
+
var output = z9.object({ account_id: pinterestId, context_hash: hash5, records: z9.array(z9.record(z9.string(), z9.unknown())), truncated: z9.boolean() }).passthrough();
|
|
1390
|
+
var labels = { name: "Name", catalog_type: "Catalog type", status: "Feed status", format: "Format", default_locale: "Locale", default_country: "Country", default_currency: "Currency", default_availability: "Default availability", preferred_processing_schedule: "Daily processing schedule" };
|
|
1391
|
+
function fields(before, requested) {
|
|
1392
|
+
return Object.entries(requested).filter(([key]) => key !== "catalog_id").map(([key, value]) => key === "location" ? { label: "Source", ...before ? { before: { origin: sourceOrigin(String(before.location)), fingerprint: digest4(before.location) } } : {}, after: { origin: sourceOrigin(String(value)), fingerprint: digest4(value) } } : key === "credentials" ? { label: "Feed authentication", ...before ? { before: before.credentials != null ? "Configured; values hidden" : "Not configured" } : {}, after: value === null ? "Remove credentials" : "Configure credentials; values hidden" } : { label: labels[key] ?? key, ...before && Object.hasOwn(before, key) ? { before: before[key] } : {}, after: value });
|
|
1393
|
+
}
|
|
1394
|
+
var PinterestCatalogService = class {
|
|
1395
|
+
constructor(client) {
|
|
1396
|
+
this.client = client;
|
|
1397
|
+
}
|
|
1398
|
+
client;
|
|
1399
|
+
supports(tool) {
|
|
1400
|
+
return Object.hasOwn(writeKinds, tool);
|
|
1401
|
+
}
|
|
1402
|
+
params(account3, catalog2) {
|
|
1403
|
+
return new URLSearchParams({ ad_account_id: pinterestId.parse(account3), ...catalog2 ? { catalog_id: id3.parse(catalog2) } : {} });
|
|
1404
|
+
}
|
|
1405
|
+
async context(account3) {
|
|
1406
|
+
const value = await this.client.get(`ad_accounts/${pinterestId.parse(account3)}`, z9.object({ id: pinterestId, owner: z9.object({ username: z9.string().min(1) }) }));
|
|
1407
|
+
if (value.id !== account3) throw new AdportError7("PROVIDER_ERROR", "pinterest: catalog advertiser ID mismatch");
|
|
1408
|
+
return { account_id: account3, context_hash: digest4({ account: account3, owner: value.owner.username.toLowerCase() }) };
|
|
1409
|
+
}
|
|
1410
|
+
async page(path, schema, params, input) {
|
|
1411
|
+
params.set("page_size", String(input.page_size));
|
|
1412
|
+
if (input.bookmark) params.set("bookmark", input.bookmark);
|
|
1413
|
+
const value = await this.client.get(path, z9.object({ items: z9.array(schema), bookmark: z9.string().nullable().optional() }), params);
|
|
1414
|
+
const ids3 = value.items.flatMap((row) => isObject(row) && typeof row.id === "string" ? [row.id] : []);
|
|
1415
|
+
if (value.items.length > input.page_size || new Set(ids3).size !== ids3.length || value.bookmark && (value.bookmark === input.bookmark || !value.items.length)) throw new AdportError7("PROVIDER_ERROR", "pinterest: catalog pagination did not advance consistently");
|
|
1416
|
+
return { ...value, truncated: Boolean(value.bookmark), ...value.bookmark ? { next_cursor: value.bookmark } : {} };
|
|
1417
|
+
}
|
|
1418
|
+
async find(path, schema, params, wanted) {
|
|
1419
|
+
const seen = /* @__PURE__ */ new Set(), ids3 = /* @__PURE__ */ new Set();
|
|
1420
|
+
let bookmark;
|
|
1421
|
+
for (let pages = 0; pages < 40; pages++) {
|
|
1422
|
+
const page2 = await this.page(path, schema, new URLSearchParams(params), { page_size: 250, bookmark });
|
|
1423
|
+
for (const row of page2.items) {
|
|
1424
|
+
if (row.id && ids3.has(row.id)) throw new AdportError7("PROVIDER_ERROR", "pinterest: catalog finder repeated an identity");
|
|
1425
|
+
if (row.id) ids3.add(row.id);
|
|
1426
|
+
if (row.id === wanted) return row;
|
|
1427
|
+
}
|
|
1428
|
+
if (!page2.next_cursor) return void 0;
|
|
1429
|
+
if (seen.has(page2.next_cursor)) throw new AdportError7("PROVIDER_ERROR", "pinterest: catalog finder repeated a bookmark");
|
|
1430
|
+
seen.add(page2.next_cursor);
|
|
1431
|
+
bookmark = page2.next_cursor;
|
|
1432
|
+
}
|
|
1433
|
+
throw new AdportError7("PROVIDER_ERROR", "pinterest: catalog membership lookup exceeded 10,000 rows; membership is unconfirmed");
|
|
1434
|
+
}
|
|
1435
|
+
async ownedCatalog(account3, catalogId) {
|
|
1436
|
+
const value = await this.find("catalogs", catalog, this.params(account3), id3.parse(catalogId));
|
|
1437
|
+
if (!value) throw new AdportError7("INVALID_INPUT", "pinterest: catalog was not found for the selected advertiser owner");
|
|
1438
|
+
return value;
|
|
1439
|
+
}
|
|
1440
|
+
validateFeed(value, selected3) {
|
|
1441
|
+
if (value.catalog_type !== selected3.catalog_type || value.catalog_id != null && value.catalog_id !== selected3.id) throw new AdportError7("PROVIDER_ERROR", "pinterest: feed catalog/type mismatch");
|
|
1442
|
+
return value;
|
|
1443
|
+
}
|
|
1444
|
+
async ownedFeed(account3, catalogId, feedId) {
|
|
1445
|
+
const selected3 = await this.ownedCatalog(account3, catalogId), member = await this.find("catalogs/feeds", feed, this.params(account3, catalogId), id3.parse(feedId));
|
|
1446
|
+
if (!member) throw new AdportError7("INVALID_INPUT", "pinterest: feed was not found in the selected advertiser catalog");
|
|
1447
|
+
this.validateFeed(member, selected3);
|
|
1448
|
+
const value = await this.client.get(`catalogs/feeds/${feedId}`, feed, this.params(account3));
|
|
1449
|
+
if (value.id !== feedId) throw new AdportError7("PROVIDER_ERROR", "pinterest: feed ID mismatch");
|
|
1450
|
+
return this.validateFeed(value, selected3);
|
|
1451
|
+
}
|
|
1452
|
+
async catalogs(input) {
|
|
1453
|
+
const context = await this.context(input.account_id), page2 = await this.page("catalogs", catalog, this.params(input.account_id), input);
|
|
1454
|
+
return { ...context, ...page2, records: page2.items.map((value) => ({ ...value, snapshot_hash: digest4({ id: value.id, name: value.name, catalog_type: value.catalog_type }) })) };
|
|
1455
|
+
}
|
|
1456
|
+
async getCatalog(account3, catalogId) {
|
|
1457
|
+
const context = await this.context(account3), value = await this.ownedCatalog(account3, catalogId);
|
|
1458
|
+
return { ...context, catalog: value, records: [value], truncated: false };
|
|
1459
|
+
}
|
|
1460
|
+
async feeds(input) {
|
|
1461
|
+
const context = await this.context(input.account_id), selected3 = await this.ownedCatalog(input.account_id, input.catalog_id), page2 = await this.page("catalogs/feeds", feed, this.params(input.account_id, input.catalog_id), input);
|
|
1462
|
+
const items = page2.items.map((value) => publicFeed(this.validateFeed(value, selected3)));
|
|
1463
|
+
return { ...context, ...page2, items, records: items, catalog_id: selected3.id };
|
|
1464
|
+
}
|
|
1465
|
+
async getFeed(account3, catalogId, feedId) {
|
|
1466
|
+
const context = await this.context(account3), value = publicFeed(await this.ownedFeed(account3, catalogId, feedId));
|
|
1467
|
+
return { ...context, feed: value, records: [value], truncated: false };
|
|
1468
|
+
}
|
|
1469
|
+
async results(input) {
|
|
1470
|
+
const context = await this.context(input.account_id), current = await this.ownedFeed(input.account_id, input.catalog_id, input.feed_id);
|
|
1471
|
+
const page2 = await this.safe(current, () => this.page(`catalogs/feeds/${current.id}/processing_results`, processing, this.params(input.account_id), input));
|
|
1472
|
+
const items = page2.items.map((value) => redact(value, privateValues(current)));
|
|
1473
|
+
return { ...context, ...page2, items, records: items, feed_id: current.id };
|
|
1474
|
+
}
|
|
1475
|
+
async issues(input) {
|
|
1476
|
+
const context = await this.context(input.account_id), current = await this.ownedFeed(input.account_id, input.catalog_id, input.feed_id);
|
|
1477
|
+
const result = await this.safe(current, () => this.find(`catalogs/feeds/${current.id}/processing_results`, processing, this.params(input.account_id), input.processing_result_id));
|
|
1478
|
+
if (!result) throw new AdportError7("INVALID_INPUT", "pinterest: processing result was not found for this feed");
|
|
1479
|
+
const params = this.params(input.account_id);
|
|
1480
|
+
if (input.item_numbers) params.set("item_numbers", input.item_numbers.join(","));
|
|
1481
|
+
if (input.item_validation_issue) params.set("item_validation_issue", input.item_validation_issue);
|
|
1482
|
+
const page2 = await this.safe(current, () => this.page(`catalogs/processing_results/${result.id}/item_issues`, z9.record(z9.string(), z9.unknown()), params, input));
|
|
1483
|
+
const items = page2.items.map((value) => redact(value, privateValues(current)));
|
|
1484
|
+
return { ...context, ...page2, items, records: items, feed_id: current.id, processing_result_id: result.id, notes: ["Native issues contain samples of up to 20 affected items per error or warning, not a complete affected-product inventory."] };
|
|
1485
|
+
}
|
|
1486
|
+
async safe(current, fn) {
|
|
1487
|
+
try {
|
|
1488
|
+
return await fn();
|
|
1489
|
+
} catch (error) {
|
|
1490
|
+
if (!(error instanceof AdportError7)) throw new AdportError7("PROVIDER_ERROR", "pinterest: catalog request was not confirmed; reconcile before retrying");
|
|
1491
|
+
throw new AdportError7(error.code, redact(error.message, privateValues(current)), redact(error.details, privateValues(current)));
|
|
1492
|
+
}
|
|
1493
|
+
}
|
|
1494
|
+
async verify(resource, fn) {
|
|
1495
|
+
try {
|
|
1496
|
+
if (!await fn()) throw new Error("readback mismatch");
|
|
1497
|
+
} catch {
|
|
1498
|
+
throw new AdportError7("PROVIDER_ERROR", "pinterest: catalog write readback unconfirmed; reconcile the resource ID before a new approval", { resource_ids: [resource] });
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
async plan(op) {
|
|
1502
|
+
if (op.provider !== "pinterest" || !this.supports(op.tool) || op.kind !== writeKinds[op.tool]) throw new AdportError7("INVALID_INPUT", "pinterest: catalog operation kind mismatch");
|
|
1503
|
+
const context = await this.context(op.accountId), base = { coercions: [], budgetDeltas: [], notes: [] };
|
|
1504
|
+
const review = (title, subject, fields2, notices) => ({ provider: "pinterest", accountId: op.accountId, kind: op.kind, title, subject, fields: fields2, notices });
|
|
1505
|
+
if (op.tool === "pinterest_create_catalog") {
|
|
1506
|
+
const input2 = createCatalog.parse(op.payload);
|
|
1507
|
+
if (input2.expected_context_hash !== context.context_hash) throw new AdportError7("INVALID_INPUT", "pinterest: catalog advertiser context changed; read catalogs again");
|
|
1508
|
+
const body2 = { name: input2.name, catalog_type: input2.catalog_type };
|
|
1509
|
+
return { ...base, summary: `Create Pinterest ${input2.catalog_type} catalog "${input2.name}"`, changes: [`+ ${JSON.stringify(body2)}`], review: review("Create catalog", input2.name, fields(void 0, body2), ["Creates an empty catalog. No feed, products, Pins or ads are created. Native catalog-program eligibility is still required."]), execute: async () => {
|
|
1510
|
+
const value = await this.client.mutate("catalogs", "POST", body2, catalog, this.params(op.accountId));
|
|
1511
|
+
await this.verify(value.id, async () => {
|
|
1512
|
+
const current2 = await this.ownedCatalog(op.accountId, value.id);
|
|
1513
|
+
return current2.name === body2.name && current2.catalog_type === body2.catalog_type;
|
|
1514
|
+
});
|
|
1515
|
+
return [value.id];
|
|
1516
|
+
} };
|
|
1517
|
+
}
|
|
1518
|
+
if (op.tool === "pinterest_create_feed") {
|
|
1519
|
+
const input2 = createFeed.parse(op.payload), body2 = input2.feed, selected3 = await this.ownedCatalog(op.accountId, body2.catalog_id);
|
|
1520
|
+
if (input2.expected_context_hash !== context.context_hash || selected3.catalog_type !== body2.catalog_type) throw new AdportError7("INVALID_INPUT", "pinterest: catalog advertiser context/type changed; read catalogs again");
|
|
1521
|
+
if (body2.status === "ACTIVE" && !input2.confirm_publication) throw new AdportError7("INVALID_INPUT", "pinterest: active feeds may create public product Pins; confirm publication and source access");
|
|
1522
|
+
const changes2 = fields(void 0, body2);
|
|
1523
|
+
return { ...base, summary: `Create Pinterest feed "${body2.name}"`, changes: changes2.map((field) => `+ ${field.label}: ${JSON.stringify(field.after)}`), review: review("Create feed", body2.name, changes2, ["Pinterest will store the source URL and any supplied credentials. ACTIVE feeds process automatically and may create product Pins used by ads. No campaign status is changed."]), execute: async () => {
|
|
1524
|
+
const value = await this.client.mutate("catalogs/feeds", "POST", body2, feed, this.params(op.accountId));
|
|
1525
|
+
await this.verify(value.id, async () => this.matches(await this.ownedFeed(op.accountId, selected3.id, value.id), body2));
|
|
1526
|
+
return [value.id];
|
|
1527
|
+
}, resultWarnings: () => ["Saved feed configuration is not proof of source authentication or imported products; read processing results."] };
|
|
1528
|
+
}
|
|
1529
|
+
const input = op.tool === "pinterest_update_feed" ? updateFeed.parse(op.payload) : op.tool === "pinterest_delete_feed" ? deleteFeed.parse(op.payload) : ingestFeed.parse(op.payload);
|
|
1530
|
+
const current = await this.ownedFeed(op.accountId, input.catalog_id, input.feed_id);
|
|
1531
|
+
if (publicFeed(current).snapshot_hash !== input.expected_snapshot_hash) throw new AdportError7("INVALID_INPUT", "pinterest: feed configuration changed; read the feed again");
|
|
1532
|
+
if (current.status === "DELETED") throw new AdportError7("INVALID_INPUT", "pinterest: this feed is deleted");
|
|
1533
|
+
if (op.tool === "pinterest_delete_feed") return { ...base, summary: `Delete Pinterest feed ${current.id}`, changes: [`- feed ${current.id}`], review: review("Delete feed", current.name ?? current.id, [{ label: "Feed", before: current.id, after: null }], ["Permanent removal; no restore endpoint is exposed. Review catalog product and ad dependencies before deletion."]), execute: async () => {
|
|
1534
|
+
const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}`, "DELETE", void 0, z9.union([feed, z9.undefined()]), this.params(op.accountId)));
|
|
1535
|
+
if (result && result.id !== current.id) throw new AdportError7("PROVIDER_ERROR", "pinterest: feed delete receipt ID mismatch", { resource_ids: [current.id] });
|
|
1536
|
+
await this.verify(current.id, async () => {
|
|
1537
|
+
const remaining = await this.find("catalogs/feeds", feed, this.params(op.accountId, input.catalog_id), current.id);
|
|
1538
|
+
return !remaining || remaining.status === "DELETED";
|
|
1539
|
+
});
|
|
1540
|
+
return [current.id];
|
|
1541
|
+
} };
|
|
1542
|
+
if (op.tool === "pinterest_ingest_feed") {
|
|
1543
|
+
let details, warning = [];
|
|
1544
|
+
return { ...base, summary: `Process Pinterest feed ${current.id}`, changes: [`~ request processing for feed ${current.id}`], review: review("Process feed", current.name ?? current.id, [{ label: "Source", after: { origin: sourceOrigin(current.location), fingerprint: digest4(current.location) } }], ["Requests native processing of the existing source. This may create/update public product Pins and affect catalog ads. A job receipt is not proof of imported products. Partner access is required."]), execute: async () => {
|
|
1545
|
+
const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}/ingest`, "POST", void 0, ingestion, this.params(op.accountId)));
|
|
1546
|
+
if (result.feed_id !== current.id) throw new AdportError7("PROVIDER_ERROR", "pinterest: ingestion receipt feed mismatch", { resource_ids: [current.id, result.id] });
|
|
1547
|
+
details = { status: result.status === "PROCESSING" ? "ACCEPTED_FOR_PROCESSING" : result.status, processed: result.status === "COMPLETED", native_status: result.status, ingestion_id: result.id, feed_id: current.id, next_tool: "pinterest_feed_processing_results" };
|
|
1548
|
+
if (result.status === "FAILED") warning = ["Pinterest reports that the requested ingestion failed. Read processing results; do not automatically retry."];
|
|
1549
|
+
return [result.id];
|
|
1550
|
+
}, resultDetails: () => details, resultWarnings: () => warning };
|
|
1551
|
+
}
|
|
1552
|
+
const update = updateFeed.parse(op.payload), changes = update.changes;
|
|
1553
|
+
if (current.catalog_type !== "RETAIL" && Object.hasOwn(changes, "default_availability")) throw new AdportError7("INVALID_INPUT", "pinterest: default availability is retail-only");
|
|
1554
|
+
if ((changes.location !== void 0 || changes.credentials != null || changes.status === "ACTIVE") && !update.confirm_source_access) throw new AdportError7("INVALID_INPUT", "pinterest: changing feed source/authentication or activating processing requires source-access confirmation");
|
|
1555
|
+
if ((changes.status ?? current.status) === "ACTIVE" && Object.keys(changes).some((key) => key !== "name") && !update.confirm_publication) throw new AdportError7("INVALID_INPUT", "pinterest: changes to an active feed may affect public product Pins; confirm publication");
|
|
1556
|
+
if (!Object.entries(changes).some(([key, value]) => key === "credentials" || !same(current[key], value))) throw new AdportError7("INVALID_INPUT", "pinterest: no supplied feed settings would change");
|
|
1557
|
+
const body = { catalog_type: current.catalog_type, ...changes }, visible = fields(current, changes);
|
|
1558
|
+
return { ...base, summary: `Update Pinterest feed ${current.id}`, changes: visible.map((field) => `~ ${field.label}: ${JSON.stringify(field.before)} \u2192 ${JSON.stringify(field.after)}`), review: review("Update feed", current.name ?? current.id, visible, ["Only supplied fields are patched. Existing credential values and source paths are hidden. Credentials are replaced only when explicitly supplied; the snapshot cannot detect password-only changes made elsewhere."]), execute: async () => {
|
|
1559
|
+
const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}`, "PATCH", body, feed, this.params(op.accountId)));
|
|
1560
|
+
if (result.id !== current.id) throw new AdportError7("PROVIDER_ERROR", "pinterest: feed update receipt ID mismatch", { resource_ids: [current.id] });
|
|
1561
|
+
await this.verify(current.id, async () => this.matches(await this.ownedFeed(op.accountId, input.catalog_id, current.id), changes));
|
|
1562
|
+
return [current.id];
|
|
1563
|
+
}, resultWarnings: () => changes.location !== void 0 || changes.credentials != null ? ["Source downloading/authentication is unverified until native processing results confirm success."] : [] };
|
|
1564
|
+
}
|
|
1565
|
+
matches(current, wanted) {
|
|
1566
|
+
return Object.entries(wanted).every(([key, value]) => {
|
|
1567
|
+
if (key === "catalog_id" && current.catalog_id == null) return true;
|
|
1568
|
+
if (key === "credentials") return value === null ? current.credentials == null : current.credentials != null;
|
|
1569
|
+
return same(current[key], value);
|
|
1570
|
+
});
|
|
1571
|
+
}
|
|
1572
|
+
};
|
|
1573
|
+
function pinterestCatalogTools(provider) {
|
|
1574
|
+
return [
|
|
1575
|
+
defineTool6({ name: "pinterest_catalogs", namespace: "pinterest", description: "List selected advertiser-owner catalogs and context_hash with native bookmarks. Requires catalogs:read; no token-owner fallback.", input: z9.object({ ...account2, ...paging }).strict(), output, presentation: "records", pagination: { cursorInput: "bookmark" }, annotations: { readOnly: true }, handler: (input) => provider.catalogs.catalogs(input) }),
|
|
1576
|
+
defineTool6({ name: "pinterest_get_catalog", namespace: "pinterest", description: "Find an exact owned catalog via the native scoped finder (bounded 10,000 rows; Pinterest has no catalog GET-by-ID endpoint).", input: z9.object({ ...account2, ...selected2 }).strict(), output, presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.catalogs.getCatalog(input.account_id, input.catalog_id) }),
|
|
1577
|
+
defineTool6({ name: "pinterest_feeds", namespace: "pinterest", description: "List one advertiser-owned catalog\u2019s feeds and configuration snapshots. Native bookmarks; source paths/query values and feed credentials stay hidden.", input: z9.object({ ...account2, ...selected2, ...paging }).strict(), output, presentation: "records", pagination: { cursorInput: "bookmark" }, annotations: { readOnly: true }, handler: (input) => provider.catalogs.feeds(input) }),
|
|
1578
|
+
defineTool6({ name: "pinterest_get_feed", namespace: "pinterest", description: "Verify selected catalog membership and read current feed configuration/snapshot_hash. Authentication values and full source URLs are never returned.", input: z9.object({ ...account2, ...reference2 }).strict(), output, presentation: "records", annotations: { readOnly: true }, handler: (input) => provider.catalogs.getFeed(input.account_id, input.catalog_id, input.feed_id) }),
|
|
1579
|
+
defineTool6({ name: "pinterest_feed_processing_results", namespace: "pinterest", description: "Read feed processing status, native product counts and diagnostics with bookmarks. Verifies feed ownership; ingestion acceptance is not product readiness.", input: z9.object({ ...account2, ...reference2, ...paging }).strict(), output, presentation: "records", pagination: { cursorInput: "bookmark" }, annotations: { readOnly: true }, handler: (input) => provider.catalogs.results(input) }),
|
|
1580
|
+
defineTool6({ name: "pinterest_feed_item_issues", namespace: "pinterest", description: "Read sampled item errors/warnings after verifying processing-result membership in this feed. Up to20 affected items per code; not a complete product inventory.", input: z9.object({ ...account2, ...reference2, processing_result_id: id3, ...paging, item_numbers: z9.array(z9.number().int().nonnegative().safe()).min(1).max(1e3).optional(), item_validation_issue: z9.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/).optional() }).strict().refine((value) => !value.item_numbers || !value.item_validation_issue, "Native item-number and validation-issue filters cannot be combined"), output, presentation: "records", pagination: { cursorInput: "bookmark" }, annotations: { readOnly: true }, handler: (input) => provider.catalogs.issues(input) }),
|
|
1581
|
+
guardedWriteTool6({ name: "pinterest_create_catalog", namespace: "pinterest", provider: "pinterest", kind: "create", destructive: false, payload: createCatalog, description: "Create an empty RETAIL, HOTEL or CREATIVE_ASSETS catalog with context_hash from pinterest_catalogs. No feed/products/ads; catalog programs and catalogs:write required." }),
|
|
1582
|
+
guardedWriteTool6({ name: "pinterest_create_feed", namespace: "pinterest", provider: "pinterest", kind: "create", payload: createFeed, sensitiveInputs: ["feed.location", "feed.credentials"], description: "Create a feed in an explicitly selected owned catalog. Defaults INACTIVE; supports native formats, schedules and optional private-source credentials. Confirm source access; ACTIVE also requires publication confirmation. Source/auth values are omitted from previews/audits; the agent applies with identical arguments instead of passing secrets to a widget. Requires catalogs read/write." }),
|
|
1583
|
+
guardedWriteTool6({ name: "pinterest_update_feed", namespace: "pinterest", provider: "pinterest", kind: "update", payload: updateFeed, sensitiveInputs: ["changes.location", "changes.credentials"], description: "Patch supplied feed settings with a current snapshot_hash, preserving omitted settings. New source/authentication or ACTIVE requires source-access confirmation; active feeds require publication confirmation. Null credentials removes authentication; source/auth changes are applied by the agent without echoing private arguments to a widget." }),
|
|
1584
|
+
guardedWriteTool6({ name: "pinterest_delete_feed", namespace: "pinterest", provider: "pinterest", kind: "remove", payload: deleteFeed, description: "Permanently delete an owned feed with exact snapshot and explicit deletion confirmation. No restore endpoint is exposed; review product/ad dependencies. Native deletion is reconciled before reporting success." }),
|
|
1585
|
+
guardedWriteTool6({ name: "pinterest_ingest_feed", namespace: "pinterest", provider: "pinterest", kind: "update", payload: ingestFeed, description: "Request processing for an owned feed with current snapshot and explicit source/publication confirmations. This can create/update product Pins. Partner-only endpoint; returns native job status, never retries and never activates campaigns." })
|
|
1586
|
+
];
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
// src/product-groups.ts
|
|
1590
|
+
import { createHash as createHash6 } from "crypto";
|
|
1591
|
+
import { AdportError as AdportError8 } from "@adport/core";
|
|
1592
|
+
import { z as z11 } from "zod";
|
|
1593
|
+
|
|
1594
|
+
// src/product-group-schemas.ts
|
|
1595
|
+
import { z as z10 } from "zod";
|
|
1596
|
+
|
|
1597
|
+
// src/product-group-filter-spec.ts
|
|
1598
|
+
var filterFields = {
|
|
1599
|
+
"RETAIL": {
|
|
1600
|
+
"MIN_PRICE": "CatalogsProductGroupPricingCriteria",
|
|
1601
|
+
"MAX_PRICE": "CatalogsProductGroupPricingCriteria",
|
|
1602
|
+
"CURRENCY": "CatalogsProductGroupCurrencyCriteria",
|
|
1603
|
+
"ITEM_ID": "CatalogsProductGroupMultipleStringCriteria",
|
|
1604
|
+
"AVAILABILITY": "CatalogsProductGroupMultipleStringCriteria",
|
|
1605
|
+
"BRAND": "CatalogsProductGroupMultipleStringCriteria",
|
|
1606
|
+
"CONDITION": "CatalogsProductGroupMultipleStringCriteria",
|
|
1607
|
+
"CUSTOM_LABEL_0": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1608
|
+
"CUSTOM_LABEL_1": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1609
|
+
"CUSTOM_LABEL_2": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1610
|
+
"CUSTOM_LABEL_3": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1611
|
+
"CUSTOM_LABEL_4": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1612
|
+
"ITEM_GROUP_ID": "CatalogsProductGroupMultipleStringCriteria",
|
|
1613
|
+
"GENDER": "CatalogsProductGroupMultipleGenderCriteria",
|
|
1614
|
+
"MEDIA_TYPE": "CatalogsProductGroupMultipleMediaTypesCriteria",
|
|
1615
|
+
"PRODUCT_TYPE_4": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1616
|
+
"PRODUCT_TYPE_3": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1617
|
+
"PRODUCT_TYPE_2": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1618
|
+
"PRODUCT_TYPE_1": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1619
|
+
"PRODUCT_TYPE_0": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1620
|
+
"GOOGLE_PRODUCT_CATEGORY_6": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1621
|
+
"GOOGLE_PRODUCT_CATEGORY_5": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1622
|
+
"GOOGLE_PRODUCT_CATEGORY_4": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1623
|
+
"GOOGLE_PRODUCT_CATEGORY_3": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1624
|
+
"GOOGLE_PRODUCT_CATEGORY_2": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1625
|
+
"GOOGLE_PRODUCT_CATEGORY_1": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1626
|
+
"GOOGLE_PRODUCT_CATEGORY_0": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1627
|
+
"CUSTOM_NUMBER_0": "CatalogsProductGroupUint32Criteria",
|
|
1628
|
+
"CUSTOM_NUMBER_1": "CatalogsProductGroupUint32Criteria",
|
|
1629
|
+
"CUSTOM_NUMBER_2": "CatalogsProductGroupUint32Criteria",
|
|
1630
|
+
"CUSTOM_NUMBER_3": "CatalogsProductGroupUint32Criteria",
|
|
1631
|
+
"CUSTOM_NUMBER_4": "CatalogsProductGroupUint32Criteria",
|
|
1632
|
+
"TITLE_KEYWORDS": "CatalogsProductGroupMultipleStringCriteria",
|
|
1633
|
+
"PINTEREST_PRODUCT_CATEGORIES": "CatalogsProductGroupMultiplePinterestProductCategoryCriteria",
|
|
1634
|
+
"PRODUCT_GROUP": "CatalogsProductGroupMultipleStringCriteria"
|
|
1635
|
+
},
|
|
1636
|
+
"HOTEL": {
|
|
1637
|
+
"PRICE": "PriceFilterPrice",
|
|
1638
|
+
"HOTEL_ID": "CatalogsProductGroupMultipleStringCriteria",
|
|
1639
|
+
"BRAND": "CatalogsProductGroupMultipleStringCriteria",
|
|
1640
|
+
"CUSTOM_LABEL_0": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1641
|
+
"CUSTOM_LABEL_1": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1642
|
+
"CUSTOM_LABEL_2": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1643
|
+
"CUSTOM_LABEL_3": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1644
|
+
"CUSTOM_LABEL_4": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1645
|
+
"COUNTRY": "CatalogsProductGroupMultipleCountriesCriteria",
|
|
1646
|
+
"TITLE_KEYWORDS": "CatalogsProductGroupMultipleStringCriteria"
|
|
1647
|
+
},
|
|
1648
|
+
"CREATIVE_ASSETS": {
|
|
1649
|
+
"CREATIVE_ASSETS_ID": "CatalogsProductGroupMultipleStringCriteria",
|
|
1650
|
+
"CUSTOM_LABEL_0": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1651
|
+
"CUSTOM_LABEL_1": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1652
|
+
"CUSTOM_LABEL_2": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1653
|
+
"CUSTOM_LABEL_3": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1654
|
+
"CUSTOM_LABEL_4": "CatalogsProductGroupFilterOperatorTypeCriteria",
|
|
1655
|
+
"GOOGLE_PRODUCT_CATEGORY_6": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1656
|
+
"GOOGLE_PRODUCT_CATEGORY_5": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1657
|
+
"GOOGLE_PRODUCT_CATEGORY_4": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1658
|
+
"GOOGLE_PRODUCT_CATEGORY_3": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1659
|
+
"GOOGLE_PRODUCT_CATEGORY_2": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1660
|
+
"GOOGLE_PRODUCT_CATEGORY_1": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1661
|
+
"GOOGLE_PRODUCT_CATEGORY_0": "CatalogsProductGroupMultipleStringListCriteria",
|
|
1662
|
+
"MEDIA_TYPE": "CatalogsProductGroupMultipleMediaTypesCriteria",
|
|
1663
|
+
"TITLE_KEYWORDS": "CatalogsProductGroupMultipleStringCriteria",
|
|
1664
|
+
"LINK": "CatalogsProductGroupFilterOperatorTypeCriteria"
|
|
1665
|
+
}
|
|
1666
|
+
};
|
|
1667
|
+
var filterEnums = { "Country": ["AD", "AE", "AF", "AG", "AI", "AL", "AM", "AO", "AQ", "AR", "AS", "AT", "AU", "AW", "AX", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BL", "BM", "BN", "BO", "BQ", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD", "CF", "CG", "CH", "CI", "CK", "CL", "CM", "CN", "CO", "CR", "CU", "CV", "CW", "CX", "CY", "CZ", "DE", "DJ", "DK", "DM", "DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ", "FK", "FM", "FO", "FR", "GA", "GB", "GD", "GE", "GF", "GG", "GH", "GI", "GL", "GM", "GN", "GP", "GQ", "GR", "GS", "GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID", "IE", "IL", "IM", "IN", "IO", "IQ", "IR", "IS", "IT", "JE", "JM", "JO", "JP", "KE", "KG", "KH", "KI", "KM", "KN", "KR", "KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT", "LU", "LV", "LY", "MA", "MC", "MD", "ME", "MF", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ", "MR", "MS", "MT", "MU", "MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI", "NL", "NO", "NP", "NR", "NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM", "PN", "PR", "PS", "PT", "PW", "PY", "QA", "RE", "RO", "RS", "RU", "RW", "SA", "SB", "SC", "SD", "SE", "SG", "SH", "SI", "SJ", "SK", "SL", "SM", "SN", "SO", "SR", "SS", "ST", "SV", "SX", "SY", "SZ", "TC", "TD", "TF", "TG", "TH", "TJ", "TK", "TL", "TM", "TN", "TO", "TR", "TT", "TV", "TW", "TZ", "UA", "UG", "UM", "US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF", "WS", "YE", "YT", "ZA", "ZM", "ZW"], "CatalogsLocale": ["af-ZA", "ar-SA", "bg-BG", "bn-IN", "cs-CZ", "da-DK", "de", "el-GR", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-419", "es-AR", "es-ES", "es-MX", "fi-FI", "fr", "fr-CA", "he-IL", "hi-IN", "hr-HR", "hu-HU", "id-ID", "it", "ja", "ko-KR", "ms-MY", "nb-NO", "nl", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "ru-RU", "sk-SK", "sv-SE", "te-IN", "th-TH", "tl-PH", "tr", "uk-UA", "vi-VN", "zh-CN", "zh-TW"], "NonNullableCatalogsCurrency": ["AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BRL", "BSD", "BTN", "BWP", "BYN", "BYR", "BZD", "CAD", "CDF", "CHF", "CLP", "CNY", "COP", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GGP", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "IMP", "INR", "IQD", "IRR", "ISK", "JEP", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SPL", "SRD", "STD", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TVD", "TWD", "TZS", "UAH", "UGX", "USD", "UYU", "UZS", "VEF", "VND", "VUV", "WST", "XAF", "XCD", "XDR", "XOF", "XPF", "YER", "ZAR", "ZMW", "ZWD"], "Gender": ["FEMALE", "MALE", "UNISEX"], "MediaType": ["IMAGE", "VIDEO"], "ProductCategoryEnum": ["ACCENT_TABLES", "ACCESSORIES", "ANKLETS", "APRONS", "AREA_RUGS", "ARMOIRES_AND_WARDROBES", "ART_AND_CRAFT_PAINTS", "ART_BRUSHES", "ARTIFICIAL_FLORA", "ARTWORK", "AUDIO", "AUDIO_ACCESSORIES", "BACKPACKS", "BAG_AND_LUGGAGE_ACCESSORIES", "BAGS_AND_LUGGAGE", "BAKEWARE", "BANDANAS", "BAR_CARTS", "BARWARE", "BASKETS", "BATH_AND_BODY", "BATH_AND_SHOWER", "BATH_MATS_AND_RUGS", "BATH_TOWELS_AND_WASHCLOTHS", "BATHROOM_ACCESSORIES", "BATHROOM_ACCESSORY_SETS", "BATHROOM_VANITIES", "BEACH_TOWELS", "BEADS_AND_JEWELRY_MAKING_SUPPLIES", "BEAUTY_SUPPLEMENTS", "BED_SHEETS", "BEDDING", "BEDROOM_VANITIES", "BEDS_AND_ACCESSORIES", "BEDS_AND_BED_FRAMES", "BELT_BAGS", "BELTS_AND_SUSPENDERS", "BENCHES", "BEVERAGES", "BIRD_SUPPLIES", "BLANKETS", "BLOUSES", "BLUSHES_AND_BRONZERS", "BODY_CARE", "BODY_JEWELRY", "BODY_MAKEUP", "BODY_MOISTURIZERS", "BODY_WASHES", "BOOKCASES_AND_STANDING_SHELVES", "BOOKENDS", "BOOKS", "BOOTS", "BRACELETS", "BRIDESMAID_DRESSES", "BROOCHES_AND_LAPEL_PINS", "BROW_MAKEUP", "BUFFETS_AND_SIDEBOARDS", "BUTTON_DOWN_SHIRTS", "CABINET_HARDWARE", "CABINETS_AND_STORAGE_FURNITURE", "CAKE_DECORATING_SUPPLIES", "CAMPING_AND_HIKING", "CANDLE_HOLDERS", "CANDLES", "CARDSTOCK_PAPERS", "CASUAL_PANTS", "CAT_SUPPLIES", "CHAIRS", "CHANDELIERS", "CHARMS_AND_PENDANTS", "CHINA_CABINETS_AND_HUTCHES", "CLOGS_AND_MULES", "CLOTH_NAPKINS", "CLOTHING", "CLOTHING_AND_CLOSET_STORAGE", "CLOTHING_SETS", "COASTERS", "COATS_AND_JACKETS", "COFFEE_AND_TEA_CUPS", "COFFEE_MAKERS_AND_ESPRESSO_MACHINES", "COLORING_BOOKS", "COMMUNICATIONS", "COMPUTER_ACCESSORIES", "COOKIE_CUTTERS", "COOKWARE", "COOKWARE_AND_BAKEWARE", "COSMETIC_AND_TOILETRY_BAGS", "COSTUMES_AND_ACCESSORIES", "CRAFT_ADHESIVES_AND_MAGNETS", "CRAFT_CUTTING_TOOLS", "CRAFT_MOLDS", "CRIBS_AND_TODDLER_BEDS", "CURTAIN_AND_DRAPE_RODS", "CURTAINS_AND_DRAPES", "CUTTING_BOARDS", "CYCLING", "DECORATIVE_BOWLS", "DECORATIVE_JARS", "DECORATIVE_TAPESTRIES", "DECORATIVE_TRAYS", "DEODORANTS_AND_ANTIPERSPIRANTS", "DESK_AND_SHELF_CLOCKS", "DESKS", "DIAPER_BAGS", "DINNERWARE", "DISHWASHERS", "DOG_SUPPLIES", "DOOR_MATS", "DRAWING_AND_PAINTING", "DRESS_PANTS", "DRESSERS", "DRESSES", "DRILLS_AND_SCREWDRIVERS", "DRINKWARE", "DUFFEL_BAGS", "DUVET_COVERS", "DVDS_AND_VIDEOS", "EARRINGS", "ELECTRONICS_ACCESSORIES", "ENGAGEMENT_AND_WEDDING_RINGS", "ENTERTAINMENT_CENTERS_AND_TV_STANDS", "ERASERS", "EYE_MAKEUP", "EYE_SHADOW", "EYELINERS", "FABRIC", "FACE_COVERINGS", "FACE_LOTIONS_AND_CREAMS", "FACE_MAKEUP", "FACIAL_CLEANSERS", "FACIAL_MOISTURIZERS", "FALSE_EYELASHES", "FIGURINES", "FIREPLACE_AND_WOOD_STOVE_ACCESSORIES", "FIREPLACES", "FISHING", "FLAGS_AND_WINDSOCKS", "FLATS", "FLATWARE", "FLOOR_LAMPS", "FLOWER_GIRL_DRESSES", "FOOD_AND_BEVERAGE_CARRIERS", "FOOD_COOKERS_AND_STEAMERS", "FOOD_ITEMS", "FOOD_MIXERS_AND_BLENDERS", "FOOD_STORAGE_CONTAINERS", "FOOD_STORAGE_SUPPLIES", "FOUNDATIONS_AND_CONCEALERS", "FOUNTAINS_AND_PONDS", "FRAGRANCE", "FURNITURE", "FURNITURE_SETS", "GAMES", "GARDENING", "GARDENING_TOOLS", "GLOVES_AND_MITTENS", "GLUES_AND_TAPES", "GROOM_AND_GROOMSMEN_SUITS", "HAIR", "HAIR_ACCESSORIES", "HAIR_CARE", "HAIR_COLOR", "HAIR_COMBS", "HAIR_PINS_CLAWS_AND_CLIPS", "HAIR_REMOVAL", "HAIR_TOOLS", "HAIR_TREATMENT", "HAIR_WREATHS", "HAND_AND_FOOT_CARE", "HAND_SOAPS_AND_SANITIZERS", "HANDBAGS", "HANDKERCHIEFS", "HARDWARE_SUPPLIES", "HATS", "HEADBOARDS_AND_FOOTBOARDS", "HEADWEAR", "HIGHLIGHTERS", "HOBBIES_AND_CREATIVE_ARTS", "HOME_ACCESSORIES", "HOME_DECOR_DECALS", "HOME_FRAGRANCE_ACCESSORIES", "HOME_FRAGRANCES", "HOME_IMPROVEMENT_TOOLS_AND_SUPPLIES", "HOSIERY", "HOUSEHOLD_APPLIANCES", "HOUSEHOLD_SUPPLIES", "INCENSE", "INDOOR_GAMES", "JEANS", "JEWELRY_AND_WATCH_ACCESSORIES", "JEWELRY_AND_WATCHES", "JEWELRY_SETS", "JUMPSUITS_AND_ROMPERS", "KEYCHAINS", "KITCHEN_AND_DINING", "KITCHEN_AND_DINING_ROOM_TABLES", "KITCHEN_APPLIANCES", "KITCHEN_KNIVES", "KITCHEN_LINENS", "KITCHEN_MATS", "KITCHEN_ORGANIZERS", "KITCHEN_TOOLS_AND_UTENSILS", "KITCHEN_TOWELS", "KNITTING_AND_CROCHET", "KNITTING_AND_CROCHET_TOOLS", "LAMP_SHADES", "LAMPS", "LANYARDS", "LAUNDRY_HAMPERS_AND_SUPPLIES", "LAWN_AND_GARDEN", "LAWN_AND_GARDEN_DECOR", "LAWN_ORNAMENTS_AND_GARDEN_SCULPTURES", "LEGGINGS", "LEOTARDS_AND_UNITARDS", "LIGHTING", "LIGHTING_ACCESSORIES", "LIGHTING_FIXTURES", "LIP_BALMS", "LIP_CARE", "LIP_MAKEUP", "LIPSTICKS_AND_LIP_GLOSSES", "MAGAZINES_AND_NEWSPAPERS", "MAGNETS", "MAKEUP", "MAKEUP_TOOLS", "MASCARAS", "MATTRESSES", "MEASURES_AND_RULERS", "MEASURING_TOOLS_AND_SENSORS", "MESSENGER_BAGS", "MIRRORS", "MUSIC_AND_SOUND_RECORDINGS", "NAIL_ART", "NAIL_ART_KIT_AND_TOOLS", "NAIL_CARE", "NAIL_POLISHES", "NAILS", "NECKLACES", "NECKTIES", "NIGHT_LIGHTS_AND_AMBIENT_LIGHTING", "NIGHTSTANDS", "NOVELTY_SIGNS", "ONE_PIECES", "ONESIES", "OTTOMANS", "OUTDOOR_FURNITURE", "OUTDOOR_FURNITURE_SETS", "OUTDOOR_GAMES", "OUTDOOR_GRILLS", "OUTDOOR_LIVING", "OUTDOOR_PLAY_EQUIPMENT", "OUTDOOR_RECREATION", "OUTDOOR_RUGS", "OUTDOOR_SEATING", "OUTDOOR_STRUCTURES", "OUTDOOR_TABLES", "OUTERWEAR", "OVENS_AND_COOKTOPS", "OVERALLS", "OXFORDS_AND_LOAFERS", "PAINT_AND_PAINT_TOOLS", "PANTS", "PAPER_CRAFTS", "PARASOLS_AND_RAIN_UMBRELLAS", "PARTY_AND_CELEBRATION", "PENDANT_LIGHTS", "PENS_AND_PENCILS", "PERFUMES_AND_COLOGNES", "PET_CARRIERS_AND_CRATES", "PET_COLLARS_AND_HARNESSES", "PET_SUPPLIES", "PHOTO_ALBUMS_AND_STORAGE", "PICTURE_FRAMES", "PILLOWCASES_AND_SHAMS", "PINBACK_BUTTONS", "PLACEMATS", "PLANTS", "PONYTAIL_HOLDERS", "POOL_AND_SPA_ACCESSORIES", "POSTERS_PRINTS_AND_VISUAL_ARTWORK", "POTS_AND_PLANTERS", "POTTERY_AND_SCULPTING", "PRIMERS_AND_MAKEUP_SETTERS", "PUMPS", "PUZZLES", "QUILTS_AND_COMFORTERS", "RAZORS_AND_SHAVING_TOOLS", "RINGS", "RUGS", "RUNNER_RUGS", "SANDALS", "SASHES", "SAWS", "SCARVES_AND_SHAWLS", "SCULPTURES_AND_STATUES", "SEASONAL_AND_HOLIDAY_DECORATIONS", "SEATING", "SERUMS_AND_ESSENCES", "SERVEWARE", "SEWING_MACHINES", "SEWING_PATTERNS", "SHAMPOO_AND_CONDITIONER", "SHOE_ACCESSORIES", "SHOES", "SHOPPING_TOTES", "SHORTS", "SHOWER_CURTAINS", "SKINCARE", "SKINCARE_MASKS_AND_PEELS", "SKIRTS", "SLEEPWEAR_AND_LOUNGEWEAR", "SLIPCOVERS_AND_CUSHIONS", "SLIPPERS", "SNEAKERS_AND_ATHLETIC_SHOES", "SOCKS_AND_TIGHTS", "SOFAS", "SPORTS_UNIFORMS", "STEMWARE", "STOCKINGS", "STORAGE_AND_ORGANIZATION", "STORAGE_CABINETS_AND_LOCKERS", "STORAGE_HOOKS_AND_RACKS", "SUITCASES", "SUITS", "SUITS_AND_SUIT_SEPARATES", "GLASSES_AND_SUNGLASSES", "SUNSCREEN", "SWEATERS_AND_CARDIGANS", "SWEATSHIRTS_AND_HOODIES", "SWIMWEAR", "T_SHIRTS", "TABLE_LAMPS", "TABLE_RUNNERS", "TABLECLOTHS", "TABLES", "TABLEWARE", "TANK_TOPS", "TANNING_OILS_AND_LOTIONS", "TEETH_WHITENING", "TEETH_WHITENING_TOOLS", "TELEPHONY", "TEXTILE_AND_SEWING", "THREAD_AND_YARN", "THROW_PILLOWS", "TIARAS", "TOILET_PAPER_HOLDERS", "TONERS_AND_ASTRINGENTS", "TOOL_STORAGE_AND_ORGANIZATION", "TOOLS", "TOPS", "TOWEL_RACKS_AND_HOLDERS", "TOYS", "TRADITIONAL_AND_CEREMONIAL_CLOTHING", "TUMBLERS_AND_WATER_BOTTLES", "UNIFORMS", "VASES", "VEHICLE_PARTS_AND_ACCESSORIES", "VEILS", "WALL_CLOCKS", "WALL_LIGHT_FIXTURES", "WALL_PAINTS", "WALL_SHELVES_AND_LEDGES", "WALLETS_AND_CARD_CASES", "WALLPAPERS", "WATCHES", "WATERING_AND_IRRIGATION", "WEDDING_CEREMONY_DECOR", "WEDDING_CLOTHING", "WEDDING_DECOR", "WEDDING_DRESS", "WEDDING_GIFTS", "WEDDING_STATIONERY", "WEDDING_TABLE_DECOR", "WIGS_AND_HAIR_EXTENSIONS", "WINDOW_BLINDS_AND_SHADES", "WINDOW_TREATMENT_ACCESSORIES", "WINDOW_TREATMENTS", "WINE_RACKS", "WOOD_BOARDS_AND_PLANKS", "WOODWORKING_MATERIALS", "WOODWORKING_PLANS", "WORK_BENCHES", "WREATHS_AND_GARLANDS"] };
|
|
1668
|
+
|
|
1669
|
+
// src/product-group-schemas.ts
|
|
1670
|
+
var catalogType = z10.enum(["RETAIL", "HOTEL", "CREATIVE_ASSETS"]);
|
|
1671
|
+
var groupId = z10.string().regex(/^\d{1,30}$/);
|
|
1672
|
+
var groupHash = z10.string().regex(/^[a-f0-9]{64}$/);
|
|
1673
|
+
var text2 = z10.string().min(1).max(1024);
|
|
1674
|
+
var negated = z10.boolean().optional();
|
|
1675
|
+
var strings2 = z10.array(text2).min(1).max(100);
|
|
1676
|
+
var numericOperator = z10.enum(["GREATER_THAN", "GREATER_THAN_OR_EQUALS", "LESS_THAN", "LESS_THAN_OR_EQUALS"]);
|
|
1677
|
+
var criteria = {
|
|
1678
|
+
CatalogsProductGroupMultipleStringCriteria: z10.object({ values: strings2, negated }).strict(),
|
|
1679
|
+
CatalogsProductGroupMultipleStringListCriteria: z10.object({ values: z10.array(strings2).min(1).max(100), negated }).strict(),
|
|
1680
|
+
CatalogsProductGroupFilterOperatorTypeCriteria: z10.object({ values: strings2, negated, filter_operator_type: z10.enum(["IS", "CONTAINS"]).optional() }).strict(),
|
|
1681
|
+
CatalogsProductGroupPricingCriteria: z10.object({ values: z10.number().nonnegative().max(Number.MAX_SAFE_INTEGER), negated, inclusion: z10.boolean().optional() }).strict(),
|
|
1682
|
+
CatalogsProductGroupUint32Criteria: z10.object({ value: z10.number().int().min(0).max(4294967295), negated, operator: numericOperator }).strict(),
|
|
1683
|
+
CatalogsProductGroupCurrencyCriteria: z10.object({ values: z10.enum(filterEnums.NonNullableCatalogsCurrency), negated: z10.literal(false).optional() }).strict(),
|
|
1684
|
+
CatalogsProductGroupMultipleGenderCriteria: z10.object({ values: z10.array(z10.enum(filterEnums.Gender)).min(1).max(100), negated }).strict(),
|
|
1685
|
+
CatalogsProductGroupMultipleCountriesCriteria: z10.object({ values: z10.array(z10.enum(filterEnums.Country)).min(1).max(100), negated }).strict(),
|
|
1686
|
+
CatalogsProductGroupMultipleMediaTypesCriteria: z10.object({ values: z10.array(z10.enum(filterEnums.MediaType)).min(1).max(100), negated }).strict(),
|
|
1687
|
+
CatalogsProductGroupMultiplePinterestProductCategoryCriteria: z10.object({ values: z10.array(z10.enum(filterEnums.ProductCategoryEnum)).min(1).max(100), negated }).strict(),
|
|
1688
|
+
PriceFilterPrice: z10.object({ currency: z10.enum(filterEnums.NonNullableCatalogsCurrency), negated, operator: numericOperator, value: z10.number().nonnegative().max(Number.MAX_SAFE_INTEGER) }).strict()
|
|
1689
|
+
};
|
|
1690
|
+
function productGroupFilterSchema(type2, allowEmpty = false) {
|
|
1691
|
+
const fields2 = Object.entries(filterFields[type2]).map(([key, value]) => z10.object({ [key]: criteria[value] }).strict());
|
|
1692
|
+
const clause = z10.union([fields2[0], fields2[1], ...fields2.slice(2)]);
|
|
1693
|
+
const list = z10.array(clause).min(allowEmpty ? 0 : 1).max(32);
|
|
1694
|
+
return z10.union([z10.object({ any_of: list }).strict(), z10.object({ all_of: list }).strict()]);
|
|
1695
|
+
}
|
|
1696
|
+
var groupFilters = z10.record(z10.string(), z10.json()).refine((value) => Buffer.byteLength(JSON.stringify(value), "utf8") <= 262144, "Filters exceed the 256 KiB Adport bound");
|
|
1697
|
+
var groupDefinition = z10.object({
|
|
1698
|
+
mode: z10.enum(["FEED", "CATALOG"]),
|
|
1699
|
+
catalog_type: catalogType,
|
|
1700
|
+
feed_id: groupId.optional(),
|
|
1701
|
+
name: text2,
|
|
1702
|
+
description: z10.string().max(1e4).nullable().optional(),
|
|
1703
|
+
filters: groupFilters,
|
|
1704
|
+
country: z10.enum(filterEnums.Country).optional(),
|
|
1705
|
+
locale: z10.enum(filterEnums.CatalogsLocale).optional(),
|
|
1706
|
+
confirm_all_products: z10.literal(true).optional()
|
|
1707
|
+
}).strict().superRefine((value, ctx) => {
|
|
1708
|
+
if (value.mode === "FEED" ? value.catalog_type !== "RETAIL" || !value.feed_id || value.country !== void 0 || value.locale !== void 0 : value.feed_id !== void 0 || value.catalog_type !== "RETAIL" && (value.country !== void 0 || value.locale !== void 0)) ctx.addIssue({ code: "custom", message: "FEED mode requires RETAIL and feed_id without country/locale; CATALOG mode forbids feed_id and supports country/locale only for RETAIL" });
|
|
1709
|
+
validateGroupFilters(value.catalog_type, value.filters, value.confirm_all_products, ctx);
|
|
1710
|
+
});
|
|
1711
|
+
function validateGroupFilters(type2, filters, all, ctx) {
|
|
1712
|
+
if (!productGroupFilterSchema(type2, type2 !== "RETAIL" && all === true).safeParse(filters).success) ctx.addIssue({ code: "custom", message: "Invalid native filter shape, field, enum or bound. Call pinterest_product_group_filter_schema; empty non-retail filters require confirm_all_products." });
|
|
1713
|
+
}
|
|
1714
|
+
var groupChanges = z10.object({ name: text2.optional(), description: z10.string().max(1e4).nullable().optional(), filters: groupFilters.optional(), country: z10.enum(filterEnums.Country).optional(), locale: z10.enum(filterEnums.CatalogsLocale).optional(), confirm_all_products: z10.literal(true).optional() }).strict().refine((value) => Object.keys(value).some((key) => key !== "confirm_all_products"), "Supply at least one setting");
|
|
1715
|
+
var selection = { catalog_id: groupId };
|
|
1716
|
+
var reference3 = { ...selection, product_group_id: groupId };
|
|
1717
|
+
var groupCreate = z10.object({ ...selection, expected_context_hash: groupHash, definition: groupDefinition }).strict();
|
|
1718
|
+
var groupUpdate = z10.object({ ...reference3, expected_context_hash: groupHash, changes: groupChanges, acknowledge_live_effects: z10.literal(true) }).strict();
|
|
1719
|
+
var groupDelete = z10.object({ ...reference3, expected_context_hash: groupHash, confirm_name: z10.string().min(1).max(1024), acknowledge_live_effects: z10.literal(true), confirm_permanent_deletion: z10.literal(true) }).strict();
|
|
1720
|
+
var groupAction = z10.discriminatedUnion("kind", [
|
|
1721
|
+
z10.object({ kind: z10.literal("create"), definition: groupDefinition }).strict(),
|
|
1722
|
+
z10.object({ kind: z10.literal("update"), product_group_id: groupId, changes: groupChanges }).strict(),
|
|
1723
|
+
z10.object({ kind: z10.literal("delete"), product_group_id: groupId, confirm_name: z10.string().min(1).max(1024) }).strict()
|
|
1724
|
+
]);
|
|
1725
|
+
var groupContext = z10.object({ account_id: pinterestId, ...selection, action: groupAction }).strict();
|
|
1726
|
+
var groupPaging = { page_size: z10.number().int().min(1).max(250).default(25), bookmark: z10.string().min(1).max(8192).optional() };
|
|
1727
|
+
var groupList = z10.object({ account_id: pinterestId, ...selection, feed_id: groupId.optional(), product_group_ids: z10.array(groupId).min(1).max(100).refine((ids3) => new Set(ids3).size === ids3.length).optional(), ...groupPaging }).strict();
|
|
1728
|
+
var groupReference = z10.object({ account_id: pinterestId, ...reference3 }).strict();
|
|
1729
|
+
var nativeGroup = z10.looseObject({ id: groupId, catalog_id: groupId, catalog_type: catalogType, name: z10.string().max(1024).optional(), description: z10.string().max(1e4).nullable().optional(), filters: groupFilters, feed_id: groupId.nullable().optional(), type: z10.string().optional(), country: z10.string().nullable().optional(), locale: z10.string().nullable().optional(), created_at: z10.number().int().safe().optional(), updated_at: z10.number().int().safe().optional() }).superRefine((value, ctx) => {
|
|
1730
|
+
if (value.catalog_type === "RETAIL" && (!Object.hasOwn(value, "feed_id") || !value.type) || value.catalog_type === "HOTEL" && !value.type) ctx.addIssue({ code: "custom", message: "Missing native product group mode/type" });
|
|
1731
|
+
});
|
|
1732
|
+
|
|
1733
|
+
// src/product-groups.ts
|
|
1734
|
+
var canonical4 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
1735
|
+
var hash6 = (value) => createHash6("sha256").update(canonical4(value)).digest("hex");
|
|
1736
|
+
var normalizeFilters = (filters) => {
|
|
1737
|
+
if (!filters || typeof filters !== "object" || Array.isArray(filters)) return filters;
|
|
1738
|
+
return Object.fromEntries(Object.entries(filters).map(([key, raw]) => {
|
|
1739
|
+
const value = ["MIN_PRICE", "MAX_PRICE"].includes(key) && raw && typeof raw === "object" && !Array.isArray(raw) ? { inclusion: true, ...raw } : raw;
|
|
1740
|
+
return [key, Array.isArray(value) && ["any_of", "all_of", "values"].includes(key) ? value.map((item) => key === "values" && Array.isArray(item) ? item : normalizeFilters(item)).sort((a, b) => canonical4(a).localeCompare(canonical4(b))) : normalizeFilters(value)];
|
|
1741
|
+
}));
|
|
1742
|
+
};
|
|
1743
|
+
var configuration = (value) => ({ ...Object.fromEntries(Object.entries(value).filter(([key]) => !["created_at", "updated_at"].includes(key))), filters: normalizeFilters(value.filters) });
|
|
1744
|
+
var mismatch = () => new AdportError8("PROVIDER_ERROR", "pinterest: product group scope, native response or pagination could not be verified.");
|
|
1745
|
+
var notes = ["Product group edits change matching products and can affect existing ads using the group. No ad is activated and no budget, bid or source item is changed.", "Native catalog/Creative Assets eligibility remains authoritative. Local preview and configuration readback do not prove final matched inventory, product Pin publication or serving.", "No atomic compare-and-set is available. No native write is automatically retried; reconcile known IDs after an uncertain result."];
|
|
1746
|
+
var cursor2 = z11.object({ selection: z11.string().regex(/^[a-f0-9]{64}$/), native: z11.string().min(1).max(4096) }).strict();
|
|
1747
|
+
var count = z11.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
1748
|
+
var counts = z11.discriminatedUnion("catalog_type", [z11.object({ catalog_type: z11.literal("RETAIL"), in_stock: count, out_of_stock: count, preorder: count, total: count, videos: count.optional() }).strict(), z11.object({ catalog_type: z11.literal("HOTEL"), total: count }).strict(), z11.object({ catalog_type: z11.literal("CREATIVE_ASSETS"), total: count, videos: count, images: count, app_links: count }).strict()]);
|
|
1749
|
+
var product2 = z11.object({ catalog_type: catalogType, metadata: z11.record(z11.string(), z11.json()), pin: z11.record(z11.string(), z11.json()) });
|
|
1750
|
+
var PinterestProductGroups = class {
|
|
1751
|
+
constructor(client, catalogs) {
|
|
1752
|
+
this.client = client;
|
|
1753
|
+
this.catalogs = catalogs;
|
|
1754
|
+
}
|
|
1755
|
+
client;
|
|
1756
|
+
catalogs;
|
|
1757
|
+
params(account3, extra = {}) {
|
|
1758
|
+
return new URLSearchParams({ ad_account_id: pinterestId.parse(account3), ...extra });
|
|
1759
|
+
}
|
|
1760
|
+
scope(group, catalog2, wanted) {
|
|
1761
|
+
if (group.catalog_id !== catalog2.id || group.catalog_type !== catalog2.catalog_type || wanted && group.id !== wanted || group.catalog_type !== "RETAIL" && group.feed_id != null) throw mismatch();
|
|
1762
|
+
return group;
|
|
1763
|
+
}
|
|
1764
|
+
snapshot(account3, group) {
|
|
1765
|
+
return hash6({ account_id: account3, configuration: configuration(group) });
|
|
1766
|
+
}
|
|
1767
|
+
async read(account3, catalog2, id4) {
|
|
1768
|
+
return this.scope(await this.client.get(`catalogs/product_groups/${groupId.parse(id4)}`, nativeGroup, this.params(account3)), catalog2, id4);
|
|
1769
|
+
}
|
|
1770
|
+
async page(path, schema, account3, selection2, input, query2) {
|
|
1771
|
+
const key = hash6({ account: account3, selection: selection2, page_size: input.page_size });
|
|
1772
|
+
let native;
|
|
1773
|
+
if (input.bookmark) {
|
|
1774
|
+
let parsed;
|
|
1775
|
+
try {
|
|
1776
|
+
parsed = cursor2.parse(JSON.parse(Buffer.from(input.bookmark, "base64url").toString("utf8")));
|
|
1777
|
+
} catch {
|
|
1778
|
+
throw new AdportError8("INVALID_INPUT", "Invalid product group cursor; restart this selection.");
|
|
1779
|
+
}
|
|
1780
|
+
if (parsed.selection !== key) throw new AdportError8("PENDING_MISMATCH", "Product group selection changed; restart its first page.");
|
|
1781
|
+
native = parsed.native;
|
|
1782
|
+
}
|
|
1783
|
+
const params = this.params(account3, { ...query2, page_size: String(input.page_size), ...native ? { bookmark: native } : {} }), value = await this.client.get(path, z11.object({ items: z11.array(schema).max(250), bookmark: z11.string().min(1).max(4096).nullable().optional() }), params);
|
|
1784
|
+
if (value.items.length > input.page_size || value.bookmark && (value.bookmark === native || !value.items.length)) throw mismatch();
|
|
1785
|
+
const complete = value.bookmark === null ? true : value.bookmark === void 0 ? null : false;
|
|
1786
|
+
return { items: value.items, complete, truncated: complete !== true, ...value.bookmark ? { next_cursor: Buffer.from(JSON.stringify({ selection: key, native: value.bookmark })).toString("base64url") } : {} };
|
|
1787
|
+
}
|
|
1788
|
+
async list(value) {
|
|
1789
|
+
const input = groupList.parse(value), context = await this.catalogs.getCatalog(input.account_id, input.catalog_id);
|
|
1790
|
+
if (input.feed_id) {
|
|
1791
|
+
if (context.catalog.catalog_type !== "RETAIL") throw new AdportError8("INVALID_INPUT", "Feed-based groups are RETAIL only.");
|
|
1792
|
+
await this.catalogs.getFeed(input.account_id, input.catalog_id, input.feed_id);
|
|
1793
|
+
}
|
|
1794
|
+
const selected3 = { catalog_id: input.catalog_id, feed_id: input.feed_id, product_group_ids: input.product_group_ids ? [...input.product_group_ids].sort() : void 0 }, page2 = await this.page("catalogs/product_groups", nativeGroup, input.account_id, selected3, input, { catalog_id: input.catalog_id, ...input.feed_id ? { feed_id: input.feed_id } : {}, ...input.product_group_ids ? { id: input.product_group_ids.join(",") } : {} });
|
|
1795
|
+
if (new Set(page2.items.map((row) => row.id)).size !== page2.items.length || page2.items.some((row) => input.feed_id && row.feed_id !== input.feed_id || input.product_group_ids && !input.product_group_ids.includes(row.id))) throw mismatch();
|
|
1796
|
+
const items = page2.items.map((row) => ({ ...this.scope(row, context.catalog), snapshot_hash: this.snapshot(input.account_id, row) }));
|
|
1797
|
+
return { ...page2, items, records: items, notes };
|
|
1798
|
+
}
|
|
1799
|
+
async get(value) {
|
|
1800
|
+
const input = groupReference.parse(value), context = await this.catalogs.getCatalog(input.account_id, input.catalog_id), row = await this.read(input.account_id, context.catalog, input.product_group_id), group = { ...row, snapshot_hash: this.snapshot(input.account_id, row) };
|
|
1801
|
+
return { group, records: [group], notes };
|
|
1802
|
+
}
|
|
1803
|
+
async counts(value) {
|
|
1804
|
+
const input = groupReference.parse(value), { group } = await this.get(input), data = await this.client.get(`catalogs/product_groups/${input.product_group_id}/product_counts`, counts, this.params(input.account_id));
|
|
1805
|
+
if (data.catalog_type !== group.catalog_type) throw mismatch();
|
|
1806
|
+
return { counts: data, group_snapshot_hash: group.snapshot_hash, records: [{ id: group.id, name: group.name ?? group.id, ...data }], notes: ["Native counts are a separate observation, not a frozen membership snapshot or proof of ad eligibility."] };
|
|
1807
|
+
}
|
|
1808
|
+
async products(value) {
|
|
1809
|
+
const input = groupReference.extend(groupPaging).parse(value), { group } = await this.get({ account_id: input.account_id, catalog_id: input.catalog_id, product_group_id: input.product_group_id }), page2 = await this.page(`catalogs/product_groups/${group.id}/products`, product2, input.account_id, { catalog_id: input.catalog_id, product_group_id: group.id, snapshot_hash: group.snapshot_hash }, input, {});
|
|
1810
|
+
const records2 = page2.items.map((row) => {
|
|
1811
|
+
const key = row.catalog_type === "RETAIL" ? "item_id" : row.catalog_type === "HOTEL" ? "hotel_id" : "creative_assets_id", nativeId = row.metadata[key];
|
|
1812
|
+
if (row.catalog_type !== group.catalog_type || typeof nativeId !== "string" || !nativeId || nativeId.length > 1024) throw mismatch();
|
|
1813
|
+
return { id: `${row.catalog_type}:${nativeId}:${hash6(row)}`, name: typeof row.pin.title === "string" ? row.pin.title : nativeId, source_id: nativeId, catalog_type: row.catalog_type, metadata: row.metadata, pin: row.pin };
|
|
1814
|
+
});
|
|
1815
|
+
if (new Set(records2.map((row) => row.id)).size !== records2.length) throw mismatch();
|
|
1816
|
+
return { ...page2, records: records2, group_snapshot_hash: group.snapshot_hash, notes: ["Native product/Pin fields are preserved as data. No preview URL, product ID alias or publication state is invented."] };
|
|
1817
|
+
}
|
|
1818
|
+
mutable(row) {
|
|
1819
|
+
if (row.catalog_type !== "CREATIVE_ASSETS" && row.type !== "MERCHANT_CREATED") throw new AdportError8("INVALID_INPUT", "Only merchant-created retail/hotel product groups can be edited or deleted; automatic groups are read-only.");
|
|
1820
|
+
}
|
|
1821
|
+
references(filters) {
|
|
1822
|
+
const result = /* @__PURE__ */ new Set();
|
|
1823
|
+
const walk = (value) => {
|
|
1824
|
+
if (!value || typeof value !== "object") return;
|
|
1825
|
+
if (Array.isArray(value)) {
|
|
1826
|
+
value.forEach(walk);
|
|
1827
|
+
return;
|
|
1828
|
+
}
|
|
1829
|
+
for (const [key, item] of Object.entries(value)) {
|
|
1830
|
+
if (key === "PRODUCT_GROUP") {
|
|
1831
|
+
const parsed = z11.object({ values: z11.array(groupId).min(1).max(100) }).safeParse(item);
|
|
1832
|
+
if (!parsed.success) throw mismatch();
|
|
1833
|
+
parsed.data.values.forEach((id4) => result.add(id4));
|
|
1834
|
+
} else walk(item);
|
|
1835
|
+
}
|
|
1836
|
+
};
|
|
1837
|
+
walk(filters);
|
|
1838
|
+
return [...result].sort();
|
|
1839
|
+
}
|
|
1840
|
+
async context(value) {
|
|
1841
|
+
const input = groupContext.parse(value), owner2 = await this.catalogs.getCatalog(input.account_id, input.catalog_id), catalog2 = owner2.catalog, action = input.action;
|
|
1842
|
+
const current = action.kind === "create" ? void 0 : await this.read(input.account_id, catalog2, action.product_group_id);
|
|
1843
|
+
if (current) this.mutable(current);
|
|
1844
|
+
let body = {}, feed2;
|
|
1845
|
+
if (action.kind === "create") {
|
|
1846
|
+
const { mode, catalog_type, feed_id, confirm_all_products: _all, ...fields2 } = action.definition;
|
|
1847
|
+
if (catalog_type !== catalog2.catalog_type) throw new AdportError8("INVALID_INPUT", "Product group type differs from selected catalog.");
|
|
1848
|
+
if (mode === "FEED") {
|
|
1849
|
+
const currentFeed = (await this.catalogs.getFeed(input.account_id, catalog2.id, feed_id)).feed;
|
|
1850
|
+
feed2 = { id: feed_id, snapshot_hash: currentFeed.snapshot_hash };
|
|
1851
|
+
}
|
|
1852
|
+
body = mode === "FEED" ? { feed_id, ...fields2 } : { catalog_id: catalog2.id, catalog_type, ...fields2 };
|
|
1853
|
+
} else if (action.kind === "update") {
|
|
1854
|
+
const { confirm_all_products, ...changes } = groupChanges.parse(action.changes);
|
|
1855
|
+
if ((current.catalog_type !== "RETAIL" || current.feed_id != null) && (changes.country !== void 0 || changes.locale !== void 0)) throw new AdportError8("INVALID_INPUT", "Country/locale apply only to catalog-based RETAIL groups.");
|
|
1856
|
+
if (changes.filters && !productGroupFilterSchema(current.catalog_type, current.catalog_type !== "RETAIL" && confirm_all_products === true).safeParse(changes.filters).success) throw new AdportError8("INVALID_INPUT", "Invalid filter selection; use pinterest_product_group_filter_schema.");
|
|
1857
|
+
body = { ...current.feed_id != null ? {} : { catalog_type: current.catalog_type }, ...changes };
|
|
1858
|
+
} else if (!current.name || current.name !== action.confirm_name) throw new AdportError8("INVALID_INPUT", "Permanent deletion requires the exact current product group name.");
|
|
1859
|
+
const referenced = /* @__PURE__ */ new Map(), visit = async (id4, stack) => {
|
|
1860
|
+
if (id4 === current?.id || stack.has(id4)) throw new AdportError8("INVALID_INPUT", "Product group filter references contain a cycle.");
|
|
1861
|
+
if (referenced.has(id4)) return;
|
|
1862
|
+
if (referenced.size >= 40) throw new AdportError8("INVALID_INPUT", "Reference proof exceeds the 40-group Adport bound.");
|
|
1863
|
+
const row = await this.read(input.account_id, catalog2, id4);
|
|
1864
|
+
if (current?.feed_id != null && row.feed_id !== current.feed_id || action.kind === "create" && action.definition.mode === "FEED" && row.feed_id !== action.definition.feed_id) throw new AdportError8("INVALID_INPUT", "Referenced groups must belong to the selected retail feed.");
|
|
1865
|
+
referenced.set(id4, row);
|
|
1866
|
+
for (const next of this.references(row.filters)) await visit(next, /* @__PURE__ */ new Set([...stack, id4]));
|
|
1867
|
+
};
|
|
1868
|
+
if (action.kind !== "delete") for (const id4 of this.references(body.filters ?? current?.filters)) await visit(id4, /* @__PURE__ */ new Set());
|
|
1869
|
+
const context_hash = hash6({ account_id: input.account_id, owner: owner2.context_hash, catalog: { id: catalog2.id, name: catalog2.name, catalog_type: catalog2.catalog_type }, action, current: current ? configuration(current) : void 0, body, feed: feed2, references: [...referenced.values()].map((row) => configuration(row)).sort((a, b) => String(a.id).localeCompare(String(b.id))) });
|
|
1870
|
+
return { context_hash, catalog: catalog2, current, body, records: [current ? { ...current, snapshot_hash: this.snapshot(input.account_id, current) } : { id: catalog2.id, name: catalog2.name, catalog_type: catalog2.catalog_type }, ...[...referenced.values()].map((row) => ({ id: row.id, name: row.name ?? row.id, reference: true, snapshot_hash: this.snapshot(input.account_id, row) }))], reference_count: referenced.size, notes };
|
|
1871
|
+
}
|
|
1872
|
+
async plan(op) {
|
|
1873
|
+
const create2 = op.tool === "pinterest_create_product_group", update = op.tool === "pinterest_update_product_group", remove = op.tool === "pinterest_delete_product_group";
|
|
1874
|
+
if (op.provider !== "pinterest" || !(create2 || update || remove) || op.kind !== (create2 ? "create" : update ? "update" : "remove")) throw new AdportError8("INVALID_INPUT", "Invalid Pinterest product group operation.");
|
|
1875
|
+
const input = create2 ? groupCreate.parse(op.payload) : update ? groupUpdate.parse(op.payload) : groupDelete.parse(op.payload);
|
|
1876
|
+
const action = "definition" in input ? { kind: "create", definition: input.definition } : "changes" in input ? { kind: "update", product_group_id: input.product_group_id, changes: input.changes } : { kind: "delete", product_group_id: input.product_group_id, confirm_name: input.confirm_name };
|
|
1877
|
+
const prepare = async () => {
|
|
1878
|
+
const context = await this.context({ account_id: op.accountId, catalog_id: input.catalog_id, action });
|
|
1879
|
+
if (context.context_hash !== input.expected_context_hash) throw new AdportError8("PENDING_MISMATCH", "Product group context, references or source settings changed; read context and preview again.");
|
|
1880
|
+
return context;
|
|
1881
|
+
}, before = await prepare();
|
|
1882
|
+
const title = create2 ? "Create product group" : update ? "Update product group" : "Delete product group permanently", subject = create2 ? String(before.body.name) : before.current.name ?? before.current.id;
|
|
1883
|
+
let receipt;
|
|
1884
|
+
return {
|
|
1885
|
+
summary: `${title} \xB7 ${subject}`,
|
|
1886
|
+
changes: [remove ? "- " + subject : `${create2 ? "+" : "~"} ${canonical4(before.body)}`],
|
|
1887
|
+
coercions: [],
|
|
1888
|
+
budgetDeltas: [],
|
|
1889
|
+
notes,
|
|
1890
|
+
review: { provider: "pinterest", accountId: op.accountId, kind: op.kind, title, subject, fields: [{ label: "Catalog", after: { id: before.catalog.id, name: before.catalog.name, type: before.catalog.catalog_type } }, { label: "Source mode", after: before.body.feed_id ?? before.current?.feed_id ? "Retail feed" : "Catalog" }, ...remove ? [{ label: "Remove", before: configuration(before.current), after: null }] : Object.entries(before.body).filter(([key]) => !["catalog_id", "catalog_type"].includes(key)).map(([key, after]) => ({ label: { filters: "Product selection", feed_id: "Feed", name: "Name", description: "Description", country: "Country", locale: "Locale" }[key] ?? key, ...before.current && Object.hasOwn(before.current, key) ? { before: before.current[key] } : {}, after })), { label: "Verified filter references", after: before.reference_count }], notices: notes },
|
|
1891
|
+
execute: async () => {
|
|
1892
|
+
const fresh = await prepare();
|
|
1893
|
+
let id4 = fresh.current?.id;
|
|
1894
|
+
try {
|
|
1895
|
+
const path = `catalogs/product_groups${id4 ? "/" + id4 : ""}`;
|
|
1896
|
+
const result = await this.client.mutate(path, create2 ? "POST" : update ? "PATCH" : "DELETE", remove ? void 0 : fresh.body, remove ? z11.union([nativeGroup, z11.undefined()]) : nativeGroup, this.params(op.accountId));
|
|
1897
|
+
if (result) {
|
|
1898
|
+
if (id4 && result.id !== id4) throw mismatch();
|
|
1899
|
+
id4 = result.id;
|
|
1900
|
+
this.scope(result, fresh.catalog, id4);
|
|
1901
|
+
}
|
|
1902
|
+
if (!id4) throw mismatch();
|
|
1903
|
+
if (remove) {
|
|
1904
|
+
const absence = await this.list({ account_id: op.accountId, catalog_id: input.catalog_id, product_group_ids: [id4], page_size: 1 });
|
|
1905
|
+
if (absence.complete !== true || absence.items.length) throw mismatch();
|
|
1906
|
+
receipt = { deletion_readback: "ABSENT_FROM_COMPLETE_FILTERED_LIST", items_deleted: false };
|
|
1907
|
+
} else {
|
|
1908
|
+
const actual = await this.read(op.accountId, fresh.catalog, id4);
|
|
1909
|
+
if (create2 && !fresh.body.feed_id && actual.feed_id != null) throw mismatch();
|
|
1910
|
+
const wanted = update ? { ...configuration(fresh.current), ...fresh.body, ...fresh.body.filters ? { filters: normalizeFilters(fresh.body.filters) } : {} } : { ...fresh.body, filters: normalizeFilters(fresh.body.filters), ...fresh.catalog.catalog_type === "CREATIVE_ASSETS" ? {} : { type: "MERCHANT_CREATED" } };
|
|
1911
|
+
if (Object.entries(wanted).some(([key, value]) => canonical4(configuration(actual)[key]) !== canonical4(value))) throw mismatch();
|
|
1912
|
+
receipt = { configuration_readback: "VERIFIED", matched_inventory_verified: false, snapshot_hash: this.snapshot(op.accountId, actual), next_tool: "pinterest_product_group_products", next_arguments: { account_id: op.accountId, catalog_id: input.catalog_id, product_group_id: id4 } };
|
|
1913
|
+
}
|
|
1914
|
+
return [id4];
|
|
1915
|
+
} catch (error) {
|
|
1916
|
+
const data = error instanceof AdportError8 && error.details && typeof error.details === "object" ? error.details : {}, returned = Array.isArray(data.resource_ids) ? data.resource_ids.filter((value) => typeof value === "string" && groupId.safeParse(value).success) : [];
|
|
1917
|
+
throw new AdportError8("PROVIDER_ERROR", "Pinterest product group mutation is unconfirmed. No write was retried; reconcile known IDs before another preview.", { resource_ids: [.../* @__PURE__ */ new Set([...id4 ? [id4] : [], ...returned])], ...typeof data.http_status === "number" ? { http_status: data.http_status } : {} });
|
|
1918
|
+
}
|
|
1919
|
+
},
|
|
1920
|
+
resultDetails: () => receipt,
|
|
1921
|
+
resultWarnings: () => notes.slice(1)
|
|
1922
|
+
};
|
|
1923
|
+
}
|
|
1924
|
+
};
|
|
1925
|
+
|
|
1926
|
+
// src/catalog-items.ts
|
|
1927
|
+
import { createHash as createHash7 } from "crypto";
|
|
1928
|
+
import { z as z14 } from "zod";
|
|
1929
|
+
import { AdportError as AdportError9, MAX_PROJECT_MEDIA_BYTES, verifyMedia } from "@adport/core";
|
|
1930
|
+
|
|
1931
|
+
// src/catalog-item-attributes.ts
|
|
1932
|
+
import { z as z12 } from "zod";
|
|
1933
|
+
var itemAttributeSchemas = {
|
|
1934
|
+
retailCreate: z12.object({ "ad_image_0_link": z12.string().max(2e3).nullable().optional(), "ad_image_0_tag": z12.string().max(511).nullable().optional(), "ad_image_10_link": z12.string().max(2e3).nullable().optional(), "ad_image_10_tag": z12.string().max(511).nullable().optional(), "ad_image_11_link": z12.string().max(2e3).nullable().optional(), "ad_image_11_tag": z12.string().max(511).nullable().optional(), "ad_image_12_link": z12.string().max(2e3).nullable().optional(), "ad_image_12_tag": z12.string().max(511).nullable().optional(), "ad_image_13_link": z12.string().max(2e3).nullable().optional(), "ad_image_13_tag": z12.string().max(511).nullable().optional(), "ad_image_14_link": z12.string().max(2e3).nullable().optional(), "ad_image_14_tag": z12.string().max(511).nullable().optional(), "ad_image_15_link": z12.string().max(2e3).nullable().optional(), "ad_image_15_tag": z12.string().max(511).nullable().optional(), "ad_image_16_link": z12.string().max(2e3).nullable().optional(), "ad_image_16_tag": z12.string().max(511).nullable().optional(), "ad_image_17_link": z12.string().max(2e3).nullable().optional(), "ad_image_17_tag": z12.string().max(511).nullable().optional(), "ad_image_18_link": z12.string().max(2e3).nullable().optional(), "ad_image_18_tag": z12.string().max(511).nullable().optional(), "ad_image_19_link": z12.string().max(2e3).nullable().optional(), "ad_image_19_tag": z12.string().max(511).nullable().optional(), "ad_image_1_link": z12.string().max(2e3).nullable().optional(), "ad_image_1_tag": z12.string().max(511).nullable().optional(), "ad_image_2_link": z12.string().max(2e3).nullable().optional(), "ad_image_2_tag": z12.string().max(511).nullable().optional(), "ad_image_3_link": z12.string().max(2e3).nullable().optional(), "ad_image_3_tag": z12.string().max(511).nullable().optional(), "ad_image_4_link": z12.string().max(2e3).nullable().optional(), "ad_image_4_tag": z12.string().max(511).nullable().optional(), "ad_image_5_link": z12.string().max(2e3).nullable().optional(), "ad_image_5_tag": z12.string().max(511).nullable().optional(), "ad_image_6_link": z12.string().max(2e3).nullable().optional(), "ad_image_6_tag": z12.string().max(511).nullable().optional(), "ad_image_7_link": z12.string().max(2e3).nullable().optional(), "ad_image_7_tag": z12.string().max(511).nullable().optional(), "ad_image_8_link": z12.string().max(2e3).nullable().optional(), "ad_image_8_tag": z12.string().max(511).nullable().optional(), "ad_image_9_link": z12.string().max(2e3).nullable().optional(), "ad_image_9_tag": z12.string().max(511).nullable().optional(), "ad_link": z12.string().max(65536).nullable().optional(), "ad_video_0_link": z12.string().max(2e3).nullable().optional(), "ad_video_0_tag": z12.string().max(511).nullable().optional(), "ad_video_1_link": z12.string().max(2e3).nullable().optional(), "ad_video_1_tag": z12.string().max(511).nullable().optional(), "ad_video_2_link": z12.string().max(2e3).nullable().optional(), "ad_video_2_tag": z12.string().max(511).nullable().optional(), "additional_image_link": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "adult": z12.boolean().nullable().optional(), "age_group": z12.string().max(65536).nullable().optional(), "ai_disclosures": z12.array(z12.object({ "disclosure": z12.array(z12.enum(["ai_modified", "synthetic_performer"])).min(1).max(1e3), "url": z12.string().max(2e3) }).strict()).max(1e3).optional(), "android_deep_link": z12.string().max(65536).optional(), "availability": z12.string().max(65536).optional(), "average_review_rating": z12.number().nullable().optional(), "brand": z12.string().max(65536).nullable().optional(), "checkout_enabled": z12.boolean().nullable().optional(), "color": z12.string().max(65536).nullable().optional(), "condition": z12.string().max(65536).nullable().optional(), "custom_label_0": z12.string().max(511).nullable().optional(), "custom_label_1": z12.string().max(511).nullable().optional(), "custom_label_2": z12.string().max(511).nullable().optional(), "custom_label_3": z12.string().max(511).nullable().optional(), "custom_label_4": z12.string().max(511).nullable().optional(), "custom_number_0": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_1": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_2": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_3": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_4": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "description": z12.string().max(65536).optional(), "free_shipping_label": z12.boolean().nullable().optional(), "free_shipping_limit": z12.string().max(65536).nullable().optional(), "gender": z12.string().max(65536).nullable().optional(), "google_product_category": z12.string().max(65536).nullable().optional(), "gtin": z12.union([z12.string().max(65536).nullable(), z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), "id": z12.string().max(65536).optional(), "image_link": z12.union([z12.string().max(65536), z12.array(z12.string().max(65536)).min(1).max(1)]).optional(), "installment_price": z12.string().max(65536).nullable().optional(), "ios_deep_link": z12.string().max(65536).optional(), "item_group_id": z12.string().max(65536).nullable().optional(), "last_updated_time": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "link": z12.string().max(65536).optional(), "material": z12.string().max(65536).nullable().optional(), "min_ad_price": z12.string().max(65536).nullable().optional(), "mobile_link": z12.string().max(65536).nullable().optional(), "mpn": z12.string().max(65536).nullable().optional(), "number_of_ratings": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "number_of_reviews": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "pattern": z12.string().max(65536).nullable().optional(), "price": z12.string().max(65536).optional(), "product_type": z12.string().max(65536).nullable().optional(), "promotion_id": z12.string().max(65536).nullable().optional(), "sale_price": z12.string().max(65536).nullable().optional(), "sale_price_effective_date": z12.string().max(65536).nullable().optional(), "save_pin_disabled": z12.boolean().optional(), "shipping": z12.string().max(65536).nullable().optional(), "shipping_height": z12.string().max(65536).nullable().optional(), "shipping_weight": z12.string().max(65536).nullable().optional(), "shipping_width": z12.string().max(65536).nullable().optional(), "size": z12.string().max(65536).nullable().optional(), "size_system": z12.string().max(65536).nullable().optional(), "size_type": z12.string().max(65536).nullable().optional(), "tax": z12.string().max(65536).nullable().optional(), "title": z12.string().max(65536).optional(), "unit_pricing_base_measure": z12.string().max(65536).nullable().optional(), "unit_pricing_measure": z12.string().max(65536).nullable().optional(), "variant_names": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "variant_values": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "video_link": z12.string().max(65536).nullable().optional() }).strict(),
|
|
1935
|
+
retailUpdate: z12.object({ "ad_image_0_link": z12.string().max(2e3).nullable().optional(), "ad_image_0_tag": z12.string().max(511).nullable().optional(), "ad_image_10_link": z12.string().max(2e3).nullable().optional(), "ad_image_10_tag": z12.string().max(511).nullable().optional(), "ad_image_11_link": z12.string().max(2e3).nullable().optional(), "ad_image_11_tag": z12.string().max(511).nullable().optional(), "ad_image_12_link": z12.string().max(2e3).nullable().optional(), "ad_image_12_tag": z12.string().max(511).nullable().optional(), "ad_image_13_link": z12.string().max(2e3).nullable().optional(), "ad_image_13_tag": z12.string().max(511).nullable().optional(), "ad_image_14_link": z12.string().max(2e3).nullable().optional(), "ad_image_14_tag": z12.string().max(511).nullable().optional(), "ad_image_15_link": z12.string().max(2e3).nullable().optional(), "ad_image_15_tag": z12.string().max(511).nullable().optional(), "ad_image_16_link": z12.string().max(2e3).nullable().optional(), "ad_image_16_tag": z12.string().max(511).nullable().optional(), "ad_image_17_link": z12.string().max(2e3).nullable().optional(), "ad_image_17_tag": z12.string().max(511).nullable().optional(), "ad_image_18_link": z12.string().max(2e3).nullable().optional(), "ad_image_18_tag": z12.string().max(511).nullable().optional(), "ad_image_19_link": z12.string().max(2e3).nullable().optional(), "ad_image_19_tag": z12.string().max(511).nullable().optional(), "ad_image_1_link": z12.string().max(2e3).nullable().optional(), "ad_image_1_tag": z12.string().max(511).nullable().optional(), "ad_image_2_link": z12.string().max(2e3).nullable().optional(), "ad_image_2_tag": z12.string().max(511).nullable().optional(), "ad_image_3_link": z12.string().max(2e3).nullable().optional(), "ad_image_3_tag": z12.string().max(511).nullable().optional(), "ad_image_4_link": z12.string().max(2e3).nullable().optional(), "ad_image_4_tag": z12.string().max(511).nullable().optional(), "ad_image_5_link": z12.string().max(2e3).nullable().optional(), "ad_image_5_tag": z12.string().max(511).nullable().optional(), "ad_image_6_link": z12.string().max(2e3).nullable().optional(), "ad_image_6_tag": z12.string().max(511).nullable().optional(), "ad_image_7_link": z12.string().max(2e3).nullable().optional(), "ad_image_7_tag": z12.string().max(511).nullable().optional(), "ad_image_8_link": z12.string().max(2e3).nullable().optional(), "ad_image_8_tag": z12.string().max(511).nullable().optional(), "ad_image_9_link": z12.string().max(2e3).nullable().optional(), "ad_image_9_tag": z12.string().max(511).nullable().optional(), "ad_link": z12.string().max(65536).nullable().optional(), "ad_video_0_link": z12.string().max(2e3).nullable().optional(), "ad_video_0_tag": z12.string().max(511).nullable().optional(), "ad_video_1_link": z12.string().max(2e3).nullable().optional(), "ad_video_1_tag": z12.string().max(511).nullable().optional(), "ad_video_2_link": z12.string().max(2e3).nullable().optional(), "ad_video_2_tag": z12.string().max(511).nullable().optional(), "adult": z12.boolean().nullable().optional(), "age_group": z12.string().max(65536).nullable().optional(), "android_deep_link": z12.string().max(65536).optional(), "availability": z12.string().max(65536).optional(), "average_review_rating": z12.number().nullable().optional(), "brand": z12.string().max(65536).nullable().optional(), "checkout_enabled": z12.boolean().nullable().optional(), "color": z12.string().max(65536).nullable().optional(), "condition": z12.string().max(65536).nullable().optional(), "custom_label_0": z12.string().max(511).nullable().optional(), "custom_label_1": z12.string().max(511).nullable().optional(), "custom_label_2": z12.string().max(511).nullable().optional(), "custom_label_3": z12.string().max(511).nullable().optional(), "custom_label_4": z12.string().max(511).nullable().optional(), "custom_number_0": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_1": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_2": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_3": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_4": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "description": z12.string().max(65536).optional(), "free_shipping_label": z12.boolean().nullable().optional(), "free_shipping_limit": z12.string().max(65536).nullable().optional(), "gender": z12.string().max(65536).nullable().optional(), "google_product_category": z12.string().max(65536).nullable().optional(), "gtin": z12.union([z12.string().max(65536).nullable(), z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), "id": z12.string().max(65536).optional(), "installment_price": z12.string().max(65536).nullable().optional(), "ios_deep_link": z12.string().max(65536).optional(), "item_group_id": z12.string().max(65536).nullable().optional(), "last_updated_time": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "link": z12.string().max(65536).optional(), "material": z12.string().max(65536).nullable().optional(), "min_ad_price": z12.string().max(65536).nullable().optional(), "mobile_link": z12.string().max(65536).nullable().optional(), "mpn": z12.string().max(65536).nullable().optional(), "number_of_ratings": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "number_of_reviews": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "pattern": z12.string().max(65536).nullable().optional(), "price": z12.string().max(65536).optional(), "product_type": z12.string().max(65536).nullable().optional(), "promotion_id": z12.string().max(65536).nullable().optional(), "sale_price": z12.string().max(65536).nullable().optional(), "sale_price_effective_date": z12.string().max(65536).nullable().optional(), "shipping": z12.string().max(65536).nullable().optional(), "shipping_height": z12.string().max(65536).nullable().optional(), "shipping_weight": z12.string().max(65536).nullable().optional(), "shipping_width": z12.string().max(65536).nullable().optional(), "size": z12.string().max(65536).nullable().optional(), "size_system": z12.string().max(65536).nullable().optional(), "size_type": z12.string().max(65536).nullable().optional(), "tax": z12.string().max(65536).nullable().optional(), "title": z12.string().max(65536).optional(), "unit_pricing_base_measure": z12.string().max(65536).nullable().optional(), "unit_pricing_measure": z12.string().max(65536).nullable().optional(), "variant_names": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "variant_values": z12.array(z12.string().max(65536)).max(1e3).nullable().optional() }).strict(),
|
|
1936
|
+
retailRead: z12.object({ "ad_image_0_link": z12.string().max(2e3).nullable().optional(), "ad_image_0_tag": z12.string().max(511).nullable().optional(), "ad_image_10_link": z12.string().max(2e3).nullable().optional(), "ad_image_10_tag": z12.string().max(511).nullable().optional(), "ad_image_11_link": z12.string().max(2e3).nullable().optional(), "ad_image_11_tag": z12.string().max(511).nullable().optional(), "ad_image_12_link": z12.string().max(2e3).nullable().optional(), "ad_image_12_tag": z12.string().max(511).nullable().optional(), "ad_image_13_link": z12.string().max(2e3).nullable().optional(), "ad_image_13_tag": z12.string().max(511).nullable().optional(), "ad_image_14_link": z12.string().max(2e3).nullable().optional(), "ad_image_14_tag": z12.string().max(511).nullable().optional(), "ad_image_15_link": z12.string().max(2e3).nullable().optional(), "ad_image_15_tag": z12.string().max(511).nullable().optional(), "ad_image_16_link": z12.string().max(2e3).nullable().optional(), "ad_image_16_tag": z12.string().max(511).nullable().optional(), "ad_image_17_link": z12.string().max(2e3).nullable().optional(), "ad_image_17_tag": z12.string().max(511).nullable().optional(), "ad_image_18_link": z12.string().max(2e3).nullable().optional(), "ad_image_18_tag": z12.string().max(511).nullable().optional(), "ad_image_19_link": z12.string().max(2e3).nullable().optional(), "ad_image_19_tag": z12.string().max(511).nullable().optional(), "ad_image_1_link": z12.string().max(2e3).nullable().optional(), "ad_image_1_tag": z12.string().max(511).nullable().optional(), "ad_image_2_link": z12.string().max(2e3).nullable().optional(), "ad_image_2_tag": z12.string().max(511).nullable().optional(), "ad_image_3_link": z12.string().max(2e3).nullable().optional(), "ad_image_3_tag": z12.string().max(511).nullable().optional(), "ad_image_4_link": z12.string().max(2e3).nullable().optional(), "ad_image_4_tag": z12.string().max(511).nullable().optional(), "ad_image_5_link": z12.string().max(2e3).nullable().optional(), "ad_image_5_tag": z12.string().max(511).nullable().optional(), "ad_image_6_link": z12.string().max(2e3).nullable().optional(), "ad_image_6_tag": z12.string().max(511).nullable().optional(), "ad_image_7_link": z12.string().max(2e3).nullable().optional(), "ad_image_7_tag": z12.string().max(511).nullable().optional(), "ad_image_8_link": z12.string().max(2e3).nullable().optional(), "ad_image_8_tag": z12.string().max(511).nullable().optional(), "ad_image_9_link": z12.string().max(2e3).nullable().optional(), "ad_image_9_tag": z12.string().max(511).nullable().optional(), "ad_link": z12.string().max(65536).nullable().optional(), "ad_video_0_link": z12.string().max(2e3).nullable().optional(), "ad_video_0_tag": z12.string().max(511).nullable().optional(), "ad_video_1_link": z12.string().max(2e3).nullable().optional(), "ad_video_1_tag": z12.string().max(511).nullable().optional(), "ad_video_2_link": z12.string().max(2e3).nullable().optional(), "ad_video_2_tag": z12.string().max(511).nullable().optional(), "adult": z12.boolean().nullable().optional(), "age_group": z12.string().max(65536).nullable().optional(), "android_deep_link": z12.string().max(65536).optional(), "availability": z12.string().max(65536).optional(), "average_review_rating": z12.number().nullable().optional(), "brand": z12.string().max(65536).nullable().optional(), "checkout_enabled": z12.boolean().nullable().optional(), "color": z12.string().max(65536).nullable().optional(), "condition": z12.string().max(65536).nullable().optional(), "custom_label_0": z12.string().max(511).nullable().optional(), "custom_label_1": z12.string().max(511).nullable().optional(), "custom_label_2": z12.string().max(511).nullable().optional(), "custom_label_3": z12.string().max(511).nullable().optional(), "custom_label_4": z12.string().max(511).nullable().optional(), "custom_number_0": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_1": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_2": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_3": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "custom_number_4": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "description": z12.string().max(65536).optional(), "free_shipping_label": z12.boolean().nullable().optional(), "free_shipping_limit": z12.string().max(65536).nullable().optional(), "gender": z12.string().max(65536).nullable().optional(), "google_product_category": z12.string().max(65536).nullable().optional(), "gtin": z12.union([z12.string().max(65536).nullable(), z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), "id": z12.string().max(65536).optional(), "installment_price": z12.string().max(65536).nullable().optional(), "ios_deep_link": z12.string().max(65536).optional(), "item_group_id": z12.string().max(65536).nullable().optional(), "last_updated_time": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "link": z12.string().max(65536).optional(), "material": z12.string().max(65536).nullable().optional(), "min_ad_price": z12.string().max(65536).nullable().optional(), "mobile_link": z12.string().max(65536).nullable().optional(), "mpn": z12.string().max(65536).nullable().optional(), "number_of_ratings": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "number_of_reviews": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "pattern": z12.string().max(65536).nullable().optional(), "price": z12.string().max(65536).optional(), "product_type": z12.string().max(65536).nullable().optional(), "promotion_id": z12.string().max(65536).nullable().optional(), "sale_price": z12.string().max(65536).nullable().optional(), "sale_price_effective_date": z12.string().max(65536).nullable().optional(), "shipping": z12.string().max(65536).nullable().optional(), "shipping_height": z12.string().max(65536).nullable().optional(), "shipping_weight": z12.string().max(65536).nullable().optional(), "shipping_width": z12.string().max(65536).nullable().optional(), "size": z12.string().max(65536).nullable().optional(), "size_system": z12.string().max(65536).nullable().optional(), "size_type": z12.string().max(65536).nullable().optional(), "tax": z12.string().max(65536).nullable().optional(), "title": z12.string().max(65536).optional(), "unit_pricing_base_measure": z12.string().max(65536).nullable().optional(), "unit_pricing_measure": z12.string().max(65536).nullable().optional(), "variant_names": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "variant_values": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "additional_image_link": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "ai_disclosures": z12.array(z12.object({ "disclosure": z12.array(z12.enum(["ai_modified", "synthetic_performer"])).min(1).max(1e3), "url": z12.string().max(2e3) }).strict()).max(1e3).optional(), "image_link": z12.array(z12.string().max(65536)).min(1).max(1e3).optional(), "video_link": z12.string().max(65536).nullable().optional() }).strict(),
|
|
1937
|
+
hotelCreate: z12.object({ "address": z12.object({ "addr1": z12.string().max(65536).optional(), "city": z12.string().max(65536).optional(), "country": z12.string().max(65536).optional(), "postal_code": z12.string().max(65536).optional(), "region": z12.string().max(65536).optional() }).strict().optional(), "base_price": z12.string().max(65536).nullable().optional(), "brand": z12.string().max(65536).nullable().optional(), "category": z12.string().max(65536).nullable().optional(), "custom_label_0": z12.string().max(65536).nullable().optional(), "custom_label_1": z12.string().max(65536).nullable().optional(), "custom_label_2": z12.string().max(65536).nullable().optional(), "custom_label_3": z12.string().max(65536).nullable().optional(), "custom_label_4": z12.string().max(65536).nullable().optional(), "description": z12.string().max(65536).nullable().optional(), "guest_ratings": z12.object({ "max_score": z12.number().nullable().optional(), "number_of_reviewers": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "rating_system": z12.string().max(65536).nullable().optional(), "score": z12.number().nullable().optional() }).strict().optional(), "latitude": z12.number().optional(), "link": z12.string().max(65536).nullable().optional(), "longitude": z12.number().nullable().optional(), "name": z12.string().max(65536).nullable().optional(), "neighborhood": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "sale_price": z12.string().max(65536).nullable().optional(), "additional_image_link": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "ai_disclosures": z12.array(z12.object({ "disclosure": z12.array(z12.enum(["ai_modified", "synthetic_performer"])).min(1).max(1e3), "url": z12.string().max(2e3) }).strict()).max(1e3).optional(), "main_image": z12.object({ "link": z12.string().max(65536).optional(), "tag": z12.array(z12.string().max(65536)).max(1e3).nullable().optional() }).strict().optional() }).strict(),
|
|
1938
|
+
hotelUpdate: z12.object({ "address": z12.object({ "addr1": z12.string().max(65536).optional(), "city": z12.string().max(65536).optional(), "country": z12.string().max(65536).optional(), "postal_code": z12.string().max(65536).optional(), "region": z12.string().max(65536).optional() }).strict().optional(), "base_price": z12.string().max(65536).nullable().optional(), "brand": z12.string().max(65536).nullable().optional(), "category": z12.string().max(65536).nullable().optional(), "custom_label_0": z12.string().max(65536).nullable().optional(), "custom_label_1": z12.string().max(65536).nullable().optional(), "custom_label_2": z12.string().max(65536).nullable().optional(), "custom_label_3": z12.string().max(65536).nullable().optional(), "custom_label_4": z12.string().max(65536).nullable().optional(), "description": z12.string().max(65536).nullable().optional(), "guest_ratings": z12.object({ "max_score": z12.number().nullable().optional(), "number_of_reviewers": z12.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), "rating_system": z12.string().max(65536).nullable().optional(), "score": z12.number().nullable().optional() }).strict().optional(), "latitude": z12.number().optional(), "link": z12.string().max(65536).nullable().optional(), "longitude": z12.number().nullable().optional(), "name": z12.string().max(65536).nullable().optional(), "neighborhood": z12.array(z12.string().max(65536)).max(1e3).nullable().optional(), "sale_price": z12.string().max(65536).nullable().optional() }).strict(),
|
|
1939
|
+
creativeCreate: z12.object({ "android_deep_link": z12.string().max(65536).nullable().optional(), "custom_label_0": z12.string().max(65536).nullable().optional(), "custom_label_1": z12.string().max(65536).nullable().optional(), "custom_label_2": z12.string().max(65536).nullable().optional(), "custom_label_3": z12.string().max(65536).nullable().optional(), "custom_label_4": z12.string().max(65536).nullable().optional(), "description": z12.string().max(65536).optional(), "google_product_category": z12.string().max(65536).nullable().optional(), "ios_deep_link": z12.string().max(65536).nullable().optional(), "link": z12.string().max(65536).optional(), "title": z12.string().max(65536).optional(), "visibility": z12.string().max(65536).nullable().optional(), "ai_disclosures": z12.array(z12.object({ "disclosure": z12.array(z12.enum(["ai_modified", "synthetic_performer"])).min(1).max(1e3), "url": z12.string().max(2e3) }).strict()).max(1e3).optional(), "image_link": z12.string().max(65536).optional(), "video_link": z12.string().max(65536).optional() }).strict(),
|
|
1940
|
+
creativeUpdate: z12.object({ "android_deep_link": z12.string().max(65536).nullable().optional(), "custom_label_0": z12.string().max(65536).nullable().optional(), "custom_label_1": z12.string().max(65536).nullable().optional(), "custom_label_2": z12.string().max(65536).nullable().optional(), "custom_label_3": z12.string().max(65536).nullable().optional(), "custom_label_4": z12.string().max(65536).nullable().optional(), "description": z12.string().max(65536).optional(), "google_product_category": z12.string().max(65536).nullable().optional(), "ios_deep_link": z12.string().max(65536).nullable().optional(), "link": z12.string().max(65536).optional(), "title": z12.string().max(65536).optional(), "visibility": z12.string().max(65536).nullable().optional() }).strict()
|
|
1941
|
+
};
|
|
1942
|
+
var itemUpdateMask = z12.enum(["ad_link", "adult", "age_group", "availability", "average_review_rating", "brand", "checkout_enabled", "color", "condition", "custom_label_0", "custom_label_1", "custom_label_2", "custom_label_3", "custom_label_4", "custom_number_0", "custom_number_1", "custom_number_2", "custom_number_3", "custom_number_4", "description", "free_shipping_label", "free_shipping_limit", "gender", "google_product_category", "gtin", "item_group_id", "last_updated_time", "link", "material", "min_ad_price", "mpn", "number_of_ratings", "number_of_reviews", "pattern", "price", "product_type", "sale_price", "shipping", "shipping_height", "shipping_weight", "shipping_width", "size", "size_system", "size_type", "tax", "title", "variant_names", "variant_values", "promotion_id"]);
|
|
1943
|
+
var itemLanguages = ["af-ZA", "ar-SA", "bg-BG", "bn-IN", "cs-CZ", "da-DK", "de", "el-GR", "en-AU", "en-CA", "en-GB", "en-IN", "en-US", "es-419", "es-AR", "es-ES", "es-MX", "fi-FI", "fr", "fr-CA", "he-IL", "hi-IN", "hr-HR", "hu-HU", "id-ID", "it", "ja", "ko-KR", "ms-MY", "nb-NO", "nl", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "ru-RU", "sk-SK", "sv-SE", "te-IN", "th-TH", "tl-PH", "tr", "uk-UA", "vi-VN", "zh-CN", "zh-TW", "AM", "AR", "AZ", "BG", "BN", "BS", "CA", "CS", "DA", "DV", "DZ", "DE", "EL", "EN", "ES", "ET", "FA", "FI", "FR", "HE", "HI", "HR", "HU", "HY", "ID", "IN", "IS", "IT", "IW", "JA", "KA", "KM", "KO", "LO", "LT", "LV", "MK", "MN", "MS", "MY", "NB", "NE", "NL", "NO", "PL", "PT", "RO", "RU", "SK", "SL", "SQ", "SR", "SV", "TL", "UK", "VI", "TE", "TH", "TR", "XX", "ZH"];
|
|
1944
|
+
|
|
1945
|
+
// src/catalog-item-schemas.ts
|
|
1946
|
+
import { z as z13 } from "zod";
|
|
1947
|
+
var itemOperation = z13.enum(["CREATE", "UPDATE", "UPSERT", "DELETE"]);
|
|
1948
|
+
var sourceId = z13.string().min(1).max(1024).regex(/^[^\x00-\x1f\x7f]+$/);
|
|
1949
|
+
var itemObject = z13.record(z13.string(), z13.json());
|
|
1950
|
+
var itemSelection = z13.object({ account_id: pinterestId, catalog_id: groupId, country: z13.enum(filterEnums.Country), language: z13.enum(itemLanguages) }).strict();
|
|
1951
|
+
var itemRead = itemSelection.extend({ item_ids: z13.array(sourceId).min(1).max(1e3).refine((ids3) => new Set(ids3).size === ids3.length), limit: z13.number().int().min(1).max(100).default(24), cursor: z13.string().min(1).max(8192).optional() });
|
|
1952
|
+
var itemMutationBase = z13.object({ source_id: sourceId, operation: itemOperation, attributes: itemObject.optional(), clear_fields: z13.array(itemUpdateMask).min(1).max(100).refine((values) => new Set(values).size === values.length).optional(), last_updated_time: z13.number().int().nonnegative().safe().optional() }).strict();
|
|
1953
|
+
var itemMutation = itemMutationBase.superRefine((value, ctx) => {
|
|
1954
|
+
if (value.operation === "DELETE" ? value.attributes !== void 0 || value.clear_fields !== void 0 : value.attributes === void 0 || value.last_updated_time !== void 0 || value.operation !== "UPDATE" && value.clear_fields !== void 0) ctx.addIssue({ code: "custom", message: "CREATE/UPSERT/UPDATE require attributes; only UPDATE supports clear_fields; only DELETE accepts last_updated_time" });
|
|
1955
|
+
if (value.operation === "UPDATE" && !Object.keys(value.attributes ?? {}).length && !value.clear_fields?.length) ctx.addIssue({ code: "custom", message: "Supply changed attributes or explicit clear_fields" });
|
|
1956
|
+
if (value.clear_fields?.some((key) => Object.hasOwn(value.attributes ?? {}, key))) ctx.addIssue({ code: "custom", message: "A field cannot be both supplied and cleared" });
|
|
1957
|
+
});
|
|
1958
|
+
var itemMedia = z13.object({ item_index: z13.number().int().min(0).max(999), field: z13.string().regex(/^(?:image_link|video_link|additional_image_link|main_image\.link|ad_image_(?:[0-9]|1[0-9])_link|ad_video_[0-2]_link)$/), image_index: z13.number().int().min(0).max(999).optional(), media_id: z13.string().uuid(), expected_sha256: groupHash }).strict();
|
|
1959
|
+
var itemRequest = z13.object({ operations: z13.array(itemMutation).min(1).max(1e3).refine((rows) => new Set(rows.map((row) => row.source_id)).size === rows.length, "Each item may appear only once in a batch"), media_assets: z13.array(itemMedia).max(1e3).default([]), acknowledge_replacement: z13.literal(true).optional(), acknowledge_unconfirmed_existing: z13.literal(true).optional() }).strict();
|
|
1960
|
+
var itemContext = itemSelection.extend(itemRequest.shape);
|
|
1961
|
+
var write = itemSelection.omit({ account_id: true }).extend({ expected_context_hash: groupHash, confirm_publication: z13.literal(true), acknowledge_catalog_effects: z13.literal(true), confirm_permanent_deletion: z13.literal(true).optional() });
|
|
1962
|
+
var itemBatchApply = write.extend(itemRequest.shape).superRefine((value, ctx) => {
|
|
1963
|
+
if (value.operations.some((row) => row.operation === "UPSERT") && !value.acknowledge_replacement) ctx.addIssue({ code: "custom", message: "UPSERT replaces full item attributes; acknowledge_replacement is required" });
|
|
1964
|
+
if (value.operations.some((row) => row.operation === "DELETE") && !value.confirm_permanent_deletion) ctx.addIssue({ code: "custom", message: "Catalog deletion affects all data sources; confirm_permanent_deletion is required" });
|
|
1965
|
+
});
|
|
1966
|
+
var itemNamedApply = (operation) => write.extend({
|
|
1967
|
+
items: z13.array(itemMutationBase.omit({ operation: true })).min(1).max(1e3),
|
|
1968
|
+
media_assets: itemRequest.shape.media_assets,
|
|
1969
|
+
acknowledge_replacement: z13.literal(true).optional(),
|
|
1970
|
+
acknowledge_unconfirmed_existing: z13.literal(true).optional()
|
|
1971
|
+
}).superRefine((value, ctx) => {
|
|
1972
|
+
const result = itemBatchApply.safeParse({ ...Object.fromEntries(Object.entries(value).filter(([key]) => key !== "items")), operations: value.items.map((row) => ({ ...row, operation })) });
|
|
1973
|
+
if (!result.success) for (const issue of result.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message });
|
|
1974
|
+
});
|
|
1975
|
+
var itemCopy = itemSelection.omit({ account_id: true }).extend({ source_id: sourceId, expected_snapshot_hash: groupHash, title: z13.string().max(65536).optional(), description: z13.string().max(65536).optional(), confirm_publication: z13.literal(true), acknowledge_catalog_effects: z13.literal(true) }).strict().refine((value) => value.title !== void 0 || value.description !== void 0, "Supply copy to change");
|
|
1976
|
+
var batchReference = z13.object({ account_id: pinterestId, batch_receipt: z13.string().min(100).max(2e6) }).strict();
|
|
1977
|
+
var itemSchemaQuery = z13.object({ catalog_type: catalogType, operation: itemOperation }).strict();
|
|
1978
|
+
function attributeSchema(type2, operation) {
|
|
1979
|
+
if (operation === "DELETE") return z13.object({}).strict();
|
|
1980
|
+
return type2 === "RETAIL" ? operation === "UPDATE" ? itemAttributeSchemas.retailUpdate : itemAttributeSchemas.retailCreate : type2 === "HOTEL" ? operation === "UPDATE" ? itemAttributeSchemas.hotelUpdate : itemAttributeSchemas.hotelCreate : operation === "UPDATE" ? itemAttributeSchemas.creativeUpdate : itemAttributeSchemas.creativeCreate;
|
|
1981
|
+
}
|
|
1982
|
+
var itemIdField = { RETAIL: "item_id", HOTEL: "hotel_id", CREATIVE_ASSETS: "creative_assets_id" };
|
|
1983
|
+
var itemIdsField = { RETAIL: "item_ids", HOTEL: "hotel_ids", CREATIVE_ASSETS: "creative_assets_ids" };
|
|
1984
|
+
var itemWriteOperations = { pinterest_create_catalog_items: "CREATE", pinterest_update_catalog_items: "UPDATE", pinterest_upsert_catalog_items: "UPSERT", pinterest_delete_catalog_items: "DELETE" };
|
|
1985
|
+
|
|
1986
|
+
// src/catalog-items.ts
|
|
1987
|
+
var canonical5 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
1988
|
+
var hash7 = (value) => createHash7("sha256").update(canonical5(value)).digest("hex");
|
|
1989
|
+
var object3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
1990
|
+
var batchId = z14.string().regex(/^[A-Za-z0-9_-]{1,100}$/);
|
|
1991
|
+
var diagnostic = z14.object({ code: z14.number().int().safe().optional(), attribute: z14.string().max(256).optional(), message: z14.string().max(1e5).optional() });
|
|
1992
|
+
var diagnostics = (value) => z14.array(diagnostic).max(1e4).parse(value ?? []).map(({ message, ...row }) => ({ ...row, message_present: !!message }));
|
|
1993
|
+
var nativeBatch = z14.object({ catalog_type: catalogType, batch_id: batchId.optional(), created_time: z14.string().max(100).nullable().optional(), completed_time: z14.string().max(100).nullable().optional(), status: z14.enum(["PROCESSING", "COMPLETED", "FAILED"]).optional(), items: z14.array(z14.record(z14.string(), z14.json())).max(1e3).optional() });
|
|
1994
|
+
var manifestRow = z14.object({ source_id: sourceId, operation: itemOperation, desired_keys: z14.array(z14.string()).max(108), clear_keys: z14.array(z14.string()).max(100), desired_hash: groupHash.optional(), preserved_hash: groupHash.optional() }).strict();
|
|
1995
|
+
var receiptSchema = itemSelection.extend({ version: z14.literal("pinterest_items_v1"), scope_id: z14.string().min(1).max(200), catalog_type: catalogType, owner_context_hash: groupHash, batch_id: batchId, expires_at: z14.number().int().safe(), manifest: z14.array(manifestRow).min(1).max(1e3), media_expires_at: z14.string().max(100).optional() }).strict();
|
|
1996
|
+
var notes2 = ["Catalog item changes can publish product Pins and affect groups or ads using these items. DELETE removes the item across all data sources; UPSERT supplies the full replacement attributes. No ad is activated and no budget or bid is changed.", "The preview is local. Batch submission, per-item processing, independent configuration readback and Pin/ad readiness are separate states. Missing item responses and native item errors never establish absence.", "Native updates are not atomic conditional writes. No native mutation is automatically replayed after partial, failed or uncertain outcomes. Retain the signed batch receipt for scoped status and reconciliation."];
|
|
1997
|
+
var failure = (error, ids3 = [], extra = {}) => {
|
|
1998
|
+
const data = error instanceof AdportError9 ? object3(error.details) : {};
|
|
1999
|
+
return new AdportError9("PROVIDER_ERROR", "Pinterest catalog item operation is unconfirmed. No write was retried; reconcile known batch IDs before another preview. Native bodies and private media URLs are hidden.", { ...ids3.length ? { resource_ids: ids3 } : {}, ...typeof data.http_status === "number" ? { http_status: data.http_status } : {}, ...extra });
|
|
2000
|
+
};
|
|
2001
|
+
function bounded(value) {
|
|
2002
|
+
if (Buffer.byteLength(canonical5(value)) > 2 * 1024 * 1024) throw new AdportError9("INVALID_INPUT", "Catalog batch exceeds the 2 MiB Adport bound; use smaller batches.");
|
|
2003
|
+
}
|
|
2004
|
+
function publicValue(value, key = "") {
|
|
2005
|
+
if (Array.isArray(value)) return value.map((item) => publicValue(item, key));
|
|
2006
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name3, item]) => [name3, publicValue(item, name3)]));
|
|
2007
|
+
if (typeof value === "string" && /link|url/i.test(key)) {
|
|
2008
|
+
const match2 = value.match(/^https:\/\/adport\.invalid\/media\/([a-f0-9-]+)\/([a-f0-9]+)$/);
|
|
2009
|
+
if (match2) return { media_id: match2[1], sha256: match2[2] };
|
|
2010
|
+
try {
|
|
2011
|
+
const url2 = new URL(value);
|
|
2012
|
+
return { origin: url2.origin, fingerprint: hash7(value) };
|
|
2013
|
+
} catch {
|
|
2014
|
+
return { fingerprint: hash7(value) };
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
return value;
|
|
2018
|
+
}
|
|
2019
|
+
function normalized(type2, values) {
|
|
2020
|
+
return { ...values, ...type2 === "RETAIL" && typeof values.image_link === "string" ? { image_link: [values.image_link] } : {} };
|
|
2021
|
+
}
|
|
2022
|
+
function wantedValues(type2, attrs, keys, clears) {
|
|
2023
|
+
return normalized(type2, Object.fromEntries(keys.map((key) => [key, clears.includes(key) ? null : attrs[key] ?? null])));
|
|
2024
|
+
}
|
|
2025
|
+
function preserved(attrs, keys) {
|
|
2026
|
+
return Object.fromEntries(Object.entries(attrs).filter(([key]) => !keys.includes(key) && key !== "last_updated_time"));
|
|
2027
|
+
}
|
|
2028
|
+
var safeMediaUrl = (value) => {
|
|
2029
|
+
try {
|
|
2030
|
+
const url2 = new URL(value);
|
|
2031
|
+
return url2.protocol === "https:" && !url2.username && !url2.password && !url2.hash;
|
|
2032
|
+
} catch {
|
|
2033
|
+
return false;
|
|
2034
|
+
}
|
|
2035
|
+
};
|
|
2036
|
+
var PinterestCatalogItems = class {
|
|
2037
|
+
constructor(client, catalogs, media) {
|
|
2038
|
+
this.client = client;
|
|
2039
|
+
this.catalogs = catalogs;
|
|
2040
|
+
this.media = media;
|
|
2041
|
+
}
|
|
2042
|
+
client;
|
|
2043
|
+
catalogs;
|
|
2044
|
+
media;
|
|
2045
|
+
supports(tool) {
|
|
2046
|
+
return tool === "pinterest_apply_catalog_items_batch" || tool === "pinterest_update_catalog_item_copy" || Object.hasOwn(itemWriteOperations, tool);
|
|
2047
|
+
}
|
|
2048
|
+
scopeId() {
|
|
2049
|
+
const value = this.media.scopeId;
|
|
2050
|
+
return typeof value === "string" && value ? value : "local";
|
|
2051
|
+
}
|
|
2052
|
+
params(account3) {
|
|
2053
|
+
return new URLSearchParams({ ad_account_id: account3 });
|
|
2054
|
+
}
|
|
2055
|
+
snapshot(selection2, type2, owner2, row) {
|
|
2056
|
+
return hash7({ selection: selection2, catalog_type: type2, owner: owner2, id: row.id, state: row.state, attributes: row.attributes, diagnostic_hash: row.diagnostic_hash });
|
|
2057
|
+
}
|
|
2058
|
+
async selected(selection2) {
|
|
2059
|
+
const result = await this.catalogs.getCatalog(selection2.account_id, selection2.catalog_id);
|
|
2060
|
+
return { catalog: result.catalog, owner: result.context_hash };
|
|
2061
|
+
}
|
|
2062
|
+
async readSet(selection2, type2, ids3) {
|
|
2063
|
+
const result = await this.client.mutate("catalogs/items", "POST", { country: selection2.country, language: selection2.language, filters: { catalog_id: selection2.catalog_id, catalog_type: type2, [itemIdsField[type2]]: ids3 } }, z14.object({ items: z14.array(z14.record(z14.string(), z14.json())).max(1e3) }), this.params(selection2.account_id)).catch((error) => {
|
|
2064
|
+
throw failure(error);
|
|
2065
|
+
});
|
|
2066
|
+
const found = /* @__PURE__ */ new Map();
|
|
2067
|
+
for (const raw of result.items) {
|
|
2068
|
+
const id4 = sourceId.parse(raw[itemIdField[type2]]), errors = diagnostics(raw.errors), kind = raw.item_response_kind, family = type2 === "RETAIL" ? "retail" : type2 === "HOTEL" ? "hotel" : "creative_assets";
|
|
2069
|
+
if (!ids3.includes(id4) || found.has(id4) || raw.catalog_type !== type2 || raw.catalog_id !== void 0 && raw.catalog_id !== selection2.catalog_id || kind !== void 0 && ![family + "_item", family + "_item_error"].includes(String(kind)) || errors.length && raw.attributes !== void 0 || kind === family + "_item_error" && raw.attributes !== void 0) throw failure(void 0);
|
|
2070
|
+
const attrs = raw.attributes === void 0 ? void 0 : z14.record(z14.string(), z14.json()).parse(raw.attributes), state2 = attrs ? "PRESENT" : "NATIVE_ITEM_ERROR";
|
|
2071
|
+
found.set(id4, { id: id4, state: state2, attributes: attrs, pins: raw.pins === null ? null : raw.pins === void 0 ? void 0 : z14.array(z14.unknown()).max(11).parse(raw.pins), diagnostics: errors, diagnostic_hash: errors.length ? hash7(raw.errors) : void 0 });
|
|
2072
|
+
}
|
|
2073
|
+
return ids3.map((id4) => found.get(id4) ?? { id: id4, state: "NOT_RETURNED", diagnostics: [] });
|
|
2074
|
+
}
|
|
2075
|
+
previewMedia(pins) {
|
|
2076
|
+
const result = [];
|
|
2077
|
+
for (const pin of pins ?? []) for (const image of Object.values(object3(object3(object3(pin).media).images))) {
|
|
2078
|
+
const url2 = object3(image).url;
|
|
2079
|
+
if (typeof url2 !== "string") continue;
|
|
2080
|
+
let parsed;
|
|
2081
|
+
try {
|
|
2082
|
+
parsed = new URL(url2);
|
|
2083
|
+
} catch {
|
|
2084
|
+
continue;
|
|
2085
|
+
}
|
|
2086
|
+
if (safeMediaUrl(url2) && (parsed.hostname === "i.pinimg.com" || parsed.hostname.endsWith(".pinimg.com"))) {
|
|
2087
|
+
result.push({ type: "image", url: url2 });
|
|
2088
|
+
break;
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
return result.slice(0, 11);
|
|
2092
|
+
}
|
|
2093
|
+
async list(value) {
|
|
2094
|
+
const input = itemRead.parse(value), selection2 = itemSelection.parse(Object.fromEntries(Object.entries(input).filter(([key2]) => ["account_id", "catalog_id", "country", "language"].includes(key2)))), { catalog: catalog2, owner: owner2 } = await this.selected(selection2), key = hash7({ selection: selection2, ids: input.item_ids, limit: input.limit });
|
|
2095
|
+
let offset = 0;
|
|
2096
|
+
if (input.cursor) {
|
|
2097
|
+
let navigation;
|
|
2098
|
+
try {
|
|
2099
|
+
navigation = z14.object({ selection: groupHash, offset: z14.number().int().min(1).max(999) }).strict().parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")));
|
|
2100
|
+
} catch {
|
|
2101
|
+
throw new AdportError9("INVALID_INPUT", "Invalid catalog item cursor.");
|
|
2102
|
+
}
|
|
2103
|
+
if (navigation.selection !== key || navigation.offset >= input.item_ids.length) throw new AdportError9("PENDING_MISMATCH", "Catalog item selection changed; restart its first page.");
|
|
2104
|
+
offset = navigation.offset;
|
|
2105
|
+
}
|
|
2106
|
+
const ids3 = input.item_ids.slice(offset, offset + input.limit), current = await this.readSet(selection2, catalog2.catalog_type, ids3), records2 = current.map((row) => ({ id: row.id, name: String(row.attributes?.title ?? row.attributes?.name ?? row.id), status: row.state, attributes: publicValue(row.attributes), diagnostics: row.diagnostics, snapshot_hash: this.snapshot(selection2, catalog2.catalog_type, owner2, row) }));
|
|
2107
|
+
const creatives = current.map((row, index) => {
|
|
2108
|
+
const title = row.attributes?.title ?? row.attributes?.name, description2 = row.attributes?.description;
|
|
2109
|
+
return { id: row.id, provider: "pinterest", account_id: input.account_id, name: records2[index].name, type: "CATALOG_" + catalog2.catalog_type, status: row.state, headlines: typeof title === "string" ? [title] : [], descriptions: typeof description2 === "string" ? [description2] : [], landing_urls: [], media: this.previewMedia(row.pins), actions: row.state === "PRESENT" ? [{ label: "Edit copy", tool: "pinterest_update_catalog_item_copy", arguments: { ...selection2, source_id: row.id, expected_snapshot_hash: records2[index].snapshot_hash, confirm_publication: true, acknowledge_catalog_effects: true }, fields: [{ key: "title", label: catalog2.catalog_type === "HOTEL" ? "Name" : "Title", type: "text", value: typeof title === "string" ? title : "" }, { key: "description", label: "Description", type: "text", value: typeof description2 === "string" ? description2 : "" }] }] : [] };
|
|
2110
|
+
});
|
|
2111
|
+
const next = offset + ids3.length;
|
|
2112
|
+
return { records: records2, creatives, catalog_type: catalog2.catalog_type, truncated: next < input.item_ids.length, ...next < input.item_ids.length ? { next_cursor: Buffer.from(JSON.stringify({ selection: key, offset: next })).toString("base64url") } : {}, notes: ["This pages only the requested item IDs, not the whole catalog. Missing rows and native item errors do not prove absence. Media-source URLs are fingerprinted; only native Pinterest CDN Pin previews are displayed."] };
|
|
2113
|
+
}
|
|
2114
|
+
async materialize(request, type2, mint) {
|
|
2115
|
+
const rows = structuredClone(request.operations), targets = /* @__PURE__ */ new Set(), resolved = /* @__PURE__ */ new Map(), sources = [];
|
|
2116
|
+
let expires;
|
|
2117
|
+
if (request.media_assets.length && !this.media.providerUrl) throw new AdportError9("INVALID_INPUT", "Upload project media first; this runtime has no private provider URL staging.");
|
|
2118
|
+
for (const asset of request.media_assets) {
|
|
2119
|
+
const row = rows[asset.item_index], key = `${asset.item_index}:${asset.field}:${asset.image_index ?? ""}`;
|
|
2120
|
+
if (!row?.attributes || row.operation === "DELETE" || targets.has(key)) throw new AdportError9("INVALID_INPUT", "Media references require distinct existing non-delete item slots.");
|
|
2121
|
+
targets.add(key);
|
|
2122
|
+
const options = { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: /video/.test(asset.field) ? ["video/mp4"] : ["image/png", "image/jpeg", "image/webp"] }, source2 = { media_id: asset.media_id, expected_sha256: asset.expected_sha256 }, file = await this.media.read(source2, options), verified = verifyMedia(file.bytes, file.name, source2.expected_sha256, { ...options, contentType: file.contentType });
|
|
2123
|
+
const cacheKey = canonical5({ source: source2, type: verified.contentType });
|
|
2124
|
+
let url2 = resolved.get(cacheKey);
|
|
2125
|
+
if (!url2) {
|
|
2126
|
+
url2 = `https://adport.invalid/media/${asset.media_id}/${asset.expected_sha256}`;
|
|
2127
|
+
if (mint) {
|
|
2128
|
+
const grant = await this.media.providerUrl(source2, options);
|
|
2129
|
+
if (!safeMediaUrl(grant.url) || grant.sha256 !== verified.sha256 || !(Date.parse(grant.expires_at) > Date.now() + 10 * 6e4)) throw new AdportError9("PROVIDER_ERROR", "Media staging returned an invalid or short-lived grant.");
|
|
2130
|
+
url2 = grant.url;
|
|
2131
|
+
if (!expires || Date.parse(grant.expires_at) < Date.parse(expires)) expires = grant.expires_at;
|
|
2132
|
+
}
|
|
2133
|
+
resolved.set(cacheKey, url2);
|
|
2134
|
+
}
|
|
2135
|
+
const parts = asset.field.split("."), attrs = parts.length === 2 ? object3(row.attributes[parts[0]]) : row.attributes, field = parts.at(-1);
|
|
2136
|
+
if (parts.length === 2) {
|
|
2137
|
+
const parent2 = row.attributes[parts[0]];
|
|
2138
|
+
if (parent2 !== void 0 && (!parent2 || typeof parent2 !== "object" || Array.isArray(parent2))) throw new AdportError9("INVALID_INPUT", "A nested media reference requires an object field.");
|
|
2139
|
+
row.attributes[parts[0]] = attrs;
|
|
2140
|
+
}
|
|
2141
|
+
const array = field === "additional_image_link" || field === "image_link" && type2 === "RETAIL";
|
|
2142
|
+
if (array) {
|
|
2143
|
+
if (asset.image_index === void 0) throw new AdportError9("INVALID_INPUT", "An array media field requires image_index.");
|
|
2144
|
+
const values = attrs[field] === void 0 ? [] : Array.isArray(attrs[field]) ? attrs[field] : [attrs[field]];
|
|
2145
|
+
if (values[asset.image_index] != null) throw new AdportError9("INVALID_INPUT", "A media slot already has a native URL.");
|
|
2146
|
+
values[asset.image_index] = url2;
|
|
2147
|
+
attrs[field] = values;
|
|
2148
|
+
} else {
|
|
2149
|
+
if (asset.image_index !== void 0 || attrs[field] !== void 0) throw new AdportError9("INVALID_INPUT", "Scalar media fields cannot have image_index or an existing URL.");
|
|
2150
|
+
attrs[field] = url2;
|
|
2151
|
+
}
|
|
2152
|
+
sources.push({ source_id: row.source_id, field: asset.field, image_index: asset.image_index, media_id: asset.media_id, sha256: verified.sha256, name: verified.name, content_type: verified.contentType, byte_length: verified.bytes.length });
|
|
2153
|
+
}
|
|
2154
|
+
for (const row of rows) {
|
|
2155
|
+
if (row.operation === "DELETE") {
|
|
2156
|
+
if (type2 !== "RETAIL" && row.last_updated_time !== void 0) throw new AdportError9("INVALID_INPUT", "Only RETAIL deletion supports last_updated_time.");
|
|
2157
|
+
continue;
|
|
2158
|
+
}
|
|
2159
|
+
if (!attributeSchema(type2, row.operation).safeParse(row.attributes).success) throw new AdportError9("INVALID_INPUT", "Attributes do not match this native catalog type/operation. Use pinterest_catalog_item_schema; no field is silently dropped.");
|
|
2160
|
+
if (row.attributes?.id !== void 0 && row.attributes.id !== row.source_id) throw new AdportError9("INVALID_INPUT", "Deprecated attribute id cannot differ from the selected source_id.");
|
|
2161
|
+
if (row.clear_fields?.length && (type2 !== "RETAIL" || Object.keys(row.attributes).some((key) => !itemUpdateMask.safeParse(key).success))) throw new AdportError9("INVALID_INPUT", "Explicit unsetting is RETAIL-only; all supplied fields must be native update-mask fields when combined with clears.");
|
|
2162
|
+
}
|
|
2163
|
+
bounded(rows);
|
|
2164
|
+
return { rows, sources, expires };
|
|
2165
|
+
}
|
|
2166
|
+
manifest(type2, rows, before) {
|
|
2167
|
+
const result = rows.map((row) => {
|
|
2168
|
+
const desired_keys = [.../* @__PURE__ */ new Set([...Object.keys(row.attributes ?? {}), ...row.clear_fields ?? []])].sort(), clear_keys = row.clear_fields ?? [], current = before.find((value) => value.id === row.source_id);
|
|
2169
|
+
return { source_id: row.source_id, operation: row.operation, desired_keys, clear_keys, ...row.operation !== "DELETE" ? { desired_hash: hash7(wantedValues(type2, row.attributes, desired_keys, clear_keys)) } : {}, ...row.operation === "UPDATE" ? { preserved_hash: hash7(preserved(normalized(type2, current.attributes), desired_keys)) } : {} };
|
|
2170
|
+
});
|
|
2171
|
+
if (Buffer.byteLength(canonical5(result)) > 1e6) throw new AdportError9("INVALID_INPUT", "Batch proof exceeds its bound; split this batch before previewing.");
|
|
2172
|
+
return result;
|
|
2173
|
+
}
|
|
2174
|
+
async context(value) {
|
|
2175
|
+
const input = itemContext.parse(value), selection2 = itemSelection.parse(Object.fromEntries(Object.entries(input).filter(([key]) => ["account_id", "catalog_id", "country", "language"].includes(key)))), request = itemRequest.parse(Object.fromEntries(Object.entries(input).filter(([key]) => ["operations", "media_assets", "acknowledge_replacement", "acknowledge_unconfirmed_existing"].includes(key))));
|
|
2176
|
+
bounded(request);
|
|
2177
|
+
const { catalog: catalog2, owner: owner2 } = await this.selected(selection2), current = await this.readSet(selection2, catalog2.catalog_type, request.operations.map((row) => row.source_id));
|
|
2178
|
+
for (const row of request.operations) {
|
|
2179
|
+
const before = current.find((value2) => value2.id === row.source_id);
|
|
2180
|
+
if (row.operation === "CREATE" && before.state === "PRESENT") throw new AdportError9("INVALID_INPUT", "CREATE cannot overwrite an existing item.");
|
|
2181
|
+
if (["UPDATE", "DELETE"].includes(row.operation) && before.state !== "PRESENT") throw new AdportError9("INVALID_INPUT", "UPDATE/DELETE require a positively read current item; native item errors cannot establish ownership/configuration.");
|
|
2182
|
+
if (row.operation === "UPSERT" && (!request.acknowledge_replacement || before.state !== "PRESENT" && !request.acknowledge_unconfirmed_existing)) throw new AdportError9("INVALID_INPUT", "UPSERT requires replacement acknowledgement and, for unconfirmed current items, acknowledge_unconfirmed_existing.");
|
|
2183
|
+
}
|
|
2184
|
+
const prepared = await this.materialize(request, catalog2.catalog_type, false);
|
|
2185
|
+
this.manifest(catalog2.catalog_type, prepared.rows, current);
|
|
2186
|
+
const scope_id = this.scopeId();
|
|
2187
|
+
return { context_hash: hash7({ selection: selection2, owner: owner2, catalog: { id: catalog2.id, name: catalog2.name, type: catalog2.catalog_type }, scope: scope_id, request, current: current.map(({ pins: _pins, ...row }) => row) }), scope_id, selection: selection2, request, catalog: catalog2, owner: owner2, current, prepared, records: current.map((row) => ({ id: row.id, name: String(row.attributes?.title ?? row.attributes?.name ?? row.id), status: row.state, snapshot_hash: this.snapshot(selection2, catalog2.catalog_type, owner2, row), diagnostics: row.diagnostics })), notes: notes2 };
|
|
2188
|
+
}
|
|
2189
|
+
async publicContext(value) {
|
|
2190
|
+
const result = await this.context(value);
|
|
2191
|
+
return { context_hash: result.context_hash, catalog_type: result.catalog.catalog_type, records: result.records, media: result.prepared.sources, changes: result.prepared.rows.map((row) => ({ source_id: row.source_id, operation: row.operation, attributes: publicValue(row.attributes), clear_fields: row.clear_fields })), notes: notes2 };
|
|
2192
|
+
}
|
|
2193
|
+
batchRows(data, manifest) {
|
|
2194
|
+
const seen = /* @__PURE__ */ new Set(), values = /* @__PURE__ */ new Map();
|
|
2195
|
+
for (const row of data.items ?? []) {
|
|
2196
|
+
const id4 = sourceId.parse(row[itemIdField[data.catalog_type]]);
|
|
2197
|
+
if (seen.has(id4) || !manifest.some((value) => value.source_id === id4)) throw failure(void 0);
|
|
2198
|
+
seen.add(id4);
|
|
2199
|
+
const status = z14.enum(["SUCCESS", "FAILURE", "PROCESSING"]).optional().parse(row.status), errors = diagnostics(row.errors), warnings = diagnostics(row.warnings);
|
|
2200
|
+
if (status === "SUCCESS" && errors.length) throw failure(void 0);
|
|
2201
|
+
values.set(id4, { id: id4, source_id: id4, status: status ?? "UNCONFIRMED", errors, warnings });
|
|
2202
|
+
}
|
|
2203
|
+
return manifest.map((row) => values.get(row.source_id) ?? { id: row.source_id, source_id: row.source_id, status: data.status === "FAILED" ? "BATCH_FAILED" : "UNCONFIRMED", errors: [], warnings: [] });
|
|
2204
|
+
}
|
|
2205
|
+
async verifiedReceipt(value) {
|
|
2206
|
+
const input = batchReference.parse(value), proof = receiptSchema.parse(this.client.verifyCatalogBatchReceipt(input.batch_receipt));
|
|
2207
|
+
if (proof.account_id !== input.account_id || proof.scope_id !== this.scopeId() || proof.expires_at <= Math.floor(Date.now() / 1e3) || proof.expires_at > Math.floor(Date.now() / 1e3) + 30 * 86400) throw new AdportError9("INVALID_INPUT", "Batch receipt is expired or belongs to another advertiser/project.");
|
|
2208
|
+
const { catalog: catalog2, owner: owner2 } = await this.selected(proof);
|
|
2209
|
+
if (catalog2.catalog_type !== proof.catalog_type || owner2 !== proof.owner_context_hash) throw new AdportError9("POLICY_VIOLATION", "Current catalog ownership/type differs from the batch receipt.");
|
|
2210
|
+
return proof;
|
|
2211
|
+
}
|
|
2212
|
+
async status(value, reconcile = false) {
|
|
2213
|
+
const proof = await this.verifiedReceipt(value), data = await this.client.get(`catalogs/items/batch/${proof.batch_id}`, nativeBatch, this.params(proof.account_id)).catch((error) => {
|
|
2214
|
+
throw failure(error, [proof.batch_id]);
|
|
2215
|
+
});
|
|
2216
|
+
if (data.batch_id !== proof.batch_id || data.catalog_type !== proof.catalog_type) throw failure(void 0);
|
|
2217
|
+
const records2 = this.batchRows(data, proof.manifest);
|
|
2218
|
+
let readback_error;
|
|
2219
|
+
if (reconcile) {
|
|
2220
|
+
try {
|
|
2221
|
+
const current = await this.readSet(proof, proof.catalog_type, proof.manifest.map((row) => row.source_id));
|
|
2222
|
+
for (const record2 of records2) {
|
|
2223
|
+
const expected = proof.manifest.find((row) => row.source_id === record2.id), actual = current.find((row) => row.id === record2.id);
|
|
2224
|
+
record2.observed_state = actual.state;
|
|
2225
|
+
if (record2.status !== "SUCCESS") {
|
|
2226
|
+
record2.readback = "NATIVE_ITEM_NOT_SUCCESSFUL";
|
|
2227
|
+
continue;
|
|
2228
|
+
}
|
|
2229
|
+
if (expected.operation === "DELETE") {
|
|
2230
|
+
record2.readback = actual.state === "PRESENT" ? "STILL_PRESENT" : "ABSENCE_UNCONFIRMED";
|
|
2231
|
+
continue;
|
|
2232
|
+
}
|
|
2233
|
+
if (!actual.attributes) {
|
|
2234
|
+
record2.readback = "CURRENT_ITEM_UNCONFIRMED";
|
|
2235
|
+
continue;
|
|
2236
|
+
}
|
|
2237
|
+
const matches = hash7(wantedValues(proof.catalog_type, actual.attributes, expected.desired_keys, expected.clear_keys)) === expected.desired_hash, retains = !expected.preserved_hash || hash7(preserved(normalized(proof.catalog_type, actual.attributes), expected.desired_keys)) === expected.preserved_hash;
|
|
2238
|
+
record2.readback = matches && retains ? "REQUESTED_CONFIGURATION_VERIFIED" : "CONFIGURATION_UNCONFIRMED";
|
|
2239
|
+
record2.omitted_fields_preserved = expected.preserved_hash ? retains : void 0;
|
|
2240
|
+
}
|
|
2241
|
+
} catch (error) {
|
|
2242
|
+
const details = error instanceof AdportError9 ? object3(error.details) : {};
|
|
2243
|
+
readback_error = { status: "READBACK_UNAVAILABLE", ...typeof details.http_status === "number" ? { http_status: details.http_status } : {} };
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
return { batch_id: proof.batch_id, catalog_type: proof.catalog_type, status: data.status ?? "UNCONFIRMED", records: records2, submitted_items: proof.manifest.length, terminal_items: records2.filter((row) => ["SUCCESS", "FAILURE", "BATCH_FAILED"].includes(String(row.status))).length, all_items_native_successful: data.status === "COMPLETED" && records2.every((row) => row.status === "SUCCESS"), ...readback_error ? { readback_error } : {}, media_expires_at: proof.media_expires_at, notes: [...notes2, "A native SUCCESS is not proof of Pin publication, ad eligibility or permanent media hosting. Missing/error item reads never independently certify deletion."] };
|
|
2247
|
+
}
|
|
2248
|
+
async plan(op) {
|
|
2249
|
+
const copy2 = op.tool === "pinterest_update_catalog_item_copy", operation = itemWriteOperations[op.tool], expectedKind = operation === "CREATE" ? "create" : operation === "DELETE" ? "remove" : "update";
|
|
2250
|
+
if (op.provider !== "pinterest" || !this.supports(op.tool) || op.kind !== expectedKind) throw new AdportError9("INVALID_INPUT", "Invalid catalog item mutation/provider kind.");
|
|
2251
|
+
const parsed = copy2 ? itemCopy.parse(op.payload) : operation ? itemNamedApply(operation).parse(op.payload) : itemBatchApply.parse(op.payload);
|
|
2252
|
+
const selection2 = itemSelection.parse({ account_id: op.accountId, catalog_id: parsed.catalog_id, country: parsed.country, language: parsed.language });
|
|
2253
|
+
const request = "source_id" in parsed ? { operations: [{ source_id: parsed.source_id, operation: "UPDATE", attributes: {} }], media_assets: [] } : itemRequest.parse("operations" in parsed ? { operations: parsed.operations, media_assets: parsed.media_assets, acknowledge_replacement: parsed.acknowledge_replacement, acknowledge_unconfirmed_existing: parsed.acknowledge_unconfirmed_existing } : { operations: parsed.items.map((row) => ({ ...row, operation })), media_assets: parsed.media_assets, acknowledge_replacement: parsed.acknowledge_replacement, acknowledge_unconfirmed_existing: parsed.acknowledge_unconfirmed_existing });
|
|
2254
|
+
if (copy2) {
|
|
2255
|
+
const input = parsed, parent2 = await this.selected(selection2);
|
|
2256
|
+
request.operations[0].attributes = { ...input.title !== void 0 ? { [parent2.catalog.catalog_type === "HOTEL" ? "name" : "title"]: input.title } : {}, ...input.description !== void 0 ? { description: input.description } : {} };
|
|
2257
|
+
}
|
|
2258
|
+
const prepare = async () => {
|
|
2259
|
+
const result = await this.context({ ...selection2, ...request });
|
|
2260
|
+
if (copy2 ? result.records[0].snapshot_hash !== parsed.expected_snapshot_hash : result.context_hash !== parsed.expected_context_hash) throw new AdportError9("PENDING_MISMATCH", "Catalog items, selection, owner or media changed; read context and preview again.");
|
|
2261
|
+
return result;
|
|
2262
|
+
}, before = await prepare();
|
|
2263
|
+
let receipt;
|
|
2264
|
+
const title = copy2 ? "Update catalog item copy" : "Submit catalog item batch";
|
|
2265
|
+
return {
|
|
2266
|
+
summary: `${title} \xB7 ${request.operations.length} items`,
|
|
2267
|
+
changes: before.prepared.rows.map((row) => `${row.operation} ${row.source_id}`),
|
|
2268
|
+
coercions: [],
|
|
2269
|
+
budgetDeltas: [],
|
|
2270
|
+
notes: notes2,
|
|
2271
|
+
review: { provider: "pinterest", accountId: op.accountId, kind: op.kind, title, subject: before.catalog.name, fields: [{ label: "Catalog and market", after: { id: selection2.catalog_id, type: before.catalog.catalog_type, country: selection2.country, language: selection2.language } }, ...before.prepared.rows.map((row) => ({ label: row.source_id + " \xB7 " + row.operation, before: publicValue(before.current.find((value) => value.id === row.source_id).attributes) ?? "Current item unconfirmed; no absence inferred", after: row.operation === "DELETE" ? "Remove across all data sources" : { attributes: publicValue(row.attributes), clear_fields: row.clear_fields } })), ...before.prepared.sources.length ? [{ label: "Adport media", after: before.prepared.sources }] : []], notices: [...notes2, ...request.media_assets.length ? ["Media links are minted only during approved apply and expire. Native retrieval may outlast the link; inspect batch/item errors before a new approval."] : []] },
|
|
2272
|
+
execute: async () => {
|
|
2273
|
+
const fresh = await prepare();
|
|
2274
|
+
let id4;
|
|
2275
|
+
try {
|
|
2276
|
+
const materialized = await this.materialize(request, fresh.catalog.catalog_type, true), manifest = this.manifest(fresh.catalog.catalog_type, materialized.rows, fresh.current);
|
|
2277
|
+
if (this.scopeId() !== fresh.scope_id) throw new AdportError9("PENDING_MISMATCH", "Media scope changed before batch submission.");
|
|
2278
|
+
const items = materialized.rows.map((row) => ({ [itemIdField[fresh.catalog.catalog_type]]: row.source_id, operation: row.operation, ...row.attributes !== void 0 ? { attributes: row.attributes } : {}, ...row.clear_fields?.length ? { update_mask: [.../* @__PURE__ */ new Set([...Object.keys(row.attributes), ...row.clear_fields])] } : {}, ...row.last_updated_time !== void 0 ? { last_updated_time: row.last_updated_time } : {} }));
|
|
2279
|
+
const data = await this.client.mutate("catalogs/items/batch", "POST", { catalog_id: selection2.catalog_id, catalog_type: fresh.catalog.catalog_type, country: selection2.country, language: selection2.language, items }, nativeBatch, this.params(op.accountId));
|
|
2280
|
+
id4 = data.batch_id;
|
|
2281
|
+
if (!id4 || !data.status || data.catalog_type !== fresh.catalog.catalog_type || data.created_time === null) throw failure(void 0, id4 ? [id4] : []);
|
|
2282
|
+
const batch_receipt = this.client.catalogBatchReceipt({ ...selection2, version: "pinterest_items_v1", scope_id: fresh.scope_id, catalog_type: fresh.catalog.catalog_type, owner_context_hash: fresh.owner, batch_id: id4, expires_at: Math.floor(Date.now() / 1e3) + 30 * 86400, manifest, ...materialized.expires ? { media_expires_at: materialized.expires } : {} }), results = this.batchRows(data, manifest);
|
|
2283
|
+
if (data.status === "FAILED" || results.every((row) => row.status === "FAILURE")) throw failure(void 0, [id4], { batch_receipt, item_results: results, native_status: data.status });
|
|
2284
|
+
receipt = { status: "ACCEPTED_FOR_PROCESSING", processed: false, native_status: data.status, batch_id: id4, batch_receipt, records: results, native_item_count: results.filter((row) => row.status !== "UNCONFIRMED").length, source_items: manifest.length, configuration_verified: false, publication_verified: false, ...materialized.expires ? { media_expires_at: materialized.expires } : {}, next_tool: "pinterest_catalog_item_batch_status", next_arguments: { account_id: op.accountId, batch_receipt } };
|
|
2285
|
+
return [id4];
|
|
2286
|
+
} catch (error) {
|
|
2287
|
+
const details = error instanceof AdportError9 ? object3(error.details) : {};
|
|
2288
|
+
throw failure(error, id4 ? [id4] : Array.isArray(details.resource_ids) ? details.resource_ids : [], details.batch_receipt ? { batch_receipt: details.batch_receipt, item_results: details.item_results, native_status: details.native_status } : {});
|
|
2289
|
+
}
|
|
2290
|
+
},
|
|
2291
|
+
resultDetails: () => receipt,
|
|
2292
|
+
resultWarnings: () => notes2
|
|
2293
|
+
};
|
|
2294
|
+
}
|
|
2295
|
+
};
|
|
2296
|
+
|
|
2297
|
+
// src/local-stores.ts
|
|
2298
|
+
import { z as z16 } from "zod";
|
|
2299
|
+
import { AdportError as AdportError11 } from "@adport/core";
|
|
2300
|
+
|
|
2301
|
+
// src/local-catalog-schemas.ts
|
|
2302
|
+
import { createHash as createHash8 } from "crypto";
|
|
2303
|
+
import { z as z15 } from "zod";
|
|
2304
|
+
import { AdportError as AdportError10 } from "@adport/core";
|
|
2305
|
+
var localCanonical = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
2306
|
+
var localHash = (value) => createHash8("sha256").update(localCanonical(value)).digest("hex");
|
|
2307
|
+
var localObject = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
2308
|
+
var localScope = z15.object({ account_id: pinterestId, catalog_id: groupId }).strict();
|
|
2309
|
+
var localFailure = (error, ids3 = [], extra = {}) => {
|
|
2310
|
+
const detail = error instanceof AdportError10 ? localObject(error.details) : {};
|
|
2311
|
+
return new AdportError10("PROVIDER_ERROR", "Pinterest local catalog operation is unconfirmed. No mutation was retried. Reconcile known IDs before preparing another approval; native bodies and private links are hidden.", { ...typeof detail.http_status === "number" ? { http_status: detail.http_status } : {}, ...ids3.length ? { resource_ids: [...new Set(ids3)] } : {}, ...extra });
|
|
2312
|
+
};
|
|
2313
|
+
function localBound(value) {
|
|
2314
|
+
if (Buffer.byteLength(localCanonical(value)) > 2 * 1024 * 1024) throw new AdportError10("INVALID_INPUT", "Local catalog request exceeds2MiB; split the batch.");
|
|
2315
|
+
}
|
|
2316
|
+
function publicLocal(value, key = "") {
|
|
2317
|
+
if (Array.isArray(value)) return value.map((item) => publicLocal(item, key));
|
|
2318
|
+
if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([name3, item]) => [name3, publicLocal(item, name3)]));
|
|
2319
|
+
if (typeof value === "string" && /url|link/i.test(key)) {
|
|
2320
|
+
try {
|
|
2321
|
+
return { origin: new URL(value).origin, fingerprint: localHash(value) };
|
|
2322
|
+
} catch {
|
|
2323
|
+
return { fingerprint: localHash(value) };
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
2326
|
+
return value;
|
|
2327
|
+
}
|
|
2328
|
+
var text3 = z15.string().min(1).max(1024);
|
|
2329
|
+
var address = z15.string().max(4096);
|
|
2330
|
+
var localStoreDefinition = z15.object({ store_code: sourceId, name: text3, country: z15.enum(filterEnums.Country), address_primary: address.optional(), address_secondary: address.optional(), city: address.optional(), region: address.optional(), postal_code: address.optional(), latitude: z15.number().min(-90).max(90).optional(), longitude: z15.number().min(-180).max(180).optional() }).strict();
|
|
2331
|
+
var localStoreChanges = localStoreDefinition.partial().extend({ id: groupId }).strict().refine((value) => Object.keys(value).length > 1, "Supply a store setting");
|
|
2332
|
+
var nativeLocalStore = localStoreDefinition.extend({ id: groupId, created_at: z15.string().min(1).max(100), updated_at: z15.string().min(1).max(100) }).loose();
|
|
2333
|
+
var localStoreRemoval = z15.object({ id: groupId, confirm_store_code: sourceId, confirm_name: text3 }).strict();
|
|
2334
|
+
var unique = (values, key) => new Set(values.map(key)).size === values.length;
|
|
2335
|
+
var createStores = z15.array(localStoreDefinition).min(1).max(100).refine((rows) => unique(rows, (row) => row.store_code), "Duplicate store code");
|
|
2336
|
+
var updateStores = z15.array(localStoreChanges).min(1).max(100).refine((rows) => unique(rows, (row) => row.id), "Duplicate store ID");
|
|
2337
|
+
var deleteStores = z15.array(localStoreRemoval).min(1).max(100).refine((rows) => unique(rows, (row) => row.id), "Duplicate store ID");
|
|
2338
|
+
var localStoreAction = z15.discriminatedUnion("kind", [z15.object({ kind: z15.literal("create"), stores: createStores }).strict(), z15.object({ kind: z15.literal("update"), stores: updateStores, acknowledge_store_code_change: z15.literal(true).optional() }).strict(), z15.object({ kind: z15.literal("delete"), stores: deleteStores }).strict()]);
|
|
2339
|
+
var localStoreContext = localScope.extend({ action: localStoreAction });
|
|
2340
|
+
var storeWrite = localScope.omit({ account_id: true }).extend({ expected_context_hash: groupHash, acknowledge_catalog_effects: z15.literal(true), confirm_publication: z15.literal(true) });
|
|
2341
|
+
var localStoreCreate = storeWrite.extend({ stores: createStores });
|
|
2342
|
+
var localStoreUpdate = storeWrite.extend({ stores: updateStores, acknowledge_store_code_change: z15.literal(true).optional() });
|
|
2343
|
+
var localStoreDelete = storeWrite.extend({ stores: deleteStores, confirm_permanent_deletion: z15.literal(true) });
|
|
2344
|
+
var localStoreList = localScope.extend({ store_ids: z15.array(groupId).min(1).max(100).refine((ids3) => new Set(ids3).size === ids3.length).optional(), page_size: z15.number().int().min(1).max(250).default(25), bookmark: z15.string().min(1).max(16384).optional() });
|
|
2345
|
+
var inventoryPair = z15.object({ item_id: sourceId, store_code: sourceId, store_id: groupId }).strict();
|
|
2346
|
+
var inventoryKey = (value) => localCanonical([value.item_id, value.store_code]);
|
|
2347
|
+
var inventoryAttributes = z15.object({ price: z15.string().min(1).max(1024), availability: z15.enum(["in stock", "out of stock", "preorder"]), sale_price: z15.string().min(1).max(1024).optional(), ad_link: z15.string().min(1).max(65536).optional() }).strict();
|
|
2348
|
+
var inventoryUpdate = inventoryAttributes.partial().refine((value) => Object.keys(value).length > 0, "Supply changed attributes");
|
|
2349
|
+
var inventoryOperation = z15.discriminatedUnion("operation", [
|
|
2350
|
+
inventoryPair.extend({ operation: z15.literal("CREATE"), attributes: inventoryAttributes }),
|
|
2351
|
+
inventoryPair.extend({ operation: z15.literal("UPSERT"), attributes: inventoryAttributes }),
|
|
2352
|
+
inventoryPair.extend({ operation: z15.literal("UPDATE"), attributes: inventoryUpdate }),
|
|
2353
|
+
inventoryPair.extend({ operation: z15.literal("DELETE") })
|
|
2354
|
+
]);
|
|
2355
|
+
var inventoryRequest = z15.object({ operations: z15.array(inventoryOperation).min(1).max(1e3).refine((rows) => unique(rows, inventoryKey), "Duplicate item/store pair"), acknowledge_replacement: z15.literal(true).optional(), acknowledge_unconfirmed_existing: z15.literal(true).optional() }).strict();
|
|
2356
|
+
var inventoryContext = localScope.extend(inventoryRequest.shape);
|
|
2357
|
+
var inventoryList = localScope.extend({ item_filters: z15.array(inventoryPair).min(1).max(1e3).refine((rows) => unique(rows, inventoryKey), "Duplicate item/store pair"), limit: z15.number().int().min(1).max(100).default(24), cursor: z15.string().min(1).max(8192).optional() });
|
|
2358
|
+
var inventoryWrite = storeWrite.extend(inventoryRequest.shape).superRefine((value, ctx) => {
|
|
2359
|
+
if (value.operations.some((row) => row.operation === "UPSERT") && !value.acknowledge_replacement) ctx.addIssue({ code: "custom", message: "UPSERT requires full replacement acknowledgement" });
|
|
2360
|
+
if (value.operations.some((row) => row.operation === "DELETE") && !("confirm_permanent_deletion" in value && value.confirm_permanent_deletion)) ctx.addIssue({ code: "custom", message: "DELETE requires confirm_permanent_deletion" });
|
|
2361
|
+
});
|
|
2362
|
+
var inventoryBatch = inventoryWrite.safeExtend({ confirm_permanent_deletion: z15.literal(true).optional() });
|
|
2363
|
+
var inventoryNamed = (operation) => {
|
|
2364
|
+
const item = operation === "CREATE" ? inventoryOperation.options[0].omit({ operation: true }) : operation === "UPSERT" ? inventoryOperation.options[1].omit({ operation: true }) : operation === "UPDATE" ? inventoryOperation.options[2].omit({ operation: true }) : inventoryOperation.options[3].omit({ operation: true });
|
|
2365
|
+
return storeWrite.extend({ items: z15.array(item).min(1).max(1e3), acknowledge_replacement: z15.literal(true).optional(), acknowledge_unconfirmed_existing: z15.literal(true).optional(), confirm_permanent_deletion: z15.literal(true).optional() }).superRefine((value, ctx) => {
|
|
2366
|
+
const { items, ...common2 } = value, result = inventoryBatch.safeParse({ ...common2, operations: items.map((row) => ({ ...row, operation })) });
|
|
2367
|
+
if (!result.success) for (const issue of result.error.issues) ctx.addIssue({ code: "custom", path: issue.path, message: issue.message });
|
|
2368
|
+
});
|
|
2369
|
+
};
|
|
2370
|
+
var inventoryWriteTools = { pinterest_create_local_inventory: "CREATE", pinterest_update_local_inventory: "UPDATE", pinterest_upsert_local_inventory: "UPSERT", pinterest_delete_local_inventory: "DELETE" };
|
|
2371
|
+
var inventoryBatchReference = z15.object({ account_id: pinterestId, batch_receipt: z15.string().min(100).max(2e6) }).strict();
|
|
2372
|
+
|
|
2373
|
+
// src/local-stores.ts
|
|
2374
|
+
var storeValue = (value) => Object.fromEntries(Object.entries(value).filter(([key]) => !["created_at", "updated_at"].includes(key)));
|
|
2375
|
+
var storeNotes = ["Local store metadata can affect local inventory and ads using the catalog. No campaign, budget or bid is changed.", "Current ownership and configuration are rechecked before apply, without a native atomic conditional write. No mutation is replayed after partial, failed or uncertain outcomes.", "Native store-code changes do not establish that existing inventory was migrated. Native deletion has no exposed restore endpoint."];
|
|
2376
|
+
var PinterestLocalStores = class {
|
|
2377
|
+
constructor(client, catalogs) {
|
|
2378
|
+
this.client = client;
|
|
2379
|
+
this.catalogs = catalogs;
|
|
2380
|
+
}
|
|
2381
|
+
client;
|
|
2382
|
+
catalogs;
|
|
2383
|
+
supports(tool) {
|
|
2384
|
+
return ["pinterest_create_local_stores", "pinterest_update_local_stores", "pinterest_delete_local_stores"].includes(tool);
|
|
2385
|
+
}
|
|
2386
|
+
params(account3, extra = {}) {
|
|
2387
|
+
return new URLSearchParams({ ad_account_id: account3, ...extra });
|
|
2388
|
+
}
|
|
2389
|
+
path(catalog2) {
|
|
2390
|
+
return `catalogs/${catalog2}/local_stores`;
|
|
2391
|
+
}
|
|
2392
|
+
async selected(value) {
|
|
2393
|
+
const selection2 = localScope.parse(value), result = await this.catalogs.getCatalog(selection2.account_id, selection2.catalog_id);
|
|
2394
|
+
if (result.catalog.catalog_type !== "RETAIL") throw new AdportError11("INVALID_INPUT", "Local stores/inventory require a RETAIL catalog.");
|
|
2395
|
+
return { selection: selection2, catalog: result.catalog, owner: result.context_hash };
|
|
2396
|
+
}
|
|
2397
|
+
async page(selection2, ids3, size, bookmark) {
|
|
2398
|
+
const data = await this.client.get(this.path(selection2.catalog_id), z16.object({ items: z16.array(nativeLocalStore).max(250), bookmark: z16.string().max(8192).nullable().optional() }), this.params(selection2.account_id, { page_size: String(size), ...ids3 ? { ids: ids3.join(",") } : {}, ...bookmark ? { bookmark } : {} })).catch((error) => {
|
|
2399
|
+
throw localFailure(error);
|
|
2400
|
+
});
|
|
2401
|
+
if (new Set(data.items.map((row) => row.id)).size !== data.items.length || new Set(data.items.map((row) => row.store_code)).size !== data.items.length || ids3 && data.items.some((row) => !ids3.includes(row.id))) throw localFailure();
|
|
2402
|
+
return data;
|
|
2403
|
+
}
|
|
2404
|
+
async list(value) {
|
|
2405
|
+
const input = localStoreList.parse(value), selection2 = localScope.parse({ account_id: input.account_id, catalog_id: input.catalog_id }), parent2 = await this.selected(selection2), key = localHash({ selection: selection2, ids: input.store_ids, size: input.page_size });
|
|
2406
|
+
let bookmark;
|
|
2407
|
+
if (input.bookmark) {
|
|
2408
|
+
let cursor3;
|
|
2409
|
+
try {
|
|
2410
|
+
cursor3 = z16.object({ selection: groupHash, native: z16.string().min(1).max(8192) }).strict().parse(JSON.parse(Buffer.from(input.bookmark, "base64url").toString("utf8")));
|
|
2411
|
+
} catch {
|
|
2412
|
+
throw new AdportError11("INVALID_INPUT", "Invalid local-store cursor.");
|
|
2413
|
+
}
|
|
2414
|
+
if (cursor3.selection !== key) throw new AdportError11("PENDING_MISMATCH", "Local-store selection changed; restart the first page.");
|
|
2415
|
+
bookmark = cursor3.native;
|
|
2416
|
+
}
|
|
2417
|
+
const page2 = await this.page(selection2, input.store_ids, input.page_size, bookmark), complete = page2.bookmark === null ? true : page2.bookmark === void 0 ? null : false;
|
|
2418
|
+
return { records: page2.items.map((row) => ({ ...row, ...publicLocal(row), snapshot_hash: localHash({ selection: selection2, owner: parent2.owner, store: storeValue(row) }) })), complete, truncated: complete !== true, ...page2.bookmark ? { next_cursor: Buffer.from(JSON.stringify({ selection: key, native: page2.bookmark })).toString("base64url") } : {}, notes: ["Only stores in the selected advertiser-owned RETAIL catalog. Missing native bookmarks leave completeness unknown."] };
|
|
2419
|
+
}
|
|
2420
|
+
async gather(selection2, ids3) {
|
|
2421
|
+
const rows = [], seen = /* @__PURE__ */ new Set();
|
|
2422
|
+
let bookmark;
|
|
2423
|
+
for (let page2 = 0; page2 < 40; page2++) {
|
|
2424
|
+
const data = await this.page(selection2, ids3, 250, bookmark);
|
|
2425
|
+
rows.push(...data.items);
|
|
2426
|
+
if (rows.length > 1e4 || new Set(rows.map((row) => row.id)).size !== rows.length || new Set(rows.map((row) => row.store_code)).size !== rows.length) throw localFailure();
|
|
2427
|
+
if (data.bookmark === null) return rows;
|
|
2428
|
+
if (!data.bookmark || seen.has(data.bookmark)) throw new AdportError11("PROVIDER_ERROR", "Complete store inventory is unavailable; no absence or unique-code proof is inferred.");
|
|
2429
|
+
seen.add(data.bookmark);
|
|
2430
|
+
bookmark = data.bookmark;
|
|
2431
|
+
}
|
|
2432
|
+
throw new AdportError11("INVALID_INPUT", "Store lookup exceeded10,000 rows; no mutation is permitted.");
|
|
2433
|
+
}
|
|
2434
|
+
async owned(selection2, ids3) {
|
|
2435
|
+
const unique2 = [...new Set(ids3)], stores = [];
|
|
2436
|
+
for (let offset = 0; offset < unique2.length; offset += 100) stores.push(...await this.gather(selection2, unique2.slice(offset, offset + 100)));
|
|
2437
|
+
if (stores.length !== unique2.length) throw new AdportError11("INVALID_INPUT", "Selected local store was not positively read in this catalog.");
|
|
2438
|
+
return stores.sort((a, b) => a.id.localeCompare(b.id));
|
|
2439
|
+
}
|
|
2440
|
+
async context(value) {
|
|
2441
|
+
const input = localStoreContext.parse(value), parent2 = await this.selected({ account_id: input.account_id, catalog_id: input.catalog_id }), { selection: selection2 } = parent2, action = input.action;
|
|
2442
|
+
localBound(action);
|
|
2443
|
+
const inventory = action.kind === "create" || action.kind === "update" && action.stores.some((row) => row.store_code !== void 0) ? await this.gather(selection2) : void 0, current = action.kind === "create" ? [] : inventory ? inventory.filter((row) => action.stores.some((item) => item.id === row.id)) : await this.owned(selection2, action.stores.map((row) => row.id));
|
|
2444
|
+
if (action.kind !== "create" && current.length !== action.stores.length) throw new AdportError11("INVALID_INPUT", "A selected store is outside the current catalog.");
|
|
2445
|
+
if (action.kind === "create") {
|
|
2446
|
+
if (inventory.length + action.stores.length > 1e4) throw new AdportError11("INVALID_INPUT", "Catalog would exceed10,000 local stores.");
|
|
2447
|
+
if (action.stores.some((row) => inventory.some((old) => old.store_code === row.store_code))) throw new AdportError11("INVALID_INPUT", "CREATE cannot overwrite an existing store code.");
|
|
2448
|
+
}
|
|
2449
|
+
if (action.kind === "update") {
|
|
2450
|
+
const desired = (inventory ?? current).map((row) => ({ id: row.id, code: action.stores.find((item) => item.id === row.id)?.store_code ?? row.store_code }));
|
|
2451
|
+
if (new Set(desired.map((row) => row.code)).size !== desired.length) throw new AdportError11("INVALID_INPUT", "Store code would collide with another store.");
|
|
2452
|
+
if (action.stores.some((row) => row.store_code !== void 0 && row.store_code !== current.find((old) => old.id === row.id).store_code) && !action.acknowledge_store_code_change) throw new AdportError11("INVALID_INPUT", "Store-code changes require acknowledge_store_code_change.");
|
|
2453
|
+
const changed = action.stores.filter((row) => row.store_code !== void 0 && row.store_code !== current.find((old) => old.id === row.id).store_code);
|
|
2454
|
+
if (changed.some((row) => current.some((old) => old.id !== row.id && old.store_code === row.store_code))) throw new AdportError11("INVALID_INPUT", "Store-code swaps require separate reviewed operations; transient native collisions are not assumed safe.");
|
|
2455
|
+
}
|
|
2456
|
+
if (action.kind === "delete" && action.stores.some((row) => current.find((old) => old.id === row.id).store_code !== row.confirm_store_code || current.find((old) => old.id === row.id).name !== row.confirm_name)) throw new AdportError11("PENDING_MISMATCH", "Store name/code changed; read context again.");
|
|
2457
|
+
return { ...parent2, action, current, occupied_ids: inventory?.map((row) => row.id) ?? [], context_hash: localHash({ selection: selection2, owner: parent2.owner, catalog: { id: parent2.catalog.id, name: parent2.catalog.name, type: parent2.catalog.catalog_type }, action, current: current.map(storeValue).sort((a, b) => String(a.id).localeCompare(String(b.id))), ...inventory ? { codes: inventory.map((row) => ({ id: row.id, code: row.store_code })).sort((a, b) => a.id.localeCompare(b.id)) } : {} }), records: current.map((row) => ({ ...row, ...publicLocal(row), snapshot_hash: localHash({ selection: selection2, owner: parent2.owner, store: storeValue(row) }) })), notes: storeNotes };
|
|
2458
|
+
}
|
|
2459
|
+
async publicContext(value) {
|
|
2460
|
+
const data = await this.context(value);
|
|
2461
|
+
return { context_hash: data.context_hash, records: data.records, action: data.action, notes: data.notes };
|
|
2462
|
+
}
|
|
2463
|
+
async plan(op) {
|
|
2464
|
+
const create2 = op.tool === "pinterest_create_local_stores", remove = op.tool === "pinterest_delete_local_stores", kind = create2 ? "create" : remove ? "remove" : "update";
|
|
2465
|
+
if (op.provider !== "pinterest" || !this.supports(op.tool) || op.kind !== kind) throw new AdportError11("INVALID_INPUT", "Invalid local-store mutation kind.");
|
|
2466
|
+
const input = create2 ? localStoreCreate.parse(op.payload) : remove ? localStoreDelete.parse(op.payload) : localStoreUpdate.parse(op.payload), selection2 = { account_id: op.accountId, catalog_id: input.catalog_id }, action = { kind: create2 ? "create" : remove ? "delete" : "update", stores: input.stores, ..."acknowledge_store_code_change" in input ? { acknowledge_store_code_change: input.acknowledge_store_code_change } : {} };
|
|
2467
|
+
const prepare = async () => {
|
|
2468
|
+
const data = await this.context({ ...selection2, action });
|
|
2469
|
+
if (data.context_hash !== input.expected_context_hash) throw new AdportError11("PENDING_MISMATCH", "Local store selection, owner or configuration changed; preview again.");
|
|
2470
|
+
return data;
|
|
2471
|
+
}, before = await prepare();
|
|
2472
|
+
let details;
|
|
2473
|
+
const title = create2 ? "Create local stores" : remove ? "Delete local stores permanently" : "Update local stores";
|
|
2474
|
+
return {
|
|
2475
|
+
summary: `${title} \xB7 ${action.stores.length}`,
|
|
2476
|
+
changes: action.stores.map((row) => create2 ? `CREATE ${"store_code" in row ? row.store_code : ""}` : `${remove ? "DELETE" : "UPDATE"} ${"id" in row ? row.id : ""}`),
|
|
2477
|
+
coercions: [],
|
|
2478
|
+
budgetDeltas: [],
|
|
2479
|
+
notes: storeNotes,
|
|
2480
|
+
review: { provider: "pinterest", accountId: op.accountId, kind: op.kind, title, subject: before.catalog.name, fields: action.stores.map((row) => ({ label: create2 ? String("store_code" in row ? row.store_code : "") : String("id" in row ? row.id : ""), ...create2 ? {} : { before: publicLocal(storeValue(before.current.find((old) => old.id === ("id" in row ? row.id : "")))) }, after: remove ? "Remove local store" : row })), notices: storeNotes },
|
|
2481
|
+
execute: async () => {
|
|
2482
|
+
const fresh = await prepare(), known = new Set(fresh.current.map((row) => row.id));
|
|
2483
|
+
let records2 = [];
|
|
2484
|
+
try {
|
|
2485
|
+
const raw = await this.client.mutate(this.path(selection2.catalog_id), create2 ? "POST" : remove ? "DELETE" : "PATCH", remove ? void 0 : input.stores, z16.unknown(), this.params(op.accountId, remove ? { ids: input.stores.map((row) => row.id).join(",") } : {}));
|
|
2486
|
+
if (remove) {
|
|
2487
|
+
if (raw !== void 0) {
|
|
2488
|
+
if (!Array.isArray(raw) || raw.length !== action.stores.length) throw localFailure();
|
|
2489
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2490
|
+
for (const value of raw) {
|
|
2491
|
+
const row = localObject(value), id4 = z16.string().regex(/^\d{1,30}$/).parse(row.id);
|
|
2492
|
+
if (!known.has(id4) || seen.has(id4)) throw localFailure();
|
|
2493
|
+
seen.add(id4);
|
|
2494
|
+
const status = localObject(row.status);
|
|
2495
|
+
records2.push({ id: id4, native_status: status.statusCode === 204 && status.code === void 0 && status.message === void 0 ? "SUCCESS" : "FAILURE" });
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
const remaining = await this.gather(selection2, [...known]);
|
|
2499
|
+
records2 = fresh.current.map((row) => ({ id: row.id, name: row.name, status: remaining.some((value) => value.id === row.id) ? "STILL_PRESENT" : "ABSENT_FROM_COMPLETE_FILTERED_LIST", native_status: raw === void 0 ? "HTTP204" : records2.find((value) => value.id === row.id)?.native_status ?? "UNCONFIRMED" }));
|
|
2500
|
+
if (records2.some((row) => row.status !== "ABSENT_FROM_COMPLETE_FILTERED_LIST" || row.native_status === "FAILURE")) throw localFailure(void 0, [...known], { records: records2 });
|
|
2501
|
+
} else {
|
|
2502
|
+
if (!Array.isArray(raw) || raw.length !== action.stores.length) {
|
|
2503
|
+
if (Array.isArray(raw)) for (const value of raw) {
|
|
2504
|
+
const id4 = localObject(localObject(value).data ?? value).id;
|
|
2505
|
+
if (typeof id4 === "string" && /^\d{1,30}$/.test(id4)) known.add(id4);
|
|
2506
|
+
}
|
|
2507
|
+
throw localFailure();
|
|
2508
|
+
}
|
|
2509
|
+
const returned = [], seen = /* @__PURE__ */ new Set();
|
|
2510
|
+
for (const value of raw) {
|
|
2511
|
+
const row = localObject(localObject(value).data ?? value), id4 = typeof row.id === "string" && /^\d{1,30}$/.test(row.id) ? row.id : void 0;
|
|
2512
|
+
if (id4) known.add(id4);
|
|
2513
|
+
if (row.exceptions !== void 0) {
|
|
2514
|
+
const code = localObject(row.exceptions).code;
|
|
2515
|
+
records2.push({ id: id4 ?? "UNCONFIRMED", status: "FAILURE", native_error: true, ...typeof code === "number" && Number.isSafeInteger(code) ? { error_code: code } : {} });
|
|
2516
|
+
continue;
|
|
2517
|
+
}
|
|
2518
|
+
const store = nativeLocalStore.parse(row);
|
|
2519
|
+
if (create2 && fresh.occupied_ids.includes(store.id) || seen.has(store.id) || returned.some((old) => old.store_code === store.store_code) || !create2 && !fresh.current.some((old) => old.id === store.id) || create2 && !action.stores.some((item) => item.store_code === store.store_code)) throw localFailure();
|
|
2520
|
+
seen.add(store.id);
|
|
2521
|
+
returned.push(store);
|
|
2522
|
+
}
|
|
2523
|
+
const actual = returned.length ? await this.owned(selection2, returned.map((row) => row.id)) : [];
|
|
2524
|
+
for (const store of actual) {
|
|
2525
|
+
const expected = create2 ? action.stores.find((row) => row.store_code === store.store_code) : action.stores.find((row) => row.id === store.id), previous = fresh.current.find((row) => row.id === store.id), matches = expected && Object.entries(expected).every(([key, value]) => localCanonical(store[key]) === localCanonical(value)), preserved3 = !previous || Object.entries(storeValue(previous)).every(([key, value]) => expected && Object.hasOwn(expected, key) || localCanonical(store[key]) === localCanonical(value));
|
|
2526
|
+
records2.push({ id: store.id, name: store.name, store_code: store.store_code, status: matches && preserved3 ? "REQUESTED_CONFIGURATION_VERIFIED" : "CONFIGURATION_UNCONFIRMED", omitted_fields_preserved: previous ? preserved3 : void 0 });
|
|
2527
|
+
}
|
|
2528
|
+
if (records2.length !== action.stores.length || records2.some((row) => row.status !== "REQUESTED_CONFIGURATION_VERIFIED")) throw localFailure(void 0, [...known], { records: records2 });
|
|
2529
|
+
}
|
|
2530
|
+
details = { status: "COMPLETE", records: records2, configuration_verified: true, publication_verified: false };
|
|
2531
|
+
return records2.map((row) => String(row.id));
|
|
2532
|
+
} catch (error) {
|
|
2533
|
+
const data = error instanceof AdportError11 ? localObject(error.details) : {};
|
|
2534
|
+
throw localFailure(error, [...known], { ...data.records ? { records: data.records } : records2.length ? { records: records2 } : {} });
|
|
2535
|
+
}
|
|
2536
|
+
},
|
|
2537
|
+
resultDetails: () => publicLocal(details),
|
|
2538
|
+
resultWarnings: () => storeNotes
|
|
2539
|
+
};
|
|
2540
|
+
}
|
|
2541
|
+
};
|
|
2542
|
+
|
|
2543
|
+
// src/local-inventory.ts
|
|
2544
|
+
import { z as z17 } from "zod";
|
|
2545
|
+
import { AdportError as AdportError12 } from "@adport/core";
|
|
2546
|
+
var batchId2 = z17.string().regex(/^[A-Za-z0-9_-]{1,100}$/);
|
|
2547
|
+
var nativeBatch2 = z17.object({ batch_id: batchId2, created_time: z17.string().min(1).max(100), completed_time: z17.string().max(100).optional(), status: z17.enum(["PROCESSING", "COMPLETED", "FAILED"]), operation_results: z17.array(z17.record(z17.string(), z17.json())).max(1e3) });
|
|
2548
|
+
var manifestRow2 = inventoryPair.extend({ operation: itemOperation, desired_keys: z17.array(z17.enum(["price", "sale_price", "availability", "ad_link"])).max(4), desired_hash: groupHash.optional(), preserved_hash: groupHash.optional() });
|
|
2549
|
+
var receiptSchema2 = localScope.extend({ version: z17.literal("pinterest_local_inventory_v1"), scope_id: z17.string().min(1).max(200), owner_context_hash: groupHash, batch_id: batchId2, expires_at: z17.number().int().safe(), manifest: z17.array(manifestRow2).min(1).max(1e3) }).strict();
|
|
2550
|
+
var notes3 = ["Local inventory uses item_id plus store_code in an explicitly selected advertiser-owned RETAIL catalog. Store IDs are verified but never added to native operation bodies. No country/language field is invented.", "Inventory changes can affect price, availability and links used by existing local ads. No campaign, bid or budget is changed. UPSERT supplies the full replacement attributes.", "Missing query rows do not establish absence. Batch acceptance, each pair\u2019s processing result, independent readback and final publication/eligibility are separate observations. Native conditional writes and automatic mutation replay are not available."];
|
|
2551
|
+
var readAttrs = (row) => Object.fromEntries(Object.entries(row).filter(([key]) => !["item_id", "store_metadata", "created_at", "last_updated_time"].includes(key)));
|
|
2552
|
+
var preserved2 = (row, keys) => Object.fromEntries(Object.entries(row).filter(([key]) => !keys.includes(key)));
|
|
2553
|
+
var diagnostics2 = (value) => z17.array(z17.object({ attribute: z17.string().max(256), code: z17.number().int().min(-2147483648).max(2147483647), message: z17.string().max(1e5) })).max(1e4).parse(value ?? []).map(({ message, ...row }) => ({ ...row, message_present: !!message }));
|
|
2554
|
+
var PinterestLocalInventory = class {
|
|
2555
|
+
constructor(client, stores, media) {
|
|
2556
|
+
this.client = client;
|
|
2557
|
+
this.stores = stores;
|
|
2558
|
+
this.media = media;
|
|
2559
|
+
}
|
|
2560
|
+
client;
|
|
2561
|
+
stores;
|
|
2562
|
+
media;
|
|
2563
|
+
supports(tool) {
|
|
2564
|
+
return tool === "pinterest_apply_local_inventory_batch" || Object.hasOwn(inventoryWriteTools, tool);
|
|
2565
|
+
}
|
|
2566
|
+
scopeId() {
|
|
2567
|
+
const value = this.media.scopeId;
|
|
2568
|
+
return typeof value === "string" && value ? value : "local";
|
|
2569
|
+
}
|
|
2570
|
+
path(catalog2) {
|
|
2571
|
+
return `catalogs/${catalog2}/local_inventory_items`;
|
|
2572
|
+
}
|
|
2573
|
+
async selected(selection2, pairs) {
|
|
2574
|
+
const parent2 = await this.stores.selected(selection2), stores = await this.stores.owned(selection2, pairs.map((row) => row.store_id));
|
|
2575
|
+
if (pairs.some((pair) => stores.find((store) => store.id === pair.store_id)?.store_code !== pair.store_code)) throw new AdportError12("PENDING_MISMATCH", "Selected store ID/code does not match the current catalog.");
|
|
2576
|
+
return { ...parent2, stores };
|
|
2577
|
+
}
|
|
2578
|
+
async readSet(selection2, pairs) {
|
|
2579
|
+
const data = await this.client.mutate(this.path(selection2.catalog_id) + "/query", "POST", { item_filters: pairs.map(({ item_id, store_code }) => ({ item_id, store_code })) }, z17.object({ items: z17.array(z17.record(z17.string(), z17.json())).max(1e3) }), this.stores.params(selection2.account_id)).catch((error) => {
|
|
2580
|
+
throw localFailure(error);
|
|
2581
|
+
}), seen = /* @__PURE__ */ new Map();
|
|
2582
|
+
for (const raw of data.items) {
|
|
2583
|
+
inventoryAttributes.partial().loose().parse(raw);
|
|
2584
|
+
const item_id = sourceId.parse(raw.item_id), metadata = z17.looseObject({ store_id: z17.string().regex(/^\d{1,30}$/), store_code: sourceId }).parse(raw.store_metadata), key = inventoryKey({ item_id, store_code: metadata.store_code }), pair = pairs.find((row) => inventoryKey(row) === key);
|
|
2585
|
+
if (!pair || metadata.store_id !== pair.store_id || seen.has(key) || raw.catalog_id !== void 0 && raw.catalog_id !== selection2.catalog_id) throw localFailure();
|
|
2586
|
+
z17.number().int().safe().parse(raw.created_at);
|
|
2587
|
+
z17.number().int().safe().parse(raw.last_updated_time);
|
|
2588
|
+
seen.set(key, { pair, state: "PRESENT", attributes: readAttrs(raw), metadata });
|
|
2589
|
+
}
|
|
2590
|
+
return pairs.map((pair) => seen.get(inventoryKey(pair)) ?? { pair, state: "NOT_RETURNED" });
|
|
2591
|
+
}
|
|
2592
|
+
record(row) {
|
|
2593
|
+
return { id: localHash([row.pair.item_id, row.pair.store_code]), name: row.pair.item_id + " \xB7 " + row.pair.store_code, ...row.pair, status: row.state, attributes: publicLocal(row.attributes), store_metadata: row.metadata };
|
|
2594
|
+
}
|
|
2595
|
+
async list(value) {
|
|
2596
|
+
const input = inventoryList.parse(value), selection2 = localScope.parse({ account_id: input.account_id, catalog_id: input.catalog_id }), key = localHash({ selection: selection2, pairs: input.item_filters, size: input.limit });
|
|
2597
|
+
let offset = 0;
|
|
2598
|
+
if (input.cursor) {
|
|
2599
|
+
let cursor3;
|
|
2600
|
+
try {
|
|
2601
|
+
cursor3 = z17.object({ selection: groupHash, offset: z17.number().int().min(1).max(999) }).strict().parse(JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8")));
|
|
2602
|
+
} catch {
|
|
2603
|
+
throw new AdportError12("INVALID_INPUT", "Invalid local-inventory cursor.");
|
|
2604
|
+
}
|
|
2605
|
+
if (cursor3.selection !== key || cursor3.offset >= input.item_filters.length) throw new AdportError12("PENDING_MISMATCH", "Local-inventory selection changed; restart the first page.");
|
|
2606
|
+
offset = cursor3.offset;
|
|
2607
|
+
}
|
|
2608
|
+
const pairs = input.item_filters.slice(offset, offset + input.limit);
|
|
2609
|
+
await this.selected(selection2, pairs);
|
|
2610
|
+
const current = await this.readSet(selection2, pairs), next = offset + pairs.length;
|
|
2611
|
+
return { records: current.map((row) => this.record(row)), truncated: next < input.item_filters.length, ...next < input.item_filters.length ? { next_cursor: Buffer.from(JSON.stringify({ selection: key, offset: next })).toString("base64url") } : {}, notes: [...notes3, "Paging covers only the requested item/store pairs, not all inventory in the catalog."] };
|
|
2612
|
+
}
|
|
2613
|
+
manifest(request, current) {
|
|
2614
|
+
const result = request.operations.map((row) => {
|
|
2615
|
+
const pair = inventoryPair.parse({ item_id: row.item_id, store_code: row.store_code, store_id: row.store_id }), attributes = "attributes" in row ? row.attributes : void 0, keys = Object.keys(attributes ?? {}), before = current.find((old) => inventoryKey(old.pair) === inventoryKey(pair));
|
|
2616
|
+
return { ...pair, operation: row.operation, desired_keys: keys, ...attributes ? { desired_hash: localHash(attributes) } : {}, ...row.operation === "UPDATE" ? { preserved_hash: localHash(preserved2(before.attributes, keys)) } : {} };
|
|
2617
|
+
});
|
|
2618
|
+
if (Buffer.byteLength(localCanonical(result)) > 1e6) throw new AdportError12("INVALID_INPUT", "Local-inventory receipt exceeds its bound; split the batch.");
|
|
2619
|
+
return result;
|
|
2620
|
+
}
|
|
2621
|
+
async context(value) {
|
|
2622
|
+
const input = inventoryContext.parse(value), selection2 = localScope.parse({ account_id: input.account_id, catalog_id: input.catalog_id }), request = inventoryRequest.parse({ operations: input.operations, acknowledge_replacement: input.acknowledge_replacement, acknowledge_unconfirmed_existing: input.acknowledge_unconfirmed_existing });
|
|
2623
|
+
localBound(request);
|
|
2624
|
+
const pairs = request.operations.map((row) => inventoryPair.parse({ item_id: row.item_id, store_code: row.store_code, store_id: row.store_id })), parent2 = await this.selected(selection2, pairs), current = await this.readSet(selection2, pairs);
|
|
2625
|
+
for (const row of request.operations) {
|
|
2626
|
+
const before = current.find((old) => inventoryKey(old.pair) === inventoryKey(row));
|
|
2627
|
+
if (row.operation === "CREATE" && before.state === "PRESENT") throw new AdportError12("INVALID_INPUT", "CREATE cannot overwrite a positively read local item/store pair.");
|
|
2628
|
+
if (["UPDATE", "DELETE"].includes(row.operation) && before.state !== "PRESENT") throw new AdportError12("INVALID_INPUT", "UPDATE/DELETE require a positively read current item/store pair.");
|
|
2629
|
+
if (row.operation === "UPSERT" && !request.acknowledge_replacement) throw new AdportError12("INVALID_INPUT", "UPSERT requires acknowledge_replacement.");
|
|
2630
|
+
if (["CREATE", "UPSERT"].includes(row.operation) && before.state !== "PRESENT" && !request.acknowledge_unconfirmed_existing) throw new AdportError12("INVALID_INPUT", "Missing query rows do not prove absence; acknowledge_unconfirmed_existing is required.");
|
|
2631
|
+
}
|
|
2632
|
+
const scope_id = this.scopeId(), manifest = this.manifest(request, current);
|
|
2633
|
+
return { ...parent2, request, current, manifest, scope_id, context_hash: localHash({ selection: selection2, owner: parent2.owner, catalog: { id: parent2.catalog.id, name: parent2.catalog.name, type: parent2.catalog.catalog_type }, stores: parent2.stores.map(({ created_at: _created, updated_at: _updated, ...row }) => row), request, current, scope_id }), records: current.map((row) => this.record(row)), notes: notes3 };
|
|
2634
|
+
}
|
|
2635
|
+
async publicContext(value) {
|
|
2636
|
+
const result = await this.context(value);
|
|
2637
|
+
return { context_hash: result.context_hash, records: result.records, changes: result.request.operations.map((row) => publicLocal(row)), notes: [...notes3, "CREATE duplicate handling is native; Adport does not claim atomic absence or promise that a missing query proves a new pair."] };
|
|
2638
|
+
}
|
|
2639
|
+
batchRows(data, manifest) {
|
|
2640
|
+
const found = /* @__PURE__ */ new Map();
|
|
2641
|
+
for (const raw of data.operation_results) {
|
|
2642
|
+
const pair = z17.object({ item_id: sourceId, store_code: sourceId, supplemental_type: z17.literal("LOCAL_INVENTORY"), status: z17.enum(["SUCCESS", "FAILURE", "PROCESSING"]) }).parse(raw), key = inventoryKey(pair), expected = manifest.find((row) => inventoryKey(row) === key), errors = diagnostics2(raw.errors), warnings = diagnostics2(raw.warnings);
|
|
2643
|
+
if (!expected || found.has(key) || pair.status === "SUCCESS" && (errors.length || data.status === "FAILED")) throw localFailure();
|
|
2644
|
+
found.set(key, { id: localHash([pair.item_id, pair.store_code]), name: pair.item_id + " \xB7 " + pair.store_code, item_id: pair.item_id, store_code: pair.store_code, store_id: expected.store_id, status: pair.status, errors, warnings });
|
|
2645
|
+
}
|
|
2646
|
+
return manifest.map((row) => found.get(inventoryKey(row)) ?? { id: localHash([row.item_id, row.store_code]), name: row.item_id + " \xB7 " + row.store_code, item_id: row.item_id, store_code: row.store_code, store_id: row.store_id, status: data.status === "FAILED" ? "BATCH_FAILED" : "UNCONFIRMED", errors: [], warnings: [] });
|
|
2647
|
+
}
|
|
2648
|
+
async verifiedReceipt(value) {
|
|
2649
|
+
const input = inventoryBatchReference.parse(value), proof = receiptSchema2.parse(this.client.verifyCatalogBatchReceipt(input.batch_receipt));
|
|
2650
|
+
if (proof.account_id !== input.account_id || proof.scope_id !== this.scopeId() || proof.expires_at <= Math.floor(Date.now() / 1e3) || proof.expires_at > Math.floor(Date.now() / 1e3) + 30 * 86400) throw new AdportError12("INVALID_INPUT", "Local-inventory receipt expired or belongs to another advertiser/project.");
|
|
2651
|
+
const parent2 = await this.stores.selected({ account_id: proof.account_id, catalog_id: proof.catalog_id });
|
|
2652
|
+
if (parent2.owner !== proof.owner_context_hash) throw new AdportError12("POLICY_VIOLATION", "Local-inventory catalog ownership changed.");
|
|
2653
|
+
return proof;
|
|
2654
|
+
}
|
|
2655
|
+
async status(value, reconcile = false) {
|
|
2656
|
+
const proof = await this.verifiedReceipt(value), data = await this.client.get(`catalogs/${proof.catalog_id}/supplemental_items/batch/${proof.batch_id}`, nativeBatch2, this.stores.params(proof.account_id)).catch((error) => {
|
|
2657
|
+
throw localFailure(error, [proof.batch_id]);
|
|
2658
|
+
});
|
|
2659
|
+
if (data.batch_id !== proof.batch_id) throw localFailure();
|
|
2660
|
+
const records2 = this.batchRows(data, proof.manifest);
|
|
2661
|
+
let readback_error;
|
|
2662
|
+
if (reconcile) try {
|
|
2663
|
+
await this.selected({ account_id: proof.account_id, catalog_id: proof.catalog_id }, proof.manifest);
|
|
2664
|
+
const current = await this.readSet({ account_id: proof.account_id, catalog_id: proof.catalog_id }, proof.manifest);
|
|
2665
|
+
for (const record2 of records2) {
|
|
2666
|
+
const expected = proof.manifest.find((row) => inventoryKey(row) === inventoryKey(record2)), actual = current.find((row) => inventoryKey(row.pair) === inventoryKey(expected));
|
|
2667
|
+
record2.observed_state = actual.state;
|
|
2668
|
+
if (record2.status !== "SUCCESS") {
|
|
2669
|
+
record2.readback = "NATIVE_ITEM_NOT_SUCCESSFUL";
|
|
2670
|
+
continue;
|
|
2671
|
+
}
|
|
2672
|
+
if (expected.operation === "DELETE") {
|
|
2673
|
+
record2.readback = actual.state === "PRESENT" ? "STILL_PRESENT" : "ABSENCE_UNCONFIRMED";
|
|
2674
|
+
continue;
|
|
2675
|
+
}
|
|
2676
|
+
if (!actual.attributes) {
|
|
2677
|
+
record2.readback = "CURRENT_PAIR_UNCONFIRMED";
|
|
2678
|
+
continue;
|
|
2679
|
+
}
|
|
2680
|
+
const attrs = Object.fromEntries(expected.desired_keys.map((key) => [key, actual.attributes[key]])), matches = localHash(attrs) === expected.desired_hash, retains = !expected.preserved_hash || localHash(preserved2(actual.attributes, expected.desired_keys)) === expected.preserved_hash;
|
|
2681
|
+
record2.readback = matches && retains ? "REQUESTED_CONFIGURATION_VERIFIED" : "CONFIGURATION_UNCONFIRMED";
|
|
2682
|
+
record2.omitted_fields_preserved = expected.preserved_hash ? retains : void 0;
|
|
2683
|
+
}
|
|
2684
|
+
} catch (error) {
|
|
2685
|
+
const detail = error instanceof AdportError12 ? localObject(error.details) : {};
|
|
2686
|
+
readback_error = { status: "READBACK_UNAVAILABLE", ...typeof detail.http_status === "number" ? { http_status: detail.http_status } : {} };
|
|
2687
|
+
}
|
|
2688
|
+
return { batch_id: proof.batch_id, status: data.status, records: records2, submitted_items: proof.manifest.length, terminal_items: records2.filter((row) => ["SUCCESS", "FAILURE", "BATCH_FAILED"].includes(String(row.status))).length, all_items_native_successful: data.status === "COMPLETED" && records2.every((row) => row.status === "SUCCESS"), ...readback_error ? { readback_error } : {}, publication_verified: false, notes: notes3 };
|
|
2689
|
+
}
|
|
2690
|
+
async plan(op) {
|
|
2691
|
+
const operation = inventoryWriteTools[op.tool], kind = operation === "CREATE" ? "create" : operation === "DELETE" ? "remove" : "update";
|
|
2692
|
+
if (op.provider !== "pinterest" || !this.supports(op.tool) || op.kind !== kind) throw new AdportError12("INVALID_INPUT", "Invalid local-inventory mutation kind.");
|
|
2693
|
+
const parsed = operation ? inventoryNamed(operation).parse(op.payload) : inventoryBatch.parse(op.payload), selection2 = { account_id: op.accountId, catalog_id: parsed.catalog_id }, request = inventoryRequest.parse({ operations: "operations" in parsed ? parsed.operations : parsed.items.map((row) => ({ ...row, operation })), acknowledge_replacement: parsed.acknowledge_replacement, acknowledge_unconfirmed_existing: parsed.acknowledge_unconfirmed_existing });
|
|
2694
|
+
const prepare = async () => {
|
|
2695
|
+
const result = await this.context({ ...selection2, ...request });
|
|
2696
|
+
if (result.context_hash !== parsed.expected_context_hash) throw new AdportError12("PENDING_MISMATCH", "Local inventory, store, owner, project or request changed; preview again.");
|
|
2697
|
+
return result;
|
|
2698
|
+
}, before = await prepare();
|
|
2699
|
+
let details;
|
|
2700
|
+
return {
|
|
2701
|
+
summary: `Submit local inventory batch \xB7 ${request.operations.length} item/store pairs`,
|
|
2702
|
+
changes: request.operations.map((row) => `${row.operation} ${row.item_id} \xB7 ${row.store_code}`),
|
|
2703
|
+
coercions: [],
|
|
2704
|
+
budgetDeltas: [],
|
|
2705
|
+
notes: notes3,
|
|
2706
|
+
review: { provider: "pinterest", accountId: op.accountId, kind: op.kind, title: "Submit local inventory batch", subject: before.catalog.name, fields: request.operations.map((row) => ({ label: row.item_id + " \xB7 " + row.store_code, before: publicLocal(before.current.find((old) => inventoryKey(old.pair) === inventoryKey(row)).attributes) ?? "Current pair unconfirmed; absence not inferred", after: row.operation === "DELETE" ? "Remove local inventory pair" : publicLocal(row.attributes) })), notices: notes3 },
|
|
2707
|
+
execute: async () => {
|
|
2708
|
+
const fresh = await prepare();
|
|
2709
|
+
let id4;
|
|
2710
|
+
try {
|
|
2711
|
+
if (fresh.scope_id !== this.scopeId()) throw localFailure();
|
|
2712
|
+
const native = await this.client.mutate(this.path(selection2.catalog_id) + "/batch", "POST", { operations: request.operations.map(({ store_id: _store, ...row }) => row) }, nativeBatch2, this.stores.params(op.accountId));
|
|
2713
|
+
id4 = native.batch_id;
|
|
2714
|
+
const batch_receipt = this.client.catalogBatchReceipt({ ...selection2, version: "pinterest_local_inventory_v1", scope_id: fresh.scope_id, owner_context_hash: fresh.owner, batch_id: id4, expires_at: Math.floor(Date.now() / 1e3) + 30 * 86400, manifest: fresh.manifest }), records2 = this.batchRows(native, fresh.manifest);
|
|
2715
|
+
if (native.status === "FAILED" || records2.every((row) => row.status === "FAILURE")) throw localFailure(void 0, [id4], { batch_receipt, records: records2, native_status: native.status });
|
|
2716
|
+
details = { status: "ACCEPTED_FOR_PROCESSING", processed: false, native_status: native.status, batch_id: id4, batch_receipt, records: records2, configuration_verified: false, publication_verified: false, next_tool: "pinterest_local_inventory_batch_status", next_arguments: { account_id: op.accountId, batch_receipt } };
|
|
2717
|
+
return [id4];
|
|
2718
|
+
} catch (error) {
|
|
2719
|
+
const extra = error instanceof AdportError12 ? localObject(error.details) : {};
|
|
2720
|
+
throw localFailure(error, id4 ? [id4] : Array.isArray(extra.resource_ids) ? extra.resource_ids : [], extra.batch_receipt ? { batch_receipt: extra.batch_receipt, records: extra.records, native_status: extra.native_status } : {});
|
|
2721
|
+
}
|
|
2722
|
+
},
|
|
2723
|
+
resultDetails: () => details,
|
|
2724
|
+
resultWarnings: () => notes3
|
|
2725
|
+
};
|
|
2726
|
+
}
|
|
2727
|
+
};
|
|
2728
|
+
|
|
2729
|
+
// src/campaign-budgets.ts
|
|
2730
|
+
import { z as z18 } from "zod";
|
|
2731
|
+
import { AdportError as AdportError13, defineTool as defineTool7, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
|
|
2732
|
+
var campaignBudgetContext = z18.object({ account_id: pinterestId, campaign_id: pinterestId }).strict();
|
|
2733
|
+
var campaignDailyBudget = z18.object({ campaign_id: pinterestId, expected_context_hash: groupHash, daily_budget_mode: z18.enum(["FIXED", "AVERAGE"]), budget_micros: z18.number().int().positive().safe().optional(), acknowledge_variable_daily_spend: z18.literal(true).optional(), acknowledge_averaging_reset: z18.literal(true).optional() }).strict().superRefine((value, ctx) => {
|
|
2734
|
+
if (value.daily_budget_mode === "AVERAGE" && (!value.acknowledge_variable_daily_spend || !value.acknowledge_averaging_reset)) ctx.addIssue({ code: "custom", message: "AVERAGE requires variable-spend and averaging-reset acknowledgements." });
|
|
2735
|
+
});
|
|
2736
|
+
var notes4 = ["Policy caps apply to the configured budget amount in account-currency micros, not a guaranteed ceiling on actual daily delivery spend. The averaging mode is shown separately; no safety multiplier or currency conversion is invented.", "Average daily spend can vary by day. Pinterest averages Sunday through Saturday, with shortened periods after launch, edits, unpausing or an early campaign end. Earlier spend is not deducted from an edited averaging period, and same-day spend can include both old and new allocations.", "Pinterest describes125% as a delivery target, not a guaranteed daily maximum. This budget flag alone does not configure a full Performance+ campaign. No status, bid, targeting, schedule or child budget is changed by the daily-budget tool.", "Preview is local. Current configuration is rechecked before apply, with independent native readback afterward. There is no native atomic conditional write or automatic mutation replay."];
|
|
2737
|
+
var failure2 = (error, ids3 = [], extra = {}) => new AdportError13("PROVIDER_ERROR", "Pinterest campaign budget outcome is unconfirmed. No mutation was retried; reconcile known campaign IDs before another preview. Native bodies are hidden.", { ...ids3.length ? { resource_ids: [...new Set(ids3)] } : {}, ...error instanceof AdportError13 && Array.isArray(localObject(error.details).native_errors) ? { native_errors: localObject(error.details).native_errors } : {}, ...error instanceof AdportError13 && typeof localObject(error.details).verification_phase === "string" ? { verification_phase: localObject(error.details).verification_phase } : {}, ...extra, ...error instanceof AdportError13 && typeof localObject(error.details).api_code === "number" && Number.isSafeInteger(localObject(error.details).api_code) ? { api_code: localObject(error.details).api_code } : {}, ...error instanceof AdportError13 && typeof localObject(error.details).http_status === "number" ? { http_status: localObject(error.details).http_status } : {} });
|
|
2738
|
+
var configuration2 = (campaign) => Object.fromEntries(Object.entries(campaign).filter(([key]) => !["created_time", "updated_time", "summary_status"].includes(key)).map(([key, value]) => [key, ["daily_spend_cap", "lifetime_spend_cap"].includes(key) ? value ?? 0 : value]));
|
|
2739
|
+
var PinterestCampaignBudgets = class {
|
|
2740
|
+
constructor(client, campaign, projectScope) {
|
|
2741
|
+
this.client = client;
|
|
2742
|
+
this.campaign = campaign;
|
|
2743
|
+
this.projectScope = projectScope;
|
|
2744
|
+
}
|
|
2745
|
+
client;
|
|
2746
|
+
campaign;
|
|
2747
|
+
projectScope;
|
|
2748
|
+
supports(tool) {
|
|
2749
|
+
return tool === "pinterest_set_campaign_daily_budget";
|
|
2750
|
+
}
|
|
2751
|
+
async account(account3) {
|
|
2752
|
+
const result = await this.client.get(`ad_accounts/${pinterestId.parse(account3)}`, accountSchema);
|
|
2753
|
+
if (result.id !== account3) throw failure2();
|
|
2754
|
+
return { id: result.id, currency: result.currency, country: typeof result.country === "string" ? result.country : void 0, owner_fingerprint: typeof localObject(result.owner).username === "string" ? localHash(String(localObject(result.owner).username).toLowerCase()) : void 0 };
|
|
2755
|
+
}
|
|
2756
|
+
currency(value) {
|
|
2757
|
+
if (typeof value !== "string" || !/^[A-Z]{3}$/.test(value)) throw new AdportError13("INVALID_INPUT", "Native account currency is unavailable; no monetary mutation is permitted.");
|
|
2758
|
+
return value;
|
|
2759
|
+
}
|
|
2760
|
+
mode(value) {
|
|
2761
|
+
const daily = value.daily_spend_cap ?? 0, lifetime = value.lifetime_spend_cap ?? 0;
|
|
2762
|
+
if (value.is_campaign_budget_optimization !== true) return "NOT_CAMPAIGN_BUDGETED";
|
|
2763
|
+
if (daily > 0 === lifetime > 0) return "AMBIGUOUS";
|
|
2764
|
+
if (lifetime > 0) return value.is_flexible_daily_budgets === true ? "AMBIGUOUS" : "LIFETIME";
|
|
2765
|
+
return value.is_flexible_daily_budgets === true ? "AVERAGE" : value.is_flexible_daily_budgets === false ? "FIXED" : "DAILY_MODE_UNCONFIRMED";
|
|
2766
|
+
}
|
|
2767
|
+
async context(value) {
|
|
2768
|
+
const input = campaignBudgetContext.parse(value), account3 = await this.account(input.account_id), current = await this.campaign(input.account_id, input.campaign_id), mode = this.mode(current), scope = this.projectScope();
|
|
2769
|
+
return { account: account3, current, mode, scope, context_hash: localHash({ input, account: account3, current: configuration2(current), scope }), records: [{ id: current.id, name: current.name ?? current.id, status: current.status, budget_mode: mode, budget_micros: mode === "LIFETIME" ? current.lifetime_spend_cap : current.daily_spend_cap, currency: account3.currency, is_campaign_budget_optimization: current.is_campaign_budget_optimization, is_flexible_daily_budgets: current.is_flexible_daily_budgets }], notes: notes4 };
|
|
2770
|
+
}
|
|
2771
|
+
async publicContext(value) {
|
|
2772
|
+
const result = await this.context(value);
|
|
2773
|
+
return { context_hash: result.context_hash, records: result.records, notes: notes4 };
|
|
2774
|
+
}
|
|
2775
|
+
async write(account3, method, body) {
|
|
2776
|
+
const ids3 = [];
|
|
2777
|
+
if (typeof body.id === "string") ids3.push(body.id);
|
|
2778
|
+
try {
|
|
2779
|
+
const raw = localObject(await this.client.mutate(`ad_accounts/${pinterestId.parse(account3)}/campaigns`, method, [body], z18.unknown()));
|
|
2780
|
+
for (const item2 of Array.isArray(raw.items) ? raw.items.slice(0, 1e3) : []) {
|
|
2781
|
+
const id4 = localObject(localObject(item2).data).id;
|
|
2782
|
+
if (pinterestId.safeParse(id4).success) ids3.push(String(id4));
|
|
2783
|
+
}
|
|
2784
|
+
if (!Array.isArray(raw.items) || raw.items.length !== 1) throw failure2();
|
|
2785
|
+
const item = localObject(raw.items[0]);
|
|
2786
|
+
if (item.exceptions !== void 0 && (!Array.isArray(item.exceptions) || item.exceptions.length)) {
|
|
2787
|
+
const errors = Array.isArray(item.exceptions) ? item.exceptions.slice(0, 100).map((value) => {
|
|
2788
|
+
const row = localObject(value);
|
|
2789
|
+
return { ...typeof row.code === "number" && Number.isSafeInteger(row.code) ? { code: row.code } : {}, message_present: typeof row.message === "string" };
|
|
2790
|
+
}) : [];
|
|
2791
|
+
throw failure2(void 0, ids3, { verification_phase: "NATIVE_BATCH_ERRORS", native_errors: errors });
|
|
2792
|
+
}
|
|
2793
|
+
const data = campaignSchema.partial().extend({ id: pinterestId }).parse(item.data);
|
|
2794
|
+
if (data.ad_account_id !== void 0 && data.ad_account_id !== account3 || body.id !== void 0 && data.id !== body.id || Object.entries(body).some(([key, value]) => data[key] !== void 0 && localCanonical(data[key]) !== localCanonical(value))) throw failure2(void 0, ids3, { verification_phase: "NATIVE_RECEIPT" });
|
|
2795
|
+
return data;
|
|
2796
|
+
} catch (error) {
|
|
2797
|
+
throw failure2(error, ids3);
|
|
2798
|
+
}
|
|
2799
|
+
}
|
|
2800
|
+
preserved(before, after, changed) {
|
|
2801
|
+
const values = configuration2(after);
|
|
2802
|
+
return Object.entries(configuration2(before)).every(([key, value]) => changed.includes(key) || localCanonical(values[key]) === localCanonical(value));
|
|
2803
|
+
}
|
|
2804
|
+
async create(input, op, guard) {
|
|
2805
|
+
if (op.provider !== "pinterest" || op.tool !== "pinterest_create_campaign" || op.kind !== "create" || input.daily_budget_mode !== "AVERAGE" || input.budget_type !== "DAILY" || !input.acknowledge_variable_daily_spend) throw new AdportError13("INVALID_INPUT", "Invalid average-daily campaign creation.");
|
|
2806
|
+
const account3 = await this.account(op.accountId), currency2 = this.currency(account3.currency), { budget_type: _budget, daily_budget_mode: _mode, acknowledge_variable_daily_spend: _ack, budget_micros, ...rest } = input, status = guard.forcePausedCreation ? "PAUSED" : input.status, body = { ...rest, status, daily_spend_cap: budget_micros, is_campaign_budget_optimization: true, is_flexible_daily_budgets: true };
|
|
2807
|
+
let details;
|
|
2808
|
+
return { summary: `Create Pinterest campaign "${input.name}" with average daily budget`, changes: [`+ ${JSON.stringify(body)}`], coercions: status !== input.status ? ["status coerced to PAUSED by policy (paused_creation)"] : [], budgetDeltas: [{ target: "new campaign configured average DAILY budget", toMicros: budget_micros, currency: currency2 }], notes: notes4, review: { provider: "pinterest", accountId: op.accountId, kind: "create", title: "Create campaign", subject: input.name, fields: [{ label: "Budget mode", after: "Average daily" }, { label: "Configured daily average", after: budget_micros, format: "money", currency: currency2 }, { label: "Status", after: status }, { label: "Objective", after: input.objective_type }], notices: notes4 }, execute: async () => {
|
|
2809
|
+
let id4;
|
|
2810
|
+
try {
|
|
2811
|
+
const fresh = await this.account(op.accountId);
|
|
2812
|
+
if (localCanonical(fresh) !== localCanonical(account3)) throw new AdportError13("PENDING_MISMATCH", "Account currency/configuration changed.");
|
|
2813
|
+
const created = await this.write(op.accountId, "POST", body);
|
|
2814
|
+
id4 = created.id;
|
|
2815
|
+
const actual = await this.campaign(op.accountId, id4);
|
|
2816
|
+
if (Object.entries(body).some(([key, value]) => localCanonical(actual[key]) !== localCanonical(value)) || (actual.lifetime_spend_cap ?? 0) !== 0) throw failure2();
|
|
2817
|
+
details = { configuration_readback: "VERIFIED", campaign_id: id4, status: actual.status, budget_mode: "AVERAGE", configured_daily_average_micros: actual.daily_spend_cap, currency: currency2, daily_delivery_ceiling_verified: false, full_performance_plus_configuration: false };
|
|
2818
|
+
return [id4];
|
|
2819
|
+
} catch (error) {
|
|
2820
|
+
const known = error instanceof AdportError13 ? localObject(error.details).resource_ids : void 0;
|
|
2821
|
+
throw failure2(error, id4 ? [id4] : Array.isArray(known) ? known : []);
|
|
2822
|
+
}
|
|
2823
|
+
}, resultDetails: () => details, resultWarnings: () => notes4 };
|
|
2824
|
+
}
|
|
2825
|
+
async plan(op) {
|
|
2826
|
+
if (op.provider !== "pinterest" || !this.supports(op.tool) || op.kind !== "update") throw new AdportError13("INVALID_INPUT", "Invalid daily-budget mutation kind.");
|
|
2827
|
+
const input = campaignDailyBudget.parse(op.payload), prepare = async () => {
|
|
2828
|
+
const result = await this.context({ account_id: op.accountId, campaign_id: input.campaign_id });
|
|
2829
|
+
if (result.context_hash !== input.expected_context_hash) throw new AdportError13("PENDING_MISMATCH", "Campaign, budget mode, currency or project changed; preview again.");
|
|
2830
|
+
if (!["FIXED", "AVERAGE"].includes(result.mode) || !["PAUSED", "ACTIVE", "DRAFT"].includes(String(result.current.status))) throw new AdportError13("INVALID_INPUT", "Requires an editable CBO campaign with one positive daily cap and a confirmed fixed/average mode. Lifetime and ad-group budgets use their existing tools.");
|
|
2831
|
+
if ((result.mode === "AVERAGE" || input.daily_budget_mode === "AVERAGE") && (!input.acknowledge_variable_daily_spend || !input.acknowledge_averaging_reset)) throw new AdportError13("INVALID_INPUT", "Current or requested average mode requires variable-spend and averaging-reset acknowledgements.");
|
|
2832
|
+
return result;
|
|
2833
|
+
}, before = await prepare(), currency2 = this.currency(before.account.currency), amount = input.budget_micros ?? before.current.daily_spend_cap;
|
|
2834
|
+
if (before.mode === input.daily_budget_mode && amount === before.current.daily_spend_cap) throw new AdportError13("INVALID_INPUT", "No daily-budget change requested.");
|
|
2835
|
+
const body = { id: input.campaign_id, ...amount !== before.current.daily_spend_cap ? { daily_spend_cap: amount } : {}, ...before.mode !== input.daily_budget_mode ? { is_flexible_daily_budgets: input.daily_budget_mode === "AVERAGE" } : {} }, desired = { id: input.campaign_id, daily_spend_cap: amount, is_flexible_daily_budgets: input.daily_budget_mode === "AVERAGE" }, target = `campaign ${input.campaign_id} configured ${input.daily_budget_mode === "AVERAGE" ? "average daily budget" : "fixed daily cap"}`;
|
|
2836
|
+
let details;
|
|
2837
|
+
return { summary: `Change Pinterest campaign "${before.current.name ?? input.campaign_id}" daily budget`, changes: [`~ ${input.campaign_id} ${before.mode} \u2192 ${input.daily_budget_mode}; ${before.current.daily_spend_cap} \u2192 ${amount} micros`], coercions: [], budgetDeltas: [{ target, fromMicros: before.current.daily_spend_cap, toMicros: amount, currency: currency2 }], notes: notes4, review: { provider: "pinterest", accountId: op.accountId, kind: "update", title: "Change daily budget", subject: before.current.name ?? input.campaign_id, fields: [{ label: "Budget mode", before: before.mode, after: input.daily_budget_mode }, { label: input.daily_budget_mode === "AVERAGE" ? "Configured daily average" : "Fixed daily cap", before: before.current.daily_spend_cap, after: amount, format: "money", currency: currency2 }, { label: "Status", before: before.current.status, after: before.current.status }], notices: notes4 }, execute: async () => {
|
|
2838
|
+
await prepare();
|
|
2839
|
+
try {
|
|
2840
|
+
await this.write(op.accountId, "PATCH", body);
|
|
2841
|
+
const actual = await this.campaign(op.accountId, input.campaign_id);
|
|
2842
|
+
if (Object.entries(desired).some(([key, value]) => localCanonical(actual[key]) !== localCanonical(value)) || !this.preserved(before.current, actual, ["daily_spend_cap", "is_flexible_daily_budgets"])) throw failure2(void 0, [input.campaign_id], { verification_phase: "INDEPENDENT_READBACK" });
|
|
2843
|
+
details = { configuration_readback: "VERIFIED", campaign_id: actual.id, status: actual.status, budget_mode: input.daily_budget_mode, configured_budget_micros: amount, currency: currency2, omitted_configuration_preserved: true, daily_delivery_ceiling_verified: false };
|
|
2844
|
+
return [actual.id];
|
|
2845
|
+
} catch (error) {
|
|
2846
|
+
const known = error instanceof AdportError13 ? localObject(error.details).resource_ids : void 0;
|
|
2847
|
+
throw failure2(error, [input.campaign_id, ...Array.isArray(known) ? known : []]);
|
|
2848
|
+
}
|
|
2849
|
+
}, resultDetails: () => details, resultWarnings: () => notes4 };
|
|
2850
|
+
}
|
|
2851
|
+
};
|
|
2852
|
+
function pinterestCampaignBudgetTools(provider) {
|
|
2853
|
+
const catalog2 = { category: "campaigns", exposure: "specialist" };
|
|
2854
|
+
return [
|
|
2855
|
+
defineTool7({ name: "pinterest_campaign_budget_context", namespace: "pinterest", catalog: catalog2, description: "Read scoped campaign budget mode/amount, native currency and fresh context_hash. Distinguishes fixed daily, average daily, lifetime, ad-group ownership and unconfirmed modes; no raw tracking URLs or writes.", input: campaignBudgetContext, annotations: { readOnly: true }, presentation: "records", output: z18.looseObject({ records: z18.array(z18.record(z18.string(), z18.unknown())) }), handler: (input) => provider.campaignBudgets.publicContext(input) }),
|
|
2856
|
+
guardedWriteTool7({ name: "pinterest_set_campaign_daily_budget", namespace: "pinterest", provider: "pinterest", catalog: catalog2, kind: "update", destructive: true, payload: campaignDailyBudget, description: "Set CBO fixed/average daily mode and optional configured micro amount using fresh context_hash. Average mode requires variable-spend/reset acknowledgements. Shared caps check the configured amount; native readback preserves status and omitted settings, without a daily-delivery ceiling claim." })
|
|
2857
|
+
];
|
|
2858
|
+
}
|
|
2859
|
+
|
|
147
2860
|
// src/provider.ts
|
|
148
2861
|
var LEVEL = {
|
|
149
2862
|
account: { path: "", id: "AD_ACCOUNT_ID", filter: "" },
|
|
@@ -160,11 +2873,36 @@ var DERIVED = {
|
|
|
160
2873
|
roas: ["conversion_value", "spend", 1]
|
|
161
2874
|
};
|
|
162
2875
|
var PinterestAdsProvider = class {
|
|
163
|
-
constructor(client) {
|
|
2876
|
+
constructor(client, media = new LocalMediaResolver2()) {
|
|
164
2877
|
this.client = client;
|
|
2878
|
+
this.creatives = new PinterestCreativeService(client, (account3, id4) => this.getCampaign(account3, id4));
|
|
2879
|
+
this.assets = new PinterestAssetService(client, media);
|
|
2880
|
+
this.keywords = new PinterestKeywordService(client, (account3, entity, resource) => this.creatives.getEntity(account3, entity, resource));
|
|
2881
|
+
this.audiences = new PinterestAudienceService(client, (account3, entity, resource) => this.creatives.getEntity(account3, entity, resource), (account3, resource) => this.assets.getPin(account3, resource));
|
|
2882
|
+
this.measurement = new PinterestMeasurementService(client);
|
|
2883
|
+
this.catalogs = new PinterestCatalogService(client);
|
|
2884
|
+
this.productGroups = new PinterestProductGroups(client, this.catalogs);
|
|
2885
|
+
this.catalogItems = new PinterestCatalogItems(client, this.catalogs, media);
|
|
2886
|
+
this.localStores = new PinterestLocalStores(client, this.catalogs);
|
|
2887
|
+
this.localInventory = new PinterestLocalInventory(client, this.localStores, media);
|
|
2888
|
+
this.campaignBudgets = new PinterestCampaignBudgets(client, (account3, id4) => this.getCampaign(account3, id4), () => {
|
|
2889
|
+
const value = media.scopeId;
|
|
2890
|
+
return typeof value === "string" && value ? value : "local";
|
|
2891
|
+
});
|
|
165
2892
|
}
|
|
166
2893
|
client;
|
|
167
2894
|
id = "pinterest";
|
|
2895
|
+
creatives;
|
|
2896
|
+
assets;
|
|
2897
|
+
keywords;
|
|
2898
|
+
audiences;
|
|
2899
|
+
measurement;
|
|
2900
|
+
catalogs;
|
|
2901
|
+
productGroups;
|
|
2902
|
+
catalogItems;
|
|
2903
|
+
localStores;
|
|
2904
|
+
localInventory;
|
|
2905
|
+
campaignBudgets;
|
|
168
2906
|
capabilities() {
|
|
169
2907
|
return { serverDryRun: false };
|
|
170
2908
|
}
|
|
@@ -173,20 +2911,20 @@ var PinterestAdsProvider = class {
|
|
|
173
2911
|
}
|
|
174
2912
|
async collect(path, schema, params = new URLSearchParams()) {
|
|
175
2913
|
const result = [], bookmarks = /* @__PURE__ */ new Set(), entities = /* @__PURE__ */ new Set();
|
|
176
|
-
const
|
|
177
|
-
|
|
178
|
-
const pageSchema =
|
|
2914
|
+
const query2 = new URLSearchParams(params);
|
|
2915
|
+
query2.set("page_size", "250");
|
|
2916
|
+
const pageSchema = z19.object({ items: z19.array(schema), bookmark: z19.string().nullable().optional() });
|
|
179
2917
|
while (true) {
|
|
180
|
-
const
|
|
181
|
-
for (const item of
|
|
182
|
-
if (entities.has(item.id)) throw new
|
|
2918
|
+
const page2 = await this.client.get(path, pageSchema, query2);
|
|
2919
|
+
for (const item of page2.items) {
|
|
2920
|
+
if (entities.has(item.id)) throw new AdportError14("PROVIDER_ERROR", "pinterest: pagination repeated an entity");
|
|
183
2921
|
entities.add(item.id);
|
|
184
2922
|
result.push(item);
|
|
185
2923
|
}
|
|
186
|
-
if (!
|
|
187
|
-
if (bookmarks.has(
|
|
188
|
-
bookmarks.add(
|
|
189
|
-
|
|
2924
|
+
if (!page2.bookmark) return result;
|
|
2925
|
+
if (bookmarks.has(page2.bookmark) || bookmarks.size >= 1e3) throw new AdportError14("PROVIDER_ERROR", "pinterest: pagination did not terminate");
|
|
2926
|
+
bookmarks.add(page2.bookmark);
|
|
2927
|
+
query2.set("bookmark", page2.bookmark);
|
|
190
2928
|
}
|
|
191
2929
|
}
|
|
192
2930
|
async listAccounts() {
|
|
@@ -197,34 +2935,34 @@ var PinterestAdsProvider = class {
|
|
|
197
2935
|
}
|
|
198
2936
|
async listEntities(accountId, collection, schema) {
|
|
199
2937
|
const params = new URLSearchParams();
|
|
200
|
-
|
|
2938
|
+
params.set("entity_statuses", entityStatus.options.join(","));
|
|
201
2939
|
const rows = await this.collect(`ad_accounts/${pinterestId.parse(accountId)}/${collection}`, schema, params);
|
|
202
|
-
if (rows.some((row) => row.ad_account_id !== accountId)) throw new
|
|
2940
|
+
if (rows.some((row) => row.ad_account_id !== accountId)) throw new AdportError14("PROVIDER_ERROR", "pinterest: entity account mismatch");
|
|
203
2941
|
return rows;
|
|
204
2942
|
}
|
|
205
2943
|
async getCampaign(accountId, campaignId) {
|
|
206
2944
|
const result = await this.client.get(`ad_accounts/${pinterestId.parse(accountId)}/campaigns/${pinterestId.parse(campaignId)}`, campaignSchema);
|
|
207
|
-
if (result.id !== campaignId || result.ad_account_id !== accountId) throw new
|
|
2945
|
+
if (result.id !== campaignId || result.ad_account_id !== accountId) throw new AdportError14("PROVIDER_ERROR", "pinterest: campaign account/ID mismatch");
|
|
208
2946
|
return result;
|
|
209
2947
|
}
|
|
210
|
-
async report(
|
|
211
|
-
const range = resolveDateRange(
|
|
212
|
-
const start =
|
|
2948
|
+
async report(query2) {
|
|
2949
|
+
const range = resolveDateRange(query2.dateRange);
|
|
2950
|
+
const start = z19.iso.date().parse(range.start), end = z19.iso.date().parse(range.end);
|
|
213
2951
|
const days = (Date.parse(end) - Date.parse(start)) / 864e5;
|
|
214
|
-
if (days < 0 || days > 90) throw new
|
|
215
|
-
const limit =
|
|
216
|
-
if (!Number.isSafeInteger(limit) || limit < 1) throw new
|
|
217
|
-
const level = LEVEL[
|
|
218
|
-
for (const metric of
|
|
219
|
-
if (metric in FIELDS)
|
|
220
|
-
else if (metric in DERIVED) for (const dependency of DERIVED[metric].slice(0, 2))
|
|
221
|
-
}
|
|
222
|
-
if (!
|
|
2952
|
+
if (days < 0 || days > 90) throw new AdportError14("INVALID_INPUT", "pinterest: report end must be on/after start and within 90 days");
|
|
2953
|
+
const limit = query2.limit ?? 1e3;
|
|
2954
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError14("INVALID_INPUT", "pinterest: report limit must be a positive integer");
|
|
2955
|
+
const level = LEVEL[query2.level], fields2 = /* @__PURE__ */ new Set();
|
|
2956
|
+
for (const metric of query2.metrics) {
|
|
2957
|
+
if (metric in FIELDS) fields2.add(FIELDS[metric]);
|
|
2958
|
+
else if (metric in DERIVED) for (const dependency of DERIVED[metric].slice(0, 2)) fields2.add(FIELDS[dependency]);
|
|
2959
|
+
}
|
|
2960
|
+
if (!fields2.size) throw new AdportError14("INVALID_INPUT", "pinterest: report requires at least one supported metric");
|
|
223
2961
|
const rows = [];
|
|
224
|
-
for (const
|
|
225
|
-
const accountId = pinterestId.parse(
|
|
226
|
-
const entities =
|
|
227
|
-
if (
|
|
2962
|
+
for (const id4 of [...new Set(query2.accountIds ?? (await this.listAccounts()).map((a) => a.id))]) {
|
|
2963
|
+
const accountId = pinterestId.parse(id4), base = `ad_accounts/${accountId}`;
|
|
2964
|
+
const entities = query2.level === "account" ? [await this.client.get(base, accountSchema)] : await this.listEntities(accountId, level.path, entitySchema);
|
|
2965
|
+
if (query2.level === "account" && entities.some((e) => e.id !== accountId)) throw new AdportError14("PROVIDER_ERROR", "pinterest: account ID mismatch");
|
|
228
2966
|
const lookup = new Map(entities.map((e) => [e.id, e]));
|
|
229
2967
|
const seen = /* @__PURE__ */ new Set();
|
|
230
2968
|
for (let offset = 0; offset < entities.length; offset += 250) {
|
|
@@ -233,19 +2971,19 @@ var PinterestAdsProvider = class {
|
|
|
233
2971
|
start_date: start,
|
|
234
2972
|
end_date: end,
|
|
235
2973
|
granularity: "TOTAL",
|
|
236
|
-
columns: [level.id, ...
|
|
2974
|
+
columns: [level.id, ...fields2].join(","),
|
|
237
2975
|
click_window_days: "30",
|
|
238
2976
|
view_window_days: "1",
|
|
239
2977
|
conversion_report_time: "TIME_OF_AD_ACTION"
|
|
240
2978
|
});
|
|
241
|
-
if (level.filter)
|
|
242
|
-
const data = await this.client.get(`${base}/${level.path ? `${level.path}/` : ""}analytics`,
|
|
2979
|
+
if (level.filter) params.set(level.filter, batch.map((entity) => entity.id).join(","));
|
|
2980
|
+
const data = await this.client.get(`${base}/${level.path ? `${level.path}/` : ""}analytics`, z19.array(z19.record(z19.string(), z19.unknown())), params);
|
|
243
2981
|
for (const row of data) {
|
|
244
2982
|
const entityId = pinterestId.parse(row[level.id]);
|
|
245
|
-
if (!allowed.has(entityId) || seen.has(entityId)) throw new
|
|
2983
|
+
if (!allowed.has(entityId) || seen.has(entityId)) throw new AdportError14("PROVIDER_ERROR", "pinterest: incorrectly scoped or duplicate report row");
|
|
246
2984
|
seen.add(entityId);
|
|
247
2985
|
const entity = lookup.get(entityId);
|
|
248
|
-
rows.push({ provider: this.id, accountId, entity: { level:
|
|
2986
|
+
rows.push({ provider: this.id, accountId, entity: { level: query2.level, id: entityId, name: entity.name ?? entityId, ...typeof entity.status === "string" ? { status: entity.status } : {} }, metrics: normalize(row, query2.metrics) });
|
|
249
2987
|
if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };
|
|
250
2988
|
}
|
|
251
2989
|
}
|
|
@@ -253,30 +2991,42 @@ var PinterestAdsProvider = class {
|
|
|
253
2991
|
return { rows };
|
|
254
2992
|
}
|
|
255
2993
|
async previewWrite(op, guard) {
|
|
256
|
-
const { execute: _execute, ...preview } = await this.plan(op, guard);
|
|
2994
|
+
const { execute: _execute, resultDetails: _details, resultWarnings: _warnings, ...preview } = await this.plan(op, guard);
|
|
257
2995
|
return { ...preview, serverValidated: false };
|
|
258
2996
|
}
|
|
259
2997
|
async applyWrite(op, guard) {
|
|
260
|
-
|
|
2998
|
+
const plan2 = await this.plan(op, guard), resourceIds = await plan2.execute();
|
|
2999
|
+
return { applied: true, resourceIds, ...plan2.resultDetails ? { details: plan2.resultDetails() } : {}, ...plan2.resultWarnings ? { warnings: plan2.resultWarnings() } : {} };
|
|
261
3000
|
}
|
|
262
3001
|
async write(accountId, method, body) {
|
|
263
3002
|
const result = await this.client.mutate(`ad_accounts/${accountId}/campaigns`, method, [body], batchResponseSchema);
|
|
264
3003
|
const item = result.items[0];
|
|
265
|
-
if (result.items.length !== 1 || !item?.data || item.exceptions?.length) throw new
|
|
3004
|
+
if (result.items.length !== 1 || !item?.data || item.exceptions?.length) throw new AdportError14("PROVIDER_ERROR", "pinterest: campaign batch item failed; inspect account before retrying");
|
|
266
3005
|
const parsed = campaignSchema.safeParse(item.data);
|
|
267
|
-
if (!parsed.success) throw new
|
|
3006
|
+
if (!parsed.success) throw new AdportError14("PROVIDER_ERROR", "pinterest: campaign batch returned incomplete data; inspect account before retrying");
|
|
268
3007
|
const data = parsed.data;
|
|
269
3008
|
if (data.ad_account_id !== accountId || body.id && data.id !== body.id || Object.entries(body).some(([key, value]) => ["status", "daily_spend_cap", "lifetime_spend_cap"].includes(key) && data[key] !== value)) {
|
|
270
|
-
throw new
|
|
3009
|
+
throw new AdportError14("PROVIDER_ERROR", "pinterest: campaign write response mismatch; inspect before retrying");
|
|
271
3010
|
}
|
|
272
3011
|
return [data.id];
|
|
273
3012
|
}
|
|
274
3013
|
async plan(op, guard) {
|
|
275
3014
|
const accountId = pinterestId.parse(op.accountId);
|
|
276
|
-
if (op.provider !== this.id) throw new
|
|
3015
|
+
if (op.provider !== this.id) throw new AdportError14("INVALID_INPUT", "pinterest: provider mismatch");
|
|
3016
|
+
if (this.measurement.supports(op.tool)) return this.measurement.plan(op);
|
|
3017
|
+
if (this.catalogs.supports(op.tool)) return this.catalogs.plan(op);
|
|
3018
|
+
if (this.catalogItems.supports(op.tool)) return this.catalogItems.plan(op);
|
|
3019
|
+
if (this.localStores.supports(op.tool)) return this.localStores.plan(op);
|
|
3020
|
+
if (this.localInventory.supports(op.tool)) return this.localInventory.plan(op);
|
|
3021
|
+
if (this.campaignBudgets.supports(op.tool)) return this.campaignBudgets.plan(op);
|
|
3022
|
+
if (["pinterest_create_product_group", "pinterest_update_product_group", "pinterest_delete_product_group"].includes(op.tool)) return this.productGroups.plan(op);
|
|
3023
|
+
if (this.keywords.supports(op.tool)) return this.keywords.plan(op, guard);
|
|
3024
|
+
if (this.audiences.supports(op.tool)) return this.audiences.plan(op);
|
|
3025
|
+
if (PINTEREST_ASSET_WRITES.has(op.tool)) return this.assets.plan(op);
|
|
277
3026
|
if (op.tool === "pinterest_create_campaign" && op.kind === "create") {
|
|
278
3027
|
const input = createCampaignSchema.parse(op.payload);
|
|
279
|
-
|
|
3028
|
+
if (input.daily_budget_mode === "AVERAGE") return this.campaignBudgets.create(input, op, guard);
|
|
3029
|
+
const { budget_type, budget_micros, daily_budget_mode: _mode, acknowledge_variable_daily_spend: _ack, ...rest } = input;
|
|
280
3030
|
const status = guard.forcePausedCreation ? "PAUSED" : input.status;
|
|
281
3031
|
const cap = budget_type === "DAILY" ? "daily_spend_cap" : "lifetime_spend_cap";
|
|
282
3032
|
const body = { ...rest, status, [cap]: budget_micros, is_campaign_budget_optimization: true, is_flexible_daily_budgets: false };
|
|
@@ -293,8 +3043,9 @@ var PinterestAdsProvider = class {
|
|
|
293
3043
|
const current = await this.getCampaign(accountId, input.campaign_id);
|
|
294
3044
|
if ("budget_micros" in input) {
|
|
295
3045
|
const daily = current.daily_spend_cap ?? 0, lifetime = current.lifetime_spend_cap ?? 0;
|
|
296
|
-
if (!current.is_campaign_budget_optimization || daily > 0 === lifetime > 0) throw new
|
|
297
|
-
if (current.is_flexible_daily_budgets) throw new
|
|
3046
|
+
if (!current.is_campaign_budget_optimization || daily > 0 === lifetime > 0) throw new AdportError14("INVALID_INPUT", "pinterest: campaign budget update requires CBO with exactly one existing daily/lifetime cap");
|
|
3047
|
+
if (current.is_flexible_daily_budgets) throw new AdportError14("INVALID_INPUT", "pinterest: use pinterest_campaign_budget_context and pinterest_set_campaign_daily_budget with variable-spend/reset acknowledgements for an average daily budget");
|
|
3048
|
+
if (daily > 0 && typeof current.is_flexible_daily_budgets !== "boolean") throw new AdportError14("INVALID_INPUT", "pinterest: daily budget mode is unconfirmed; read pinterest_campaign_budget_context");
|
|
298
3049
|
const cap = daily > 0 ? "daily_spend_cap" : "lifetime_spend_cap", from = daily || lifetime;
|
|
299
3050
|
return {
|
|
300
3051
|
summary: `Change Pinterest campaign "${current.name ?? current.id}" budget`,
|
|
@@ -312,7 +3063,7 @@ var PinterestAdsProvider = class {
|
|
|
312
3063
|
execute: () => this.write(accountId, "PATCH", { id: current.id, status: input.status })
|
|
313
3064
|
};
|
|
314
3065
|
}
|
|
315
|
-
|
|
3066
|
+
return this.creatives.plan(op, guard);
|
|
316
3067
|
}
|
|
317
3068
|
};
|
|
318
3069
|
function normalize(row, requested) {
|
|
@@ -321,7 +3072,7 @@ function normalize(row, requested) {
|
|
|
321
3072
|
const value = row[field];
|
|
322
3073
|
if (value === null || value === void 0) continue;
|
|
323
3074
|
const number = typeof value === "number" ? value : typeof value === "string" && /^\d+(?:\.\d+)?$/.test(value) ? Number(value) : NaN;
|
|
324
|
-
if (!Number.isFinite(number) || number < 0) throw new
|
|
3075
|
+
if (!Number.isFinite(number) || number < 0) throw new AdportError14("PROVIDER_ERROR", `pinterest: malformed ${field} metric`);
|
|
325
3076
|
mapped[metric] = number / (metric === "spend" || metric === "conversion_value" ? 1e6 : 1);
|
|
326
3077
|
}
|
|
327
3078
|
for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) {
|
|
@@ -331,14 +3082,82 @@ function normalize(row, requested) {
|
|
|
331
3082
|
}
|
|
332
3083
|
|
|
333
3084
|
// src/tools.ts
|
|
334
|
-
import { z as
|
|
335
|
-
import { defineTool, guardedWriteTool } from "@adport/core";
|
|
3085
|
+
import { z as z23 } from "zod";
|
|
3086
|
+
import { defineTool as defineTool11, guardedWriteTool as guardedWriteTool11 } from "@adport/core";
|
|
3087
|
+
|
|
3088
|
+
// src/product-group-tools.ts
|
|
3089
|
+
import { z as z20 } from "zod";
|
|
3090
|
+
import { defineTool as defineTool8, guardedWriteTool as guardedWriteTool8 } from "@adport/core";
|
|
3091
|
+
function pinterestProductGroupTools(provider) {
|
|
3092
|
+
const catalog2 = { category: "creatives", exposure: "specialist" }, read = { namespace: "pinterest", catalog: catalog2, presentation: "records", annotations: { readOnly: true }, output: z20.looseObject({ records: z20.array(z20.record(z20.string(), z20.unknown())) }) }, write2 = { namespace: "pinterest", provider: "pinterest", catalog: catalog2 };
|
|
3093
|
+
return [
|
|
3094
|
+
defineTool8({ namespace: "pinterest", catalog: catalog2, name: "pinterest_product_group_filter_schema", description: "Discover native RETAIL/HOTEL/CREATIVE_ASSETS filter fields and exact criteria/enums on demand. Adport bounds: 32 clauses, 100 values, 1024 characters per value, 256 KiB filters. Empty non-retail selections require explicit confirmation.", input: z20.object({ catalog_type: catalogType }).strict(), annotations: { readOnly: true, openWorld: false }, handler: async (input) => ({ catalog_type: input.catalog_type, fields: filterFields[input.catalog_type], schema: z20.toJSONSchema(productGroupFilterSchema(input.catalog_type)), empty_filters_supported_with_confirmation: input.catalog_type !== "RETAIL", notes: ["Each filter clause contains exactly one field. any_of/all_of are distinct native operators; numeric values and currency are passed unchanged, not converted to budget micros.", "PRODUCT_GROUP references are rechecked transitively in the same catalog and selected feed, with a 40-group bound. This read changes no catalog, source item or grant."] }) }),
|
|
3095
|
+
defineTool8({ ...read, name: "pinterest_product_groups", description: "Page product groups in an exact advertiser-owned catalog, optionally one retail feed or selected IDs. Preserves native mode/type and snapshot_hash. Cursors bind account/catalog/selection; missing native bookmarks leave completeness unknown.", input: groupList, pagination: { cursorInput: "bookmark" }, handler: (input) => provider.productGroups.list(input) }),
|
|
3096
|
+
defineTool8({ ...read, name: "pinterest_get_product_group", description: "Read one product group after advertiser-owner catalog verification. Native catalog/type/ID must match; automatic retail/hotel groups remain read-only. Returns snapshot_hash for inspection.", input: groupReference, handler: (input) => provider.productGroups.get(input) }),
|
|
3097
|
+
defineTool8({ ...read, name: "pinterest_product_group_counts", description: "Read native counts for an owned product group with catalog-type validation. Counts are a separate observation, not frozen membership or proof of ad eligibility.", input: groupReference, handler: (input) => provider.productGroups.counts(input) }),
|
|
3098
|
+
defineTool8({ ...read, name: "pinterest_product_group_products", description: "Page native product/Pin metadata for one owned product group. Cursor binds its configuration snapshot; cards append without resetting scroll. Preserves source IDs and native fields without inventing previews or publication state.", input: groupReference.extend(groupPaging), pagination: { cursorInput: "bookmark" }, handler: (input) => provider.productGroups.products(input) }),
|
|
3099
|
+
defineTool8({ ...read, name: "pinterest_product_group_context", description: "Verify exact create/update/delete selection, current catalog/feed configuration and transitive filter references. Returns context_hash; rechecks before apply. Use filter_schema before authoring filters. Creates no products, Pins, ads or permissions.", input: groupContext, handler: (input) => provider.productGroups.context(input) }),
|
|
3100
|
+
guardedWriteTool8({ ...write2, name: "pinterest_create_product_group", kind: "create", destructive: false, description: "Create a feed-based retail or catalog-based retail/hotel/creative-assets product group from exact context_hash. Native eligibility remains authoritative; independent configuration readback does not prove matched inventory or Pin publication.", payload: groupCreate }),
|
|
3101
|
+
guardedWriteTool8({ ...write2, name: "pinterest_update_product_group", kind: "update", destructive: true, description: "Edit selected product-group name/description/filter and supported retail locale/country fields using exact context_hash and live-effects acknowledgement. Revalidates references and preserves omitted native settings; automatic groups are read-only.", payload: groupUpdate }),
|
|
3102
|
+
guardedWriteTool8({ ...write2, name: "pinterest_delete_product_group", kind: "remove", destructive: true, description: "Permanently delete one owned editable product group using exact current name/context_hash and explicit confirmations. Can affect existing ads; source items stay in the catalog. Requires complete native filtered absence after deletion; no replay.", payload: groupDelete })
|
|
3103
|
+
];
|
|
3104
|
+
}
|
|
3105
|
+
|
|
3106
|
+
// src/catalog-item-tools.ts
|
|
3107
|
+
import { z as z21 } from "zod";
|
|
3108
|
+
import { creativesOutput as creativesOutput5, defineTool as defineTool9, guardedWriteTool as guardedWriteTool9 } from "@adport/core";
|
|
3109
|
+
function pinterestCatalogItemTools(provider) {
|
|
3110
|
+
const catalog2 = { category: "creatives", exposure: "specialist" }, read = { namespace: "pinterest", catalog: catalog2, annotations: { readOnly: true }, presentation: "records", output: z21.looseObject({ records: z21.array(z21.record(z21.string(), z21.unknown())) }) }, write2 = { namespace: "pinterest", provider: "pinterest", catalog: catalog2 };
|
|
3111
|
+
const named = Object.entries(itemWriteOperations).map(([name3, operation]) => guardedWriteTool9({ ...write2, name: name3, kind: operation === "CREATE" ? "create" : operation === "DELETE" ? "remove" : "update", destructive: operation !== "CREATE", sensitiveInputs: ["items"], payload: itemNamedApply(operation), description: `${operation} one market's catalog items using fresh context_hash, explicit catalog and native async batches. Read schema before attributes. UPDATE preserves omitted fields; UPSERT is full replacement; DELETE affects all sources. Returns scoped receipt, not item/publication success. Batch arguments stay private; the agent applies identical arguments.` }));
|
|
3112
|
+
return [
|
|
3113
|
+
defineTool9({ namespace: "pinterest", catalog: catalog2, name: "pinterest_catalog_item_schema", description: "On-demand native attribute schema for retail/hotel/Creative Assets CREATE/UPDATE/UPSERT/DELETE. Shows immutable media differences and retail unset-mask fields; native merchant-required fields/eligibility remain authoritative.", input: itemSchemaQuery, annotations: { readOnly: true, openWorld: false }, handler: async (input) => ({ ...input, schema: z21.toJSONSchema(attributeSchema(input.catalog_type, input.operation)), source: "https://github.com/pinterest/api-description/blob/51aca009f10a90283ccdf3956d509fc995ebac23/v5/openapi.json", notes: ["Strict known fields and native types; defaults are not inserted. Integers must be safely representable; prices/currencies pass unchanged. Native merchant-required fields remain authoritative.", "UPDATE media/clear support differs from CREATE/UPSERT. Read context with operations to bind source IDs, exact market and current metadata."] }) }),
|
|
3114
|
+
defineTool9({ ...read, name: "pinterest_catalog_items", description: "Read explicit item IDs in one owned catalog/country/language via native POST query. Pages requested IDs with native Pin previews and guarded copy editing. This is not whole-catalog enumeration; missing/error rows never prove absence. Source URLs are fingerprinted.", input: itemRead, output: creativesOutput5.passthrough(), presentation: "creatives", pagination: { cursorInput: "cursor" }, handler: (input) => provider.catalogItems.list(input) }),
|
|
3115
|
+
defineTool9({ ...read, name: "pinterest_catalog_item_context", sensitiveInputs: ["operations"], description: "Validate exact operations, native field/update-mask shapes, current owned catalog/market/items and checksum-bound media. Returns context_hash; verifies again before apply. No provider links, products, Pins or permissions are created by this read.", input: itemContext, handler: (input) => provider.catalogItems.publicContext(input) }),
|
|
3116
|
+
defineTool9({ ...read, name: "pinterest_catalog_item_batch_status", description: "Read a batch created by Adport using its signed receipt, current owner/catalog proof and advertiser/project binding. Keeps per-item failures/pending/missing results distinct; overall COMPLETED is not every-item success. Sends no events or mutations.", input: batchReference, handler: (input) => provider.catalogItems.status(input) }),
|
|
3117
|
+
defineTool9({ ...read, name: "pinterest_reconcile_catalog_item_batch", description: "Independently re-read receipt-bound item IDs after native processing, verify requested fields and UPDATE preservation. Unknown/error item reads never certify deletion. Keeps native status, configuration checks and Pin/ad readiness separate; no replay.", input: batchReference, handler: (input) => provider.catalogItems.status(input, true) }),
|
|
3118
|
+
...named,
|
|
3119
|
+
guardedWriteTool9({ ...write2, name: "pinterest_apply_catalog_items_batch", kind: "update", destructive: true, sensitiveInputs: ["operations"], payload: itemBatchApply, description: "Submit one explicit mixed CREATE/UPDATE/UPSERT/DELETE batch with fresh context_hash and effect confirmations. Native IDs/catalog/market stay fixed; private media is minted only at apply. Async partial results retain per-item states and signed receipt; no automatic retry. Batch arguments stay private; the agent applies identical arguments." }),
|
|
3120
|
+
guardedWriteTool9({ ...write2, name: "pinterest_update_catalog_item_copy", kind: "update", destructive: false, payload: itemCopy, description: "Edit catalog item title/name or description from a current item snapshot_hash, preserving other fields. Native batch receipt and Processing pending remain separate from independent readback or publication. Uses the normal exact preview/apply gate." })
|
|
3121
|
+
];
|
|
3122
|
+
}
|
|
3123
|
+
|
|
3124
|
+
// src/local-catalog-tools.ts
|
|
3125
|
+
import { z as z22 } from "zod";
|
|
3126
|
+
import { defineTool as defineTool10, guardedWriteTool as guardedWriteTool10 } from "@adport/core";
|
|
3127
|
+
function pinterestLocalCatalogTools(provider) {
|
|
3128
|
+
const catalog2 = { category: "creatives", exposure: "specialist" }, read = { namespace: "pinterest", catalog: catalog2, annotations: { readOnly: true }, presentation: "records", output: z22.looseObject({ records: z22.array(z22.record(z22.string(), z22.unknown())) }) }, write2 = { namespace: "pinterest", provider: "pinterest", catalog: catalog2 };
|
|
3129
|
+
return [
|
|
3130
|
+
defineTool10({ ...read, name: "pinterest_local_stores", description: "Page local stores in an explicit advertiser-owned RETAIL catalog. Optional store_ids map to native ids CSV. Opaque cursor binds selection; missing native bookmarks leave completeness unknown.", input: localStoreList, pagination: { cursorInput: "bookmark" }, handler: (input) => provider.localStores.list(input) }),
|
|
3131
|
+
defineTool10({ ...read, name: "pinterest_local_store_context", description: "Read fresh local-store create/update/delete context. Checks catalog ownership, complete store-code uniqueness/capacity, selected stores and exact removal names/codes. Returns context_hash; writes recheck it.", input: localStoreContext, handler: (input) => provider.localStores.publicContext(input) }),
|
|
3132
|
+
guardedWriteTool10({ ...write2, name: "pinterest_create_local_stores", kind: "create", destructive: false, payload: localStoreCreate, description: "Create up to100 physical stores with native location metadata and fresh context_hash. Existing store codes cannot be overwritten. Can affect catalog ads; verifies scoped native configuration after apply, without activation or a native atomic absence guarantee." }),
|
|
3133
|
+
guardedWriteTool10({ ...write2, name: "pinterest_update_local_stores", kind: "update", destructive: true, payload: localStoreUpdate, description: "Patch owned local stores using fresh context_hash, preserving omitted configuration. Store-code changes require acknowledgement and current unique-code proof; code swaps are blocked. Native inventory migration is not promised." }),
|
|
3134
|
+
guardedWriteTool10({ ...write2, name: "pinterest_delete_local_stores", kind: "remove", destructive: true, payload: localStoreDelete, description: "Permanently delete exact owned store IDs with current name/code confirmations. Requires complete filtered absence after native deletion. May affect inventory and ads; no exposed restore endpoint or automatic replay." }),
|
|
3135
|
+
defineTool10({ ...read, name: "pinterest_local_inventory", description: "Read item/store pairs in a selected RETAIL catalog using native POST query. Supply store_id to verify the current store_code. Pages only requested pairs; unknown/missing rows do not prove absence and private ad links are fingerprinted.", input: inventoryList, pagination: { cursorInput: "cursor" }, handler: (input) => provider.localInventory.list(input) }),
|
|
3136
|
+
defineTool10({ ...read, name: "pinterest_local_inventory_context", description: "Validate exact CREATE/UPDATE/UPSERT/DELETE operations against current owned stores and local inventory. Returns context_hash binding advertiser/catalog/store metadata, pair identity, project and request. Missing rows require explicit acknowledgement; no write occurs.", input: inventoryContext, sensitiveInputs: ["operations"], handler: (input) => provider.localInventory.publicContext(input) }),
|
|
3137
|
+
defineTool10({ ...read, name: "pinterest_local_inventory_batch_status", description: "Read scoped supplemental batch status using an Adport-signed receipt and current catalog ownership. Preserves per-store failures and missing results; overall COMPLETED is not every-pair success.", input: inventoryBatchReference, handler: (input) => provider.localInventory.status(input) }),
|
|
3138
|
+
defineTool10({ ...read, name: "pinterest_reconcile_local_inventory_batch", description: "Read receipt-bound item/store pairs after native processing, checking requested fields and omitted UPDATE configuration. Native errors/missing pairs never independently prove deletion; source links stay private, and no write is replayed.", input: inventoryBatchReference, handler: (input) => provider.localInventory.status(input, true) }),
|
|
3139
|
+
...Object.entries(inventoryWriteTools).map(([name3, operation]) => guardedWriteTool10({ ...write2, name: name3, kind: operation === "CREATE" ? "create" : operation === "DELETE" ? "remove" : "update", destructive: operation !== "CREATE", payload: inventoryNamed(operation), sensitiveInputs: ["items"], description: `${operation} local item/store pairs with fresh context_hash. Prices stay native strings. UPDATE preserves omitted attributes; UPSERT is full replacement. Returns processing receipt, not publication success. Batch arguments stay private; the agent applies identical arguments.` })),
|
|
3140
|
+
guardedWriteTool10({ ...write2, name: "pinterest_apply_local_inventory_batch", kind: "update", destructive: true, payload: inventoryBatch, sensitiveInputs: ["operations"], description: "Submit mixed local-inventory operations for verified item_id/store_code pairs. Fresh context, publication/effect acknowledgements and permanent-delete confirmation required. Signed async receipt retains per-pair outcomes; agent applies private arguments, with no automatic retry." })
|
|
3141
|
+
];
|
|
3142
|
+
}
|
|
3143
|
+
|
|
3144
|
+
// src/tools.ts
|
|
336
3145
|
function pinterestTools(provider) {
|
|
337
3146
|
return [
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
3147
|
+
...pinterestAssetTools(provider),
|
|
3148
|
+
...pinterestKeywordTools(provider),
|
|
3149
|
+
...pinterestAudienceTools(provider),
|
|
3150
|
+
...pinterestMeasurementTools(provider),
|
|
3151
|
+
...pinterestCatalogTools(provider),
|
|
3152
|
+
...pinterestProductGroupTools(provider),
|
|
3153
|
+
...pinterestCatalogItemTools(provider),
|
|
3154
|
+
...pinterestLocalCatalogTools(provider),
|
|
3155
|
+
...pinterestCampaignBudgetTools(provider),
|
|
3156
|
+
...pinterestCreativeTools(provider),
|
|
3157
|
+
defineTool11({ name: "pinterest_list_campaigns", namespace: "pinterest", description: "List Pinterest campaigns, including archived and draft entities.", input: z23.object({ account_id: pinterestId }), annotations: { readOnly: true }, handler: (input) => provider.listCampaigns(input.account_id) }),
|
|
3158
|
+
guardedWriteTool11({ name: "pinterest_create_campaign", namespace: "pinterest", provider: "pinterest", kind: "create", description: "Create a CBO campaign, paused by policy. Integer account-currency micros; lifetime needs end_time. Daily mode defaults FIXED; AVERAGE requires acknowledge_variable_daily_spend and is a configured average, not a delivery ceiling or full Performance+ setup.", payload: createCampaignSchema }),
|
|
3159
|
+
guardedWriteTool11({ name: "pinterest_set_campaign_status", namespace: "pinterest", provider: "pinterest", kind: "update", description: "Pause or activate an existing Pinterest campaign.", payload: setStatusSchema }),
|
|
3160
|
+
guardedWriteTool11({ name: "pinterest_set_budget", namespace: "pinterest", provider: "pinterest", kind: "update", description: "Change an existing Pinterest CBO campaign budget in micros, preserving its daily/lifetime type.", payload: setBudgetSchema })
|
|
342
3161
|
];
|
|
343
3162
|
}
|
|
344
3163
|
|
|
@@ -362,13 +3181,17 @@ async function resolvePinterestCredentials(store) {
|
|
|
362
3181
|
return void 0;
|
|
363
3182
|
}
|
|
364
3183
|
async function createPinterestModule(store) {
|
|
365
|
-
const
|
|
366
|
-
if (!
|
|
367
|
-
const provider = new PinterestAdsProvider(new PinterestAdsClient(
|
|
3184
|
+
const credentials2 = await resolvePinterestCredentials(store);
|
|
3185
|
+
if (!credentials2) return void 0;
|
|
3186
|
+
const provider = new PinterestAdsProvider(new PinterestAdsClient(credentials2));
|
|
368
3187
|
return { provider, tools: pinterestTools(provider) };
|
|
369
3188
|
}
|
|
370
3189
|
export {
|
|
3190
|
+
PINTEREST_ADS_SCOPES,
|
|
371
3191
|
PINTEREST_API_BASE,
|
|
3192
|
+
PINTEREST_CATALOG_SCOPES,
|
|
3193
|
+
PINTEREST_PIN_SCOPES,
|
|
3194
|
+
PINTEREST_SECRET_PIN_SCOPES,
|
|
372
3195
|
PINTEREST_TOKEN_URL,
|
|
373
3196
|
PinterestAdsClient,
|
|
374
3197
|
PinterestAdsProvider,
|
|
@@ -377,6 +3200,7 @@ export {
|
|
|
377
3200
|
campaignSchema,
|
|
378
3201
|
createPinterestModule,
|
|
379
3202
|
exchangePinterestCode,
|
|
3203
|
+
pinterestAuthorizationScopes,
|
|
380
3204
|
pinterestTools,
|
|
381
3205
|
resolvePinterestCredentials
|
|
382
3206
|
};
|