@adport/provider-pinterest 0.9.0 → 0.11.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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/creatives.ts","../src/creative-tools.ts","../src/schemas.ts","../src/assets.ts","../src/keywords.ts","../src/audiences.ts","../src/measurement.ts","../src/catalogs.ts","../src/product-groups.ts","../src/product-group-schemas.ts","../src/product-group-filter-spec.ts","../src/catalog-items.ts","../src/catalog-item-attributes.ts","../src/catalog-item-schemas.ts","../src/local-stores.ts","../src/local-catalog-schemas.ts","../src/local-inventory.ts","../src/campaign-budgets.ts","../src/tools.ts","../src/product-group-tools.ts","../src/catalog-item-tools.ts","../src/local-catalog-tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\nimport { z } from 'zod';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport const PINTEREST_API_BASE = 'https://api.pinterest.com/v5/';\nexport const PINTEREST_TOKEN_URL = `${PINTEREST_API_BASE}oauth/token`;\nexport const PINTEREST_ADS_SCOPES = ['ads:read', 'ads:write'] as const;\nexport const PINTEREST_PIN_SCOPES = [...PINTEREST_ADS_SCOPES, 'boards:read', 'boards:write', 'pins:read', 'pins:write', 'user_accounts:read'] as const;\nexport const PINTEREST_SECRET_PIN_SCOPES = [...PINTEREST_PIN_SCOPES, 'boards:read_secret', 'boards:write_secret', 'pins:read_secret', 'pins:write_secret'] as const;\nexport const PINTEREST_CATALOG_SCOPES = ['catalogs:read', 'catalogs:write'] as const;\nexport interface PinterestAuthorizationOptions {\n pinManagement?: boolean;\n secretPins?: boolean;\n catalogManagement?: boolean;\n}\nexport function pinterestAuthorizationScopes(options: PinterestAuthorizationOptions = {}): readonly string[] {\n return [...(options.secretPins ? PINTEREST_SECRET_PIN_SCOPES : options.pinManagement ? PINTEREST_PIN_SCOPES : PINTEREST_ADS_SCOPES), ...(options.catalogManagement ? PINTEREST_CATALOG_SCOPES : [])];\n}\nexport interface PinterestCredentials {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n onRefreshToken?: (refreshToken: string) => Promise<void>;\n}\nconst tokenSchema = z.object({\n access_token: z.string().min(1), expires_in: z.number().positive(),\n refresh_token: z.string().min(1).optional(),\n scope: z.string().optional(),\n});\n\nexport function buildPinterestAuthUrl(clientId: string, redirectUri: string, state: string, options: PinterestAuthorizationOptions = {}): string {\n return `https://www.pinterest.com/oauth/?${new URLSearchParams({\n client_id: clientId, response_type: 'code', redirect_uri: redirectUri, state, scope: pinterestAuthorizationScopes(options).join(','),\n })}`;\n}\n\nasync function tokenRequest(credentials: Pick<PinterestCredentials, 'clientId' | 'clientSecret'>, body: URLSearchParams, fetchImpl: typeof fetch) {\n const response = await fetchImpl(PINTEREST_TOKEN_URL, {\n method: 'POST', headers: {\n authorization: `Basic ${Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n }, body, redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `pinterest: OAuth ${body.get('grant_type')} failed (HTTP ${response.status})`);\n const parsed = tokenSchema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'pinterest: malformed OAuth response');\n return parsed.data;\n}\n\nexport async function exchangePinterestCode(input: { clientId: string; clientSecret: string; code: string; redirectUri: string } & PinterestAuthorizationOptions, fetchImpl: typeof fetch = fetch): Promise<string> {\n const token = await tokenRequest(input, new URLSearchParams({\n grant_type: 'authorization_code', code: input.code, redirect_uri: input.redirectUri, continuous_refresh: 'true',\n }), fetchImpl);\n if (!token.refresh_token) throw new AdportError('PROVIDER_ERROR', 'pinterest: OAuth exchange did not return a refresh token');\n if (input.pinManagement || input.secretPins || input.catalogManagement) {\n const granted = new Set(token.scope?.split(/[\\s,]+/).filter(Boolean));\n const requested = pinterestAuthorizationScopes(input);\n 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.`);\n }\n return token.refresh_token;\n}\n\nexport class PinterestAdsClient {\n private token?: { value: string; expiresAt: number; scopes?: ReadonlySet<string> };\n private refreshToken: string;\n private refreshing?: Promise<string>;\n constructor(private readonly credentials: PinterestCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n this.refreshToken = credentials.refreshToken;\n }\n catalogBatchReceipt(value: unknown): string {\n const encoded = Buffer.from(JSON.stringify(value)).toString('base64url');\n if (encoded.length > 1_500_000) throw new AdportError('INVALID_INPUT', 'Catalog batch proof exceeds its bound; split this batch before previewing.');\n return encoded + '.' + createHmac('sha256', this.credentials.clientSecret).update('pinterest_catalog_batch_v1:' + this.credentials.clientId + ':' + encoded).digest('hex');\n }\n verifyCatalogBatchReceipt(value: string): unknown {\n const [encoded, signature, extra] = value.split('.');\n if (extra !== undefined || !encoded || encoded.length > 1_500_000 || !/^[a-f0-9]{64}$/.test(signature ?? '')) throw new AdportError('INVALID_INPUT', 'Invalid catalog batch receipt.');\n const expected = createHmac('sha256', this.credentials.clientSecret).update('pinterest_catalog_batch_v1:' + this.credentials.clientId + ':' + encoded).digest();\n if (!timingSafeEqual(expected, Buffer.from(signature!, 'hex'))) throw new AdportError('INVALID_INPUT', 'Catalog batch receipt belongs to another application or was changed.');\n try { return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')); } catch { throw new AdportError('INVALID_INPUT', 'Invalid catalog batch receipt.'); }\n }\n async get<T>(path: string, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, 'GET', schema, undefined, params);\n }\n async mutate<T>(path: string, method: 'POST' | 'PATCH' | 'DELETE', body: unknown, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, method, schema, body, params);\n }\n async uploadVideo(url: string, parameters: Record<string, string>, bytes: Uint8Array<ArrayBuffer>, name: string) {\n const destination = new URL(url);\n 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');\n const required = ['Content-Type', 'key', 'policy', 'x-amz-algorithm', 'x-amz-credential', 'x-amz-date', 'x-amz-security-token', 'x-amz-signature'];\n if (Object.keys(parameters).length !== required.length || required.some(key => !parameters[key] || parameters[key]!.length > 32_768) || 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');\n const body = new FormData();\n for (const key of required) body.set(key, parameters[key]!);\n body.set('file', new Blob([bytes], { type: 'video/mp4' }), name);\n // The signed Storage capability replaces OAuth here; never forward a bearer token.\n const response = await this.fetchImpl(destination.href, { method: 'POST', body, redirect: 'error', signal: AbortSignal.timeout(120_000) });\n if (response.status !== 204) throw new AdportError('PROVIDER_ERROR', 'pinterest: video transfer was not confirmed');\n }\n private async request<T>(path: string, method: 'GET' | 'POST' | 'PATCH' | 'DELETE', schema: z.ZodType<T>, body?: unknown, params = new URLSearchParams(), retry = true): Promise<T> {\n if (!/^[a-z_]+(?:\\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'pinterest: invalid API resource path');\n const url = new URL(path, PINTEREST_API_BASE);\n url.search = params.toString();\n const token = await this.accessToken();\n const missingCatalogScope = method === 'GET' && (path === 'catalogs' || path.startsWith('catalogs/'))\n && this.token?.value === token && this.token.scopes !== undefined && !this.token.scopes.has('catalogs:read');\n const response = await this.fetchImpl(url.href, {\n method, headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}), redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (response.status === 401 && method === 'GET' && retry && !missingCatalogScope) {\n if (this.token?.value === token) this.token = undefined;\n return this.request(path, method, schema, body, params, false);\n }\n if (!response.ok) {\n const advice = response.status === 401 && missingCatalogScope\n ? ' The current token is missing catalogs:read. Ask the connection owner to review catalog access; refreshing the same grant cannot add permissions.'\n : response.status === 403 ? ' Check app Trial/Standard access, endpoint-specific scopes and ad-account permissions; reauthorization alone may not help.' : '';\n const details: Record<string, unknown> = { http_status: response.status };\n if (response.status === 401 && missingCatalogScope) details.missing_scopes = ['catalogs:read'];\n if ([400, 404, 409, 422].includes(response.status)) {\n const error = z.object({ code: z.union([z.string(), z.number()]).optional(), message: z.string().max(2000).optional() }).safeParse(await response.json().catch(() => undefined));\n if (error.success) {\n if (error.data.code !== undefined) details.api_code = error.data.code;\n const payload = body && typeof body === 'object' && !Array.isArray(body) ? body as Record<string, unknown> : {};\n const auth = payload.credentials && typeof payload.credentials === 'object' ? payload.credentials as Record<string, unknown> : {};\n const sourceSecrets = path.startsWith('catalogs/') ? [payload.location, auth.username, auth.password].filter((value): value is string => typeof value === 'string' && value.length > 0) : [];\n if (error.data.message) details.api_message = [...sourceSecrets, this.credentials.clientId, this.credentials.clientSecret, this.credentials.refreshToken, this.refreshToken, token].reduce((text, secret) => secret ? text.replaceAll(secret, '[redacted]') : text, error.data.message);\n }\n }\n throw new AdportError('PROVIDER_ERROR', `pinterest: HTTP ${response.status}.${advice}${details.api_message ? ` ${details.api_message}` : ''}`, details);\n }\n const raw: unknown = response.status === 204 ? undefined : await response.json();\n const parsed = schema.safeParse(raw);\n if (!parsed.success) {\n const value = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};\n const resourceIds = [value.id, value.media_id].filter((id): id is string => typeof id === 'string' && /^\\d{1,30}$/.test(id));\n 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);\n 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)] } : {}) });\n }\n return parsed.data;\n }\n private async accessToken(): Promise<string> {\n if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.value;\n if (!this.refreshing) this.refreshing = this.refresh().finally(() => { this.refreshing = undefined; });\n return this.refreshing;\n }\n private async refresh(): Promise<string> {\n const token = await tokenRequest(this.credentials, new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.refreshToken }), this.fetchImpl);\n if (token.refresh_token && token.refresh_token !== this.refreshToken) {\n this.refreshToken = token.refresh_token;\n await this.credentials.onRefreshToken?.(token.refresh_token);\n }\n this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1000,\n ...(token.scope?.trim() ? { scopes: new Set(token.scope.split(/[\\s,]+/).filter(Boolean)) } : {}) };\n return token.access_token;\n }\n}\n","import { z } from 'zod';\nimport {\n AdportError, LocalMediaResolver, resolveDateRange, type Account, type AdProvider, type MediaResolver, type MetricName,\n type NormalizedQuery, type Report, type ReportRow, type StandardActions,\n type WriteGuard, type WriteOperation, type WritePreview, type WriteResult,\n} from '@adport/core';\nimport { PinterestAdsClient } from './client.js';\nimport { PinterestCreativeService } from './creatives.js';\nimport { PINTEREST_ASSET_WRITES, PinterestAssetService } from './assets.js';\nimport { PinterestKeywordService } from './keywords.js';\nimport { PinterestAudienceService } from './audiences.js';\nimport { PinterestMeasurementService } from './measurement.js';\nimport { PinterestCatalogService } from './catalogs.js';\nimport { PinterestProductGroups } from './product-groups.js';\nimport { PinterestCatalogItems } from './catalog-items.js';\nimport { PinterestLocalStores } from './local-stores.js';\nimport { PinterestLocalInventory } from './local-inventory.js';\nimport { PinterestCampaignBudgets } from './campaign-budgets.js';\nimport { accountSchema, batchResponseSchema, campaignSchema, createCampaignSchema, entitySchema, entityStatus, pinterestId, setBudgetSchema, setStatusSchema } from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]>; resultDetails?: () => unknown; resultWarnings?: () => string[] }\nconst LEVEL = {\n account: { path: '', id: 'AD_ACCOUNT_ID', filter: '' },\n campaign: { path: 'campaigns', id: 'CAMPAIGN_ID', filter: 'campaign_ids' },\n ad_group: { path: 'ad_groups', id: 'AD_GROUP_ID', filter: 'ad_group_ids' },\n ad: { path: 'ads', id: 'AD_ID', filter: 'ad_ids' },\n} as const;\nconst FIELDS = { spend: 'SPEND_IN_MICRO_DOLLAR', impressions: 'PAID_IMPRESSION', clicks: 'OUTBOUND_CLICK_1', conversions: 'TOTAL_CHECKOUT', conversion_value: 'TOTAL_CHECKOUT_VALUE_IN_MICRO_DOLLAR' } as const;\nconst DERIVED = {\n ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000],\n cpa: ['spend', 'conversions', 1], roas: ['conversion_value', 'spend', 1],\n} as const;\n\nexport class PinterestAdsProvider implements AdProvider {\n readonly id = 'pinterest';\n readonly creatives: PinterestCreativeService;\n readonly assets: PinterestAssetService;\n readonly keywords: PinterestKeywordService;\n readonly audiences: PinterestAudienceService;\n readonly measurement: PinterestMeasurementService;\n readonly catalogs: PinterestCatalogService;\n readonly productGroups: PinterestProductGroups;\n readonly catalogItems: PinterestCatalogItems;\n readonly localStores: PinterestLocalStores;\n readonly localInventory: PinterestLocalInventory;\n readonly campaignBudgets: PinterestCampaignBudgets;\n constructor(private readonly client: PinterestAdsClient, media: MediaResolver = new LocalMediaResolver()) {\n this.creatives = new PinterestCreativeService(client, (account, id) => this.getCampaign(account, id));\n this.assets = new PinterestAssetService(client, media);\n this.keywords = new PinterestKeywordService(client, (account, entity, resource) => this.creatives.getEntity(account, entity, resource));\n this.audiences = new PinterestAudienceService(client, (account, entity, resource) => this.creatives.getEntity(account, entity, resource), (account, resource) => this.assets.getPin(account, resource));\n this.measurement = new PinterestMeasurementService(client);\n this.catalogs = new PinterestCatalogService(client);\n this.productGroups = new PinterestProductGroups(client, this.catalogs);\n this.catalogItems = new PinterestCatalogItems(client, this.catalogs, media);\n this.localStores = new PinterestLocalStores(client, this.catalogs);\n this.localInventory = new PinterestLocalInventory(client, this.localStores, media);\n this.campaignBudgets = new PinterestCampaignBudgets(client, (account, id) => this.getCampaign(account, id), () => { const value = (media as { scopeId?: unknown }).scopeId;return typeof value === 'string' && value ? value : 'local'; });\n }\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions {\n return { pauseCampaign: (accountId, campaignId) => ({ tool: 'pinterest_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) };\n }\n private async collect<T extends { id: string }>(path: string, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T[]> {\n const result: T[] = [], bookmarks = new Set<string>(), entities = new Set<string>();\n const query = new URLSearchParams(params);\n query.set('page_size', '250');\n const pageSchema = z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() });\n while (true) {\n const page = await this.client.get(path, pageSchema, query);\n for (const item of page.items) {\n if (entities.has(item.id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: pagination repeated an entity');\n entities.add(item.id); result.push(item);\n }\n if (!page.bookmark) return result;\n if (bookmarks.has(page.bookmark) || bookmarks.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'pinterest: pagination did not terminate');\n bookmarks.add(page.bookmark); query.set('bookmark', page.bookmark);\n }\n }\n async listAccounts(): Promise<Account[]> {\n return (await this.collect('ad_accounts', accountSchema)).map(a => ({ provider: this.id, id: a.id, name: a.name ?? a.id, ...(a.currency ? { currency: a.currency } : {}) }));\n }\n async listCampaigns(accountId: string) {\n return this.listEntities(accountId, 'campaigns', campaignSchema);\n }\n private async listEntities<T extends z.infer<typeof entitySchema>>(accountId: string, collection: string, schema: z.ZodType<T>) {\n const params = new URLSearchParams();\n // Live v5 requires CSV arrays; repeated status parameters select only the\n // final value despite the specification's omitted explode annotation.\n params.set('entity_statuses', entityStatus.options.join(','));\n const rows = await this.collect(`ad_accounts/${pinterestId.parse(accountId)}/${collection}`, schema, params);\n if (rows.some(row => row.ad_account_id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: entity account mismatch');\n return rows;\n }\n async getCampaign(accountId: string, campaignId: string) {\n const result = await this.client.get(`ad_accounts/${pinterestId.parse(accountId)}/campaigns/${pinterestId.parse(campaignId)}`, campaignSchema);\n if (result.id !== campaignId || result.ad_account_id !== accountId) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign account/ID mismatch');\n return result;\n }\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const start = z.iso.date().parse(range.start), end = z.iso.date().parse(range.end);\n const days = (Date.parse(end) - Date.parse(start)) / 86_400_000;\n if (days < 0 || days > 90) throw new AdportError('INVALID_INPUT', 'pinterest: report end must be on/after start and within 90 days');\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'pinterest: report limit must be a positive integer');\n const level = LEVEL[query.level], fields = new Set<string>();\n for (const metric of query.metrics) {\n if (metric in FIELDS) fields.add(FIELDS[metric as keyof typeof FIELDS]);\n else if (metric in DERIVED) for (const dependency of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) fields.add(FIELDS[dependency as keyof typeof FIELDS]);\n }\n if (!fields.size) throw new AdportError('INVALID_INPUT', 'pinterest: report requires at least one supported metric');\n const rows: ReportRow[] = [];\n for (const id of [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))]) {\n const accountId = pinterestId.parse(id), base = `ad_accounts/${accountId}`;\n const entities = query.level === 'account'\n ? [await this.client.get(base, accountSchema)]\n : await this.listEntities(accountId, level.path, entitySchema);\n if (query.level === 'account' && entities.some(e => e.id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: account ID mismatch');\n const lookup = new Map(entities.map(e => [e.id, e]));\n const seen = new Set<string>();\n for (let offset = 0; offset < entities.length; offset += 250) {\n const batch = entities.slice(offset, offset + 250), allowed = new Set(batch.map(e => e.id));\n const params = new URLSearchParams({\n start_date: start, end_date: end, granularity: 'TOTAL', columns: [level.id, ...fields].join(','),\n click_window_days: '30', view_window_days: '1', conversion_report_time: 'TIME_OF_AD_ACTION',\n });\n if (level.filter) params.set(level.filter, batch.map(entity => entity.id).join(','));\n const data = await this.client.get(`${base}/${level.path ? `${level.path}/` : ''}analytics`, z.array(z.record(z.string(), z.unknown())), params);\n for (const row of data) {\n const entityId = pinterestId.parse(row[level.id]);\n if (!allowed.has(entityId) || seen.has(entityId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: incorrectly scoped or duplicate report row');\n seen.add(entityId);\n const entity = lookup.get(entityId)!;\n rows.push({ provider: this.id, accountId, entity: { level: query.level, id: entityId, name: entity.name ?? entityId, ...(typeof entity.status === 'string' ? { status: entity.status } : {}) }, metrics: normalize(row, query.metrics) });\n if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };\n }\n }\n }\n return { rows };\n }\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, resultDetails: _details, resultWarnings: _warnings, ...preview } = await this.plan(op, guard);\n return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard), resourceIds = await plan.execute();\n return { applied: true, resourceIds, ...(plan.resultDetails ? { details: plan.resultDetails() } : {}), ...(plan.resultWarnings ? { warnings: plan.resultWarnings() } : {}) };\n }\n private async write(accountId: string, method: 'POST' | 'PATCH', body: Record<string, unknown>) {\n const result = await this.client.mutate(`ad_accounts/${accountId}/campaigns`, method, [body], batchResponseSchema);\n const item = result.items[0];\n if (result.items.length !== 1 || !item?.data || item.exceptions?.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign batch item failed; inspect account before retrying');\n const parsed = campaignSchema.safeParse(item.data);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign batch returned incomplete data; inspect account before retrying');\n const data = parsed.data;\n if (data.ad_account_id !== accountId || (body.id && data.id !== body.id)\n || Object.entries(body).some(([key, value]) => ['status', 'daily_spend_cap', 'lifetime_spend_cap'].includes(key) && data[key] !== value)) {\n throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign write response mismatch; inspect before retrying');\n }\n return [data.id];\n }\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const accountId = pinterestId.parse(op.accountId);\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'pinterest: provider mismatch');\n if (this.measurement.supports(op.tool)) return this.measurement.plan(op);\n if (this.catalogs.supports(op.tool)) return this.catalogs.plan(op);\n if (this.catalogItems.supports(op.tool)) return this.catalogItems.plan(op);\n if (this.localStores.supports(op.tool)) return this.localStores.plan(op);\n if (this.localInventory.supports(op.tool)) return this.localInventory.plan(op);\n if (this.campaignBudgets.supports(op.tool)) return this.campaignBudgets.plan(op);\n if (['pinterest_create_product_group', 'pinterest_update_product_group', 'pinterest_delete_product_group'].includes(op.tool)) return this.productGroups.plan(op);\n if (this.keywords.supports(op.tool)) return this.keywords.plan(op, guard);\n if (this.audiences.supports(op.tool)) return this.audiences.plan(op);\n if (PINTEREST_ASSET_WRITES.has(op.tool)) return this.assets.plan(op);\n if (op.tool === 'pinterest_create_campaign' && op.kind === 'create') {\n const input = createCampaignSchema.parse(op.payload);\n if (input.daily_budget_mode === 'AVERAGE') return this.campaignBudgets.create(input, op, guard);\n const { budget_type, budget_micros, daily_budget_mode: _mode, acknowledge_variable_daily_spend: _ack, ...rest } = input;\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const cap = budget_type === 'DAILY' ? 'daily_spend_cap' : 'lifetime_spend_cap';\n const body = { ...rest, status, [cap]: budget_micros, is_campaign_budget_optimization: true, is_flexible_daily_budgets: false };\n return {\n summary: `Create Pinterest campaign \"${input.name}\"`, changes: [`+ ${JSON.stringify(body)}`],\n coercions: status !== input.status ? ['status coerced to PAUSED by policy (paused_creation)'] : [],\n budgetDeltas: [{ target: `new campaign ${budget_type} budget`, toMicros: budget_micros }],\n execute: () => this.write(accountId, 'POST', body),\n };\n }\n if (op.kind === 'update' && ['pinterest_set_campaign_status', 'pinterest_set_budget'].includes(op.tool)) {\n const input = op.tool === 'pinterest_set_budget' ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);\n const current = await this.getCampaign(accountId, input.campaign_id);\n if ('budget_micros' in input) {\n const daily = current.daily_spend_cap ?? 0, lifetime = current.lifetime_spend_cap ?? 0;\n if (!current.is_campaign_budget_optimization || (daily > 0) === (lifetime > 0)) throw new AdportError('INVALID_INPUT', 'pinterest: campaign budget update requires CBO with exactly one existing daily/lifetime cap');\n if (current.is_flexible_daily_budgets) throw new AdportError('INVALID_INPUT', 'pinterest: use pinterest_campaign_budget_context and pinterest_set_campaign_daily_budget with variable-spend/reset acknowledgements for an average daily budget');\n if (daily > 0 && typeof current.is_flexible_daily_budgets !== 'boolean') throw new AdportError('INVALID_INPUT', 'pinterest: daily budget mode is unconfirmed; read pinterest_campaign_budget_context');\n const cap = daily > 0 ? 'daily_spend_cap' : 'lifetime_spend_cap', from = daily || lifetime;\n return {\n summary: `Change Pinterest campaign \"${current.name ?? current.id}\" budget`, changes: [`~ ${current.id} ${cap}: ${from} → ${input.budget_micros} micros`], coercions: [],\n budgetDeltas: [{ target: `campaign ${current.id} ${cap}`, fromMicros: from, toMicros: input.budget_micros }],\n execute: () => this.write(accountId, 'PATCH', { id: current.id, [cap]: input.budget_micros }),\n };\n }\n return {\n summary: `Change Pinterest campaign \"${current.name ?? current.id}\" status`, changes: [`~ ${current.id} status: ${current.status ?? 'unknown'} → ${input.status}`], coercions: [], budgetDeltas: [],\n execute: () => this.write(accountId, 'PATCH', { id: current.id, status: input.status }),\n };\n }\n return this.creatives.plan(op, guard);\n }\n}\n\nfunction normalize(row: Record<string, unknown>, requested: MetricName[]) {\n const mapped: Partial<Record<MetricName, number>> = {};\n for (const [metric, field] of Object.entries(FIELDS)) {\n const value = row[field];\n if (value === null || value === undefined) continue;\n const number = typeof value === 'number' ? value : typeof value === 'string' && /^\\d+(?:\\.\\d+)?$/.test(value) ? Number(value) : NaN;\n if (!Number.isFinite(number) || number < 0) throw new AdportError('PROVIDER_ERROR', `pinterest: malformed ${field} metric`);\n // MICRO_DOLLAR is Pinterest's historical field name; units are always\n // micros of the advertiser's account currency, not necessarily USD.\n mapped[metric as MetricName] = number / (metric === 'spend' || metric === 'conversion_value' ? 1_000_000 : 1);\n }\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) {\n if (mapped[numerator] !== undefined && mapped[denominator] !== undefined) mapped[metric as MetricName] = mapped[denominator] ? mapped[numerator]! / mapped[denominator]! * factor : 0;\n }\n return Object.fromEntries(requested.filter(metric => mapped[metric] !== undefined).map(metric => [metric, mapped[metric]]));\n}\n","import { AdportError, creativeStatusAction, type Creative, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport { createAd, createGroup, updateAd, updateGroup } from './creative-tools.js';\nimport { campaignSchema, pinterestId } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ninterface Page { account_id: string; page_size: number; bookmark?: string }\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst object = z.record(z.string(), z.unknown());\nconst response = z.looseObject({ id: pinterestId, ad_account_id: pinterestId.optional() });\nfunction record(value: unknown): Row { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Row : {}; }\nfunction query(input: Row) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(input)) if (value !== undefined) params.set(key, Array.isArray(value) ? value.map(String).join(',') : String(value)); return params; }\nfunction safeUrl(value: unknown): string[] { if (typeof value !== 'string') return []; try { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password ? [value] : []; } catch { return []; } }\n\n/** Native batch and targeting contracts from Pinterest-owned v5 OpenAPI5.28.0. */\nexport class PinterestCreativeService {\n constructor(private readonly client: PinterestAdsClient, private readonly campaign: (account: string, id: string) => Promise<z.infer<typeof campaignSchema>>) {}\n private base(account: string) { return `ad_accounts/${pinterestId.parse(account)}`; }\n async read(account: string, path: string) { return this.client.get(`${this.base(account)}/${path}`, object); }\n async getEntity(account: string, entity: 'campaigns' | 'ad_groups' | 'ads', id: string) { return this.owned(account, entity, id); }\n async page(input: Page & Row, collection: 'ad_groups' | 'ads' | 'audiences') {\n const { account_id, ...params } = input;\n const data = await this.client.get(`${this.base(account_id)}/${collection}`, z.looseObject({ items: z.array(response), bookmark: z.string().nullable().optional() }), query({ ...params, ...(collection !== 'audiences' && !params.entity_statuses ? { entity_statuses: ['ACTIVE', 'PAUSED', 'ARCHIVED', 'DRAFT', 'DELETED_DRAFT'] } : {}) }));\n if (data.items.some(row => row.ad_account_id !== undefined && row.ad_account_id !== account_id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: collection returned a foreign account');\n if (data.bookmark && data.bookmark === input.bookmark) throw new AdportError('PROVIDER_ERROR', 'pinterest: pagination repeated a bookmark');\n return { ...data, truncated: Boolean(data.bookmark), ...(data.bookmark ? { next_cursor: data.bookmark } : {}) };\n }\n async ads(input: Page & Row) {\n const { include_pin_details, ...filters } = input;\n const data = await this.page(filters, 'ads');\n const pins = new Map<string, Row>(), warnings: Array<{ provider: string; message: string }> = [];\n if (include_pin_details) {\n const ids = [...new Set(data.items.map(ad => typeof ad.pin_id === 'string' && /^\\d{1,30}$/.test(ad.pin_id) ? ad.pin_id : '').filter(Boolean))];\n let cursor = 0, denied = false;\n await Promise.all(Array.from({ length: Math.min(4, ids.length) }, async () => {\n while (cursor < ids.length && !denied) {\n const id = ids[cursor++]!;\n try {\n const pin = await this.client.get(`pins/${id}`, z.looseObject({ id: z.string().regex(/^\\d+$/) }), query({ ad_account_id: input.account_id }));\n if (pin.id !== id) throw new AdportError('PROVIDER_ERROR', 'pinterest: referenced Pin response ID mismatch');\n pins.set(id, pin);\n } catch (error) {\n const forbidden = error instanceof AdportError && record(error.details).http_status === 403;\n if (forbidden) denied = true;\n 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'}`;\n if (!warnings.some(warning => warning.message === message)) warnings.push({ provider: 'pinterest', message });\n }\n }\n }));\n }\n const creatives: Creative[] = data.items.map(ad => {\n const status = typeof ad.status === 'string' ? ad.status : '', args = { account_id: input.account_id, ad_id: ad.id };\n const pin = pins.get(String(ad.pin_id));\n 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) ? [] : [\n ...(['ACTIVE', 'PAUSED'].includes(status) ? [creativeStatusAction('pinterest_set_ad_status', args, status, ['ACTIVE', 'PAUSED'])] : []),\n { 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' as const, value: ad.destination_url, max_length: 2048 }] : [])] },\n ] };\n });\n return { ...data, creatives, warnings };\n }\n async targetingOptions(account: string, type: string) { return this.client.get(`resources/targeting/${type}`, z.array(object), query({ ad_account_id: pinterestId.parse(account) })); }\n async estimate(input: { account_id: string } & Row) { const { account_id, ...body } = input; return this.client.mutate(`${this.base(account_id)}/ad_groups/audience_sizing`, 'POST', body, object); }\n\n private async owned(account: string, collection: 'campaigns' | 'ad_groups' | 'ads', id: string): Promise<Row> {\n if (collection === 'campaigns') return this.campaign(account, id);\n const row = await this.client.get(`${this.base(account)}/${collection}/${pinterestId.parse(id)}`, response);\n if (row.id !== id || (row.ad_account_id !== undefined && row.ad_account_id !== account)) throw new AdportError('PROVIDER_ERROR', 'pinterest: resource ID/account mismatch');\n if (collection === 'ad_groups') await this.campaign(account, pinterestId.parse(row.campaign_id));\n else {\n const parent = await this.owned(account, 'ad_groups', pinterestId.parse(row.ad_group_id));\n if (row.campaign_id !== undefined && row.campaign_id !== parent.campaign_id) throw new AdportError('PROVIDER_ERROR', 'pinterest: ad campaign hierarchy mismatch');\n }\n return row;\n }\n\n private async batch(account: string, collection: string, method: 'POST' | 'PATCH', body: Row) {\n const data = await this.client.mutate(`${this.base(account)}/${collection}`, method, [body], z.object({ items: z.array(z.object({ data: object.nullable().optional(), exceptions: z.array(z.unknown()).optional() })) }));\n const item = data.items[0], parsed = response.safeParse(item?.data);\n const ids = parsed.success ? [parsed.data.id] : [];\n if (data.items.length !== 1 || !parsed.success || item?.exceptions?.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: native batch item failed or returned incomplete data; reconcile before retrying', { resource_ids: ids });\n if ((parsed.data.ad_account_id !== undefined && parsed.data.ad_account_id !== account) || (body.id && parsed.data.id !== body.id) || (body.status !== undefined && parsed.data.status !== body.status)) throw new AdportError('PROVIDER_ERROR', 'pinterest: mutation receipt ID/account/status mismatch; reconcile before retrying', { resource_ids: ids });\n if (['campaign_id', 'ad_group_id', 'budget_in_micro_currency', 'bid_in_micro_currency'].some(key => body[key] !== undefined && parsed.data[key] !== body[key])) throw new AdportError('PROVIDER_ERROR', 'pinterest: mutation receipt parent/money mismatch; read configuration before retrying', { resource_ids: ids });\n const goals = record(body.optimization_goal_metadata), returnedGoals = record(parsed.data.optimization_goal_metadata);\n 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']]) {\n const expected = record(goals[key!])[field!], returned = record(returnedGoals[key!])[field!];\n if (expected !== undefined && (returned == null || !/^\\d+$/.test(String(returned)) || Number(returned) !== Number(expected))) throw new AdportError('PROVIDER_ERROR', 'pinterest: monetary optimization receipt mismatch; read configuration before retrying', { resource_ids: ids });\n }\n return ids;\n }\n\n private async verifyOptimization(account: string, input: unknown) {\n const tag = record(record(input).conversion_tag_v3_goal_metadata).conversion_tag_id;\n if (tag === undefined) return;\n const result = await this.client.get(`${this.base(account)}/conversion_tags/${pinterestId.parse(tag)}`, z.looseObject({ id: pinterestId, ad_account_id: pinterestId }));\n if (result.id !== tag || result.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'pinterest: conversion tag is not owned by the selected advertiser');\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const p = op.payload, account = op.accountId, coercions: string[] = [], budgetDeltas: WritePreview['budgetDeltas'] = [];\n let collection: 'campaigns' | 'ad_groups' | 'ads', body: Row, method: 'POST' | 'PATCH' = 'PATCH';\n const paused = (status: string) => { if (guard.forcePausedCreation && status !== 'PAUSED') { coercions.push('status coerced to PAUSED by policy (paused_creation)'); return 'PAUSED'; } return status; };\n switch (op.tool) {\n case 'pinterest_create_ad_group': {\n const input = createGroup.parse(p), parent = await this.campaign(account, input.campaign_id);\n if (typeof parent.is_campaign_budget_optimization !== 'boolean') throw new AdportError('INVALID_INPUT', 'pinterest: campaign CBO mode is unavailable; cannot determine budget ownership');\n if (parent.is_campaign_budget_optimization && input.budget_in_micro_currency !== undefined) throw new AdportError('INVALID_INPUT', 'pinterest: CBO campaigns own the budget; omit an ad-group budget');\n if (!parent.is_campaign_budget_optimization && input.budget_in_micro_currency === undefined) throw new AdportError('INVALID_INPUT', 'pinterest: non-CBO campaigns require an ad-group budget');\n if (parent.is_campaign_budget_optimization && input.pacing_delivery_type !== 'STANDARD') throw new AdportError('INVALID_INPUT', 'pinterest: CBO permits only STANDARD pacing');\n if (input.budget_type === 'LIFETIME' && !input.end_time) throw new AdportError('INVALID_INPUT', 'pinterest: lifetime budgets require end_time');\n if (input.lifetime_frequency_cap && !input.end_time) throw new AdportError('INVALID_INPUT', 'pinterest: a frequency cap requires end_time');\n checkTargeting(input.targeting_spec);\n await this.verifyOptimization(account, input.optimization_goal_metadata);\n body = { ...input, status: paused(input.status), ...(input.budget_in_micro_currency !== undefined ? { budget_type: input.budget_type ?? 'DAILY' } : {}) };\n collection = 'ad_groups'; method = 'POST'; moneyDeltas(body, {}, `new ad group ${input.name}`, budgetDeltas); break;\n }\n case 'pinterest_create_ad': {\n const input = createAd.parse(p); await this.owned(account, 'ad_groups', input.ad_group_id);\n collection = 'ads'; method = 'POST'; body = { ...input, status: paused(input.status) }; break;\n }\n case 'pinterest_update_ad_group': {\n const input = updateGroup.parse(p), { ad_group_id, ...fields } = input, current = await this.owned(account, 'ad_groups', ad_group_id);\n body = { id: ad_group_id, ...fields };\n if (fields.targeting_spec) { body.targeting_spec = { ...record(current.targeting_spec), ...fields.targeting_spec }; checkTargeting(body.targeting_spec); }\n if (fields.optimization_goal_metadata) {\n await this.verifyOptimization(account, fields.optimization_goal_metadata);\n const previous = record(current.optimization_goal_metadata), merged: Row = { ...previous, ...fields.optimization_goal_metadata };\n for (const [key, value] of Object.entries(fields.optimization_goal_metadata)) merged[key] = { ...record(previous[key]), ...record(value) };\n body.optimization_goal_metadata = merged;\n }\n const effective = { ...current, ...body };\n if (effective.start_time && effective.end_time && Number(effective.end_time) <= Number(effective.start_time)) throw new AdportError('INVALID_INPUT', 'pinterest: end_time must follow start_time');\n moneyDeltas(body, current, `ad group ${ad_group_id}`, budgetDeltas); collection = 'ad_groups'; break;\n }\n case 'pinterest_update_ad': {\n const input = updateAd.parse(p), { ad_id, ...fields } = input, current = await this.owned(account, 'ads', ad_id);\n if (input.pin_id !== undefined && current.status !== 'DRAFT') throw new AdportError('INVALID_INPUT', 'pinterest: pin_id can only be replaced on DRAFT ads. Create a new paused ad for a different Pin.');\n collection = 'ads'; body = { id: ad_id, ...fields }; break;\n }\n case 'pinterest_set_ad_status':\n case 'pinterest_set_ad_group_status': {\n collection = op.tool === 'pinterest_set_ad_status' ? 'ads' : 'ad_groups';\n const id = pinterestId.parse(p[collection === 'ads' ? 'ad_id' : 'ad_group_id']); await this.owned(account, collection, id);\n body = { id, status: z.enum(['ACTIVE', 'PAUSED']).parse(p.status) }; break;\n }\n case 'pinterest_set_ad_group_budget': {\n const id = pinterestId.parse(p.ad_group_id), current = await this.owned(account, 'ad_groups', id), parent = await this.campaign(account, String(current.campaign_id));\n if (parent.is_campaign_budget_optimization) throw new AdportError('INVALID_INPUT', 'pinterest: this ad group uses the campaign’s CBO budget');\n if (!['DAILY', 'LIFETIME'].includes(String(current.budget_type)) || typeof current.budget_in_micro_currency !== 'number') throw new AdportError('INVALID_INPUT', 'pinterest: current ad-group budget/type is unavailable');\n collection = 'ad_groups'; body = { id, budget_in_micro_currency: z.number().int().positive().safe().parse(p.budget_micros) }; moneyDeltas(body, current, `ad group ${id}`, budgetDeltas); break;\n }\n case 'pinterest_set_ad_group_bidding': {\n const id = pinterestId.parse(p.ad_group_id), current = await this.owned(account, 'ad_groups', id);\n body = { id, ...(p.bid_strategy_type !== undefined ? { bid_strategy_type: p.bid_strategy_type } : {}), ...(p.bid_micros !== undefined ? { bid_in_micro_currency: p.bid_micros } : {}) };\n if ((body.bid_strategy_type ?? current.bid_strategy_type) === 'MAX_BID' && !(body.bid_in_micro_currency ?? current.bid_in_micro_currency)) throw new AdportError('INVALID_INPUT', 'pinterest: MAX_BID requires a monetary bid');\n moneyDeltas(body, current, `ad group ${id}`, budgetDeltas); collection = 'ad_groups'; break;\n }\n case 'pinterest_archive_entity': {\n collection = z.enum(['campaigns', 'ad_groups', 'ads']).parse(p.entity); const id = pinterestId.parse(p.resource_id); await this.owned(account, collection, id); body = { id, status: 'ARCHIVED' }; break;\n }\n default: throw new AdportError('INVALID_INPUT', `pinterest: unsupported write ${op.tool}`);\n }\n return { summary: `Pinterest ${op.tool.replace(/^pinterest_/, '').replaceAll('_', ' ')}`, changes: [`${method} ${collection}: ${JSON.stringify(body)}`], coercions, budgetDeltas, execute: () => this.batch(account, collection, method, body) };\n }\n}\n\nfunction checkTargeting(input: unknown) {\n if (!input) return;\n const target = record(input);\n if (!(Array.isArray(target.GEO) && target.GEO.length) && !(Array.isArray(target.LOCATION) && target.LOCATION.length)) throw new AdportError('INVALID_INPUT', 'pinterest: targeting requires GEO or LOCATION');\n if (Array.isArray(target.AGE_BUCKET) && target.AGE_BUCKET.length && (target.MINIMUM_AGE || target.MAXIMUM_AGE)) throw new AdportError('INVALID_INPUT', 'pinterest: choose AGE_BUCKET or minimum/maximum age');\n 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 AdportError('INVALID_INPUT', 'pinterest: minimum and maximum age must be supplied together and ordered');\n}\nexport function pinMedia(input: unknown, depth = 0): Creative['media'] {\n if (depth > 2) return [];\n const media = record(input), result: Creative['media'] = [];\n const variants = (value: unknown) => 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));\n const video = variants(media.video_list).find(item => safeUrl(item.url).some(url => url.startsWith('https:')));\n if (video) result.push({ type: 'video', url: String(video.url) });\n else {\n const image = variants(media.images).find(item => safeUrl(item.url).some(url => url.startsWith('https:')));\n if (image) result.push({ type: 'image', url: String(image.url) });\n }\n for (const item of (Array.isArray(media.items) ? media.items : []).slice(0, 10)) result.push(...pinMedia(item, depth + 1));\n return result.slice(0, 10);\n}\nfunction moneyDeltas(next: Row, current: Row, target: string, deltas: WritePreview['budgetDeltas']) {\n const amount = (label: string, value: unknown, old: unknown) => {\n const parse = (input: unknown) => { const n = typeof input === 'number' ? input : typeof input === 'string' && /^\\d+$/.test(input) ? Number(input) : NaN; if (!Number.isSafeInteger(n) || n < 0) throw new AdportError('PROVIDER_ERROR', `pinterest: invalid ${label} money value`); return n; };\n const to = parse(value);\n if (old !== undefined && old !== null) deltas.push({ target: `${target} ${label}`, fromMicros: parse(old), toMicros: to });\n else deltas.push({ target: `${target} ${label}`, toMicros: to });\n };\n for (const key of ['budget_in_micro_currency', 'bid_in_micro_currency']) if (next[key] !== undefined) amount(key, next[key], current[key]);\n const goals = record(next.optimization_goal_metadata), previous = record(current.optimization_goal_metadata);\n 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!] !== undefined) amount(field!, record(goals[key!])[field!], record(previous[key!])[field!]);\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { entityStatus, pinterestId } from './schemas.js';\n\nconst id = pinterestId, pinId = z.string().regex(/^\\d+$/).max(30), money = z.number().int().positive().safe(), strings = z.array(z.string().min(1)).max(1000);\nconst url = z.string().url().refine(value => { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) URL without embedded credentials');\nconst microsString = z.string().regex(/^\\d+$/).refine(value => Number.isSafeInteger(Number(value)), 'Micro amount must be a safe integer');\nexport const targeting = z.object({ AGE_BUCKET: strings.optional(), APPTYPE: strings.optional(), AUDIENCE_EXCLUDE: z.array(id).optional(), AUDIENCE_INCLUDE: z.array(id).optional(), GENDER: z.array(z.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: z.string().regex(/^\\d+$/).optional(), MAXIMUM_AGE: z.string().regex(/^\\d+\\+?$/).optional(), TARGETING_STRATEGY: strings.optional() }).strict();\nexport const optimization = z.object({ conversion_tag_v3_goal_metadata: z.object({ conversion_tag_id: id.optional(), conversion_event: z.string().min(1).optional(), cpa_goal_value_in_micro_currency: microsString.optional(), is_roas_optimized: z.boolean().optional(), reporting_event: z.string().optional() }).strict().optional(), frequency_goal_metadata: z.object({ frequency: z.number().int().min(2).max(20), timerange: z.enum(['THIRTY_DAY', 'DAY', 'SEVEN_DAY', 'TWENTY_MINUTE', 'TEN_MINUTE', 'TWENTY_FOUR_HOUR']) }).strict().optional(), scrollup_goal_metadata: z.object({ scrollup_goal_value_in_micro_currency: microsString }).strict().optional() }).strict();\nconst bidStrategy = z.enum(['AUTOMATIC_BID', 'MAX_BID', 'TARGET_AVG']);\nconst groupFields = { name: z.string().trim().min(1).max(255).optional(), targeting_spec: targeting.optional(), auto_targeting_enabled: z.boolean().optional(), placement_group: z.enum(['ALL', 'SEARCH', 'BROWSE', 'OTHER']).optional(), start_time: z.number().int().positive().safe().optional(), end_time: z.number().int().positive().safe().optional(), lifetime_frequency_cap: z.number().int().positive().optional(), optimization_goal_metadata: optimization.optional() };\nexport const createGroup = z.object({ ...groupFields, name: z.string().trim().min(1).max(255), targeting_spec: targeting, auto_targeting_enabled: z.boolean().default(false), campaign_id: id, billable_event: z.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: z.enum(['DAILY', 'LIFETIME']).optional(), pacing_delivery_type: z.enum(['STANDARD', 'ACCELERATED']).default('STANDARD'), status: z.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');\nexport const updateGroup = z.object({ ad_group_id: id, ...groupFields }).refine(v => Object.keys(v).length > 1, 'Provide an ad-group field');\nexport const createAd = z.object({ ad_group_id: id, pin_id: pinId, creative_type: z.enum(['REGULAR', 'VIDEO', 'SHOPPING', 'CAROUSEL', 'MAX_VIDEO', 'COLLECTION', 'IDEA', 'SHOWCASE', 'QUIZ', 'COLLAGE', 'MAX_WIDTH_REGULAR_COLLECTION', 'MAX_WIDTH_VIDEO_COLLECTION', 'APP']), name: z.string().min(1).max(255), destination_url: url.optional(), click_tracking_url: url.optional(), view_tracking_url: url.optional(), status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED') });\nexport const updateAd = z.object({ ad_id: id, name: z.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');\nconst page = { page_size: z.number().int().positive().max(250).default(50), bookmark: z.string().min(1).optional() };\nconst account = { account_id: id };\nconst ids = z.array(id).min(1).max(250);\n\nexport function pinterestCreativeTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (input: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'pinterest', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' = 'update') => guardedWriteTool({ name, namespace: 'pinterest', provider: 'pinterest', description, payload, kind });\n return [\n read('pinterest_get_entity', 'Read a campaign, ad group or ad by ID through the native resource endpoint, verifying advertiser and parent ownership.', z.object({ ...account, entity: z.enum(['campaigns', 'ad_groups', 'ads']), resource_id: id }), input => provider.creatives.getEntity(input.account_id, input.entity, input.resource_id)),\n read('pinterest_ad_groups', 'Read advertiser ad-group targeting, budgets, bids and schedules with native bookmark pagination.', z.object({ ...account, campaign_ids: ids.optional(), ad_group_ids: ids.optional(), entity_statuses: z.array(entityStatus).optional(), ...page }), input => provider.creatives.page(input, 'ad_groups')),\n 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: z.object({ ...account, campaign_ids: ids.optional(), ad_group_ids: ids.optional(), ad_ids: ids.optional(), entity_statuses: z.array(entityStatus).optional(), include_pin_details: z.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) }),\n read('pinterest_targeting_options', 'Read native targeting resources for the selected advertiser; returns provider codes and labels.', z.object({ ...account, targeting_type: z.enum(['APPTYPE', 'GENDER', 'LOCALE', 'AGE_BUCKET', 'LOCATION', 'GEO', 'INTEREST', 'KEYWORD', 'AUDIENCE_INCLUDE', 'AUDIENCE_EXCLUDE']) }), input => provider.creatives.targetingOptions(input.account_id, input.targeting_type)),\n read('pinterest_audience_estimate', 'Get a native non-binding audience-size estimate via read-only POST. No targeting or delivery changes.', z.object({ ...account, targeting_spec: targeting, auto_targeting_enabled: z.boolean(), placement_group: z.enum(['ALL', 'SEARCH', 'BROWSE', 'OTHER']).default('ALL') }), input => provider.creatives.estimate(input)),\n write('pinterest_create_ad_group', 'Create a verified campaign’s ad group, paused by policy. Budgets/bids are integer account-currency micros; non-CBO campaigns require an ad-group budget.', createGroup, 'create'),\n write('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),\n write('pinterest_create_ad', 'Create a paused advertiser ad using an existing eligible Pin. This does not edit or publish an organic Pin.', createAd, 'create'),\n write('pinterest_update_ad', 'Patch the verified advertiser ad’s name/destination/tracking fields. Pin replacement is allowed only for DRAFT ads; existing Pins remain unchanged.', updateAd),\n ...(['ad_group', 'ad'] as const).map(entity => write(`pinterest_set_${entity}_status`, 'Pause or activate an account-owned child entity after checking its parent hierarchy.', z.object({ [entity === 'ad' ? 'ad_id' : 'ad_group_id']: id, status: z.enum(['PAUSED', 'ACTIVE']) }))),\n write('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.', z.object({ ad_group_id: id, budget_micros: money })),\n write('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.', z.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')),\n write('pinterest_archive_entity', 'Archive a verified advertiser campaign, ad group or ad through native batch PATCH. This does not delete an original Pin.', z.object({ entity: z.enum(['campaigns', 'ad_groups', 'ads']), resource_id: id })),\n ];\n}\n","import { z } from 'zod';\n\n// Pinterest's official OpenAPI 5.28.0, reviewed 2026-08-31.\nexport const pinterestId = z.string().regex(/^\\d+$/).max(18);\nexport const entityStatus = z.enum(['ACTIVE', 'PAUSED', 'ARCHIVED', 'DRAFT', 'DELETED_DRAFT']);\nconst micros = z.number().int().nonnegative().safe();\nexport const accountSchema = z.looseObject({ id: pinterestId, name: z.string().optional(), currency: z.string().optional() });\nexport const entitySchema = z.looseObject({ id: pinterestId, ad_account_id: pinterestId, name: z.string().nullable().optional(), status: entityStatus.optional() });\nexport const campaignSchema = entitySchema.extend({\n daily_spend_cap: micros.nullable().optional(), lifetime_spend_cap: micros.nullable().optional(),\n is_campaign_budget_optimization: z.boolean().nullable().optional(),\n is_flexible_daily_budgets: z.boolean().nullable().optional(),\n});\nexport const batchResponseSchema = z.object({ items: z.array(z.object({\n data: campaignSchema.partial().optional(), exceptions: z.array(z.unknown()).optional(),\n})) });\nexport const createCampaignSchema = z.object({\n name: z.string().trim().min(1).max(255),\n objective_type: z.enum(['AWARENESS', 'CONSIDERATION', 'WEB_CONVERSION', 'CATALOG_SALES', 'VIDEO_COMPLETION', 'APP_INSTALL', 'SALES', 'LEADS', 'CTV_CONSIDERATION']),\n status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED'),\n budget_type: z.enum(['DAILY', 'LIFETIME']).default('DAILY'),\n daily_budget_mode: z.enum(['FIXED', 'AVERAGE']).default('FIXED'),\n acknowledge_variable_daily_spend: z.literal(true).optional(),\n budget_micros: micros.positive(),\n start_time: z.number().int().positive().safe().optional(),\n end_time: z.number().int().positive().safe().optional(),\n app_id: z.string().min(1).optional(), app_platform: z.enum(['IOS', 'ANDROID']).optional(),\n}).superRefine((value, ctx) => {\n 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.' });\n if (value.budget_type === 'LIFETIME' && !value.end_time) ctx.addIssue({ code: 'custom', path: ['end_time'], message: 'Lifetime campaign budgets require an end time.' });\n 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.' });\n 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.' });\n});\nexport const setStatusSchema = z.object({ campaign_id: pinterestId, status: z.enum(['PAUSED', 'ACTIVE']) });\nexport const setBudgetSchema = z.object({ campaign_id: pinterestId, budget_micros: micros.positive() });\n","import { createHash } from 'node:crypto';\nimport { AdportError, LocalMediaResolver, creativesOutput, defineTool, guardedWriteTool, mediaSourceFields, type AnyToolDefinition, type Creative, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestId } from './schemas.js';\nimport { pinMedia } from './creatives.js';\n\nconst id = z.string().regex(/^\\d+$/).max(30), hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst privacy = z.enum(['PUBLIC', 'PROTECTED', 'SECRET']);\nconst username = z.string().min(1), owner = z.object({ username });\nconst boardSchema = z.looseObject({ id, name: z.string(), description: z.string().nullable().optional(), privacy, owner, is_ads_only: z.boolean().optional(), pin_count: z.number().int().nonnegative().optional(), collaborator_count: z.number().int().nonnegative().optional(), follower_count: z.number().int().nonnegative().optional() });\nconst pinSchema = z.looseObject({ id, board_id: id, title: z.string().nullable().optional(), description: z.string().nullable().optional(), alt_text: z.string().nullable().optional(), link: z.string().nullable().optional(), is_owner: z.boolean().optional(), has_been_promoted: z.boolean().optional() });\nconst mediaSchema = z.object({ media_id: id, media_type: z.literal('video'), status: z.enum(['registered', 'processing', 'succeeded', 'failed']) });\nconst source = z.object(mediaSourceFields).refine(v => Boolean(v.media_id) !== Boolean(v.file_path), 'Choose project media_id or local file_path');\nconst link = z.string().max(2048).url().refine(value => { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password; }, 'Use an HTTP(S) destination without credentials');\nconst copy = { title: z.string().max(100).nullable().optional(), description: z.string().max(800).nullable().optional(), alt_text: z.string().max(500).nullable().optional(), link: link.nullable().optional() };\nconst pinCreation = { board_id: id, expected_board_privacy: privacy, original_content: z.literal(true), confirm_publication: z.boolean().default(false), ...copy };\nconst createImage = source.safeExtend(pinCreation);\nconst createVideo = z.object({ ...pinCreation, native_media_id: id, cover_image_key_frame_time: z.number().int().nonnegative().safe().default(0) });\nconst createBoard = z.object({ name: z.string().trim().min(1).max(180), description: z.string().max(500).optional(), privacy: privacy.default('SECRET'), confirm_publication: z.boolean().default(false) });\nconst boardReference = { board_id: id, expected_snapshot_hash: hash };\nconst updateBoard = z.object({ ...boardReference, name: z.string().trim().min(1).max(180).optional(), description: z.string().max(500).nullable().optional() }).strict().refine(v => v.name !== undefined || v.description !== undefined, 'Provide a board name or description');\nconst deleteEmptyBoard = z.object({ ...boardReference, confirm_permanent_deletion: z.literal(true) }).strict();\nconst updatePin = z.object({ pin_id: id, expected_snapshot_hash: hash, ...copy }).strict().refine(v => Object.keys(copy).some(key => v[key as keyof typeof v] !== undefined), 'Provide Pin copy to update');\nconst deletePin = z.object({ pin_id: id, expected_snapshot_hash: hash }).strict();\nconst 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' } as const;\nexport const PINTEREST_ASSET_WRITES = new Set(Object.keys(kinds));\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]> };\ntype Page = { account_id: string; page_size: number; bookmark?: string };\ntype Pin = z.infer<typeof pinSchema>;\ntype Board = z.infer<typeof boardSchema>;\nfunction boardSnapshot(board: Board) {\n 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');\n}\nfunction snapshot(pin: Pin, board: z.infer<typeof boardSchema>) {\n 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');\n}\nfunction copyFields(input: Record<string, unknown>) { return Object.fromEntries(Object.keys(copy).filter(key => input[key] !== undefined).map(key => [key, input[key]])); }\nfunction plan(summary: string, changes: string[], execute: Plan['execute']): Plan { 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 }; }\n\n/** Contracts from Pinterest-owned v5 OpenAPI 5.28.0, fetched 2026-11-04. */\nexport class PinterestAssetService {\n constructor(private readonly client: PinterestAdsClient, private readonly media: MediaResolver = new LocalMediaResolver()) {}\n private params(account: string) { return new URLSearchParams({ ad_account_id: pinterestId.parse(account) }); }\n private async account(account: string) {\n const current = await this.client.get(`ad_accounts/${pinterestId.parse(account)}`, z.object({ id: pinterestId, owner }));\n if (current.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: advertiser response ID mismatch');\n return current;\n }\n private async ownedBoard(account: string, boardId: string) {\n const current = await this.account(account);\n const board = await this.client.get(`boards/${id.parse(boardId)}`, boardSchema, this.params(account));\n if (board.id !== boardId || board.owner.username.toLowerCase() !== current.owner.username.toLowerCase()) throw new AdportError('INVALID_INPUT', 'pinterest: board is not owned by the selected advertiser; collaborator boards are not writable through this workflow');\n return board;\n }\n private async nativeOwner(account: string) {\n const current = await this.account(account);\n // /media has no ad_account_id parameter: bind this credential-global resource\n // to the selected advertiser, rather than silently using the token user's library.\n const tokenOwner = await this.client.get('user_account', z.object({ username }));\n if (current.owner.username.toLowerCase() !== tokenOwner.username.toLowerCase()) throw new AdportError('INVALID_INPUT', 'pinterest: native video uploads belong to the token user; the selected advertiser must have that same owner');\n }\n private async page<T>(path: string, schema: z.ZodType<T>, input: Page, params: URLSearchParams) {\n params.set('page_size', String(input.page_size));\n if (input.bookmark) params.set('bookmark', input.bookmark);\n const data = await this.client.get(path, z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() }), params);\n if (data.items.length > input.page_size || data.bookmark && (data.bookmark === input.bookmark || !data.items.length)) throw new AdportError('PROVIDER_ERROR', 'pinterest: media pagination did not advance');\n return { ...data, truncated: Boolean(data.bookmark), ...(data.bookmark ? { next_cursor: data.bookmark } : {}) };\n }\n async boards(input: Page & { privacy?: 'ALL' | 'PUBLIC' | 'PROTECTED' | 'SECRET' | 'PUBLIC_AND_SECRET' }) {\n const current = await this.account(input.account_id), params = this.params(input.account_id);\n if (input.privacy) params.set('privacy', input.privacy);\n const result = await this.page('boards', boardSchema, input, params);\n return { ...result, items: result.items.map(board => ({ ...board, owned_by_advertiser: board.owner.username.toLowerCase() === current.owner.username.toLowerCase() })) };\n }\n async getBoard(account: string, boardId: string) {\n const board = await this.ownedBoard(account, boardId), snapshotHash = boardSnapshot(board);\n const creative: Creative = { id: board.id, provider: 'pinterest', account_id: account, 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: account, board_id: board.id, expected_snapshot_hash: snapshotHash }, fields: [...(board.is_ads_only === true || board.privacy === 'PROTECTED' ? [] : [{ key: 'name', label: 'Board name', type: 'text' as const, value: board.name, max_length: 180 }]), { key: 'description', label: 'Description', type: 'text', value: board.description ?? '', max_length: 500 }] }] };\n 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.'] };\n }\n private async requireEmptyBoard(account: string, board: Board) {\n if (board.privacy !== 'SECRET' || board.is_ads_only !== false || board.pin_count !== 0 || board.collaborator_count !== 0 || board.follower_count !== 0) throw new AdportError('INVALID_INPUT', 'pinterest: empty-board deletion requires an explicitly SECRET, non-ad-only board with known zero Pins, collaborators and followers');\n const input = { account_id: account, page_size: 1 };\n const pins = await this.page(`boards/${board.id}/pins`, pinSchema, input, this.params(account));\n const sections = await this.page(`boards/${board.id}/sections`, z.object({ id: id.optional(), name: z.string() }), input, this.params(account));\n if (pins.items.length || pins.truncated || sections.items.length || sections.truncated) throw new AdportError('INVALID_INPUT', 'pinterest: board still contains Pins or sections; empty-board deletion does not remove content');\n }\n async getPin(account: string, pinId: string) {\n const pin = await this.client.get(`pins/${id.parse(pinId)}`, pinSchema, this.params(account));\n if (pin.id !== pinId) throw new AdportError('PROVIDER_ERROR', 'pinterest: Pin response ID mismatch');\n const board = await this.ownedBoard(account, pin.board_id);\n const snapshotHash = snapshot(pin, board);\n const creative: Creative = { id: pin.id, provider: 'pinterest', account_id: account, 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: account, 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' as const, value: pin.link, max_length: 2048 }] : [])] }] : [] };\n return { pin, board, snapshot_hash: snapshotHash, creatives: [creative], truncated: false };\n }\n async pins(input: Page & { board_id?: string }) {\n if (input.board_id) await this.ownedBoard(input.account_id, input.board_id); else await this.account(input.account_id);\n const data = await this.page(input.board_id ? `boards/${input.board_id}/pins` : 'pins', pinSchema, input, this.params(input.account_id));\n if (input.board_id && data.items.some(pin => pin.board_id !== input.board_id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: Pin collection returned another board');\n const creatives: Creative[] = 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: [] }));\n 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.'] };\n }\n async getMedia(account: string, mediaId: string) {\n await this.nativeOwner(account);\n const current = await this.client.get(`media/${id.parse(mediaId)}`, mediaSchema);\n if (current.media_id !== mediaId) throw new AdportError('PROVIDER_ERROR', 'pinterest: media response ID mismatch');\n return current;\n }\n private checkPublication(board: { privacy: string }, expected: string, confirmed: boolean) {\n if (board.privacy !== expected) throw new AdportError('PENDING_MISMATCH', 'pinterest: board privacy changed; read boards and prepare a new preview');\n if (board.privacy === 'PUBLIC' && !confirmed) throw new AdportError('INVALID_INPUT', 'pinterest: a public board publishes organic content; explicit confirm_publication is required');\n }\n private checkPinReceipt(pin: Pin, boardId: string, fields: Record<string, unknown>, pinId?: string) {\n if (pinId && pin.id !== pinId || pin.board_id !== boardId || Object.entries(fields).some(([key, value]) => (pin[key] ?? null) !== value)) throw new AdportError('PROVIDER_ERROR', 'pinterest: Pin write receipt differs from approved content; reconcile before retrying', { resource_ids: [pin.id] });\n return [pin.id];\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'pinterest' || !PINTEREST_ASSET_WRITES.has(op.tool) || op.kind !== kinds[op.tool as keyof typeof kinds]) throw new AdportError('INVALID_INPUT', 'pinterest: invalid asset operation kind');\n const account = pinterestId.parse(op.accountId), params = this.params(account);\n if (op.tool === 'pinterest_create_board') {\n const input = createBoard.parse(op.payload), current = await this.account(account);\n this.checkPublication(input, input.privacy, input.confirm_publication);\n const { confirm_publication: _confirmed, ...body } = input;\n const native = { ...body, ...(input.privacy === 'PROTECTED' ? { is_ads_only: true } : {}) };\n return plan(`Create Pinterest ${input.privacy} board`, [JSON.stringify(native), input.privacy === 'PROTECTED' ? 'Pinterest names ad-only boards “Ad-only Pins”; they are protected, not secret.' : `Board owned by ${current.owner.username}; no Pin or ad is created.`], async () => {\n const created = await this.client.mutate('boards', 'POST', native, boardSchema, params);\n if (created.owner.username.toLowerCase() !== current.owner.username.toLowerCase() || created.privacy !== input.privacy || input.privacy !== 'PROTECTED' && created.name !== input.name || input.privacy === 'PROTECTED' && created.is_ads_only !== true) throw new AdportError('PROVIDER_ERROR', 'pinterest: created board owner/privacy/name mismatch; reconcile before retrying', { resource_ids: [created.id] });\n return [created.id];\n });\n }\n if (op.tool === 'pinterest_update_board' || op.tool === 'pinterest_delete_empty_board') {\n const input = op.tool === 'pinterest_update_board' ? updateBoard.parse(op.payload) : deleteEmptyBoard.parse(op.payload), board = await this.ownedBoard(account, input.board_id);\n if (boardSnapshot(board) !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: board copy, privacy or ownership changed; read the board again');\n if (op.tool === 'pinterest_delete_empty_board') {\n await this.requireEmptyBoard(account, board);\n return plan(`Permanently delete empty Pinterest board “${board.name}”`, [`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 () => {\n // Recheck immediately before DELETE as well as when the apply plan is built.\n const fresh = await this.ownedBoard(account, board.id);\n if (boardSnapshot(fresh) !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: board changed before deletion; read it again');\n await this.requireEmptyBoard(account, fresh);\n const receipt = await this.client.mutate(`boards/${board.id}`, 'DELETE', undefined, boardSchema.optional(), params);\n if (receipt && receipt.id !== board.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: board deletion receipt ID mismatch; reconcile before retrying', { resource_ids: [board.id] });\n return [board.id];\n });\n }\n const patch = updateBoard.parse(input);\n if (patch.name !== undefined && (board.is_ads_only === true || board.privacy === 'PROTECTED')) throw new AdportError('INVALID_INPUT', 'pinterest: ad-only board names are assigned by Pinterest; edit only the description');\n const fields = { ...(patch.name !== undefined ? { name: patch.name } : {}), ...(patch.description !== undefined ? { description: patch.description } : {}) };\n const edit = plan(`Edit Pinterest board “${board.name}”`, [`Board ${board.id}; visibility ${board.privacy} is preserved. Pins, sections and delivery are unchanged.`, ...Object.entries(fields).map(([key, value]) => `${key}: ${JSON.stringify(board[key] ?? null)} → ${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 () => {\n const receipt = await this.client.mutate(`boards/${board.id}`, 'PATCH', fields, boardSchema, params);\n 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(fields).some(([key, value]) => (receipt[key] ?? null) !== value) || patch.name === undefined && receipt.name !== board.name || patch.description === undefined && (receipt.description ?? null) !== (board.description ?? null)) throw new AdportError('PROVIDER_ERROR', 'pinterest: board update receipt differs from approved copy or preserved visibility/ownership; reconcile before retrying', { resource_ids: [board.id] });\n return [board.id];\n });\n return { ...edit, fieldChanges: Object.entries(fields).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)') })) };\n }\n if (op.tool === 'pinterest_upload_video') {\n const input = source.parse(op.payload); await this.nativeOwner(account);\n const file = await this.media.read(input, { maxBytes: 50 * 1024 * 1024, contentTypes: ['video/mp4'] });\n 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 () => {\n let mediaId: string | undefined;\n try {\n const result = await this.client.mutate('media', 'POST', { media_type: 'video' }, z.object({ media_id: id, media_type: z.literal('video'), upload_url: z.string().url().optional(), upload_parameters: z.record(z.string(), z.string()).optional() }));\n mediaId = result.media_id;\n if (!result.upload_url || !result.upload_parameters) throw new Error('incomplete native upload instructions');\n await this.client.uploadVideo(result.upload_url, result.upload_parameters, file.bytes, file.name);\n } catch (error) {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n const ids = mediaId ? [mediaId] : Array.isArray(details.resource_ids) ? details.resource_ids.filter((value): value is string => typeof value === 'string' && /^\\d{1,30}$/.test(value)).slice(0, 2) : [];\n throw new AdportError('PROVIDER_ERROR', 'pinterest: native video registration/transfer was not confirmed; reconcile before retrying. No mutation was retried.', { resource_ids: ids });\n }\n return [mediaId!];\n });\n }\n if (op.tool === 'pinterest_create_image_pin' || op.tool === 'pinterest_create_video_pin') {\n const image = op.tool === 'pinterest_create_image_pin' ? createImage.parse(op.payload) : undefined, video = image ? undefined : createVideo.parse(op.payload), input = image ?? video!;\n const board = await this.ownedBoard(account, input.board_id);\n this.checkPublication(board, input.expected_board_privacy, input.confirm_publication);\n let mediaSource: Record<string, unknown>, mediaNote: string;\n if (image) {\n const file = await this.media.read(image, { maxBytes: 20 * 1024 * 1024, contentTypes: ['image/png', 'image/jpeg'] });\n mediaSource = { source_type: 'image_base64', content_type: file.contentType, data: Buffer.from(file.bytes).toString('base64') };\n mediaNote = `${file.name}; ${file.bytes.length} bytes; SHA-256 ${file.sha256}.`;\n } else {\n const native = await this.getMedia(account, video!.native_media_id);\n if (native.status !== 'succeeded') throw new AdportError('INVALID_INPUT', `pinterest: video processing is ${native.status}; only succeeded media can create a Pin`);\n mediaSource = { source_type: 'video_id', media_id: native.media_id, cover_image_key_frame_time: video!.cover_image_key_frame_time };\n mediaNote = `Native video ${native.media_id}; cover keyframe ${video!.cover_image_key_frame_time}s.`;\n }\n const fields = copyFields(input), body = { board_id: board.id, ...fields, media_source: mediaSource };\n return plan(`Create Pinterest ${image ? 'image' : 'video'} Pin on ${board.privacy} board`, [mediaNote, `Board ${board.id} “${board.name}”; visibility ${board.privacy}.`, JSON.stringify(fields), '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, fields));\n }\n const input = op.tool === 'pinterest_update_pin' ? updatePin.parse(op.payload) : deletePin.parse(op.payload), current = await this.getPin(account, input.pin_id);\n if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: Pin copy, ownership, promotion or board privacy changed; read the Pin again');\n if (current.pin.is_owner !== true || current.pin.has_been_promoted !== false) throw new AdportError('INVALID_INPUT', 'pinterest: only an explicitly owned, never-promoted original Pin can be edited/deleted here. Create a replacement for promoted or unknown usage.');\n 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 () => {\n const receipt = await this.client.mutate(`pins/${input.pin_id}`, 'DELETE', undefined, pinSchema.optional(), params);\n if (receipt && receipt.id !== input.pin_id) throw new AdportError('PROVIDER_ERROR', 'pinterest: deletion receipt ID mismatch; reconcile before retrying', { resource_ids: [input.pin_id] });\n return [input.pin_id];\n });\n const fields = copyFields(input);\n 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(fields).map(([key, value]) => `${key}: ${JSON.stringify(current.pin[key] ?? null)} → ${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', fields, pinSchema, params), current.board.id, fields, input.pin_id));\n }\n}\n\nexport function pinterestAssetTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const account = { account_id: pinterestId }, paging = { page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).optional() };\n return [\n defineTool({ 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: z.object({ ...account, ...paging, privacy: z.enum(['ALL', 'PUBLIC', 'PROTECTED', 'SECRET', 'PUBLIC_AND_SECRET']).optional() }), annotations: { readOnly: true }, handler: input => provider.assets.boards(input) }),\n defineTool({ 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: z.object({ ...account, board_id: id }), output: creativesOutput.passthrough(), presentation: 'records', annotations: { readOnly: true }, handler: input => provider.assets.getBoard(input.account_id, input.board_id) }),\n defineTool({ 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: z.object({ ...account, ...paging, board_id: id.optional() }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: input => provider.assets.pins(input) }),\n defineTool({ 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: z.object({ ...account, pin_id: id }), output: creativesOutput.passthrough(), presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.assets.getPin(input.account_id, input.pin_id) }),\n defineTool({ 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: z.object({ ...account, native_media_id: id }), annotations: { readOnly: true }, handler: input => provider.assets.getMedia(input.account_id, input.native_media_id) }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, creativesOutput, defineTool, guardedWriteTool, planningViewSchema, type AnyToolDefinition, type Creative, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestId as id } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]> };\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), cursor = z.string().min(1).max(4096);\nconst parent = z.discriminatedUnion('type', [z.object({ type: z.literal('account') }).strict(), z.object({ type: z.literal('campaign'), campaign_id: id }).strict(), z.object({ type: z.literal('ad_group'), ad_group_id: id }).strict()]);\nconst match = z.enum(['BROAD', 'PHRASE', 'EXACT', 'EXACT_NEGATIVE', 'PHRASE_NEGATIVE']);\n// The native metrics endpoint rejects other ISO markets (live verified2026-11-04).\nconst metricsCountry = z.enum(['CA', 'GB', 'US', 'IE', 'AU', 'NZ']);\nconst keyword = z.looseObject({ id, parent_id: id, parent_type: z.string().optional(), match_type: match.nullable(), value: z.string(), archived: z.boolean().optional(), bid: z.number().int().nullable().optional() });\ntype Keyword = z.infer<typeof keyword>;\nconst reference = { parent, expected_parent_hash: hash };\nconst create = z.object({ ...reference, keywords: z.array(z.object({ value: z.string().trim().min(1).max(120), match_type: match }).strict()).min(1).max(100) }).strict().superRefine((v, ctx) => {\n 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' });\n 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' });\n});\nconst archive = z.object({ ...reference, keywords: z.array(z.object({ keyword_id: id, expected_snapshot_hash: hash }).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');\ntype Parent = z.infer<typeof parent>;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');\nconst snapshot = (value: Keyword) => 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 });\nconst writes = new Set(['pinterest_create_keywords', 'pinterest_archive_keywords']);\n\n/** Pinterest-owned v5 OpenAPI5.28.0 /keywords, fetched 2026-11-04. */\nexport class PinterestKeywordService {\n constructor(private readonly client: PinterestAdsClient, private readonly entity: (account: string, type: 'campaigns' | 'ad_groups', resource: string) => Promise<Row>) {}\n supports(tool: string) { return writes.has(tool); }\n private base(account: string) { return `ad_accounts/${id.parse(account)}/keywords`; }\n async context(account: string, selected: Parent) {\n const scope = parent.parse(selected);\n let entity: Row, campaign: Row | undefined;\n if (scope.type === 'account') {\n entity = await this.client.get(`ad_accounts/${id.parse(account)}`, z.looseObject({ id }));\n if (entity.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword account response mismatch');\n } else if (scope.type === 'campaign') entity = await this.entity(account, 'campaigns', scope.campaign_id);\n else { entity = await this.entity(account, 'ad_groups', scope.ad_group_id); campaign = await this.entity(account, 'campaigns', id.parse(entity.campaign_id)); }\n const parentId = id.parse(entity.id), configuration = { account_id: account, parent: scope, parent_id: parentId, status: entity.status ?? null, ...(campaign ? { campaign_id: campaign.id, campaign_status: campaign.status ?? null } : {}) };\n return { ...configuration, entity, ...(campaign ? { campaign } : {}), parent_snapshot_hash: digest(configuration), 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.'] };\n }\n private scoped(value: Keyword, context: { parent: Parent; parent_id: string }) {\n const types = context.parent.type === 'account' ? ['advertiser', 'account', 'adaccount'] : context.parent.type === 'campaign' ? ['campaign'] : ['adgroup'];\n if (value.parent_id !== context.parent_id || value.parent_type && !types.includes(value.parent_type.toLowerCase().replaceAll('_', ''))) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword collection returned another parent');\n return value;\n }\n private async page(account: string, context: Awaited<ReturnType<PinterestKeywordService['context']>>, size: number, bookmark?: string, matches?: z.infer<typeof match>[]) {\n const params = new URLSearchParams({ page_size: String(size) });\n if (context.parent.type === 'campaign') params.set('campaign_id', context.parent_id);\n if (context.parent.type === 'ad_group') params.set('ad_group_id', context.parent_id);\n if (bookmark) params.set('bookmark', bookmark);\n if (matches) params.set('match_types', matches.join(','));\n const data = await this.client.get(this.base(account), z.object({ items: z.array(keyword), bookmark: z.string().nullable().optional() }), params);\n 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 AdportError('PROVIDER_ERROR', 'pinterest: keyword pagination did not advance or returned duplicate/oversized rows');\n if (matches && data.items.some(v => v.match_type === null || !matches.includes(v.match_type))) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword collection ignored the match-type selection');\n return { ...data, items: data.items.map(v => this.scoped(v, context)), truncated: Boolean(data.bookmark), ...(data.bookmark ? { next_cursor: data.bookmark } : {}) };\n }\n private view(account: string, scope: Parent, parentHash: string, item: Keyword): Creative {\n return { id: item.id, provider: 'pinterest', account_id: account, 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: account, parent: scope, expected_parent_hash: parentHash, keywords: [{ keyword_id: item.id, expected_snapshot_hash: snapshot(item) }] }, fields: [] }] : [] };\n }\n async list(input: { account_id: string; parent: Parent; page_size: number; bookmark?: string; match_types?: z.infer<typeof match>[] }) {\n 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);\n 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: snapshot(value) })), creatives: data.items.map(value => this.view(input.account_id, context.parent, context.parent_snapshot_hash, value)), notes: context.notes };\n }\n private async find(account: string, context: Awaited<ReturnType<PinterestKeywordService['context']>>, wanted: Set<string>) {\n const found = new Map<string, Keyword>(), cursors = new Set<string>(), seen = new Set<string>();\n let bookmark: string | undefined;\n for (let page = 0; page < 40; page++) {\n const result = await this.page(account, context, 250, bookmark);\n for (const row of result.items) {\n if (seen.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword inventory repeated an ID'); seen.add(row.id);\n if (wanted.has(row.id)) found.set(row.id, row);\n }\n if (found.size === wanted.size) return found;\n if (!result.next_cursor) throw new AdportError('INVALID_INPUT', 'pinterest: requested keyword is not visible in this parent; archived keywords cannot be safely rediscovered/unarchived through this API');\n if (cursors.has(result.next_cursor)) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword inventory repeated a cursor');\n cursors.add(result.next_cursor); bookmark = result.next_cursor;\n }\n throw new AdportError('INVALID_INPUT', 'pinterest: keyword ownership lookup exceeded 10,000 rows; no write was made');\n }\n async get(account: string, scope: Parent, keywordId: string) {\n const context = await this.context(account, scope), found = (await this.find(account, context, new Set([keywordId]))).get(keywordId)!;\n return { keyword: found, snapshot_hash: snapshot(found), parent_snapshot_hash: context.parent_snapshot_hash, creatives: [this.view(account, scope, context.parent_snapshot_hash, found)], truncated: false, notes: context.notes };\n }\n async metrics(input: { account_id: string; country_code: string; keywords: string[] }) {\n metricsCountry.parse(input.country_code);\n const data = await this.client.get(`${this.base(input.account_id)}/metrics`, z.object({ data: z.array(z.looseObject({ keyword: z.string(), metrics: z.looseObject({ keyword_query_volume: z.string().optional() }).optional() })) }), new URLSearchParams({ country_code: input.country_code, keywords: input.keywords.join(',') }));\n const wanted = new Set(input.keywords), seen = new Set<string>();\n for (const item of data.data) { if (!wanted.has(item.keyword) || seen.has(item.keyword)) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword metrics returned another or repeated keyword'); seen.add(item.keyword); }\n 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.'] } };\n }\n private async batch(account: string, context: Awaited<ReturnType<PinterestKeywordService['context']>>, method: 'POST' | 'PATCH', body: Row, expected: Array<{ id?: string; value?: string; match_type?: string | null; archived?: boolean }>) {\n const data = await this.client.mutate(this.base(account), method, body, z.object({ keywords: z.array(z.unknown()), errors: z.array(z.unknown()) }));\n const ids = data.keywords.flatMap(value => { const parsed = z.object({ id }).safeParse(value); return parsed.success ? [parsed.data.id] : []; });\n const parsed = z.array(keyword).safeParse(data.keywords);\n if (data.errors.length || !parsed.success || parsed.data.length !== expected.length || new Set(ids).size !== ids.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword batch was partial or incomplete; reconcile returned IDs before retrying', { resource_ids: ids });\n const unmatched = [...expected];\n for (const row of parsed.data) {\n try { this.scoped(row, context); } catch { throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword receipt belongs to another parent; reconcile before retrying', { resource_ids: ids }); }\n const index = unmatched.findIndex(item => Object.entries(item).every(([key, value]) => row[key] === value));\n if (index < 0) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword receipt differs from approved keywords; reconcile before retrying', { resource_ids: ids });\n unmatched.splice(index, 1);\n }\n return ids;\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n if (op.provider !== 'pinterest' || !this.supports(op.tool) || op.kind !== (op.tool === 'pinterest_create_keywords' ? 'create' : 'update')) throw new AdportError('INVALID_INPUT', 'pinterest: invalid keyword operation');\n const input = op.tool === 'pinterest_create_keywords' ? create.parse(op.payload) : archive.parse(op.payload), context = await this.context(op.accountId, input.parent);\n if (context.parent_snapshot_hash !== input.expected_parent_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: keyword parent state changed; read its context again');\n const notes = ['Preview is local; Pinterest has no server dry-run for keyword writes.', ...context.notes];\n if (op.tool === 'pinterest_create_keywords') {\n const value = create.parse(input), positive = value.keywords.some(item => !item.match_type.endsWith('_NEGATIVE'));\n if (guard.forcePausedCreation && positive && context.entity.status !== 'PAUSED' && context.campaign?.status !== 'PAUSED') throw new AdportError('POLICY_VIOLATION', 'pinterest: positive keywords cannot be paused individually; paused_creation requires a paused parent ad group or campaign');\n return { summary: `Create ${value.keywords.length} Pinterest keywords`, changes: [`Parent ${context.parent.type} ${context.parent_id}.`, ...value.keywords.map(item => `${item.match_type}: ${item.value}`), 'Keyword bids are omitted; existing ad-group bidding is preserved.'], coercions: [], budgetDeltas: [], notes, execute: () => this.batch(op.accountId, context, 'POST', { parent_id: context.parent_id, keywords: value.keywords }, value.keywords.map(item => ({ ...item, archived: false }))) };\n }\n const value = archive.parse(input), current = await this.find(op.accountId, context, new Set(value.keywords.map(item => item.keyword_id)));\n for (const item of value.keywords) if (snapshot(current.get(item.keyword_id)!) !== item.expected_snapshot_hash || current.get(item.keyword_id)!.archived !== false) throw new AdportError('PENDING_MISMATCH', 'pinterest: keyword contents or archive state changed; read it again');\n return { summary: `Archive ${value.keywords.length} Pinterest keywords`, changes: [...current.values()].map(item => `${item.match_type}: ${item.value} (${item.id}) → archived`), coercions: [], budgetDeltas: [], notes: [...notes, '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 }))) };\n }\n}\n\nexport function pinterestKeywordTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const account = { account_id: id }, selected = { ...account, parent: parent.default({ type: 'account' }) };\n return [\n defineTool({ 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: z.object(selected), annotations: { readOnly: true }, handler: v => provider.keywords.context(v.account_id, v.parent) }),\n defineTool({ name: 'pinterest_keywords', namespace: 'pinterest', description: 'List one verified parent’s 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: z.object({ ...selected, page_size: z.number().int().min(1).max(250).default(50), bookmark: cursor.optional(), match_types: z.array(match).min(1).max(5).optional() }), output: creativesOutput.passthrough(), presentation: 'records', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: v => provider.keywords.list(v) }),\n defineTool({ 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: z.object({ ...selected, keyword_id: id }), output: creativesOutput.passthrough(), presentation: 'records', annotations: { readOnly: true }, handler: v => provider.keywords.get(v.account_id, v.parent, v.keyword_id) }),\n defineTool({ 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: z.object({ ...account, country_code: metricsCountry, keywords: z.array(z.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: z.object({ planning: planningViewSchema }).passthrough(), presentation: 'planning', annotations: { readOnly: true }, handler: v => provider.keywords.metrics(v) }),\n guardedWriteTool({ 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 }),\n guardedWriteTool({ 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 }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition, type Creative, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestId as id } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]> };\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), name = z.string().trim().min(1).max(255), description = z.string().max(1000).nullable();\nconst ids = z.array(id).min(1).max(100).refine(v => new Set(v).size === v.length, 'Use unique IDs');\nconst href = z.string().url().max(2048).refine(value => { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) URL without credentials');\nconst domain = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z]{2,63}$/);\nconst customer = z.object({ audience_type: z.literal('CUSTOMER_LIST'), customer_list_id: id, expected_source_hash: hash }).strict();\nconst visitor = z.object({ audience_type: z.literal('VISITOR'), visitor_source_ids: ids, retention_days: z.number().int().min(1).max(540), prefill: z.boolean(), event: z.string().min(1).max(100).optional(), event_source: z.array(z.enum(['web', 'mobile', 'offline'])).min(1).max(3).optional(), ingestion_source: z.array(z.enum(['tag', 'mmp', 'file_upload', 'conversions_api'])).min(1).max(4).optional(), url: z.array(href).min(1).max(100).optional() }).strict();\nconst engagement = z.object({ audience_type: z.literal('ENGAGEMENT'), engagement_domains: z.array(domain).min(1).max(10), engagement_type: z.enum(['click', 'save', 'closeup', 'comment', 'like']).optional(), engager_type: z.number().int().min(1).max(2).optional(), retention_days: z.number().int().min(1).max(540).optional(), campaign_ids: ids.optional(), ad_ids: ids.optional(), pin_ids: z.array(z.string().regex(/^\\d{1,30}$/)).min(1).max(100).optional(), objective_types: z.array(z.enum(['AWARENESS', 'CONSIDERATION', 'WEB_CONVERSION', 'CATALOG_SALES', 'VIDEO_COMPLETION', 'SALES'])).min(1).max(6).optional(), url: z.array(href).min(1).max(100).optional() }).strict();\nconst actalike = z.object({ audience_type: z.literal('ACTALIKE'), seeds: z.array(z.object({ audience_id: id, expected_snapshot_hash: hash }).strict()).min(1).max(100).refine(v => new Set(v.map(s => s.audience_id)).size === v.length, 'Use unique seeds'), country: z.enum(['US', 'CA', 'GB']), percentage: z.number().int().min(1).max(10) }).strict();\nconst definition = z.discriminatedUnion('audience_type', [customer, visitor, engagement, actalike]);\ntype Definition = z.infer<typeof definition>;\nconst audience = z.looseObject({ id, ad_account_id: id.optional(), name: z.string().optional(), description: z.string().nullable().optional(), audience_type: z.string().optional(), rule: z.record(z.string(), z.unknown()).optional(), is_nca: z.boolean().optional(), status: z.string().optional() });\nconst customerList = z.object({ id, name: z.string(), ad_account_id: id.optional(), is_nca: z.boolean().optional(), status: z.string().optional(), created_time: z.number().finite().optional(), updated_time: z.number().finite().optional(), num_batches: z.number().int().nonnegative().optional(), num_uploaded_user_records: z.number().int().nonnegative().optional(), num_removed_user_records: z.number().int().nonnegative().optional(), exceptions: z.record(z.string(), z.unknown()).optional() });\nconst selected = { audience_id: id, expected_snapshot_hash: hash };\nconst createAudience = z.object({ name, description: description.optional(), definition }).strict();\nconst updateAudience = z.object({ ...selected, name: name.optional(), description: description.optional() }).strict().refine(v => v.name !== undefined || v.description !== undefined, 'Supply audience copy');\nconst replaceRule = z.object({ ...selected, expected_context_hash: hash, definition }).strict();\nconst removeAudience = z.object({ audience_id: id, expected_context_hash: hash, confirm_permanent_removal: z.literal(true) }).strict();\nconst records = z.array(hash).min(1).max(10_000).refine(v => new Set(v).size === v.length, 'Use unique SHA-256 records');\nconst createList = z.object({ name, list_type: z.enum(['EMAIL', 'IDFA', 'MAID']).default('EMAIL'), is_nca: z.boolean().default(false), records_sha256: records, confirm_data_rights: z.literal(true) }).strict();\nconst updateRecords = z.object({ customer_list_id: id, expected_snapshot_hash: hash, operation_type: z.enum(['ADD', 'REMOVE']), records_sha256: records, confirm_data_rights: z.literal(true) }).strict();\nconst writes = new Map<string, WriteOperation['kind']>([['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']]);\nconst object = (value: unknown): Row => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\nfunction canonical(value: unknown): unknown {\n if (typeof value === 'number' && Number.isInteger(value) && !Number.isSafeInteger(value)) throw new AdportError('PROVIDER_ERROR', 'pinterest: unsafe native identifier or counter in audience configuration');\n if (Array.isArray(value)) return value.map(canonical);\n return value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\n}\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst audienceSnapshot = (value: z.infer<typeof audience>) => digest(Object.fromEntries(['id', 'ad_account_id', 'name', 'description', 'audience_type', 'rule', 'is_nca'].map(key => [key, value[key] ?? null])));\nconst listSnapshot = (value: z.infer<typeof customerList>) => digest(Object.fromEntries((['id', 'ad_account_id', 'name', 'is_nca', 'updated_time', 'num_batches', 'num_uploaded_user_records', 'num_removed_user_records'] as const).map(key => [key, value[key] ?? null])));\nfunction normalizeRule(value: unknown): Row {\n const rule = { ...object(value) };\n if (rule.percentage !== undefined) rule.percentage = String(rule.percentage);\n if (typeof rule.visitor_source_id === 'string') rule.visitor_source_id = [rule.visitor_source_id];\n if (Array.isArray(rule.seed_id)) { canonical(rule.seed_id); rule.seed_id = rule.seed_id.map(String); }\n return rule;\n}\nfunction includesFields(actual: unknown, expected: unknown): boolean {\n if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => includesFields(actual[index], value));\n if (expected !== null && typeof expected === 'object') return Object.entries(object(expected)).every(([key, value]) => includesFields(object(actual)[key], value));\n return actual === expected;\n}\n\n/** Pinterest-owned v5 OpenAPI5.28.0 audience/customer-list contracts, fetched2026-11-04. */\nexport class PinterestAudienceService {\n constructor(private readonly client: PinterestAdsClient, private readonly entity: (account: string, type: 'campaigns' | 'ads', resource: string) => Promise<Row>, private readonly pin: (account: string, resource: string) => Promise<{ pin: Row }>) {}\n supports(tool: string) { return writes.has(tool); }\n private base(account: string) { return `ad_accounts/${id.parse(account)}`; }\n private async page<T>(account: string, path: string, schema: z.ZodType<T>, size: number, bookmark?: string, extra: Record<string, string> = {}) {\n const data = await this.client.get(`${this.base(account)}/${path}`, z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() }), new URLSearchParams({ ...extra, page_size: String(size), ...(bookmark ? { bookmark } : {}) }));\n if (data.items.length > size || data.bookmark && (!data.items.length || data.bookmark === bookmark)) throw new AdportError('PROVIDER_ERROR', 'pinterest: audience pagination did not advance or exceeded page size');\n return { ...data, truncated: Boolean(data.bookmark), ...(data.bookmark ? { next_cursor: data.bookmark } : {}) };\n }\n async list(input: { account_id: string; ownership_type: 'OWNED' | 'RECEIVED'; page_size: number; bookmark?: string }) {\n const data = await this.page(input.account_id, 'audiences', audience, input.page_size, input.bookmark, { ownership_type: input.ownership_type });\n 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 !== undefined && v.ad_account_id !== input.account_id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: owned audience list returned foreign ownership or duplicate IDs');\n return { ...data, items: data.items.map(v => ({ ...v, owned_by_advertiser: v.ad_account_id === input.account_id, snapshot_hash: audienceSnapshot(v) })) };\n }\n async get(account: string, audienceId: string) {\n const current = await this.client.get(`${this.base(account)}/audiences/${id.parse(audienceId)}`, audience);\n if (current.id !== audienceId || current.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'pinterest: audience ownership was not confirmed for this advertiser; received audiences are not writable');\n const snapshotHash = audienceSnapshot(current);\n const creative: Creative = { id: current.id, provider: 'pinterest', account_id: account, 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: account, 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: 1000 }] }] };\n 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.'] };\n }\n async getCustomerList(account: string, resource: string) {\n const current = await this.client.get(`${this.base(account)}/customer_lists/${id.parse(resource)}`, customerList);\n if (current.id !== resource || current.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'pinterest: customer list is not explicitly owned by this advertiser');\n const { exceptions: _exceptions, ...metadata } = current;\n return { customer_list: metadata, snapshot_hash: listSnapshot(current), has_exceptions: Boolean(current.exceptions && Object.keys(object(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.'] };\n }\n async customerLists(input: { account_id: string; page_size: number; bookmark?: string }) {\n const data = await this.page(input.account_id, 'customer_lists', customerList, input.page_size, input.bookmark);\n 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 AdportError('PROVIDER_ERROR', 'pinterest: customer list returned foreign/missing ownership or duplicate IDs');\n return { ...data, items: data.items.map(value => { const { exceptions: _exceptions, ...metadata } = value; return { ...metadata, snapshot_hash: listSnapshot(value) }; }) };\n }\n async sources(account: string) {\n const current = await this.client.get(this.base(account), z.object({ id, owner: z.object({ username: z.string() }) }));\n if (current.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: audience account ID mismatch');\n const native = await this.client.get('user_account', z.object({ username: z.string() }));\n 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’s domains. Account-scoped tag/list/seed workflows remain available.'] };\n const websites: Array<{ website: string; status?: string; verified_at?: string }> = [], seen = new Set<string>();\n let bookmark: string | undefined;\n for (let page = 0; page < 20; page++) {\n const data = await this.client.get('user_account/websites', z.object({ items: z.array(z.object({ website: z.string(), status: z.string().optional(), verified_at: z.string().optional() })), bookmark: z.string().nullable().optional() }), new URLSearchParams({ page_size: '250', ...(bookmark ? { bookmark } : {}) }));\n if (data.items.length > 250 || data.bookmark && (!data.items.length || seen.has(data.bookmark) || data.bookmark === bookmark)) throw new AdportError('PROVIDER_ERROR', 'pinterest: website pagination did not advance');\n websites.push(...data.items);\n 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.'] };\n seen.add(data.bookmark); bookmark = data.bookmark;\n }\n return { token_owner_matches: true, websites, complete: false, notes: ['Website inventory exceeded 5,000 entries; engagement-domain validation is blocked.'] };\n }\n private async rule(account: string, value: Definition): Promise<Row> {\n if (value.audience_type === 'CUSTOMER_LIST') {\n const source = await this.getCustomerList(account, value.customer_list_id);\n if (source.snapshot_hash !== value.expected_source_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: customer-list source changed; read it again');\n return { customer_list_id: value.customer_list_id };\n }\n if (value.audience_type === 'ACTALIKE') {\n for (const seed of value.seeds) {\n const source = await this.get(account, seed.audience_id);\n if (source.snapshot_hash !== seed.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: seed audience configuration changed; read it again');\n }\n return { seed_id: value.seeds.map(v => v.audience_id), country: value.country, percentage: value.percentage };\n }\n if (value.audience_type === 'VISITOR') {\n for (const source of value.visitor_source_ids) {\n const tag = await this.client.get(`${this.base(account)}/conversion_tags/${source}`, z.object({ id, ad_account_id: id }));\n if (tag.id !== source || tag.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'pinterest: visitor source tag is not owned by this advertiser');\n }\n 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 } : {}) };\n }\n const available = await this.sources(account);\n const hosts = new Set(available.websites.flatMap(v => { try { return [new URL(v.website.includes('://') ? v.website : `https://${v.website}`).hostname]; } catch { return []; } }));\n if (!available.complete || !available.token_owner_matches || value.engagement_domains.some(v => !hosts.has(v))) throw new AdportError('INVALID_INPUT', 'pinterest: engagement domains are not present in the complete advertiser-owner website inventory');\n for (const campaign of value.campaign_ids ?? []) await this.entity(account, 'campaigns', campaign);\n for (const ad of value.ad_ids ?? []) await this.entity(account, 'ads', ad);\n for (const pin of value.pin_ids ?? []) if ((await this.pin(account, pin)).pin.is_owner !== true) throw new AdportError('INVALID_INPUT', 'pinterest: engagement Pin is not explicitly owned');\n 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 } : {}) };\n }\n private async inventory<T>(account: string, path: string, schema: z.ZodType<T>, extra: Record<string, string> = {}) {\n const items: T[] = [], cursors = new Set<string>(); let bookmark: string | undefined;\n for (let page = 0; page < 50; page++) {\n const data = await this.page(account, path, schema, 100, bookmark, extra); items.push(...data.items);\n if (!data.next_cursor) return { items, complete: true };\n if (cursors.has(data.next_cursor)) throw new AdportError('PROVIDER_ERROR', 'pinterest: usage inventory repeated a cursor');\n cursors.add(data.next_cursor); bookmark = data.next_cursor;\n }\n return { items, complete: false };\n }\n async usage(account: string, resource: string) {\n const current = await this.get(account, resource);\n const groups = await this.inventory(account, 'ad_groups', z.looseObject({ id, ad_account_id: id.optional(), status: z.string().optional(), targeting_spec: z.record(z.string(), z.unknown()).optional() }), { entity_statuses: 'ACTIVE,PAUSED,ARCHIVED,DRAFT,DELETED_DRAFT' });\n const audiences = await this.inventory(account, 'audiences', audience, { ownership_type: 'OWNED' });\n const sharing = [];\n for (const type of ['AD_ACCOUNT', 'BUSINESS_ACCOUNT']) {\n const data = await this.inventory(account, 'audiences/shared/accounts', z.object({ account_id: id, account_type: z.enum(['AD_ACCOUNT', 'BUSINESS_ACCOUNT']) }), { audience_id: resource, account_type: type });\n if (data.items.some(v => v.account_type !== type) || new Set(data.items.map(v => v.account_id)).size !== data.items.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: sharing returned the wrong account type or repeated accounts');\n sharing.push(data);\n }\n const seen = new Set<string>(), references: Array<{ kind: string; id: string; status?: string; targeting_dimensions?: string[]; snapshot_hash?: string }> = [];\n let configurationComplete = true;\n for (const group of groups.items) {\n if (seen.has(group.id) || group.ad_account_id !== undefined && group.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: usage returned a foreign or repeated ad group'); seen.add(group.id);\n if (!group.targeting_spec) configurationComplete = false;\n const targeting = group.targeting_spec ?? {};\n for (const key of ['AUDIENCE_INCLUDE', 'AUDIENCE_EXCLUDE']) if (targeting[key] !== undefined && !z.array(id).safeParse(targeting[key]).success) throw new AdportError('PROVIDER_ERROR', 'pinterest: audience targeting references could not be inspected');\n const dimensions = ['AUDIENCE_INCLUDE', 'AUDIENCE_EXCLUDE'].filter(key => Array.isArray(targeting[key]) && (targeting[key] as string[]).includes(resource));\n if (dimensions.length) references.push({ kind: 'ad_group', id: group.id, ...(typeof group.status === 'string' ? { status: group.status } : {}), targeting_dimensions: dimensions });\n }\n seen.clear();\n for (const source of audiences.items) {\n if (seen.has(source.id) || source.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: usage returned a foreign or repeated owned audience'); seen.add(source.id);\n const seed = source.rule?.seed_id; canonical(seed);\n if (!['CUSTOMER_LIST', 'VISITOR', 'ENGAGEMENT', 'ACTALIKE'].includes(source.audience_type ?? '') || source.audience_type === 'ACTALIKE' && !Array.isArray(seed)) configurationComplete = false;\n if (source.id !== resource && Array.isArray(seed) && seed.some(v => String(v) === resource)) references.push({ kind: 'derived_audience', id: source.id, snapshot_hash: audienceSnapshot(source) });\n }\n const shared_accounts = sharing.flatMap(v => v.items).filter(v => v.account_type !== 'AD_ACCOUNT' || v.account_id !== account), scan_complete = configurationComplete && groups.complete && audiences.complete && sharing.every(v => v.complete);\n references.sort((a, b) => `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`)); shared_accounts.sort((a, b) => `${a.account_type}:${a.account_id}`.localeCompare(`${b.account_type}:${b.account_id}`));\n const context = { snapshot_hash: current.snapshot_hash, references, shared_accounts, scan_complete };\n return { ...current, ...context, context_hash: digest(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.'] };\n }\n private planWrite(summary: string, changes: string[], execute: Plan['execute'], fieldChanges?: WritePreview['fieldChanges']): Plan {\n 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 };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'pinterest' || writes.get(op.tool) !== op.kind) throw new AdportError('INVALID_INPUT', 'pinterest: invalid audience operation');\n const account = id.parse(op.accountId);\n if (op.tool === 'pinterest_create_customer_list' || op.tool === 'pinterest_update_customer_list_records') {\n const create = op.tool === 'pinterest_create_customer_list', input = create ? createList.parse(op.payload) : updateRecords.parse(op.payload);\n let resource: string | undefined;\n if ('customer_list_id' in input) { resource = input.customer_list_id; const current = await this.getCustomerList(account, resource); if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: customer-list batches or metadata changed; read it again'); }\n const recordsDigest = digest(input.records_sha256), body = create ? { name: createList.parse(input).name, list_type: createList.parse(input).list_type, is_nca: createList.parse(input).is_nca, records: input.records_sha256.join(',') } : { operation_type: updateRecords.parse(input).operation_type, records: input.records_sha256.join(',') };\n return this.planWrite(`${create ? 'Create' : 'Update'} Pinterest customer list`, [`${input.records_sha256.length} unique SHA-256 identifiers; batch digest ${recordsDigest}. Identifiers are not included in this preview.`, create ? `New ${createList.parse(input).list_type} list “${createList.parse(input).name}”; expanded matching is_nca=${createList.parse(input).is_nca}.` : `${updateRecords.parse(input).operation_type} membership records on ${resource}.`, 'Native processing is asynchronous. This does not confirm matched users; read customer-list status.'], async () => {\n let result: z.infer<typeof customerList>;\n try { result = await this.client.mutate(`${this.base(account)}/customer_lists${resource ? `/${resource}` : ''}`, create ? 'POST' : 'PATCH', body, customerList); }\n catch (error) {\n const details = error instanceof AdportError ? object(error.details) : {}, ids = Array.isArray(details.resource_ids) ? details.resource_ids.filter(v => id.safeParse(v).success) : resource ? [resource] : [];\n throw new AdportError('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: ids });\n }\n if (result.ad_account_id !== account || resource && result.id !== resource || create && (result.name !== createList.parse(input).name || result.is_nca !== createList.parse(input).is_nca)) throw new AdportError('PROVIDER_ERROR', 'pinterest: customer-list receipt ownership/name/matching mode mismatch; reconcile before retrying', { resource_ids: [result.id] });\n return [result.id];\n });\n }\n if (op.tool === 'pinterest_create_audience') {\n const input = createAudience.parse(op.payload), rule = await this.rule(account, input.definition), body = { ad_account_id: account, name: input.name, ...(input.description !== undefined ? { description: input.description } : {}), audience_type: input.definition.audience_type, rule };\n return this.planWrite(`Create Pinterest ${input.definition.audience_type} audience “${input.name}”`, [JSON.stringify(body), '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(account, undefined, body, await this.client.mutate(`${this.base(account)}/audiences`, 'POST', body, audience)));\n }\n if (op.tool === 'pinterest_remove_audience') {\n const input = removeAudience.parse(op.payload), current = await this.usage(account, input.audience_id);\n if (current.context_hash !== input.expected_context_hash || !current.scan_complete) throw new AdportError('PENDING_MISMATCH', 'pinterest: audience usage changed or is incomplete; read it again');\n if (current.references.length || current.shared_accounts.length) throw new AdportError('INVALID_INPUT', 'pinterest: audience still has targeting, derived audiences or sharing references');\n return this.planWrite(`Remove Pinterest audience “${current.audience.name ?? input.audience_id}”`, [`Native operation_type REMOVE on ${input.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(account, input.audience_id, {}, await this.client.mutate(`${this.base(account)}/audiences/${input.audience_id}`, 'PATCH', { operation_type: 'REMOVE' }, audience)));\n }\n const replacement = op.tool === 'pinterest_replace_audience_rule', input = replacement ? replaceRule.parse(op.payload) : updateAudience.parse(op.payload), current = replacement ? await this.usage(account, input.audience_id) : await this.get(account, input.audience_id);\n if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: audience copy/configuration changed; read it again');\n const body: Row = { operation_type: 'UPDATE' }, changes: NonNullable<WritePreview['fieldChanges']> = [];\n if (replacement) {\n const value = replaceRule.parse(input), context = current as Awaited<ReturnType<PinterestAudienceService['usage']>>;\n if (context.context_hash !== value.expected_context_hash || !context.scan_complete) throw new AdportError('PENDING_MISMATCH', 'pinterest: audience usage changed or is incomplete; read it again');\n if (context.shared_accounts.length) throw new AdportError('INVALID_INPUT', 'pinterest: shared audience rules cannot be replaced through this workflow');\n if (value.definition.audience_type !== current.audience.audience_type) throw new AdportError('INVALID_INPUT', 'pinterest: rule replacement must preserve audience type');\n 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 AdportError('INVALID_INPUT', 'pinterest: an audience cannot use itself or a direct derived audience as a seed');\n body.rule = await this.rule(account, value.definition); changes.push({ field: 'Rule', before: JSON.stringify(current.audience.rule ?? null), after: JSON.stringify(body.rule) });\n } else {\n const value = updateAudience.parse(input);\n for (const key of ['name', 'description'] as const) if (value[key] !== undefined) { body[key] = value[key]; 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)') }); }\n }\n return this.planWrite(`Edit Pinterest audience “${current.audience.name ?? input.audience_id}”`, [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(account, input.audience_id, body, await this.client.mutate(`${this.base(account)}/audiences/${input.audience_id}`, 'PATCH', body, audience), current.audience), changes);\n }\n private receipt(account: string, resource: string | undefined, expected: Row, current: z.infer<typeof audience>, previous?: z.infer<typeof audience>) {\n const fields = Object.entries(expected).filter(([key]) => key !== 'operation_type');\n if (current.ad_account_id !== account || resource && current.id !== resource || fields.some(([key, value]) => key === 'rule' ? !includesFields(normalizeRule(current.rule), normalizeRule(value)) : digest(current[key] ?? null) !== digest(value)) || previous && ['name', 'description', 'rule', 'audience_type', 'is_nca'].some(key => expected[key] === undefined && digest(current[key] ?? null) !== digest(previous[key] ?? null))) throw new AdportError('PROVIDER_ERROR', 'pinterest: audience receipt differs from approved fields or preserved ownership/configuration; reconcile before retrying', { resource_ids: [current.id] });\n return [current.id];\n }\n}\n\nexport function pinterestAudienceTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const account = { account_id: id }, page = { page_size: z.number().int().min(1).max(250).default(50), bookmark: z.string().min(1).max(4096).optional() };\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (input: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'pinterest', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: WriteOperation['kind']) => guardedWriteTool({ name, namespace: 'pinterest', provider: 'pinterest', description, payload, kind });\n return [\n 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.', z.object({ ...account, ...page, ownership_type: z.enum(['OWNED', 'RECEIVED']).default('OWNED') }), v => provider.audiences.list(v)),\n defineTool({ 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: z.object({ ...account, audience_id: id }), output: creativesOutput.passthrough(), presentation: 'records', annotations: { readOnly: true }, handler: v => provider.audiences.get(v.account_id, v.audience_id) }),\n 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.', z.object({ ...account, audience_id: id }), v => provider.audiences.usage(v.account_id, v.audience_id)),\n read('pinterest_audience_sources', 'Read the advertiser owner’s 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.', z.object(account), v => provider.audiences.sources(v.account_id)),\n read('pinterest_customer_lists', 'Read selected advertiser customer-list metadata, counts, processing status and snapshots with pagination. Never returns records or native exception contents.', z.object({ ...account, ...page }), v => provider.audiences.customerLists(v)),\n 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.', z.object({ ...account, customer_list_id: id }), v => provider.audiences.getCustomerList(v.account_id, v.customer_list_id)),\n write('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'),\n write('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'),\n write('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'),\n write('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'),\n write('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'),\n write('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'),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { isIP } from 'node:net';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestId as id } from './schemas.js';\n\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]>; resultDetails?(): unknown; resultWarnings?(): string[] };\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), text = z.string().min(1).max(4096), decimal = z.string().regex(/^\\d+(?:\\.\\d+)?$/);\nconst optionalText = text.nullable().optional(), integer = z.number().int().nonnegative().safe();\nconst aem = { aem_db_enabled: z.boolean().default(false), aem_enabled: z.boolean().default(false), aem_external_id_enabled: z.boolean().default(false), aem_fnln_enabled: z.boolean().default(false), aem_ge_enabled: z.boolean().default(false), aem_loc_enabled: z.boolean().default(false), aem_ph_enabled: z.boolean().default(false) };\nconst tag = z.looseObject({ id: id.optional(), ad_account_id: id, name: z.string(), status: z.string().optional(), configs: z.record(z.string(), z.unknown()).optional(), last_fired_time_ms: z.number().nullable().optional() });\nconst tagCreate = z.object({ name: z.string().trim().min(1).max(255), ...aem, md_frequency: z.number().default(1), expected_context_hash: hash, confirm_enhanced_match_consent: z.boolean().default(false) }).strict().refine(value => !Object.keys(aem).some(key => value[key as keyof typeof aem]) || value.confirm_enhanced_match_consent, 'Enabling enhanced match requires explicit consent confirmation');\nconst eventMetadata = z.looseObject({ ad_account_id: id.optional(), conversion_tag_id: id.optional(), conversion_event: z.string().optional(), created_time: z.number().int().optional(), reporting_conversion_event: z.string().optional() });\nconst sourcePlatform = z.enum(['WEB', 'MOBILE', 'MOBILE_ANDROID', 'MOBILE_IOS', 'OFFLINE', 'PINTEREST_WEB', 'PINTEREST_ANDROID', 'PINTEREST_IOS', 'POINT_OF_SALE']);\nconst ingestionSource = z.enum(['TAG', 'MMP', 'FILE_UPLOAD', 'CONVERSIONS_API', 'NATIVE']);\nconst qualityInput = z.object({ account_id: id, lookback_period: z.enum(['1d', '14d']), source_platform: sourcePlatform.optional(), ingestion_source: ingestionSource.optional() }).strict();\nconst component = z.looseObject({ coverage: z.number(), overlap: z.number().optional(), issues: z.array(z.looseObject({ id: z.string(), name: z.string(), reason: z.string() })).optional() });\nconst quality = z.looseObject({ overall_status: z.enum(['NEEDS_IMPROVEMENT', 'FAIR', 'GOOD']), quality_components: z.record(z.string(), z.record(z.string(), component)), ingestion_source: ingestionSource, source_platform: sourcePlatform, lookback_period: z.enum(['1d', '14d']) });\nconst hashedValues = z.array(hash).min(1).max(100);\nconst userData = z.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: z.string().refine(value => isIP(value) !== 0 && !['0.0.0.0', '::'].includes(value), 'Use a valid, non-unspecified IP address').optional(), client_user_agent: z.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');\nconst product = z.object({ id: text.optional(), item_brand: text.optional(), item_brand_id: z.string().max(64).optional(), item_category: text.optional(), item_name: text.optional(), item_price: decimal.optional(), quantity: integer.optional() }).strict();\nconst customData = z.object({ content_brand: optionalText, content_category: optionalText, content_ids: z.array(text).max(1000).optional(), content_name: optionalText, contents: z.array(product).max(1000).optional(), currency: z.string().regex(/^[A-Z]{3}$/).nullable().optional(), external_measurement_id: optionalText, external_measurement_vendor_id: z.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');\nconst appInfo = z.object({ app_id: z.string().max(200).optional(), app_name: z.string().max(200).optional(), app_package_name: z.string().max(200).optional(), app_store: z.string().max(100).optional(), app_version: z.string().max(100).optional(), install_time: integer.optional(), user_agent: z.string().max(16384).optional(), window_height: integer.max(30720).optional(), window_width: integer.max(30720).optional() }).strict();\nconst deviceInfo = z.object({ battery_level: integer.max(100).optional(), brand: z.string().max(100).optional(), carrier: z.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: z.enum(['desktop', 'laptop', 'cellphone', 'tablet', 'smartwatch', 'tv', 'vr', 'console', 'other']).optional(), kernel_version: z.string().max(100).optional(), languages: z.array(z.string()).max(100).optional(), locale: z.string().max(35).optional(), model: z.string().max(100).optional(), network_type: z.enum(['wifi', 'cellular_2g', 'cellular_3g', 'cellular_4g', 'cellular_5g', 'cellular_6g', 'ethernet', 'unknown']).optional(), os_family: z.enum(['ios', 'android', 'macos', 'windows', 'linux', 'bsd', 'other']).optional(), os_name: z.string().max(100).optional(), os_release_name: z.string().max(100).optional(), os_version: z.string().max(100).optional(), screen_density: integer.max(100000).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: z.string().max(40).optional(), timezone_abbr: z.string().max(5).optional(), type: z.string().max(100).optional() }).strict();\nconst sourceUrl = z.string().url().max(16384).refine(value => { const url = new URL(value); return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password; }, 'Use an HTTP(S) source URL without credentials');\nconst event = z.object({ action_source: z.enum(['web', 'app_android', 'app_ios', 'offline']), event_id: z.string().min(1).max(512), event_name: z.string().regex(/^[A-Za-z0-9_-]{1,100}$/), event_time: integer.refine(value => value <= Math.floor(Date.now() / 1000) + 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: z.boolean().optional(), os_version: optionalText, partner_name: optionalText, wifi: z.boolean().optional() }).strict();\nconst sendEvents = z.object({ expected_context_hash: hash, test: z.boolean().default(true), confirm_data_rights: z.literal(true), confirm_live_events: z.boolean().default(false), data: z.array(event).min(1).max(1000) }).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');\nconst eventResponse = z.object({ num_events_received: integer, num_events_processed: integer, events: z.array(z.object({ status: z.enum(['failed', 'processed']), error_message: z.string().nullable().optional(), warning_message: z.string().nullable().optional() })) });\nconst writes = new Set(['pinterest_create_conversion_tag', 'pinterest_send_conversion_events']);\n\n/** Native wire contracts: Pinterest-owned v5 OpenAPI5.28.0 and Conversions API guide, checked2026-11-04. */\nexport class PinterestMeasurementService {\n constructor(private readonly client: PinterestAdsClient) {}\n supports(tool: string) { return writes.has(tool); }\n private base(account: string) { return `ad_accounts/${id.parse(account)}`; }\n private owned<T extends { ad_account_id?: string }>(account: string, row: T): T {\n if (row.ad_account_id !== undefined && row.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: measurement response belongs to another advertiser');\n return row;\n }\n async tags(account: string, filterDeleted = false) {\n const result = await this.client.get(`${this.base(account)}/conversion_tags`, z.object({ items: z.array(tag) }), new URLSearchParams({ filter_deleted: String(filterDeleted) }));\n result.items.forEach(row => this.owned(account, row));\n const ids = result.items.flatMap(row => row.id ? [row.id] : []);\n if (new Set(ids).size !== ids.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: duplicate conversion-tag IDs');\n return { ...result, account_id: account, truncated: false };\n }\n async context(account: string) {\n const advertiser = await this.client.get(this.base(account), z.looseObject({ id, name: z.string().optional(), currency: z.string().optional() }));\n if (advertiser.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: measurement account ID mismatch');\n const tags = await this.tags(account);\n const configuration = 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)));\n return { account_id: account, advertiser, tags: tags.items, snapshot_hash: digest({ account_id: account, currency: advertiser.currency ?? null, tags: configuration }), 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.'] };\n }\n async getTag(account: string, tagId: string) {\n const row = await this.client.get(`${this.base(account)}/conversion_tags/${id.parse(tagId)}`, tag);\n this.owned(account, row);\n if (row.id !== tagId) throw new AdportError('PROVIDER_ERROR', 'pinterest: conversion-tag ID mismatch');\n return row;\n }\n async eligible(account: string) {\n const result = await this.client.get(`${this.base(account)}/conversion_tags/ocpm_eligible`, z.record(z.string(), z.array(eventMetadata)));\n if (Object.keys(result).some(key => key !== account)) throw new AdportError('PROVIDER_ERROR', 'pinterest: eligible-event mapping belongs to another advertiser');\n return { account_id: account, events: (result[account] ?? []).map(row => this.owned(account, row)) };\n }\n async visits(input: { account_id: string; page_size: number; bookmark?: string; order: 'ASCENDING' | 'DESCENDING' }) {\n const params = new URLSearchParams({ page_size: String(input.page_size), order: input.order });\n if (input.bookmark) params.set('bookmark', input.bookmark);\n const result = await this.client.get(`${this.base(input.account_id)}/conversion_tags/page_visit`, z.object({ items: z.array(eventMetadata), bookmark: z.string().nullable().optional() }), params);\n if (result.items.length > input.page_size || result.bookmark && (!result.items.length || result.bookmark === input.bookmark)) throw new AdportError('PROVIDER_ERROR', 'pinterest: page-visit pagination did not advance');\n result.items.forEach(row => this.owned(input.account_id, row));\n return { ...result, account_id: input.account_id, truncated: Boolean(result.bookmark), ...(result.bookmark ? { next_cursor: result.bookmark } : {}) };\n }\n async quality(input: z.infer<typeof qualityInput>) {\n const parsed = qualityInput.parse(input), params = new URLSearchParams({ lookback_period: parsed.lookback_period });\n if (parsed.source_platform) params.set('source_platform', parsed.source_platform);\n if (parsed.ingestion_source) params.set('ingestion_source', parsed.ingestion_source);\n const result = await this.client.get(`${this.base(parsed.account_id)}/conversion_eqs`, z.array(quality), params);\n 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 AdportError('PROVIDER_ERROR', 'pinterest: event-quality response ignored the selected filters');\n return { account_id: parsed.account_id, items: result };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.kind !== 'create') throw new AdportError('INVALID_INPUT', 'pinterest: measurement writes require create kind');\n if (op.tool === 'pinterest_create_conversion_tag') {\n const input = tagCreate.parse(op.payload), context = await this.context(op.accountId);\n this.checkContext(input.expected_context_hash, context.snapshot_hash);\n if (context.tags.some(row => !row.id) || context.tags.some(row => row.name.toLowerCase() === input.name.toLowerCase())) throw new AdportError('INVALID_INPUT', 'pinterest: conversion tag already exists or tag identity is incomplete; inspect existing tags');\n const { expected_context_hash: _hash, confirm_enhanced_match_consent: _consent, ...body } = input;\n return { summary: `Create Pinterest conversion tag \"${input.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 () => {\n const row = await this.client.mutate(`${this.base(op.accountId)}/conversion_tags`, 'POST', body, tag);\n const resourceIds = row.id ? [row.id] : [];\n if (row.ad_account_id !== op.accountId || !row.id || row.name !== input.name || row.configs && Object.entries(body).some(([key, value]) => key !== 'name' && row.configs![key] !== undefined && row.configs![key] !== value)) throw new AdportError('PROVIDER_ERROR', 'pinterest: conversion-tag creation not confirmed; inspect before any retry', { resource_ids: resourceIds });\n return resourceIds;\n } };\n }\n if (op.tool !== 'pinterest_send_conversion_events') throw new AdportError('INVALID_INPUT', 'pinterest: unsupported measurement write');\n const input = sendEvents.parse(op.payload), context = await this.context(op.accountId);\n this.checkContext(input.expected_context_hash, context.snapshot_hash);\n const count = input.data.length, batchHash = digest(input.data), mode = input.test ? 'TEST' : 'LIVE';\n let details: unknown, warnings: string[] = [];\n 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.'];\n return { summary: `Send ${count} Pinterest conversion events (${mode})`, changes: [`+ ${count} 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: count }, { label: 'Batch SHA-256', after: batchHash }], notices }, resultDetails: () => details, resultWarnings: () => warnings, execute: async () => {\n let result: z.infer<typeof eventResponse>;\n try { result = await this.client.mutate(`${this.base(op.accountId)}/events`, 'POST', { data: input.data }, eventResponse, new URLSearchParams({ test: String(input.test) })); }\n catch (error) {\n const native = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n throw new AdportError('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: count, ...(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 } : {}) });\n }\n const rows = result.events.map((row, index) => ({ index, status: row.status, has_error: Boolean(row.error_message), has_warning: Boolean(row.warning_message) }));\n const processed = rows.filter(row => row.status === 'processed').length;\n if (result.num_events_received !== count || result.events.length !== count || result.num_events_processed !== processed) throw new AdportError('PROVIDER_ERROR', 'pinterest: conversion-event receipt counts disagree; no automatic retry', { status: 'UNCONFIRMED', mode, batch_sha256: batchHash, record_count: count, num_events_received: result.num_events_received, num_events_processed: result.num_events_processed, rows });\n const complete = processed === count && rows.every(row => !row.has_error);\n details = { status: complete ? 'COMPLETE' : 'PARTIAL_OR_UNCONFIRMED', mode, batch_sha256: batchHash, record_count: count, num_events_received: result.num_events_received, num_events_processed: result.num_events_processed, failed_count: count - processed, rows };\n if (!processed) throw new AdportError('PROVIDER_ERROR', 'pinterest: no conversion events were processed; inspect row outcomes before any new submission', details);\n if (!complete || rows.some(row => row.has_warning)) warnings.push(`${processed} of ${count} events processed; ${count - processed} failed. Inspect result.details and native diagnostics before submitting again.`);\n if (input.test) warnings.push('Test-mode validation only; these events were not recorded for reporting or optimization.');\n return [];\n } };\n }\n private checkContext(expected: string, actual: string) {\n if (expected !== actual) throw new AdportError('INVALID_INPUT', 'pinterest: measurement context changed; read it again before requesting a new preview');\n }\n}\n\nexport function pinterestMeasurementTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (input: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'pinterest', description, input, annotations: { readOnly: true }, handler });\n return [\n read('pinterest_measurement_context', 'Read advertiser identity, conversion tags and a stable snapshot_hash for guarded measurement writes.', z.object({ account_id: id }), input => provider.measurement.context(input.account_id)),\n read('pinterest_conversion_tags', 'Read advertiser-owned conversion tags and code snippets as data. Unpaged native collection; does not install tracking or send events.', z.object({ account_id: id, filter_deleted: z.boolean().default(false) }), input => provider.measurement.tags(input.account_id, input.filter_deleted)),\n read('pinterest_get_conversion_tag', 'Read one advertiser-owned conversion tag by ID. Code snippets are returned as text only.', z.object({ account_id: id, conversion_tag_id: id }), input => provider.measurement.getTag(input.account_id, input.conversion_tag_id)),\n read('pinterest_conversion_tag_eligible_events', 'Read the advertiser’s native OCPM-eligible conversion-tag events without changing optimization.', z.object({ account_id: id }), input => provider.measurement.eligible(input.account_id)),\n defineTool({ name: 'pinterest_conversion_tag_page_visits', namespace: 'pinterest', description: 'Read native conversion-tag page-visit metadata with bookmark pagination.', input: z.object({ account_id: id, page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).max(4096).optional(), order: z.enum(['ASCENDING', 'DESCENDING']).default('ASCENDING') }), annotations: { readOnly: true }, pagination: { cursorInput: 'bookmark' }, handler: input => provider.measurement.visits(input) }),\n read('pinterest_event_quality', 'Read Pinterest’s native conversion-event quality diagnostics for explicit lookback/source filters. No derived score or delivery change.', qualityInput, input => provider.measurement.quality(input)),\n guardedWriteTool({ 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 }),\n guardedWriteTool({ name: 'pinterest_send_conversion_events', namespace: 'pinterest', provider: 'pinterest', kind: 'create', description: 'Send 1–1000 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 }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type ReviewField, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport { pinterestId } from './schemas.js';\nimport type { PinterestAdsProvider } from './provider.js';\n\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]>; resultDetails?(): unknown; resultWarnings?(): string[] };\nconst id = z.string().regex(/^\\d{1,30}$/), hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst type = z.enum(['RETAIL', 'HOTEL', 'CREATIVE_ASSETS']), format = z.enum(['TSV', 'CSV', 'XML', 'INTEGRATION']);\nconst state = z.enum(['ACTIVE', 'INACTIVE']);\nconst name = z.string().trim().min(1).max(1024), currency = z.string().regex(/^[A-Z]{3}$/).nullable();\nconst credentials = z.object({ username: z.string().min(1).max(4096), password: z.string().min(1).max(8192) }).strict().nullable();\nconst location = z.string().url().max(16384).refine(value => { const url = new URL(value); return ['http:', 'https:', 'ftp:', 'sftp:'].includes(url.protocol) && !url.username && !url.password && !url.hash; }, 'Use an HTTP(S), FTP or SFTP URL without inline credentials or fragments');\nconst schedule = z.object({ time: z.string().regex(/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/), timezone: z.string().min(1).max(100) }).strict().nullable();\nconst availability = z.enum(['IN_STOCK', 'OUT_OF_STOCK', 'PREORDER']).nullable();\nconst account = { account_id: pinterestId }, selected = { catalog_id: id }, reference = { ...selected, feed_id: id }, bound = { ...reference, expected_snapshot_hash: hash };\nconst paging = { page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).max(4096).optional() };\nconst catalog = z.looseObject({ id, name: z.string(), catalog_type: type, created_at: z.string(), updated_at: z.string() });\nconst feed = z.looseObject({ id, catalog_type: type, catalog_id: id.nullable().optional(), name: z.string().nullable(), status: z.string(), format, default_locale: z.string(), default_country: z.string().optional(), default_currency: z.string().nullable().optional(), default_availability: availability.optional(), preferred_processing_schedule: schedule.optional(), location: z.string(), credentials: z.unknown().optional(), created_at: z.string(), updated_at: z.string() });\nconst common = { catalog_id: id, name, location, format, default_locale: z.string().min(2).max(40), default_currency: currency.optional(), credentials: credentials.optional(), preferred_processing_schedule: schedule.optional(), status: state.default('INACTIVE') };\nconst feedCreate = z.discriminatedUnion('catalog_type', [\n z.object({ ...common, catalog_type: z.literal('RETAIL'), default_country: z.string().regex(/^[A-Z]{2}$/), default_availability: availability.optional() }).strict(),\n z.object({ ...common, catalog_type: z.literal('HOTEL') }).strict(),\n z.object({ ...common, catalog_type: z.literal('CREATIVE_ASSETS'), default_country: z.string().regex(/^[A-Z]{2}$/) }).strict(),\n]);\nconst feedChanges = z.object({ name: name.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');\nconst createCatalog = z.object({ expected_context_hash: hash, name, catalog_type: type }).strict();\nconst createFeed = z.object({ expected_context_hash: hash, feed: feedCreate, confirm_source_access: z.literal(true), confirm_publication: z.boolean().default(false) }).strict();\nconst updateFeed = z.object({ ...bound, changes: feedChanges, confirm_source_access: z.boolean().default(false), confirm_publication: z.boolean().default(false) }).strict();\nconst deleteFeed = z.object({ ...bound, confirm_permanent_deletion: z.literal(true) }).strict();\nconst ingestFeed = z.object({ ...bound, confirm_source_access: z.literal(true), confirm_publication: z.literal(true) }).strict();\nconst processing = z.looseObject({ id, status: z.enum(['COMPLETED', 'FAILED', 'PROCESSING']), created_at: z.string(), updated_at: z.string(), ingestion_details: z.record(z.string(), z.unknown()), product_counts: z.record(z.string(), z.unknown()), validation_details: z.record(z.string(), z.unknown()) });\nconst ingestion = z.object({ id, feed_id: id, status: z.enum(['COMPLETED', 'FAILED', 'PROCESSING']), created_at: z.string() });\nconst writeKinds = { pinterest_create_catalog: 'create', pinterest_create_feed: 'create', pinterest_update_feed: 'update', pinterest_delete_feed: 'remove', pinterest_ingest_feed: 'update' } as const;\nconst isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : isObject(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value)) ?? 'undefined').digest('hex');\nconst same = (a: unknown, b: unknown) => digest(a) === digest(b);\nfunction sourceOrigin(value: string): string { try { const url = new URL(value); return `${url.protocol}//${url.host}`; } catch { return 'Unavailable'; } }\nfunction privateValues(value: z.infer<typeof feed>) { const auth = isObject(value.credentials) ? value.credentials : {}; return [value.location, auth.username, auth.password].filter((v): v is string => typeof v === 'string' && v.length > 0); }\nfunction redact(value: unknown, secrets: string[]): unknown {\n if (typeof value === 'string') return secrets.reduce((text, secret) => text.replaceAll(secret, '[redacted]'), value);\n if (Array.isArray(value)) return value.map(item => redact(item, secrets));\n 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;\n}\nfunction publicFeed(value: z.infer<typeof feed>) {\n const { location, credentials, ...rest } = value;\n 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'];\n const selected = Object.fromEntries(keys.filter(key => Object.hasOwn(rest, key)).map(key => [key, rest[key]]));\n const { created_at: _created, updated_at: _updated, ...settings } = selected;\n const config = { ...settings, location, credentials_configured: credentials != null };\n return { ...selected, source_origin: sourceOrigin(location), source_fingerprint: digest(location), credentials_configured: credentials != null, snapshot_hash: digest(config) };\n}\nconst output = z.object({ account_id: pinterestId, context_hash: hash, records: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean() }).passthrough();\nconst labels: Record<string, string> = { 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' };\nfunction fields(before: Record<string, unknown> | undefined, requested: Record<string, unknown>): ReviewField[] {\n return Object.entries(requested).filter(([key]) => key !== 'catalog_id').map(([key, value]) => key === 'location'\n ? { label: 'Source', ...(before ? { before: { origin: sourceOrigin(String(before.location)), fingerprint: digest(before.location) } } : {}), after: { origin: sourceOrigin(String(value)), fingerprint: digest(value) } }\n : key === 'credentials' ? { label: 'Feed authentication', ...(before ? { before: before.credentials != null ? 'Configured; values hidden' : 'Not configured' } : {}), after: value === null ? 'Remove credentials' : 'Configure credentials; values hidden' }\n : { label: labels[key] ?? key, ...(before && Object.hasOwn(before, key) ? { before: before[key] } : {}), after: value });\n}\n\n/** Pinterest-owned OpenAPI 5.28.0, commit 2503147; contracts fetched 2026-11-05. */\nexport class PinterestCatalogService {\n constructor(private readonly client: PinterestAdsClient) {}\n supports(tool: string) { return Object.hasOwn(writeKinds, tool); }\n private params(account: string, catalog?: string) { return new URLSearchParams({ ad_account_id: pinterestId.parse(account), ...(catalog ? { catalog_id: id.parse(catalog) } : {}) }); }\n private async context(account: string) {\n const value = await this.client.get(`ad_accounts/${pinterestId.parse(account)}`, z.object({ id: pinterestId, owner: z.object({ username: z.string().min(1) }) }));\n if (value.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog advertiser ID mismatch');\n return { account_id: account, context_hash: digest({ account, owner: value.owner.username.toLowerCase() }) };\n }\n private async page<T>(path: string, schema: z.ZodType<T>, params: URLSearchParams, input: { page_size: number; bookmark?: string }) {\n params.set('page_size', String(input.page_size)); if (input.bookmark) params.set('bookmark', input.bookmark);\n const value = await this.client.get(path, z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() }), params);\n const ids = value.items.flatMap(row => isObject(row) && typeof row.id === 'string' ? [row.id] : []);\n if (value.items.length > input.page_size || new Set(ids).size !== ids.length || value.bookmark && (value.bookmark === input.bookmark || !value.items.length)) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog pagination did not advance consistently');\n return { ...value, truncated: Boolean(value.bookmark), ...(value.bookmark ? { next_cursor: value.bookmark } : {}) };\n }\n private async find<T extends { id?: string }>(path: string, schema: z.ZodType<T>, params: URLSearchParams, wanted: string): Promise<T | undefined> {\n const seen = new Set<string>(), ids = new Set<string>(); let bookmark: string | undefined;\n for (let pages = 0; pages < 40; pages++) {\n const page = await this.page(path, schema, new URLSearchParams(params), { page_size: 250, bookmark });\n for (const row of page.items) { if (row.id && ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog finder repeated an identity'); if (row.id) ids.add(row.id); if (row.id === wanted) return row; }\n if (!page.next_cursor) return undefined;\n if (seen.has(page.next_cursor)) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog finder repeated a bookmark');\n seen.add(page.next_cursor); bookmark = page.next_cursor;\n }\n throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog membership lookup exceeded 10,000 rows; membership is unconfirmed');\n }\n private async ownedCatalog(account: string, catalogId: string) {\n const value = await this.find('catalogs', catalog, this.params(account), id.parse(catalogId));\n if (!value) throw new AdportError('INVALID_INPUT', 'pinterest: catalog was not found for the selected advertiser owner');\n return value;\n }\n private validateFeed(value: z.infer<typeof feed>, selected: z.infer<typeof catalog>) {\n if (value.catalog_type !== selected.catalog_type || value.catalog_id != null && value.catalog_id !== selected.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: feed catalog/type mismatch');\n return value;\n }\n private async ownedFeed(account: string, catalogId: string, feedId: string) {\n const selected = await this.ownedCatalog(account, catalogId), member = await this.find('catalogs/feeds', feed, this.params(account, catalogId), id.parse(feedId));\n if (!member) throw new AdportError('INVALID_INPUT', 'pinterest: feed was not found in the selected advertiser catalog');\n this.validateFeed(member, selected);\n const value = await this.client.get(`catalogs/feeds/${feedId}`, feed, this.params(account));\n if (value.id !== feedId) throw new AdportError('PROVIDER_ERROR', 'pinterest: feed ID mismatch');\n return this.validateFeed(value, selected);\n }\n async catalogs(input: { account_id: string; page_size: number; bookmark?: string }) {\n const context = await this.context(input.account_id), page = await this.page('catalogs', catalog, this.params(input.account_id), input);\n return { ...context, ...page, records: page.items.map(value => ({ ...value, snapshot_hash: digest({ id: value.id, name: value.name, catalog_type: value.catalog_type }) })) };\n }\n async getCatalog(account: string, catalogId: string) {\n const context = await this.context(account), value = await this.ownedCatalog(account, catalogId);\n return { ...context, catalog: value, records: [value], truncated: false };\n }\n async feeds(input: { account_id: string; catalog_id: string; page_size: number; bookmark?: string }) {\n const context = await this.context(input.account_id), selected = await this.ownedCatalog(input.account_id, input.catalog_id), page = await this.page('catalogs/feeds', feed, this.params(input.account_id, input.catalog_id), input);\n const items = page.items.map(value => publicFeed(this.validateFeed(value, selected)));\n return { ...context, ...page, items, records: items, catalog_id: selected.id };\n }\n async getFeed(account: string, catalogId: string, feedId: string) {\n const context = await this.context(account), value = publicFeed(await this.ownedFeed(account, catalogId, feedId));\n return { ...context, feed: value, records: [value], truncated: false };\n }\n async results(input: { account_id: string; catalog_id: string; feed_id: string; page_size: number; bookmark?: string }) {\n const context = await this.context(input.account_id), current = await this.ownedFeed(input.account_id, input.catalog_id, input.feed_id);\n const page = await this.safe(current, () => this.page(`catalogs/feeds/${current.id}/processing_results`, processing, this.params(input.account_id), input));\n const items = page.items.map(value => redact(value, privateValues(current)) as Record<string, unknown>);\n return { ...context, ...page, items, records: items, feed_id: current.id };\n }\n async issues(input: { account_id: string; catalog_id: string; feed_id: string; processing_result_id: string; page_size: number; bookmark?: string; item_numbers?: number[]; item_validation_issue?: string }) {\n const context = await this.context(input.account_id), current = await this.ownedFeed(input.account_id, input.catalog_id, input.feed_id);\n const result = await this.safe(current, () => this.find(`catalogs/feeds/${current.id}/processing_results`, processing, this.params(input.account_id), input.processing_result_id));\n if (!result) throw new AdportError('INVALID_INPUT', 'pinterest: processing result was not found for this feed');\n const params = this.params(input.account_id);\n if (input.item_numbers) params.set('item_numbers', input.item_numbers.join(','));\n if (input.item_validation_issue) params.set('item_validation_issue', input.item_validation_issue);\n const page = await this.safe(current, () => this.page(`catalogs/processing_results/${result.id}/item_issues`, z.record(z.string(), z.unknown()), params, input));\n const items = page.items.map(value => redact(value, privateValues(current)) as Record<string, unknown>);\n return { ...context, ...page, 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.'] };\n }\n private async safe<T>(current: z.infer<typeof feed>, fn: () => Promise<T>): Promise<T> {\n try { return await fn(); } catch (error) {\n if (!(error instanceof AdportError)) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog request was not confirmed; reconcile before retrying');\n throw new AdportError(error.code, redact(error.message, privateValues(current)) as string, redact(error.details, privateValues(current)));\n }\n }\n private async verify(resource: string, fn: () => Promise<boolean>) {\n try { if (!await fn()) throw new Error('readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog write readback unconfirmed; reconcile the resource ID before a new approval', { resource_ids: [resource] }); }\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'pinterest' || !this.supports(op.tool) || op.kind !== writeKinds[op.tool as keyof typeof writeKinds]) throw new AdportError('INVALID_INPUT', 'pinterest: catalog operation kind mismatch');\n const context = await this.context(op.accountId), base = { coercions: [], budgetDeltas: [], notes: [] };\n const review = (title: string, subject: string, fields: ReviewField[], notices: string[]) => ({ provider: 'pinterest', accountId: op.accountId, kind: op.kind, title, subject, fields, notices });\n if (op.tool === 'pinterest_create_catalog') {\n const input = createCatalog.parse(op.payload);\n if (input.expected_context_hash !== context.context_hash) throw new AdportError('INVALID_INPUT', 'pinterest: catalog advertiser context changed; read catalogs again');\n const body = { name: input.name, catalog_type: input.catalog_type };\n return { ...base, summary: `Create Pinterest ${input.catalog_type} catalog \"${input.name}\"`, changes: [`+ ${JSON.stringify(body)}`], review: review('Create catalog', input.name, fields(undefined, body), ['Creates an empty catalog. No feed, products, Pins or ads are created. Native catalog-program eligibility is still required.']), execute: async () => {\n const value = await this.client.mutate('catalogs', 'POST', body, catalog, this.params(op.accountId));\n await this.verify(value.id, async () => { const current = await this.ownedCatalog(op.accountId, value.id); return current.name === body.name && current.catalog_type === body.catalog_type; });\n return [value.id];\n } };\n }\n if (op.tool === 'pinterest_create_feed') {\n const input = createFeed.parse(op.payload), body = input.feed, selected = await this.ownedCatalog(op.accountId, body.catalog_id);\n if (input.expected_context_hash !== context.context_hash || selected.catalog_type !== body.catalog_type) throw new AdportError('INVALID_INPUT', 'pinterest: catalog advertiser context/type changed; read catalogs again');\n if (body.status === 'ACTIVE' && !input.confirm_publication) throw new AdportError('INVALID_INPUT', 'pinterest: active feeds may create public product Pins; confirm publication and source access');\n const changes = fields(undefined, body);\n return { ...base, summary: `Create Pinterest feed \"${body.name}\"`, changes: changes.map(field => `+ ${field.label}: ${JSON.stringify(field.after)}`), review: review('Create feed', body.name, changes, ['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 () => {\n const value = await this.client.mutate('catalogs/feeds', 'POST', body, feed, this.params(op.accountId));\n await this.verify(value.id, async () => this.matches(await this.ownedFeed(op.accountId, selected.id, value.id), body));\n return [value.id];\n }, resultWarnings: () => ['Saved feed configuration is not proof of source authentication or imported products; read processing results.'] };\n }\n const input = op.tool === 'pinterest_update_feed' ? updateFeed.parse(op.payload) : op.tool === 'pinterest_delete_feed' ? deleteFeed.parse(op.payload) : ingestFeed.parse(op.payload);\n const current = await this.ownedFeed(op.accountId, input.catalog_id, input.feed_id);\n if (publicFeed(current).snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('INVALID_INPUT', 'pinterest: feed configuration changed; read the feed again');\n if (current.status === 'DELETED') throw new AdportError('INVALID_INPUT', 'pinterest: this feed is deleted');\n 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 () => {\n const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}`, 'DELETE', undefined, z.union([feed, z.undefined()]), this.params(op.accountId)));\n if (result && result.id !== current.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: feed delete receipt ID mismatch', { resource_ids: [current.id] });\n await this.verify(current.id, async () => { const remaining = await this.find('catalogs/feeds', feed, this.params(op.accountId, input.catalog_id), current.id); return !remaining || remaining.status === 'DELETED'; });\n return [current.id];\n } };\n if (op.tool === 'pinterest_ingest_feed') {\n let details: unknown, warning: string[] = [];\n 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: digest(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 () => {\n const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}/ingest`, 'POST', undefined, ingestion, this.params(op.accountId)));\n if (result.feed_id !== current.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: ingestion receipt feed mismatch', { resource_ids: [current.id, result.id] });\n 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' };\n if (result.status === 'FAILED') warning = ['Pinterest reports that the requested ingestion failed. Read processing results; do not automatically retry.'];\n return [result.id];\n }, resultDetails: () => details, resultWarnings: () => warning };\n }\n const update = updateFeed.parse(op.payload), changes = update.changes;\n if (current.catalog_type !== 'RETAIL' && Object.hasOwn(changes, 'default_availability')) throw new AdportError('INVALID_INPUT', 'pinterest: default availability is retail-only');\n if ((changes.location !== undefined || changes.credentials != null || changes.status === 'ACTIVE') && !update.confirm_source_access) throw new AdportError('INVALID_INPUT', 'pinterest: changing feed source/authentication or activating processing requires source-access confirmation');\n if ((changes.status ?? current.status) === 'ACTIVE' && Object.keys(changes).some(key => key !== 'name') && !update.confirm_publication) throw new AdportError('INVALID_INPUT', 'pinterest: changes to an active feed may affect public product Pins; confirm publication');\n if (!Object.entries(changes).some(([key, value]) => key === 'credentials' || !same(current[key], value))) throw new AdportError('INVALID_INPUT', 'pinterest: no supplied feed settings would change');\n const body = { catalog_type: current.catalog_type, ...changes }, visible = fields(current, changes);\n return { ...base, summary: `Update Pinterest feed ${current.id}`, changes: visible.map(field => `~ ${field.label}: ${JSON.stringify(field.before)} → ${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 () => {\n const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}`, 'PATCH', body, feed, this.params(op.accountId)));\n if (result.id !== current.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: feed update receipt ID mismatch', { resource_ids: [current.id] });\n await this.verify(current.id, async () => this.matches(await this.ownedFeed(op.accountId, input.catalog_id, current.id), changes));\n return [current.id];\n }, resultWarnings: () => changes.location !== undefined || changes.credentials != null ? ['Source downloading/authentication is unverified until native processing results confirm success.'] : [] };\n }\n private matches(current: z.infer<typeof feed>, wanted: Record<string, unknown>) {\n return Object.entries(wanted).every(([key, value]) => {\n if (key === 'catalog_id' && current.catalog_id == null) return true;\n if (key === 'credentials') return value === null ? current.credentials == null : current.credentials != null;\n return same(current[key], value);\n });\n }\n}\n\nexport function pinterestCatalogTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ 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: z.object({ ...account, ...paging }).strict(), output, presentation: 'records', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: input => provider.catalogs.catalogs(input) }),\n defineTool({ 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: z.object({ ...account, ...selected }).strict(), output, presentation: 'records', annotations: { readOnly: true }, handler: input => provider.catalogs.getCatalog(input.account_id, input.catalog_id) }),\n defineTool({ name: 'pinterest_feeds', namespace: 'pinterest', description: 'List one advertiser-owned catalog’s feeds and configuration snapshots. Native bookmarks; source paths/query values and feed credentials stay hidden.', input: z.object({ ...account, ...selected, ...paging }).strict(), output, presentation: 'records', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: input => provider.catalogs.feeds(input) }),\n defineTool({ 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: z.object({ ...account, ...reference }).strict(), output, presentation: 'records', annotations: { readOnly: true }, handler: input => provider.catalogs.getFeed(input.account_id, input.catalog_id, input.feed_id) }),\n defineTool({ 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: z.object({ ...account, ...reference, ...paging }).strict(), output, presentation: 'records', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: input => provider.catalogs.results(input) }),\n defineTool({ 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: z.object({ ...account, ...reference, processing_result_id: id, ...paging, item_numbers: z.array(z.number().int().nonnegative().safe()).min(1).max(1000).optional(), item_validation_issue: z.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) }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestCatalogService } from './catalogs.js';\nimport { pinterestId } from './schemas.js';\nimport { catalogType, groupAction, groupChanges, groupContext, groupCreate, groupDelete, groupId, groupList, groupPaging, groupReference, groupUpdate, nativeGroup, productGroupFilterSchema } from './product-group-schemas.js';\n\ntype Group = z.infer<typeof nativeGroup>;\ntype Action = z.infer<typeof groupAction>;\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]>; resultDetails?(): unknown; resultWarnings?(): string[] };\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst hash = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst normalizeFilters = (filters: unknown): unknown => {\n if (!filters || typeof filters !== 'object' || Array.isArray(filters)) return filters;\n return Object.fromEntries(Object.entries(filters).map(([key, raw]) => {\n // Pinterest explicitly defaults these two pricing criteria to inclusion:true.\n const value = ['MIN_PRICE', 'MAX_PRICE'].includes(key) && raw && typeof raw === 'object' && !Array.isArray(raw) ? { inclusion: true, ...raw } : raw;\n 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) => canonical(a).localeCompare(canonical(b))) : normalizeFilters(value)];\n }));\n};\nconst configuration = (value: Group): Row => ({ ...Object.fromEntries(Object.entries(value).filter(([key]) => !['created_at', 'updated_at'].includes(key))), filters: normalizeFilters(value.filters) });\nconst mismatch = () => new AdportError('PROVIDER_ERROR', 'pinterest: product group scope, native response or pagination could not be verified.');\nconst 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.'];\nconst cursor = z.object({ selection: z.string().regex(/^[a-f0-9]{64}$/), native: z.string().min(1).max(4096) }).strict();\nconst count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst counts = z.discriminatedUnion('catalog_type', [z.object({ catalog_type: z.literal('RETAIL'), in_stock: count, out_of_stock: count, preorder: count, total: count, videos: count.optional() }).strict(), z.object({ catalog_type: z.literal('HOTEL'), total: count }).strict(), z.object({ catalog_type: z.literal('CREATIVE_ASSETS'), total: count, videos: count, images: count, app_links: count }).strict()]);\nconst product = z.object({ catalog_type: catalogType, metadata: z.record(z.string(), z.json()), pin: z.record(z.string(), z.json()) });\n\n/** Pinterest-owned OpenAPI 5.28.0 at 51aca009, fetched 2026-11-06. */\nexport class PinterestProductGroups {\n constructor(private readonly client: PinterestAdsClient, private readonly catalogs: PinterestCatalogService) {}\n private params(account: string, extra: Record<string, string> = {}) { return new URLSearchParams({ ad_account_id: pinterestId.parse(account), ...extra }); }\n private scope(group: Group, catalog: { id: string; catalog_type: string }, wanted?: string) {\n if (group.catalog_id !== catalog.id || group.catalog_type !== catalog.catalog_type || wanted && group.id !== wanted || group.catalog_type !== 'RETAIL' && group.feed_id != null) throw mismatch();return group;\n }\n private snapshot(account: string, group: Group) { return hash({ account_id: account, configuration: configuration(group) }); }\n private async read(account: string, catalog: { id: string; catalog_type: string }, id: string) { return this.scope(await this.client.get(`catalogs/product_groups/${groupId.parse(id)}`, nativeGroup, this.params(account)), catalog, id); }\n private async page<S extends z.ZodType>(path: string, schema: S, account: string, selection: Row, input: { page_size: number; bookmark?: string }, query: Record<string, string>) {\n const key = hash({ account, selection, page_size: input.page_size });let native: string | undefined;\n if (input.bookmark) { let parsed: z.infer<typeof cursor>;try { parsed = cursor.parse(JSON.parse(Buffer.from(input.bookmark, 'base64url').toString('utf8'))); } catch { throw new AdportError('INVALID_INPUT', 'Invalid product group cursor; restart this selection.'); }if (parsed.selection !== key) throw new AdportError('PENDING_MISMATCH', 'Product group selection changed; restart its first page.');native = parsed.native; }\n const params = this.params(account, { ...query, page_size: String(input.page_size), ...(native ? { bookmark: native } : {}) }), value = await this.client.get(path, z.object({ items: z.array(schema).max(250), bookmark: z.string().min(1).max(4096).nullable().optional() }), params);\n if (value.items.length > input.page_size || value.bookmark && (value.bookmark === native || !value.items.length)) throw mismatch();\n const complete = value.bookmark === null ? true : value.bookmark === undefined ? null : false;\n return { items: value.items, complete, truncated: complete !== true, ...(value.bookmark ? { next_cursor: Buffer.from(JSON.stringify({ selection: key, native: value.bookmark })).toString('base64url') } : {}) };\n }\n async list(value: unknown) {\n const input = groupList.parse(value), context = await this.catalogs.getCatalog(input.account_id, input.catalog_id);\n if (input.feed_id) { if (context.catalog.catalog_type !== 'RETAIL') throw new AdportError('INVALID_INPUT', 'Feed-based groups are RETAIL only.');await this.catalogs.getFeed(input.account_id, input.catalog_id, input.feed_id); }\n const selected = { catalog_id: input.catalog_id, feed_id: input.feed_id, product_group_ids: input.product_group_ids ? [...input.product_group_ids].sort() : undefined }, page = await this.page('catalogs/product_groups', nativeGroup, input.account_id, selected, input, { catalog_id: input.catalog_id, ...(input.feed_id ? { feed_id: input.feed_id } : {}), ...(input.product_group_ids ? { id: input.product_group_ids.join(',') } : {}) });\n if (new Set(page.items.map(row => row.id)).size !== page.items.length || page.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();\n const items = page.items.map(row => ({ ...this.scope(row, context.catalog), snapshot_hash: this.snapshot(input.account_id, row) }));return { ...page, items, records: items, notes };\n }\n async get(value: unknown) { 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) };return { group, records: [group], notes }; }\n async counts(value: unknown) {\n 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));if (data.catalog_type !== group.catalog_type) throw mismatch();\n 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.'] };\n }\n async products(value: unknown) {\n 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 }), page = await this.page(`catalogs/product_groups/${group.id}/products`, product, input.account_id, { catalog_id: input.catalog_id, product_group_id: group.id, snapshot_hash: group.snapshot_hash }, input, {});\n const records = page.items.map(row => { const key = row.catalog_type === 'RETAIL' ? 'item_id' : row.catalog_type === 'HOTEL' ? 'hotel_id' : 'creative_assets_id', nativeId = row.metadata[key];if (row.catalog_type !== group.catalog_type || typeof nativeId !== 'string' || !nativeId || nativeId.length > 1024) throw mismatch();return { id: `${row.catalog_type}:${nativeId}:${hash(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 }; });\n if (new Set(records.map(row => row.id)).size !== records.length) throw mismatch();return { ...page, records, 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.'] };\n }\n private mutable(row: Group) { if (row.catalog_type !== 'CREATIVE_ASSETS' && row.type !== 'MERCHANT_CREATED') throw new AdportError('INVALID_INPUT', 'Only merchant-created retail/hotel product groups can be edited or deleted; automatic groups are read-only.'); }\n private references(filters: unknown): string[] {\n const result = new Set<string>();\n const walk = (value: unknown) => { if (!value || typeof value !== 'object') return;if (Array.isArray(value)) { value.forEach(walk);return; }for (const [key, item] of Object.entries(value)) { if (key === 'PRODUCT_GROUP') { const parsed = z.object({ values: z.array(groupId).min(1).max(100) }).safeParse(item);if (!parsed.success) throw mismatch();parsed.data.values.forEach(id => result.add(id)); }else walk(item); } };walk(filters);return [...result].sort();\n }\n async context(value: unknown) {\n const input = groupContext.parse(value), owner = await this.catalogs.getCatalog(input.account_id, input.catalog_id), catalog = owner.catalog, action = input.action;\n const current = action.kind === 'create' ? undefined : await this.read(input.account_id, catalog, action.product_group_id);if (current) this.mutable(current);\n let body: Row = {}, feed: unknown;\n if (action.kind === 'create') {\n const { mode, catalog_type, feed_id, confirm_all_products: _all, ...fields } = action.definition;if (catalog_type !== catalog.catalog_type) throw new AdportError('INVALID_INPUT', 'Product group type differs from selected catalog.');\n if (mode === 'FEED') { const currentFeed = (await this.catalogs.getFeed(input.account_id, catalog.id, feed_id!)).feed;feed = { id: feed_id, snapshot_hash: currentFeed.snapshot_hash }; }\n body = mode === 'FEED' ? { feed_id, ...fields } : { catalog_id: catalog.id, catalog_type, ...fields };\n } else if (action.kind === 'update') {\n const { confirm_all_products, ...changes } = groupChanges.parse(action.changes);\n if ((current!.catalog_type !== 'RETAIL' || current!.feed_id != null) && (changes.country !== undefined || changes.locale !== undefined)) throw new AdportError('INVALID_INPUT', 'Country/locale apply only to catalog-based RETAIL groups.');\n if (changes.filters && !productGroupFilterSchema(current!.catalog_type, current!.catalog_type !== 'RETAIL' && confirm_all_products === true).safeParse(changes.filters).success) throw new AdportError('INVALID_INPUT', 'Invalid filter selection; use pinterest_product_group_filter_schema.');\n body = { ...(current!.feed_id != null ? {} : { catalog_type: current!.catalog_type }), ...changes };\n } else if (!current!.name || current!.name !== action.confirm_name) throw new AdportError('INVALID_INPUT', 'Permanent deletion requires the exact current product group name.');\n const referenced = new Map<string, Group>(), visit = async (id: string, stack: Set<string>): Promise<void> => {\n if (id === current?.id || stack.has(id)) throw new AdportError('INVALID_INPUT', 'Product group filter references contain a cycle.');if (referenced.has(id)) return;if (referenced.size >= 40) throw new AdportError('INVALID_INPUT', 'Reference proof exceeds the 40-group Adport bound.');\n const row = await this.read(input.account_id, catalog, id);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 AdportError('INVALID_INPUT', 'Referenced groups must belong to the selected retail feed.');\n referenced.set(id, row);for (const next of this.references(row.filters)) await visit(next, new Set([...stack, id]));\n };\n // Deletion does not resolve outgoing filter references; it verifies only the\n // exact owned resource being removed, including all current configuration.\n if (action.kind !== 'delete') for (const id of this.references(body.filters ?? current?.filters)) await visit(id, new Set());\n const context_hash = hash({ account_id: input.account_id, owner: owner.context_hash, catalog: { id: catalog.id, name: catalog.name, catalog_type: catalog.catalog_type }, action, current: current ? configuration(current) : undefined, body, feed, references: [...referenced.values()].map(row => configuration(row)).sort((a, b) => String(a.id).localeCompare(String(b.id))) });\n return { context_hash, catalog, current, body, records: [current ? { ...current, snapshot_hash: this.snapshot(input.account_id, current) } : { id: catalog.id, name: catalog.name, catalog_type: catalog.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 };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const create = op.tool === 'pinterest_create_product_group', update = op.tool === 'pinterest_update_product_group', remove = op.tool === 'pinterest_delete_product_group';\n if (op.provider !== 'pinterest' || !(create || update || remove) || op.kind !== (create ? 'create' : update ? 'update' : 'remove')) throw new AdportError('INVALID_INPUT', 'Invalid Pinterest product group operation.');\n const input = create ? groupCreate.parse(op.payload) : update ? groupUpdate.parse(op.payload) : groupDelete.parse(op.payload);\n const action: 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 };\n const prepare = async () => { const context = await this.context({ account_id: op.accountId, catalog_id: input.catalog_id, action });if (context.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'Product group context, references or source settings changed; read context and preview again.');return context; }, before = await prepare();\n const title = create ? 'Create product group' : update ? 'Update product group' : 'Delete product group permanently', subject = create ? String(before.body.name) : before.current!.name ?? before.current!.id;let receipt: Row | undefined;\n return { summary: `${title} · ${subject}`, changes: [remove ? '- ' + subject : `${create ? '+' : '~'} ${canonical(before.body)}`], coercions: [], budgetDeltas: [], notes,\n 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' } as Record<string, string>)[key] ?? key, ...(before.current && Object.hasOwn(before.current, key) ? { before: before.current[key] } : {}), after }))), { label: 'Verified filter references', after: before.reference_count }], notices: notes },\n execute: async () => { const fresh = await prepare();let id = fresh.current?.id;try {\n const path = `catalogs/product_groups${id ? '/' + id : ''}`;\n const result = await this.client.mutate(path, create ? 'POST' : update ? 'PATCH' : 'DELETE', remove ? undefined : fresh.body, remove ? z.union([nativeGroup, z.undefined()]) : nativeGroup, this.params(op.accountId));\n if (result) { if (id && result.id !== id) throw mismatch();id = result.id;this.scope(result, fresh.catalog, id); }if (!id) throw mismatch();\n if (remove) {\n const absence = await this.list({ account_id: op.accountId, catalog_id: input.catalog_id, product_group_ids: [id], page_size: 1 });if (absence.complete !== true || absence.items.length) throw mismatch();receipt = { deletion_readback: 'ABSENT_FROM_COMPLETE_FILTERED_LIST', items_deleted: false };\n } else {\n const actual = await this.read(op.accountId, fresh.catalog, id);\n if (create && !fresh.body.feed_id && actual.feed_id != null) throw mismatch();\n 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' }) };\n if (Object.entries(wanted).some(([key, value]) => canonical(configuration(actual)[key]) !== canonical(value))) throw mismatch();\n 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: id } };\n }\n return [id];\n } catch (error) { const data = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Row : {}, returned = Array.isArray(data.resource_ids) ? data.resource_ids.filter((value): value is string => typeof value === 'string' && groupId.safeParse(value).success) : [];throw new AdportError('PROVIDER_ERROR', 'Pinterest product group mutation is unconfirmed. No write was retried; reconcile known IDs before another preview.', { resource_ids: [...new Set([...(id ? [id] : []), ...returned])], ...(typeof data.http_status === 'number' ? { http_status: data.http_status } : {}) }); }\n }, resultDetails: () => receipt, resultWarnings: () => notes.slice(1) };\n }\n}\n","import { z } from 'zod';\nimport { pinterestId } from './schemas.js';\nimport { filterEnums, filterFields } from './product-group-filter-spec.js';\n\nexport const catalogType = z.enum(['RETAIL', 'HOTEL', 'CREATIVE_ASSETS']);\nexport const groupId = z.string().regex(/^\\d{1,30}$/), groupHash = z.string().regex(/^[a-f0-9]{64}$/);\nconst text = z.string().min(1).max(1024), negated = z.boolean().optional();\nconst strings = z.array(text).min(1).max(100), numericOperator = z.enum(['GREATER_THAN', 'GREATER_THAN_OR_EQUALS', 'LESS_THAN', 'LESS_THAN_OR_EQUALS']);\nconst criteria: Record<string, z.ZodType> = {\n CatalogsProductGroupMultipleStringCriteria: z.object({ values: strings, negated }).strict(),\n CatalogsProductGroupMultipleStringListCriteria: z.object({ values: z.array(strings).min(1).max(100), negated }).strict(),\n CatalogsProductGroupFilterOperatorTypeCriteria: z.object({ values: strings, negated, filter_operator_type: z.enum(['IS', 'CONTAINS']).optional() }).strict(),\n CatalogsProductGroupPricingCriteria: z.object({ values: z.number().nonnegative().max(Number.MAX_SAFE_INTEGER), negated, inclusion: z.boolean().optional() }).strict(),\n CatalogsProductGroupUint32Criteria: z.object({ value: z.number().int().min(0).max(4_294_967_295), negated, operator: numericOperator }).strict(),\n CatalogsProductGroupCurrencyCriteria: z.object({ values: z.enum(filterEnums.NonNullableCatalogsCurrency), negated: z.literal(false).optional() }).strict(),\n CatalogsProductGroupMultipleGenderCriteria: z.object({ values: z.array(z.enum(filterEnums.Gender)).min(1).max(100), negated }).strict(),\n CatalogsProductGroupMultipleCountriesCriteria: z.object({ values: z.array(z.enum(filterEnums.Country)).min(1).max(100), negated }).strict(),\n CatalogsProductGroupMultipleMediaTypesCriteria: z.object({ values: z.array(z.enum(filterEnums.MediaType)).min(1).max(100), negated }).strict(),\n CatalogsProductGroupMultiplePinterestProductCategoryCriteria: z.object({ values: z.array(z.enum(filterEnums.ProductCategoryEnum)).min(1).max(100), negated }).strict(),\n PriceFilterPrice: z.object({ currency: z.enum(filterEnums.NonNullableCatalogsCurrency), negated, operator: numericOperator, value: z.number().nonnegative().max(Number.MAX_SAFE_INTEGER) }).strict(),\n};\nexport function productGroupFilterSchema(type: z.infer<typeof catalogType>, allowEmpty = false) {\n const fields = Object.entries(filterFields[type]).map(([key, value]) => z.object({ [key]: criteria[value]! }).strict());\n const clause = z.union([fields[0]!, fields[1]!, ...fields.slice(2)]);\n const list = z.array(clause).min(allowEmpty ? 0 : 1).max(32);\n return z.union([z.object({ any_of: list }).strict(), z.object({ all_of: list }).strict()]);\n}\n// Keep large native enums on demand; every supplied filter is validated against\n// the same pinned Zod schema before preview or native use, never silently dropped.\nexport const groupFilters = z.record(z.string(), z.json()).refine(value => Buffer.byteLength(JSON.stringify(value), 'utf8') <= 262_144, 'Filters exceed the 256 KiB Adport bound');\nexport const groupDefinition = z.object({\n mode: z.enum(['FEED', 'CATALOG']), catalog_type: catalogType, feed_id: groupId.optional(),\n name: text, description: z.string().max(10_000).nullable().optional(), filters: groupFilters,\n country: z.enum(filterEnums.Country).optional(), locale: z.enum(filterEnums.CatalogsLocale).optional(),\n confirm_all_products: z.literal(true).optional(),\n}).strict().superRefine((value, ctx) => {\n if (value.mode === 'FEED' ? value.catalog_type !== 'RETAIL' || !value.feed_id || value.country !== undefined || value.locale !== undefined : value.feed_id !== undefined || value.catalog_type !== 'RETAIL' && (value.country !== undefined || value.locale !== undefined)) 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' });\n validateGroupFilters(value.catalog_type, value.filters, value.confirm_all_products, ctx);\n});\nexport function validateGroupFilters(type: z.infer<typeof catalogType>, filters: z.infer<typeof groupFilters>, all: boolean | undefined, ctx: z.RefinementCtx) {\n if (!productGroupFilterSchema(type, type !== '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.' });\n}\nexport const groupChanges = z.object({ name: text.optional(), description: z.string().max(10_000).nullable().optional(), filters: groupFilters.optional(), country: z.enum(filterEnums.Country).optional(), locale: z.enum(filterEnums.CatalogsLocale).optional(), confirm_all_products: z.literal(true).optional() }).strict().refine(value => Object.keys(value).some(key => key !== 'confirm_all_products'), 'Supply at least one setting');\nconst selection = { catalog_id: groupId }, reference = { ...selection, product_group_id: groupId };\nexport const groupCreate = z.object({ ...selection, expected_context_hash: groupHash, definition: groupDefinition }).strict();\nexport const groupUpdate = z.object({ ...reference, expected_context_hash: groupHash, changes: groupChanges, acknowledge_live_effects: z.literal(true) }).strict();\nexport const groupDelete = z.object({ ...reference, expected_context_hash: groupHash, confirm_name: z.string().min(1).max(1024), acknowledge_live_effects: z.literal(true), confirm_permanent_deletion: z.literal(true) }).strict();\nexport const groupAction = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('create'), definition: groupDefinition }).strict(),\n z.object({ kind: z.literal('update'), product_group_id: groupId, changes: groupChanges }).strict(),\n z.object({ kind: z.literal('delete'), product_group_id: groupId, confirm_name: z.string().min(1).max(1024) }).strict(),\n]);\nexport const groupContext = z.object({ account_id: pinterestId, ...selection, action: groupAction }).strict();\nexport const groupPaging = { page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).max(8192).optional() };\nexport const groupList = z.object({ account_id: pinterestId, ...selection, feed_id: groupId.optional(), product_group_ids: z.array(groupId).min(1).max(100).refine(ids => new Set(ids).size === ids.length).optional(), ...groupPaging }).strict();\nexport const groupReference = z.object({ account_id: pinterestId, ...reference }).strict();\nexport const nativeGroup = z.looseObject({ id: groupId, catalog_id: groupId, catalog_type: catalogType, name: z.string().max(1024).optional(), description: z.string().max(10_000).nullable().optional(), filters: groupFilters, feed_id: groupId.nullable().optional(), type: z.string().optional(), country: z.string().nullable().optional(), locale: z.string().nullable().optional(), created_at: z.number().int().safe().optional(), updated_at: z.number().int().safe().optional() }).superRefine((value, ctx) => {\n 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' });\n});\n","// Pinterest-owned OpenAPI 5.28.0, 51aca009f10a90283ccdf3956d509fc995ebac23.\n// Pinned native field/enum data for on-demand filter discovery and shared validation.\nexport const filterFields = {\n \"RETAIL\": {\n \"MIN_PRICE\": \"CatalogsProductGroupPricingCriteria\",\n \"MAX_PRICE\": \"CatalogsProductGroupPricingCriteria\",\n \"CURRENCY\": \"CatalogsProductGroupCurrencyCriteria\",\n \"ITEM_ID\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"AVAILABILITY\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"BRAND\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"CONDITION\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"CUSTOM_LABEL_0\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_1\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_2\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_3\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_4\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"ITEM_GROUP_ID\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"GENDER\": \"CatalogsProductGroupMultipleGenderCriteria\",\n \"MEDIA_TYPE\": \"CatalogsProductGroupMultipleMediaTypesCriteria\",\n \"PRODUCT_TYPE_4\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"PRODUCT_TYPE_3\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"PRODUCT_TYPE_2\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"PRODUCT_TYPE_1\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"PRODUCT_TYPE_0\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_6\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_5\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_4\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_3\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_2\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_1\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_0\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"CUSTOM_NUMBER_0\": \"CatalogsProductGroupUint32Criteria\",\n \"CUSTOM_NUMBER_1\": \"CatalogsProductGroupUint32Criteria\",\n \"CUSTOM_NUMBER_2\": \"CatalogsProductGroupUint32Criteria\",\n \"CUSTOM_NUMBER_3\": \"CatalogsProductGroupUint32Criteria\",\n \"CUSTOM_NUMBER_4\": \"CatalogsProductGroupUint32Criteria\",\n \"TITLE_KEYWORDS\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"PINTEREST_PRODUCT_CATEGORIES\": \"CatalogsProductGroupMultiplePinterestProductCategoryCriteria\",\n \"PRODUCT_GROUP\": \"CatalogsProductGroupMultipleStringCriteria\"\n },\n \"HOTEL\": {\n \"PRICE\": \"PriceFilterPrice\",\n \"HOTEL_ID\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"BRAND\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"CUSTOM_LABEL_0\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_1\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_2\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_3\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_4\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"COUNTRY\": \"CatalogsProductGroupMultipleCountriesCriteria\",\n \"TITLE_KEYWORDS\": \"CatalogsProductGroupMultipleStringCriteria\"\n },\n \"CREATIVE_ASSETS\": {\n \"CREATIVE_ASSETS_ID\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"CUSTOM_LABEL_0\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_1\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_2\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_3\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_4\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_6\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_5\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_4\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_3\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_2\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_1\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_0\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"MEDIA_TYPE\": \"CatalogsProductGroupMultipleMediaTypesCriteria\",\n \"TITLE_KEYWORDS\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"LINK\": \"CatalogsProductGroupFilterOperatorTypeCriteria\"\n }\n} as const;\nexport const 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\"]} as const;\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError, MAX_PROJECT_MEDIA_BYTES, verifyMedia, type Creative, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestCatalogService } from './catalogs.js';\nimport { catalogType, groupHash } from './product-group-schemas.js';\nimport { itemUpdateMask } from './catalog-item-attributes.js';\nimport { attributeSchema, batchReference, itemBatchApply, itemContext, itemCopy, itemIdField, itemIdsField, itemNamedApply, itemOperation, itemRead, itemRequest, itemSelection, itemWriteOperations, sourceId } from './catalog-item-schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Selection = z.infer<typeof itemSelection>;\ntype Request = z.infer<typeof itemRequest>;\ntype Kind = z.infer<typeof catalogType>;\ntype Current = { id: string; state: 'PRESENT' | 'NATIVE_ITEM_ERROR' | 'NOT_RETURNED'; attributes?: Row; pins?: unknown[] | null; diagnostics: unknown; diagnostic_hash?: string };\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]>; resultDetails?(): unknown; resultWarnings?(): string[] };\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst hash = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\nconst batchId = z.string().regex(/^[A-Za-z0-9_-]{1,100}$/);\nconst diagnostic = z.object({ code: z.number().int().safe().optional(), attribute: z.string().max(256).optional(), message: z.string().max(100_000).optional() });\nconst diagnostics = (value: unknown) => z.array(diagnostic).max(10_000).parse(value ?? []).map(({ message, ...row }) => ({ ...row, message_present: !!message }));\nconst nativeBatch = z.object({ catalog_type: catalogType, batch_id: batchId.optional(), created_time: z.string().max(100).nullable().optional(), completed_time: z.string().max(100).nullable().optional(), status: z.enum(['PROCESSING', 'COMPLETED', 'FAILED']).optional(), items: z.array(z.record(z.string(), z.json())).max(1000).optional() });\nconst manifestRow = z.object({ source_id: sourceId, operation: itemOperation, desired_keys: z.array(z.string()).max(108), clear_keys: z.array(z.string()).max(100), desired_hash: groupHash.optional(), preserved_hash: groupHash.optional() }).strict();\nconst receiptSchema = itemSelection.extend({ version: z.literal('pinterest_items_v1'), scope_id: z.string().min(1).max(200), catalog_type: catalogType, owner_context_hash: groupHash, batch_id: batchId, expires_at: z.number().int().safe(), manifest: z.array(manifestRow).min(1).max(1000), media_expires_at: z.string().max(100).optional() }).strict();\nconst notes = ['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.'];\nconst failure = (error: unknown, ids: string[] = [], extra: Row = {}) => { const data = error instanceof AdportError ? object(error.details) : {};return new AdportError('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.', { ...(ids.length ? { resource_ids: ids } : {}), ...(typeof data.http_status === 'number' ? { http_status: data.http_status } : {}), ...extra }); };\nfunction bounded(value: unknown) { if (Buffer.byteLength(canonical(value)) > 2 * 1024 * 1024) throw new AdportError('INVALID_INPUT', 'Catalog batch exceeds the 2 MiB Adport bound; use smaller batches.'); }\nfunction publicValue(value: unknown, key = ''): unknown {\n if (Array.isArray(value)) return value.map(item => publicValue(item, key));\n if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, publicValue(item, name)]));\n if (typeof value === 'string' && /link|url/i.test(key)) {\n const match = value.match(/^https:\\/\\/adport\\.invalid\\/media\\/([a-f0-9-]+)\\/([a-f0-9]+)$/);if (match) return { media_id: match[1], sha256: match[2] };\n try { const url = new URL(value);return { origin: url.origin, fingerprint: hash(value) }; } catch { return { fingerprint: hash(value) }; }\n }\n return value;\n}\nfunction normalized(type: Kind, values: Row) { return { ...values, ...(type === 'RETAIL' && typeof values.image_link === 'string' ? { image_link: [values.image_link] } : {}) }; }\nfunction wantedValues(type: Kind, attrs: Row, keys: string[], clears: string[]) { return normalized(type, Object.fromEntries(keys.map(key => [key, clears.includes(key) ? null : attrs[key] ?? null]))); }\nfunction preserved(attrs: Row, keys: string[]) { return Object.fromEntries(Object.entries(attrs).filter(([key]) => !keys.includes(key) && key !== 'last_updated_time')); }\nconst safeMediaUrl = (value: string) => { try { const url = new URL(value);return url.protocol === 'https:' && !url.username && !url.password && !url.hash; } catch { return false; } };\n\n/** Native vertical item batches, Pinterest OpenAPI 5.28.0 at 51aca009. */\nexport class PinterestCatalogItems {\n constructor(private readonly client: PinterestAdsClient, private readonly catalogs: PinterestCatalogService, private readonly media: MediaResolver) {}\n supports(tool: string) { return tool === 'pinterest_apply_catalog_items_batch' || tool === 'pinterest_update_catalog_item_copy' || Object.hasOwn(itemWriteOperations, tool); }\n private scopeId() { const value = (this.media as { scopeId?: unknown }).scopeId;return typeof value === 'string' && value ? value : 'local'; }\n private params(account: string) { return new URLSearchParams({ ad_account_id: account }); }\n private snapshot(selection: Selection, type: Kind, owner: string, row: Current) { return hash({ selection, catalog_type: type, owner, id: row.id, state: row.state, attributes: row.attributes, diagnostic_hash: row.diagnostic_hash }); }\n private async selected(selection: Selection) { const result = await this.catalogs.getCatalog(selection.account_id, selection.catalog_id);return { catalog: result.catalog, owner: result.context_hash }; }\n private async readSet(selection: Selection, type: Kind, ids: string[]): Promise<Current[]> {\n const result = await this.client.mutate('catalogs/items', 'POST', { country: selection.country, language: selection.language, filters: { catalog_id: selection.catalog_id, catalog_type: type, [itemIdsField[type]]: ids } }, z.object({ items: z.array(z.record(z.string(), z.json())).max(1000) }), this.params(selection.account_id)).catch(error => { throw failure(error); });\n const found = new Map<string, Current>();\n for (const raw of result.items) {\n const id = sourceId.parse(raw[itemIdField[type]]), errors = diagnostics(raw.errors), kind = raw.item_response_kind, family = type === 'RETAIL' ? 'retail' : type === 'HOTEL' ? 'hotel' : 'creative_assets';\n if (!ids.includes(id) || found.has(id) || raw.catalog_type !== type || raw.catalog_id !== undefined && raw.catalog_id !== selection.catalog_id || kind !== undefined && ![family + '_item', family + '_item_error'].includes(String(kind)) || errors.length && raw.attributes !== undefined || kind === family + '_item_error' && raw.attributes !== undefined) throw failure(undefined);\n const attrs = raw.attributes === undefined ? undefined : z.record(z.string(), z.json()).parse(raw.attributes), state = attrs ? 'PRESENT' : 'NATIVE_ITEM_ERROR';\n found.set(id, { id, state, attributes: attrs, pins: raw.pins === null ? null : raw.pins === undefined ? undefined : z.array(z.unknown()).max(11).parse(raw.pins), diagnostics: errors, diagnostic_hash: errors.length ? hash(raw.errors) : undefined });\n }\n return ids.map(id => found.get(id) ?? { id, state: 'NOT_RETURNED', diagnostics: [] });\n }\n private previewMedia(pins: unknown[] | null | undefined): Creative['media'] {\n const result: Creative['media'] = [];\n for (const pin of pins ?? []) for (const image of Object.values(object(object(object(pin).media).images))) {\n const url = object(image).url;if (typeof url !== 'string') continue;let parsed: URL;try { parsed = new URL(url); } catch { continue; }\n if (safeMediaUrl(url) && (parsed.hostname === 'i.pinimg.com' || parsed.hostname.endsWith('.pinimg.com'))) { result.push({ type: 'image', url });break; }\n }\n return result.slice(0, 11);\n }\n async list(value: unknown) {\n const input = itemRead.parse(value), selection = itemSelection.parse(Object.fromEntries(Object.entries(input).filter(([key]) => ['account_id', 'catalog_id', 'country', 'language'].includes(key)))), { catalog, owner } = await this.selected(selection), key = hash({ selection, ids: input.item_ids, limit: input.limit });let offset = 0;\n if (input.cursor) { let navigation;try { navigation = z.object({ selection: groupHash, offset: z.number().int().min(1).max(999) }).strict().parse(JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8'))); } catch { throw new AdportError('INVALID_INPUT', 'Invalid catalog item cursor.'); }if (navigation.selection !== key || navigation.offset >= input.item_ids.length) throw new AdportError('PENDING_MISMATCH', 'Catalog item selection changed; restart its first page.');offset = navigation.offset; }\n const ids = input.item_ids.slice(offset, offset + input.limit), current = await this.readSet(selection, catalog.catalog_type, ids), records = 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(selection, catalog.catalog_type, owner, row) }));\n const creatives: Creative[] = current.map((row, index) => { const title = row.attributes?.title ?? row.attributes?.name, description = row.attributes?.description;return { id: row.id, provider: 'pinterest', account_id: input.account_id, name: records[index]!.name, type: 'CATALOG_' + catalog.catalog_type, status: row.state, headlines: typeof title === 'string' ? [title] : [], descriptions: typeof description === 'string' ? [description] : [], landing_urls: [], media: this.previewMedia(row.pins), actions: row.state === 'PRESENT' ? [{ label: 'Edit copy', tool: 'pinterest_update_catalog_item_copy', arguments: { ...selection, source_id: row.id, expected_snapshot_hash: records[index]!.snapshot_hash, confirm_publication: true, acknowledge_catalog_effects: true }, fields: [{ key: 'title', label: catalog.catalog_type === 'HOTEL' ? 'Name' : 'Title', type: 'text', value: typeof title === 'string' ? title : '' }, { key: 'description', label: 'Description', type: 'text', value: typeof description === 'string' ? description : '' }] }] : [] }; });\n const next = offset + ids.length;return { records, creatives, catalog_type: catalog.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.'] };\n }\n private async materialize(request: Request, type: Kind, mint: boolean) {\n const rows = structuredClone(request.operations), targets = new Set<string>(), resolved = new Map<string, string>(), sources: Row[] = [];let expires: string | undefined;\n if (request.media_assets.length && !this.media.providerUrl) throw new AdportError('INVALID_INPUT', 'Upload project media first; this runtime has no private provider URL staging.');\n for (const asset of request.media_assets) {\n const row = rows[asset.item_index], key = `${asset.item_index}:${asset.field}:${asset.image_index ?? ''}`;if (!row?.attributes || row.operation === 'DELETE' || targets.has(key)) throw new AdportError('INVALID_INPUT', 'Media references require distinct existing non-delete item slots.');targets.add(key);\n const options = { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: /video/.test(asset.field) ? ['video/mp4'] : ['image/png', 'image/jpeg', 'image/webp'] }, source = { media_id: asset.media_id, expected_sha256: asset.expected_sha256 }, file = await this.media.read(source, options), verified = verifyMedia(file.bytes, file.name, source.expected_sha256, { ...options, contentType: file.contentType });\n const cacheKey = canonical({ source, type: verified.contentType });let url = resolved.get(cacheKey);\n if (!url) {\n url = `https://adport.invalid/media/${asset.media_id}/${asset.expected_sha256}`;\n if (mint) { const grant = await this.media.providerUrl!(source, options);if (!safeMediaUrl(grant.url) || grant.sha256 !== verified.sha256 || !(Date.parse(grant.expires_at) > Date.now() + 10 * 60_000)) throw new AdportError('PROVIDER_ERROR', 'Media staging returned an invalid or short-lived grant.');url = grant.url;if (!expires || Date.parse(grant.expires_at) < Date.parse(expires)) expires = grant.expires_at; }\n resolved.set(cacheKey, url);\n }\n const parts = asset.field.split('.'), attrs = parts.length === 2 ? object(row.attributes[parts[0]!]) : row.attributes, field = parts.at(-1)!;\n if (parts.length === 2) { const parent = row.attributes[parts[0]!];if (parent !== undefined && (!parent || typeof parent !== 'object' || Array.isArray(parent))) throw new AdportError('INVALID_INPUT', 'A nested media reference requires an object field.');row.attributes[parts[0]!] = attrs as typeof row.attributes; }\n const array = field === 'additional_image_link' || field === 'image_link' && type === 'RETAIL';\n if (array) { if (asset.image_index === undefined) throw new AdportError('INVALID_INPUT', 'An array media field requires image_index.');const values = attrs[field] === undefined ? [] : Array.isArray(attrs[field]) ? attrs[field] as unknown[] : [attrs[field]];if (values[asset.image_index] != null) throw new AdportError('INVALID_INPUT', 'A media slot already has a native URL.');values[asset.image_index] = url;attrs[field] = values; }\n else { if (asset.image_index !== undefined || attrs[field] !== undefined) throw new AdportError('INVALID_INPUT', 'Scalar media fields cannot have image_index or an existing URL.');attrs[field] = url; }\n 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 });\n }\n for (const row of rows) {\n if (row.operation === 'DELETE') { if (type !== 'RETAIL' && row.last_updated_time !== undefined) throw new AdportError('INVALID_INPUT', 'Only RETAIL deletion supports last_updated_time.');continue; }\n if (!attributeSchema(type, row.operation).safeParse(row.attributes).success) throw new AdportError('INVALID_INPUT', 'Attributes do not match this native catalog type/operation. Use pinterest_catalog_item_schema; no field is silently dropped.');\n if (row.attributes?.id !== undefined && row.attributes.id !== row.source_id) throw new AdportError('INVALID_INPUT', 'Deprecated attribute id cannot differ from the selected source_id.');\n if (row.clear_fields?.length && (type !== 'RETAIL' || Object.keys(row.attributes!).some(key => !itemUpdateMask.safeParse(key).success))) throw new AdportError('INVALID_INPUT', 'Explicit unsetting is RETAIL-only; all supplied fields must be native update-mask fields when combined with clears.');\n }\n bounded(rows);return { rows, sources, expires };\n }\n private manifest(type: Kind, rows: Request['operations'], before: Current[]) {\n const result = rows.map(row => { const desired_keys = [...new Set([...Object.keys(row.attributes ?? {}), ...(row.clear_fields ?? [])])].sort(), clear_keys = row.clear_fields ?? [], current = before.find(value => value.id === row.source_id)!;return { source_id: row.source_id, operation: row.operation, desired_keys, clear_keys, ...(row.operation !== 'DELETE' ? { desired_hash: hash(wantedValues(type, row.attributes!, desired_keys, clear_keys)) } : {}), ...(row.operation === 'UPDATE' ? { preserved_hash: hash(preserved(normalized(type, current.attributes!), desired_keys)) } : {}) }; });\n if (Buffer.byteLength(canonical(result)) > 1_000_000) throw new AdportError('INVALID_INPUT', 'Batch proof exceeds its bound; split this batch before previewing.');return result;\n }\n async context(value: unknown) {\n const input = itemContext.parse(value), selection = 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))));bounded(request);\n const { catalog, owner } = await this.selected(selection), current = await this.readSet(selection, catalog.catalog_type, request.operations.map(row => row.source_id));\n for (const row of request.operations) {\n const before = current.find(value => value.id === row.source_id)!;\n if (row.operation === 'CREATE' && before.state === 'PRESENT') throw new AdportError('INVALID_INPUT', 'CREATE cannot overwrite an existing item.');\n if (['UPDATE', 'DELETE'].includes(row.operation) && before.state !== 'PRESENT') throw new AdportError('INVALID_INPUT', 'UPDATE/DELETE require a positively read current item; native item errors cannot establish ownership/configuration.');\n if (row.operation === 'UPSERT' && (!request.acknowledge_replacement || before.state !== 'PRESENT' && !request.acknowledge_unconfirmed_existing)) throw new AdportError('INVALID_INPUT', 'UPSERT requires replacement acknowledgement and, for unconfirmed current items, acknowledge_unconfirmed_existing.');\n }\n const prepared = await this.materialize(request, catalog.catalog_type, false);this.manifest(catalog.catalog_type, prepared.rows, current);\n const scope_id = this.scopeId();return { context_hash: hash({ selection, owner, catalog: { id: catalog.id, name: catalog.name, type: catalog.catalog_type }, scope: scope_id, request, current: current.map(({ pins: _pins, ...row }) => row) }), scope_id, selection, request, catalog, owner, 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(selection, catalog.catalog_type, owner, row), diagnostics: row.diagnostics })), notes };\n }\n async publicContext(value: unknown) { const result = await this.context(value);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 }; }\n private batchRows(data: z.infer<typeof nativeBatch>, manifest: z.infer<typeof manifestRow>[]) {\n const seen = new Set<string>(), values = new Map<string, Row>();\n for (const row of data.items ?? []) {\n const id = sourceId.parse(row[itemIdField[data.catalog_type]]);if (seen.has(id) || !manifest.some(value => value.source_id === id)) throw failure(undefined);seen.add(id);\n const status = z.enum(['SUCCESS', 'FAILURE', 'PROCESSING']).optional().parse(row.status), errors = diagnostics(row.errors), warnings = diagnostics(row.warnings);if (status === 'SUCCESS' && errors.length) throw failure(undefined);\n values.set(id, { id, source_id: id, status: status ?? 'UNCONFIRMED', errors, warnings });\n }\n 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: [] });\n }\n private async verifiedReceipt(value: unknown) {\n const input = batchReference.parse(value), proof = receiptSchema.parse(this.client.verifyCatalogBatchReceipt(input.batch_receipt));if (proof.account_id !== input.account_id || proof.scope_id !== this.scopeId() || proof.expires_at <= Math.floor(Date.now() / 1000) || proof.expires_at > Math.floor(Date.now() / 1000) + 30 * 86400) throw new AdportError('INVALID_INPUT', 'Batch receipt is expired or belongs to another advertiser/project.');\n const { catalog, owner } = await this.selected(proof);if (catalog.catalog_type !== proof.catalog_type || owner !== proof.owner_context_hash) throw new AdportError('POLICY_VIOLATION', 'Current catalog ownership/type differs from the batch receipt.');return proof;\n }\n async status(value: unknown, reconcile = false) {\n 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 => { throw failure(error, [proof.batch_id]); });if (data.batch_id !== proof.batch_id || data.catalog_type !== proof.catalog_type) throw failure(undefined);\n const records = this.batchRows(data, proof.manifest);let readback_error: Row | undefined;\n if (reconcile) {\n try {\n const current = await this.readSet(proof, proof.catalog_type, proof.manifest.map(row => row.source_id));\n for (const record of records) {\n const expected = proof.manifest.find(row => row.source_id === record.id)!, actual = current.find(row => row.id === record.id)!;\n record.observed_state = actual.state;\n if (record.status !== 'SUCCESS') { record.readback = 'NATIVE_ITEM_NOT_SUCCESSFUL';continue; }\n if (expected.operation === 'DELETE') { record.readback = actual.state === 'PRESENT' ? 'STILL_PRESENT' : 'ABSENCE_UNCONFIRMED';continue; }\n if (!actual.attributes) { record.readback = 'CURRENT_ITEM_UNCONFIRMED';continue; }\n const matches = hash(wantedValues(proof.catalog_type, actual.attributes, expected.desired_keys, expected.clear_keys)) === expected.desired_hash, retains = !expected.preserved_hash || hash(preserved(normalized(proof.catalog_type, actual.attributes), expected.desired_keys)) === expected.preserved_hash;\n record.readback = matches && retains ? 'REQUESTED_CONFIGURATION_VERIFIED' : 'CONFIGURATION_UNCONFIRMED';record.omitted_fields_preserved = expected.preserved_hash ? retains : undefined;\n }\n } catch (error) { const details = error instanceof AdportError ? object(error.details) : {};readback_error = { status: 'READBACK_UNAVAILABLE', ...(typeof details.http_status === 'number' ? { http_status: details.http_status } : {}) }; }\n }\n return { batch_id: proof.batch_id, catalog_type: proof.catalog_type, status: data.status ?? 'UNCONFIRMED', records, submitted_items: proof.manifest.length, terminal_items: records.filter(row => ['SUCCESS', 'FAILURE', 'BATCH_FAILED'].includes(String(row.status))).length, all_items_native_successful: data.status === 'COMPLETED' && records.every(row => row.status === 'SUCCESS'), ...(readback_error ? { readback_error } : {}), media_expires_at: proof.media_expires_at, notes: [...notes, 'A native SUCCESS is not proof of Pin publication, ad eligibility or permanent media hosting. Missing/error item reads never independently certify deletion.'] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const copy = op.tool === 'pinterest_update_catalog_item_copy', operation = itemWriteOperations[op.tool as keyof typeof itemWriteOperations], expectedKind = operation === 'CREATE' ? 'create' : operation === 'DELETE' ? 'remove' : 'update';\n if (op.provider !== 'pinterest' || !this.supports(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'Invalid catalog item mutation/provider kind.');\n const parsed = copy ? itemCopy.parse(op.payload) : operation ? itemNamedApply(operation).parse(op.payload) : itemBatchApply.parse(op.payload);\n const selection = itemSelection.parse({ account_id: op.accountId, catalog_id: parsed.catalog_id, country: parsed.country, language: parsed.language });\n const request: 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 });\n if (copy) { const input = parsed as z.infer<typeof itemCopy>, parent = await this.selected(selection);request.operations[0]!.attributes = { ...(input.title !== undefined ? { [parent.catalog.catalog_type === 'HOTEL' ? 'name' : 'title']: input.title } : {}), ...(input.description !== undefined ? { description: input.description } : {}) }; }\n const prepare = async () => { const result = await this.context({ ...selection, ...request });\n if (copy ? result.records[0]!.snapshot_hash !== (parsed as z.infer<typeof itemCopy>).expected_snapshot_hash : result.context_hash !== (parsed as z.infer<typeof itemBatchApply>).expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog items, selection, owner or media changed; read context and preview again.');return result; }, before = await prepare();let receipt: Row | undefined;\n const title = copy ? 'Update catalog item copy' : 'Submit catalog item batch';\n return { summary: `${title} · ${request.operations.length} items`, changes: before.prepared.rows.map(row => `${row.operation} ${row.source_id}`), coercions: [], budgetDeltas: [], notes,\n review: { provider: 'pinterest', accountId: op.accountId, kind: op.kind, title, subject: before.catalog.name, fields: [{ label: 'Catalog and market', after: { id: selection.catalog_id, type: before.catalog.catalog_type, country: selection.country, language: selection.language } }, ...before.prepared.rows.map(row => ({ label: row.source_id + ' · ' + 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: [...notes, ...(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.'] : [])] },\n execute: async () => { const fresh = await prepare();let id: string | undefined;try {\n const materialized = await this.materialize(request, fresh.catalog.catalog_type, true), manifest = this.manifest(fresh.catalog.catalog_type, materialized.rows, fresh.current);if (this.scopeId() !== fresh.scope_id) throw new AdportError('PENDING_MISMATCH', 'Media scope changed before batch submission.');\n const items = materialized.rows.map(row => ({ [itemIdField[fresh.catalog.catalog_type]]: row.source_id, operation: row.operation, ...(row.attributes !== undefined ? { attributes: row.attributes } : {}), ...(row.clear_fields?.length ? { update_mask: [...new Set([...Object.keys(row.attributes!), ...row.clear_fields])] } : {}), ...(row.last_updated_time !== undefined ? { last_updated_time: row.last_updated_time } : {}) }));\n const data = await this.client.mutate('catalogs/items/batch', 'POST', { catalog_id: selection.catalog_id, catalog_type: fresh.catalog.catalog_type, country: selection.country, language: selection.language, items }, nativeBatch, this.params(op.accountId));id = data.batch_id;\n if (!id || !data.status || data.catalog_type !== fresh.catalog.catalog_type || data.created_time === null) throw failure(undefined, id ? [id] : []);\n const batch_receipt = this.client.catalogBatchReceipt({ ...selection, version: 'pinterest_items_v1', scope_id: fresh.scope_id, catalog_type: fresh.catalog.catalog_type, owner_context_hash: fresh.owner, batch_id: id, expires_at: Math.floor(Date.now() / 1000) + 30 * 86400, manifest, ...(materialized.expires ? { media_expires_at: materialized.expires } : {}) }), results = this.batchRows(data, manifest);\n if (data.status === 'FAILED' || results.every(row => row.status === 'FAILURE')) throw failure(undefined, [id], { batch_receipt, item_results: results, native_status: data.status });\n receipt = { status: 'ACCEPTED_FOR_PROCESSING', processed: false, native_status: data.status, batch_id: id, 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 } };return [id];\n } catch (error) { const details = error instanceof AdportError ? object(error.details) : {};throw failure(error, id ? [id] : Array.isArray(details.resource_ids) ? details.resource_ids as string[] : [], details.batch_receipt ? { batch_receipt: details.batch_receipt, item_results: details.item_results, native_status: details.native_status } : {}); }\n }, resultDetails: () => receipt, resultWarnings: () => notes };\n }\n}\n","// Native attribute facts: Pinterest OpenAPI 5.28.0, 51aca009f10a90283ccdf3956d509fc995ebac23.\n// Strict known fields; native defaults are not inserted into mutation payloads.\nimport { z } from 'zod';\nexport const itemAttributeSchemas = {\n retailCreate: z.object({\"ad_image_0_link\": z.string().max(2000).nullable().optional(), \"ad_image_0_tag\": z.string().max(511).nullable().optional(), \"ad_image_10_link\": z.string().max(2000).nullable().optional(), \"ad_image_10_tag\": z.string().max(511).nullable().optional(), \"ad_image_11_link\": z.string().max(2000).nullable().optional(), \"ad_image_11_tag\": z.string().max(511).nullable().optional(), \"ad_image_12_link\": z.string().max(2000).nullable().optional(), \"ad_image_12_tag\": z.string().max(511).nullable().optional(), \"ad_image_13_link\": z.string().max(2000).nullable().optional(), \"ad_image_13_tag\": z.string().max(511).nullable().optional(), \"ad_image_14_link\": z.string().max(2000).nullable().optional(), \"ad_image_14_tag\": z.string().max(511).nullable().optional(), \"ad_image_15_link\": z.string().max(2000).nullable().optional(), \"ad_image_15_tag\": z.string().max(511).nullable().optional(), \"ad_image_16_link\": z.string().max(2000).nullable().optional(), \"ad_image_16_tag\": z.string().max(511).nullable().optional(), \"ad_image_17_link\": z.string().max(2000).nullable().optional(), \"ad_image_17_tag\": z.string().max(511).nullable().optional(), \"ad_image_18_link\": z.string().max(2000).nullable().optional(), \"ad_image_18_tag\": z.string().max(511).nullable().optional(), \"ad_image_19_link\": z.string().max(2000).nullable().optional(), \"ad_image_19_tag\": z.string().max(511).nullable().optional(), \"ad_image_1_link\": z.string().max(2000).nullable().optional(), \"ad_image_1_tag\": z.string().max(511).nullable().optional(), \"ad_image_2_link\": z.string().max(2000).nullable().optional(), \"ad_image_2_tag\": z.string().max(511).nullable().optional(), \"ad_image_3_link\": z.string().max(2000).nullable().optional(), \"ad_image_3_tag\": z.string().max(511).nullable().optional(), \"ad_image_4_link\": z.string().max(2000).nullable().optional(), \"ad_image_4_tag\": z.string().max(511).nullable().optional(), \"ad_image_5_link\": z.string().max(2000).nullable().optional(), \"ad_image_5_tag\": z.string().max(511).nullable().optional(), \"ad_image_6_link\": z.string().max(2000).nullable().optional(), \"ad_image_6_tag\": z.string().max(511).nullable().optional(), \"ad_image_7_link\": z.string().max(2000).nullable().optional(), \"ad_image_7_tag\": z.string().max(511).nullable().optional(), \"ad_image_8_link\": z.string().max(2000).nullable().optional(), \"ad_image_8_tag\": z.string().max(511).nullable().optional(), \"ad_image_9_link\": z.string().max(2000).nullable().optional(), \"ad_image_9_tag\": z.string().max(511).nullable().optional(), \"ad_link\": z.string().max(65536).nullable().optional(), \"ad_video_0_link\": z.string().max(2000).nullable().optional(), \"ad_video_0_tag\": z.string().max(511).nullable().optional(), \"ad_video_1_link\": z.string().max(2000).nullable().optional(), \"ad_video_1_tag\": z.string().max(511).nullable().optional(), \"ad_video_2_link\": z.string().max(2000).nullable().optional(), \"ad_video_2_tag\": z.string().max(511).nullable().optional(), \"additional_image_link\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"adult\": z.boolean().nullable().optional(), \"age_group\": z.string().max(65536).nullable().optional(), \"ai_disclosures\": z.array(z.object({\"disclosure\": z.array(z.enum([\"ai_modified\",\"synthetic_performer\"])).min(1).max(1000), \"url\": z.string().max(2000)}).strict()).max(1000).optional(), \"android_deep_link\": z.string().max(65536).optional(), \"availability\": z.string().max(65536).optional(), \"average_review_rating\": z.number().nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"checkout_enabled\": z.boolean().nullable().optional(), \"color\": z.string().max(65536).nullable().optional(), \"condition\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(511).nullable().optional(), \"custom_label_1\": z.string().max(511).nullable().optional(), \"custom_label_2\": z.string().max(511).nullable().optional(), \"custom_label_3\": z.string().max(511).nullable().optional(), \"custom_label_4\": z.string().max(511).nullable().optional(), \"custom_number_0\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_1\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_2\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_3\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_4\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"description\": z.string().max(65536).optional(), \"free_shipping_label\": z.boolean().nullable().optional(), \"free_shipping_limit\": z.string().max(65536).nullable().optional(), \"gender\": z.string().max(65536).nullable().optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"gtin\": z.union([z.string().max(65536).nullable(), z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), \"id\": z.string().max(65536).optional(), \"image_link\": z.union([z.string().max(65536), z.array(z.string().max(65536)).min(1).max(1)]).optional(), \"installment_price\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).optional(), \"item_group_id\": z.string().max(65536).nullable().optional(), \"last_updated_time\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"link\": z.string().max(65536).optional(), \"material\": z.string().max(65536).nullable().optional(), \"min_ad_price\": z.string().max(65536).nullable().optional(), \"mobile_link\": z.string().max(65536).nullable().optional(), \"mpn\": z.string().max(65536).nullable().optional(), \"number_of_ratings\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"number_of_reviews\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"pattern\": z.string().max(65536).nullable().optional(), \"price\": z.string().max(65536).optional(), \"product_type\": z.string().max(65536).nullable().optional(), \"promotion_id\": z.string().max(65536).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional(), \"sale_price_effective_date\": z.string().max(65536).nullable().optional(), \"save_pin_disabled\": z.boolean().optional(), \"shipping\": z.string().max(65536).nullable().optional(), \"shipping_height\": z.string().max(65536).nullable().optional(), \"shipping_weight\": z.string().max(65536).nullable().optional(), \"shipping_width\": z.string().max(65536).nullable().optional(), \"size\": z.string().max(65536).nullable().optional(), \"size_system\": z.string().max(65536).nullable().optional(), \"size_type\": z.string().max(65536).nullable().optional(), \"tax\": z.string().max(65536).nullable().optional(), \"title\": z.string().max(65536).optional(), \"unit_pricing_base_measure\": z.string().max(65536).nullable().optional(), \"unit_pricing_measure\": z.string().max(65536).nullable().optional(), \"variant_names\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"variant_values\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"video_link\": z.string().max(65536).nullable().optional()}).strict(),\n retailUpdate: z.object({\"ad_image_0_link\": z.string().max(2000).nullable().optional(), \"ad_image_0_tag\": z.string().max(511).nullable().optional(), \"ad_image_10_link\": z.string().max(2000).nullable().optional(), \"ad_image_10_tag\": z.string().max(511).nullable().optional(), \"ad_image_11_link\": z.string().max(2000).nullable().optional(), \"ad_image_11_tag\": z.string().max(511).nullable().optional(), \"ad_image_12_link\": z.string().max(2000).nullable().optional(), \"ad_image_12_tag\": z.string().max(511).nullable().optional(), \"ad_image_13_link\": z.string().max(2000).nullable().optional(), \"ad_image_13_tag\": z.string().max(511).nullable().optional(), \"ad_image_14_link\": z.string().max(2000).nullable().optional(), \"ad_image_14_tag\": z.string().max(511).nullable().optional(), \"ad_image_15_link\": z.string().max(2000).nullable().optional(), \"ad_image_15_tag\": z.string().max(511).nullable().optional(), \"ad_image_16_link\": z.string().max(2000).nullable().optional(), \"ad_image_16_tag\": z.string().max(511).nullable().optional(), \"ad_image_17_link\": z.string().max(2000).nullable().optional(), \"ad_image_17_tag\": z.string().max(511).nullable().optional(), \"ad_image_18_link\": z.string().max(2000).nullable().optional(), \"ad_image_18_tag\": z.string().max(511).nullable().optional(), \"ad_image_19_link\": z.string().max(2000).nullable().optional(), \"ad_image_19_tag\": z.string().max(511).nullable().optional(), \"ad_image_1_link\": z.string().max(2000).nullable().optional(), \"ad_image_1_tag\": z.string().max(511).nullable().optional(), \"ad_image_2_link\": z.string().max(2000).nullable().optional(), \"ad_image_2_tag\": z.string().max(511).nullable().optional(), \"ad_image_3_link\": z.string().max(2000).nullable().optional(), \"ad_image_3_tag\": z.string().max(511).nullable().optional(), \"ad_image_4_link\": z.string().max(2000).nullable().optional(), \"ad_image_4_tag\": z.string().max(511).nullable().optional(), \"ad_image_5_link\": z.string().max(2000).nullable().optional(), \"ad_image_5_tag\": z.string().max(511).nullable().optional(), \"ad_image_6_link\": z.string().max(2000).nullable().optional(), \"ad_image_6_tag\": z.string().max(511).nullable().optional(), \"ad_image_7_link\": z.string().max(2000).nullable().optional(), \"ad_image_7_tag\": z.string().max(511).nullable().optional(), \"ad_image_8_link\": z.string().max(2000).nullable().optional(), \"ad_image_8_tag\": z.string().max(511).nullable().optional(), \"ad_image_9_link\": z.string().max(2000).nullable().optional(), \"ad_image_9_tag\": z.string().max(511).nullable().optional(), \"ad_link\": z.string().max(65536).nullable().optional(), \"ad_video_0_link\": z.string().max(2000).nullable().optional(), \"ad_video_0_tag\": z.string().max(511).nullable().optional(), \"ad_video_1_link\": z.string().max(2000).nullable().optional(), \"ad_video_1_tag\": z.string().max(511).nullable().optional(), \"ad_video_2_link\": z.string().max(2000).nullable().optional(), \"ad_video_2_tag\": z.string().max(511).nullable().optional(), \"adult\": z.boolean().nullable().optional(), \"age_group\": z.string().max(65536).nullable().optional(), \"android_deep_link\": z.string().max(65536).optional(), \"availability\": z.string().max(65536).optional(), \"average_review_rating\": z.number().nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"checkout_enabled\": z.boolean().nullable().optional(), \"color\": z.string().max(65536).nullable().optional(), \"condition\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(511).nullable().optional(), \"custom_label_1\": z.string().max(511).nullable().optional(), \"custom_label_2\": z.string().max(511).nullable().optional(), \"custom_label_3\": z.string().max(511).nullable().optional(), \"custom_label_4\": z.string().max(511).nullable().optional(), \"custom_number_0\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_1\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_2\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_3\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_4\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"description\": z.string().max(65536).optional(), \"free_shipping_label\": z.boolean().nullable().optional(), \"free_shipping_limit\": z.string().max(65536).nullable().optional(), \"gender\": z.string().max(65536).nullable().optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"gtin\": z.union([z.string().max(65536).nullable(), z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), \"id\": z.string().max(65536).optional(), \"installment_price\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).optional(), \"item_group_id\": z.string().max(65536).nullable().optional(), \"last_updated_time\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"link\": z.string().max(65536).optional(), \"material\": z.string().max(65536).nullable().optional(), \"min_ad_price\": z.string().max(65536).nullable().optional(), \"mobile_link\": z.string().max(65536).nullable().optional(), \"mpn\": z.string().max(65536).nullable().optional(), \"number_of_ratings\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"number_of_reviews\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"pattern\": z.string().max(65536).nullable().optional(), \"price\": z.string().max(65536).optional(), \"product_type\": z.string().max(65536).nullable().optional(), \"promotion_id\": z.string().max(65536).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional(), \"sale_price_effective_date\": z.string().max(65536).nullable().optional(), \"shipping\": z.string().max(65536).nullable().optional(), \"shipping_height\": z.string().max(65536).nullable().optional(), \"shipping_weight\": z.string().max(65536).nullable().optional(), \"shipping_width\": z.string().max(65536).nullable().optional(), \"size\": z.string().max(65536).nullable().optional(), \"size_system\": z.string().max(65536).nullable().optional(), \"size_type\": z.string().max(65536).nullable().optional(), \"tax\": z.string().max(65536).nullable().optional(), \"title\": z.string().max(65536).optional(), \"unit_pricing_base_measure\": z.string().max(65536).nullable().optional(), \"unit_pricing_measure\": z.string().max(65536).nullable().optional(), \"variant_names\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"variant_values\": z.array(z.string().max(65536)).max(1000).nullable().optional()}).strict(),\n retailRead: z.object({\"ad_image_0_link\": z.string().max(2000).nullable().optional(), \"ad_image_0_tag\": z.string().max(511).nullable().optional(), \"ad_image_10_link\": z.string().max(2000).nullable().optional(), \"ad_image_10_tag\": z.string().max(511).nullable().optional(), \"ad_image_11_link\": z.string().max(2000).nullable().optional(), \"ad_image_11_tag\": z.string().max(511).nullable().optional(), \"ad_image_12_link\": z.string().max(2000).nullable().optional(), \"ad_image_12_tag\": z.string().max(511).nullable().optional(), \"ad_image_13_link\": z.string().max(2000).nullable().optional(), \"ad_image_13_tag\": z.string().max(511).nullable().optional(), \"ad_image_14_link\": z.string().max(2000).nullable().optional(), \"ad_image_14_tag\": z.string().max(511).nullable().optional(), \"ad_image_15_link\": z.string().max(2000).nullable().optional(), \"ad_image_15_tag\": z.string().max(511).nullable().optional(), \"ad_image_16_link\": z.string().max(2000).nullable().optional(), \"ad_image_16_tag\": z.string().max(511).nullable().optional(), \"ad_image_17_link\": z.string().max(2000).nullable().optional(), \"ad_image_17_tag\": z.string().max(511).nullable().optional(), \"ad_image_18_link\": z.string().max(2000).nullable().optional(), \"ad_image_18_tag\": z.string().max(511).nullable().optional(), \"ad_image_19_link\": z.string().max(2000).nullable().optional(), \"ad_image_19_tag\": z.string().max(511).nullable().optional(), \"ad_image_1_link\": z.string().max(2000).nullable().optional(), \"ad_image_1_tag\": z.string().max(511).nullable().optional(), \"ad_image_2_link\": z.string().max(2000).nullable().optional(), \"ad_image_2_tag\": z.string().max(511).nullable().optional(), \"ad_image_3_link\": z.string().max(2000).nullable().optional(), \"ad_image_3_tag\": z.string().max(511).nullable().optional(), \"ad_image_4_link\": z.string().max(2000).nullable().optional(), \"ad_image_4_tag\": z.string().max(511).nullable().optional(), \"ad_image_5_link\": z.string().max(2000).nullable().optional(), \"ad_image_5_tag\": z.string().max(511).nullable().optional(), \"ad_image_6_link\": z.string().max(2000).nullable().optional(), \"ad_image_6_tag\": z.string().max(511).nullable().optional(), \"ad_image_7_link\": z.string().max(2000).nullable().optional(), \"ad_image_7_tag\": z.string().max(511).nullable().optional(), \"ad_image_8_link\": z.string().max(2000).nullable().optional(), \"ad_image_8_tag\": z.string().max(511).nullable().optional(), \"ad_image_9_link\": z.string().max(2000).nullable().optional(), \"ad_image_9_tag\": z.string().max(511).nullable().optional(), \"ad_link\": z.string().max(65536).nullable().optional(), \"ad_video_0_link\": z.string().max(2000).nullable().optional(), \"ad_video_0_tag\": z.string().max(511).nullable().optional(), \"ad_video_1_link\": z.string().max(2000).nullable().optional(), \"ad_video_1_tag\": z.string().max(511).nullable().optional(), \"ad_video_2_link\": z.string().max(2000).nullable().optional(), \"ad_video_2_tag\": z.string().max(511).nullable().optional(), \"adult\": z.boolean().nullable().optional(), \"age_group\": z.string().max(65536).nullable().optional(), \"android_deep_link\": z.string().max(65536).optional(), \"availability\": z.string().max(65536).optional(), \"average_review_rating\": z.number().nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"checkout_enabled\": z.boolean().nullable().optional(), \"color\": z.string().max(65536).nullable().optional(), \"condition\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(511).nullable().optional(), \"custom_label_1\": z.string().max(511).nullable().optional(), \"custom_label_2\": z.string().max(511).nullable().optional(), \"custom_label_3\": z.string().max(511).nullable().optional(), \"custom_label_4\": z.string().max(511).nullable().optional(), \"custom_number_0\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_1\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_2\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_3\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_4\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"description\": z.string().max(65536).optional(), \"free_shipping_label\": z.boolean().nullable().optional(), \"free_shipping_limit\": z.string().max(65536).nullable().optional(), \"gender\": z.string().max(65536).nullable().optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"gtin\": z.union([z.string().max(65536).nullable(), z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), \"id\": z.string().max(65536).optional(), \"installment_price\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).optional(), \"item_group_id\": z.string().max(65536).nullable().optional(), \"last_updated_time\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"link\": z.string().max(65536).optional(), \"material\": z.string().max(65536).nullable().optional(), \"min_ad_price\": z.string().max(65536).nullable().optional(), \"mobile_link\": z.string().max(65536).nullable().optional(), \"mpn\": z.string().max(65536).nullable().optional(), \"number_of_ratings\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"number_of_reviews\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"pattern\": z.string().max(65536).nullable().optional(), \"price\": z.string().max(65536).optional(), \"product_type\": z.string().max(65536).nullable().optional(), \"promotion_id\": z.string().max(65536).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional(), \"sale_price_effective_date\": z.string().max(65536).nullable().optional(), \"shipping\": z.string().max(65536).nullable().optional(), \"shipping_height\": z.string().max(65536).nullable().optional(), \"shipping_weight\": z.string().max(65536).nullable().optional(), \"shipping_width\": z.string().max(65536).nullable().optional(), \"size\": z.string().max(65536).nullable().optional(), \"size_system\": z.string().max(65536).nullable().optional(), \"size_type\": z.string().max(65536).nullable().optional(), \"tax\": z.string().max(65536).nullable().optional(), \"title\": z.string().max(65536).optional(), \"unit_pricing_base_measure\": z.string().max(65536).nullable().optional(), \"unit_pricing_measure\": z.string().max(65536).nullable().optional(), \"variant_names\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"variant_values\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"additional_image_link\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"ai_disclosures\": z.array(z.object({\"disclosure\": z.array(z.enum([\"ai_modified\",\"synthetic_performer\"])).min(1).max(1000), \"url\": z.string().max(2000)}).strict()).max(1000).optional(), \"image_link\": z.array(z.string().max(65536)).min(1).max(1000).optional(), \"video_link\": z.string().max(65536).nullable().optional()}).strict(),\n hotelCreate: z.object({\"address\": z.object({\"addr1\": z.string().max(65536).optional(), \"city\": z.string().max(65536).optional(), \"country\": z.string().max(65536).optional(), \"postal_code\": z.string().max(65536).optional(), \"region\": z.string().max(65536).optional()}).strict().optional(), \"base_price\": z.string().max(65536).nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"category\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(65536).nullable().optional(), \"custom_label_1\": z.string().max(65536).nullable().optional(), \"custom_label_2\": z.string().max(65536).nullable().optional(), \"custom_label_3\": z.string().max(65536).nullable().optional(), \"custom_label_4\": z.string().max(65536).nullable().optional(), \"description\": z.string().max(65536).nullable().optional(), \"guest_ratings\": z.object({\"max_score\": z.number().nullable().optional(), \"number_of_reviewers\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"rating_system\": z.string().max(65536).nullable().optional(), \"score\": z.number().nullable().optional()}).strict().optional(), \"latitude\": z.number().optional(), \"link\": z.string().max(65536).nullable().optional(), \"longitude\": z.number().nullable().optional(), \"name\": z.string().max(65536).nullable().optional(), \"neighborhood\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional(), \"additional_image_link\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"ai_disclosures\": z.array(z.object({\"disclosure\": z.array(z.enum([\"ai_modified\",\"synthetic_performer\"])).min(1).max(1000), \"url\": z.string().max(2000)}).strict()).max(1000).optional(), \"main_image\": z.object({\"link\": z.string().max(65536).optional(), \"tag\": z.array(z.string().max(65536)).max(1000).nullable().optional()}).strict().optional()}).strict(),\n hotelUpdate: z.object({\"address\": z.object({\"addr1\": z.string().max(65536).optional(), \"city\": z.string().max(65536).optional(), \"country\": z.string().max(65536).optional(), \"postal_code\": z.string().max(65536).optional(), \"region\": z.string().max(65536).optional()}).strict().optional(), \"base_price\": z.string().max(65536).nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"category\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(65536).nullable().optional(), \"custom_label_1\": z.string().max(65536).nullable().optional(), \"custom_label_2\": z.string().max(65536).nullable().optional(), \"custom_label_3\": z.string().max(65536).nullable().optional(), \"custom_label_4\": z.string().max(65536).nullable().optional(), \"description\": z.string().max(65536).nullable().optional(), \"guest_ratings\": z.object({\"max_score\": z.number().nullable().optional(), \"number_of_reviewers\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"rating_system\": z.string().max(65536).nullable().optional(), \"score\": z.number().nullable().optional()}).strict().optional(), \"latitude\": z.number().optional(), \"link\": z.string().max(65536).nullable().optional(), \"longitude\": z.number().nullable().optional(), \"name\": z.string().max(65536).nullable().optional(), \"neighborhood\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional()}).strict(),\n creativeCreate: z.object({\"android_deep_link\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(65536).nullable().optional(), \"custom_label_1\": z.string().max(65536).nullable().optional(), \"custom_label_2\": z.string().max(65536).nullable().optional(), \"custom_label_3\": z.string().max(65536).nullable().optional(), \"custom_label_4\": z.string().max(65536).nullable().optional(), \"description\": z.string().max(65536).optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).nullable().optional(), \"link\": z.string().max(65536).optional(), \"title\": z.string().max(65536).optional(), \"visibility\": z.string().max(65536).nullable().optional(), \"ai_disclosures\": z.array(z.object({\"disclosure\": z.array(z.enum([\"ai_modified\",\"synthetic_performer\"])).min(1).max(1000), \"url\": z.string().max(2000)}).strict()).max(1000).optional(), \"image_link\": z.string().max(65536).optional(), \"video_link\": z.string().max(65536).optional()}).strict(),\n creativeUpdate: z.object({\"android_deep_link\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(65536).nullable().optional(), \"custom_label_1\": z.string().max(65536).nullable().optional(), \"custom_label_2\": z.string().max(65536).nullable().optional(), \"custom_label_3\": z.string().max(65536).nullable().optional(), \"custom_label_4\": z.string().max(65536).nullable().optional(), \"description\": z.string().max(65536).optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).nullable().optional(), \"link\": z.string().max(65536).optional(), \"title\": z.string().max(65536).optional(), \"visibility\": z.string().max(65536).nullable().optional()}).strict(),\n} as const;\nexport const itemUpdateMask = z.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\"]);\nexport const 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\"] as const;\n","import { z } from 'zod';\nimport { pinterestId } from './schemas.js';\nimport { groupId, groupHash, catalogType } from './product-group-schemas.js';\nimport { filterEnums } from './product-group-filter-spec.js';\nimport { itemAttributeSchemas, itemLanguages, itemUpdateMask } from './catalog-item-attributes.js';\n\nexport const itemOperation = z.enum(['CREATE', 'UPDATE', 'UPSERT', 'DELETE']);\nexport const sourceId = z.string().min(1).max(1024).regex(/^[^\\x00-\\x1f\\x7f]+$/);\nexport const itemObject = z.record(z.string(), z.json());\nexport const itemSelection = z.object({ account_id: pinterestId, catalog_id: groupId, country: z.enum(filterEnums.Country), language: z.enum(itemLanguages) }).strict();\nexport const itemRead = itemSelection.extend({ item_ids: z.array(sourceId).min(1).max(1000).refine(ids => new Set(ids).size === ids.length), limit: z.number().int().min(1).max(100).default(24), cursor: z.string().min(1).max(8192).optional() });\nconst itemMutationBase = z.object({ source_id: sourceId, operation: itemOperation, attributes: itemObject.optional(), clear_fields: z.array(itemUpdateMask).min(1).max(100).refine(values => new Set(values).size === values.length).optional(), last_updated_time: z.number().int().nonnegative().safe().optional() }).strict();\nexport const itemMutation = itemMutationBase.superRefine((value, ctx) => {\n if (value.operation === 'DELETE' ? value.attributes !== undefined || value.clear_fields !== undefined : value.attributes === undefined || value.last_updated_time !== undefined || value.operation !== 'UPDATE' && value.clear_fields !== undefined) ctx.addIssue({ code: 'custom', message: 'CREATE/UPSERT/UPDATE require attributes; only UPDATE supports clear_fields; only DELETE accepts last_updated_time' });\n 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' });\n if (value.clear_fields?.some(key => Object.hasOwn(value.attributes ?? {}, key))) ctx.addIssue({ code: 'custom', message: 'A field cannot be both supplied and cleared' });\n});\nexport const itemMedia = z.object({ item_index: z.number().int().min(0).max(999), field: z.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: z.number().int().min(0).max(999).optional(), media_id: z.string().uuid(), expected_sha256: groupHash }).strict();\nexport const itemRequest = z.object({ operations: z.array(itemMutation).min(1).max(1000).refine(rows => new Set(rows.map(row => row.source_id)).size === rows.length, 'Each item may appear only once in a batch'), media_assets: z.array(itemMedia).max(1000).default([]), acknowledge_replacement: z.literal(true).optional(), acknowledge_unconfirmed_existing: z.literal(true).optional() }).strict();\nexport const itemContext = itemSelection.extend(itemRequest.shape);\nconst write = itemSelection.omit({ account_id: true }).extend({ expected_context_hash: groupHash, confirm_publication: z.literal(true), acknowledge_catalog_effects: z.literal(true), confirm_permanent_deletion: z.literal(true).optional() });\nexport const itemBatchApply = write.extend(itemRequest.shape).superRefine((value, ctx) => {\n 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' });\n 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' });\n});\nexport const itemNamedApply = (operation: z.infer<typeof itemOperation>) => write.extend({\n items: z.array(itemMutationBase.omit({ operation: true })).min(1).max(1000), media_assets: itemRequest.shape.media_assets,\n acknowledge_replacement: z.literal(true).optional(), acknowledge_unconfirmed_existing: z.literal(true).optional(),\n}).superRefine((value, ctx) => {\n const result = itemBatchApply.safeParse({ ...Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'items')), operations: value.items.map(row => ({ ...row, operation })) });\n if (!result.success) for (const issue of result.error.issues) ctx.addIssue({ code: 'custom', path: issue.path, message: issue.message });\n});\nexport const itemCopy = itemSelection.omit({ account_id: true }).extend({ source_id: sourceId, expected_snapshot_hash: groupHash, title: z.string().max(65_536).optional(), description: z.string().max(65_536).optional(), confirm_publication: z.literal(true), acknowledge_catalog_effects: z.literal(true) }).strict().refine(value => value.title !== undefined || value.description !== undefined, 'Supply copy to change');\nexport const batchReference = z.object({ account_id: pinterestId, batch_receipt: z.string().min(100).max(2_000_000) }).strict();\nexport const itemSchemaQuery = z.object({ catalog_type: catalogType, operation: itemOperation }).strict();\nexport function attributeSchema(type: z.infer<typeof catalogType>, operation: z.infer<typeof itemOperation>) {\n if (operation === 'DELETE') return z.object({}).strict();\n return type === 'RETAIL' ? operation === 'UPDATE' ? itemAttributeSchemas.retailUpdate : itemAttributeSchemas.retailCreate : type === 'HOTEL' ? operation === 'UPDATE' ? itemAttributeSchemas.hotelUpdate : itemAttributeSchemas.hotelCreate : operation === 'UPDATE' ? itemAttributeSchemas.creativeUpdate : itemAttributeSchemas.creativeCreate;\n}\nexport const itemIdField = { RETAIL: 'item_id', HOTEL: 'hotel_id', CREATIVE_ASSETS: 'creative_assets_id' } as const;\nexport const itemIdsField = { RETAIL: 'item_ids', HOTEL: 'hotel_ids', CREATIVE_ASSETS: 'creative_assets_ids' } as const;\nexport const itemWriteOperations = { pinterest_create_catalog_items: 'CREATE', pinterest_update_catalog_items: 'UPDATE', pinterest_upsert_catalog_items: 'UPSERT', pinterest_delete_catalog_items: 'DELETE' } as const;\n","import { z } from 'zod';\nimport { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestCatalogService } from './catalogs.js';\nimport { groupHash } from './product-group-schemas.js';\nimport { localBound, localCanonical, localFailure, localHash, localObject, localScope, localStoreContext, localStoreCreate, localStoreDelete, localStoreList, localStoreUpdate, nativeLocalStore, publicLocal, type LocalRow, type LocalScope } from './local-catalog-schemas.js';\n\ntype Store = z.infer<typeof nativeLocalStore>;\ntype Action = z.infer<typeof localStoreContext>['action'];\ntype Plan = Omit<WritePreview,'serverValidated'> & { execute(): Promise<string[]>;resultDetails?():unknown;resultWarnings?():string[] };\nconst storeValue = (value: Store) => Object.fromEntries(Object.entries(value).filter(([key]) => !['created_at','updated_at'].includes(key)));\nconst 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.'];\n\nexport class PinterestLocalStores {\n constructor(private readonly client:PinterestAdsClient,private readonly catalogs:PinterestCatalogService) {}\n supports(tool:string) { return ['pinterest_create_local_stores','pinterest_update_local_stores','pinterest_delete_local_stores'].includes(tool); }\n params(account:string,extra:Record<string,string> = {}) { return new URLSearchParams({ ad_account_id:account,...extra }); }\n path(catalog:string) { return `catalogs/${catalog}/local_stores`; }\n async selected(value:LocalScope) { const selection = localScope.parse(value), result = await this.catalogs.getCatalog(selection.account_id,selection.catalog_id);if (result.catalog.catalog_type !== 'RETAIL') throw new AdportError('INVALID_INPUT','Local stores/inventory require a RETAIL catalog.');return { selection,catalog:result.catalog,owner:result.context_hash }; }\n private async page(selection:LocalScope,ids:string[]|undefined,size:number,bookmark?:string) {\n const data = await this.client.get(this.path(selection.catalog_id),z.object({ items:z.array(nativeLocalStore).max(250),bookmark:z.string().max(8192).nullable().optional() }),this.params(selection.account_id,{ page_size:String(size),...(ids?{ids:ids.join(',')}:{}),...(bookmark?{bookmark}:{}) })).catch(error=>{throw localFailure(error);});\n 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 || ids && data.items.some(row=>!ids.includes(row.id))) throw localFailure();return data;\n }\n async list(value:unknown) {\n const input = localStoreList.parse(value),selection = localScope.parse({account_id:input.account_id,catalog_id:input.catalog_id}),parent = await this.selected(selection),key = localHash({selection,ids:input.store_ids,size:input.page_size});let bookmark:string|undefined;\n if (input.bookmark) { let cursor;try { cursor = z.object({ selection:groupHash,native:z.string().min(1).max(8192) }).strict().parse(JSON.parse(Buffer.from(input.bookmark,'base64url').toString('utf8'))); } catch {throw new AdportError('INVALID_INPUT','Invalid local-store cursor.');}if (cursor.selection!==key) throw new AdportError('PENDING_MISMATCH','Local-store selection changed; restart the first page.');bookmark=cursor.native; }\n const page = await this.page(selection,input.store_ids,input.page_size,bookmark),complete = page.bookmark===null?true:page.bookmark===undefined?null:false;\n return { records:page.items.map(row=>({...row,...publicLocal(row) as LocalRow,snapshot_hash:localHash({selection,owner:parent.owner,store:storeValue(row)})})),complete,truncated:complete!==true,...(page.bookmark?{next_cursor:Buffer.from(JSON.stringify({selection:key,native:page.bookmark})).toString('base64url')} : {}),notes:['Only stores in the selected advertiser-owned RETAIL catalog. Missing native bookmarks leave completeness unknown.'] };\n }\n private async gather(selection:LocalScope,ids?:string[]) {\n const rows:Store[] = [],seen=new Set<string>();let bookmark:string|undefined;\n for (let page=0;page<40;page++) { const data = await this.page(selection,ids,250,bookmark);rows.push(...data.items);if(rows.length>10_000 || new Set(rows.map(row=>row.id)).size!==rows.length || new Set(rows.map(row=>row.store_code)).size!==rows.length) throw localFailure();if(data.bookmark===null) return rows;if(!data.bookmark||seen.has(data.bookmark)) throw new AdportError('PROVIDER_ERROR','Complete store inventory is unavailable; no absence or unique-code proof is inferred.');seen.add(data.bookmark);bookmark=data.bookmark; }\n throw new AdportError('INVALID_INPUT','Store lookup exceeded10,000 rows; no mutation is permitted.');\n }\n async owned(selection:LocalScope,ids:string[]) { const unique=[...new Set(ids)],stores:Store[]=[];for(let offset=0;offset<unique.length;offset+=100) stores.push(...await this.gather(selection,unique.slice(offset,offset+100)));if(stores.length!==unique.length) throw new AdportError('INVALID_INPUT','Selected local store was not positively read in this catalog.');return stores.sort((a,b)=>a.id.localeCompare(b.id)); }\n async context(value:unknown) {\n const input=localStoreContext.parse(value),parent=await this.selected({account_id:input.account_id,catalog_id:input.catalog_id}),{selection}=parent,action=input.action;localBound(action);\n const inventory = action.kind==='create' || action.kind==='update' && action.stores.some(row=>row.store_code!==undefined) ? await this.gather(selection) : undefined,current=action.kind==='create'?[]:inventory?inventory.filter(row=>action.stores.some(item=>item.id===row.id)):await this.owned(selection,action.stores.map(row=>row.id));\n if(action.kind!=='create'&&current.length!==action.stores.length) throw new AdportError('INVALID_INPUT','A selected store is outside the current catalog.');\n if(action.kind==='create') {if(inventory!.length+action.stores.length>10_000) throw new AdportError('INVALID_INPUT','Catalog would exceed10,000 local stores.');if(action.stores.some(row=>inventory!.some(old=>old.store_code===row.store_code))) throw new AdportError('INVALID_INPUT','CREATE cannot overwrite an existing store code.');}\n if(action.kind==='update') {const desired=(inventory??current).map(row=>({id:row.id,code:action.stores.find(item=>item.id===row.id)?.store_code??row.store_code}));if(new Set(desired.map(row=>row.code)).size!==desired.length) throw new AdportError('INVALID_INPUT','Store code would collide with another store.');if(action.stores.some(row=>row.store_code!==undefined&&row.store_code!==current.find(old=>old.id===row.id)!.store_code)&&!action.acknowledge_store_code_change) throw new AdportError('INVALID_INPUT','Store-code changes require acknowledge_store_code_change.');const changed=action.stores.filter(row=>row.store_code!==undefined&&row.store_code!==current.find(old=>old.id===row.id)!.store_code);if(changed.some(row=>current.some(old=>old.id!==row.id&&old.store_code===row.store_code))) throw new AdportError('INVALID_INPUT','Store-code swaps require separate reviewed operations; transient native collisions are not assumed safe.');}\n 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 AdportError('PENDING_MISMATCH','Store name/code changed; read context again.');\n return {...parent,action,current,occupied_ids:inventory?.map(row=>row.id)??[],context_hash:localHash({selection,owner:parent.owner,catalog:{id:parent.catalog.id,name:parent.catalog.name,type:parent.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) as LocalRow,snapshot_hash:localHash({selection,owner:parent.owner,store:storeValue(row)})})),notes:storeNotes};\n }\n async publicContext(value:unknown) {const data=await this.context(value);return {context_hash:data.context_hash,records:data.records,action:data.action,notes:data.notes};}\n async plan(op:WriteOperation):Promise<Plan> {\n const create=op.tool==='pinterest_create_local_stores',remove=op.tool==='pinterest_delete_local_stores',kind=create?'create':remove?'remove':'update';if(op.provider!=='pinterest'||!this.supports(op.tool)||op.kind!==kind) throw new AdportError('INVALID_INPUT','Invalid local-store mutation kind.');\n const input=create?localStoreCreate.parse(op.payload):remove?localStoreDelete.parse(op.payload):localStoreUpdate.parse(op.payload),selection={account_id:op.accountId,catalog_id:input.catalog_id},action= {kind:create?'create':remove?'delete':'update',stores:input.stores,...('acknowledge_store_code_change'in input?{acknowledge_store_code_change:input.acknowledge_store_code_change}:{})} as Action;\n const prepare=async()=>{const data=await this.context({...selection,action});if(data.context_hash!==input.expected_context_hash) throw new AdportError('PENDING_MISMATCH','Local store selection, owner or configuration changed; preview again.');return data;},before=await prepare();let details:LocalRow|undefined;\n const title=create?'Create local stores':remove?'Delete local stores permanently':'Update local stores';\n return {summary:`${title} · ${action.stores.length}`,changes:action.stores.map(row=>create?`CREATE ${'store_code'in row?row.store_code:''}`:`${remove?'DELETE':'UPDATE'} ${'id'in row?row.id:''}`),coercions:[],budgetDeltas:[],notes:storeNotes,review:{provider:'pinterest',accountId:op.accountId,kind:op.kind,title,subject:before.catalog.name,fields:action.stores.map(row=>({label:create?String('store_code'in row?row.store_code:''):String('id'in row?row.id:''),...(create?{}:{before:publicLocal(storeValue(before.current.find(old=>old.id===('id'in row?row.id:''))!))}),after:remove?'Remove local store':row})),notices:storeNotes},\n execute:async()=>{const fresh=await prepare(),known=new Set(fresh.current.map(row=>row.id));let records:LocalRow[]=[];try{\n const raw=await this.client.mutate(this.path(selection.catalog_id),create?'POST':remove?'DELETE':'PATCH',remove?undefined:input.stores,z.unknown(),this.params(op.accountId,remove?{ids:(input.stores as z.infer<typeof localStoreDelete>['stores']).map(row=>row.id).join(',')}:{}));\n if(remove){\n if(raw!==undefined){if(!Array.isArray(raw)||raw.length!==action.stores.length) throw localFailure();const seen=new Set<string>();for(const value of raw){const row=localObject(value),id=z.string().regex(/^\\d{1,30}$/).parse(row.id);if(!known.has(id)||seen.has(id)) throw localFailure();seen.add(id);const status=localObject(row.status);records.push({id,native_status:status.statusCode===204&&status.code===undefined&&status.message===undefined?'SUCCESS':'FAILURE'});}}\n const remaining=await this.gather(selection,[...known]);records=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===undefined?'HTTP204':records.find(value=>value.id===row.id)?.native_status??'UNCONFIRMED'}));if(records.some(row=>row.status!=='ABSENT_FROM_COMPLETE_FILTERED_LIST'||row.native_status==='FAILURE')) throw localFailure(undefined,[...known],{records});\n }else{\n if(!Array.isArray(raw)||raw.length!==action.stores.length) {if(Array.isArray(raw)) for(const value of raw){const id=localObject(localObject(value).data??value).id;if(typeof id==='string'&&/^\\d{1,30}$/.test(id))known.add(id);}throw localFailure();}\n const returned:Store[]=[],seen=new Set<string>();for(const value of raw){const row=localObject(localObject(value).data??value),id=typeof row.id==='string'&&/^\\d{1,30}$/.test(row.id)?row.id:undefined;if(id)known.add(id);if(row.exceptions!==undefined){const code=localObject(row.exceptions).code;records.push({id:id??'UNCONFIRMED',status:'FAILURE',native_error:true,...(typeof code==='number'&&Number.isSafeInteger(code)?{error_code:code}:{})});continue;}const store=nativeLocalStore.parse(row);if(create&&fresh.occupied_ids.includes(store.id)||seen.has(store.id)||returned.some(old=>old.store_code===store.store_code)||!create&&!fresh.current.some(old=>old.id===store.id)||create&&!(action.stores as z.infer<typeof localStoreCreate>['stores']).some(item=>item.store_code===store.store_code))throw localFailure();seen.add(store.id);returned.push(store);}\n const actual=returned.length?await this.owned(selection,returned.map(row=>row.id)):[];\n for(const store of actual){const expected=create?(action.stores as z.infer<typeof localStoreCreate>['stores']).find(row=>row.store_code===store.store_code):(action.stores as z.infer<typeof localStoreUpdate>['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)),preserved=!previous||Object.entries(storeValue(previous)).every(([key,value])=>expected&&Object.hasOwn(expected,key)||localCanonical(store[key])===localCanonical(value));records.push({id:store.id,name:store.name,store_code:store.store_code,status:matches&&preserved?'REQUESTED_CONFIGURATION_VERIFIED':'CONFIGURATION_UNCONFIRMED',omitted_fields_preserved:previous?preserved:undefined});}\n if(records.length!==action.stores.length||records.some(row=>row.status!=='REQUESTED_CONFIGURATION_VERIFIED'))throw localFailure(undefined,[...known],{records});\n }\n details={status:'COMPLETE',records,configuration_verified:true,publication_verified:false};return records.map(row=>String(row.id));\n }catch(error){const data=error instanceof AdportError?localObject(error.details):{};throw localFailure(error,[...known],{...(data.records?{records:data.records}:records.length?{records}:{} )});}},resultDetails:()=>publicLocal(details),resultWarnings:()=>storeNotes};\n }\n}\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\nimport { pinterestId } from './schemas.js';\nimport { groupHash, groupId } from './product-group-schemas.js';\nimport { filterEnums } from './product-group-filter-spec.js';\nimport { sourceId, itemOperation } from './catalog-item-schemas.js';\n\n// Pinterest-owned OpenAPI5.28.0 at51aca009, inspected2026-11-06. The guide\n// contains older route examples; current OpenAPI path/field shapes are used.\nexport type LocalRow = Record<string, unknown>;\nexport const localCanonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nexport const localHash = (value: unknown) => createHash('sha256').update(localCanonical(value)).digest('hex');\nexport const localObject = (value: unknown): LocalRow => value && typeof value === 'object' && !Array.isArray(value) ? value as LocalRow : {};\nexport const localScope = z.object({ account_id: pinterestId, catalog_id: groupId }).strict();\nexport type LocalScope = z.infer<typeof localScope>;\nexport const localFailure = (error?: unknown, ids: string[] = [], extra: LocalRow = {}) => { const detail = error instanceof AdportError ? localObject(error.details) : {};return new AdportError('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 } : {}), ...(ids.length ? { resource_ids: [...new Set(ids)] } : {}), ...extra }); };\nexport function localBound(value: unknown) { if (Buffer.byteLength(localCanonical(value)) > 2 * 1024 * 1024) throw new AdportError('INVALID_INPUT', 'Local catalog request exceeds2MiB; split the batch.'); }\nexport function publicLocal(value: unknown, key = ''): unknown {\n if (Array.isArray(value)) return value.map(item => publicLocal(item,key));\n if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([name,item]) => [name,publicLocal(item,name)]));\n if (typeof value === 'string' && /url|link/i.test(key)) { try { return { origin: new URL(value).origin, fingerprint: localHash(value) }; } catch { return { fingerprint: localHash(value) }; } }\n return value;\n}\nconst text = z.string().min(1).max(1024), address = z.string().max(4096);\nexport const localStoreDefinition = z.object({ store_code: sourceId, name: text, country: z.enum(filterEnums.Country), address_primary: address.optional(), address_secondary: address.optional(), city: address.optional(), region: address.optional(), postal_code: address.optional(), latitude: z.number().min(-90).max(90).optional(), longitude: z.number().min(-180).max(180).optional() }).strict();\nexport const localStoreChanges = localStoreDefinition.partial().extend({ id: groupId }).strict().refine(value => Object.keys(value).length > 1,'Supply a store setting');\nexport const nativeLocalStore = localStoreDefinition.extend({ id: groupId, created_at: z.string().min(1).max(100), updated_at: z.string().min(1).max(100) }).loose();\nexport const localStoreRemoval = z.object({ id: groupId, confirm_store_code: sourceId, confirm_name: text }).strict();\nconst unique = <T>(values: T[], key: (value: T) => string) => new Set(values.map(key)).size === values.length;\nconst createStores = z.array(localStoreDefinition).min(1).max(100).refine(rows => unique(rows,row => row.store_code),'Duplicate store code');\nconst updateStores = z.array(localStoreChanges).min(1).max(100).refine(rows => unique(rows,row => row.id),'Duplicate store ID');\nconst deleteStores = z.array(localStoreRemoval).min(1).max(100).refine(rows => unique(rows,row => row.id),'Duplicate store ID');\nexport const localStoreAction = z.discriminatedUnion('kind', [z.object({ kind: z.literal('create'), stores: createStores }).strict(), z.object({ kind: z.literal('update'), stores: updateStores, acknowledge_store_code_change: z.literal(true).optional() }).strict(), z.object({ kind: z.literal('delete'), stores: deleteStores }).strict()]);\nexport const localStoreContext = localScope.extend({ action: localStoreAction });\nconst storeWrite = localScope.omit({ account_id: true }).extend({ expected_context_hash: groupHash, acknowledge_catalog_effects: z.literal(true), confirm_publication: z.literal(true) });\nexport const localStoreCreate = storeWrite.extend({ stores: createStores });\nexport const localStoreUpdate = storeWrite.extend({ stores: updateStores, acknowledge_store_code_change: z.literal(true).optional() });\nexport const localStoreDelete = storeWrite.extend({ stores: deleteStores, confirm_permanent_deletion: z.literal(true) });\nexport const localStoreList = localScope.extend({ store_ids: z.array(groupId).min(1).max(100).refine(ids => new Set(ids).size === ids.length).optional(), page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).max(16_384).optional() });\nexport const inventoryPair = z.object({ item_id: sourceId, store_code: sourceId, store_id: groupId }).strict();\nexport const inventoryKey = (value: { item_id: string; store_code: string }) => localCanonical([value.item_id,value.store_code]);\nexport const inventoryAttributes = z.object({ price: z.string().min(1).max(1024), availability: z.enum(['in stock','out of stock','preorder']), sale_price: z.string().min(1).max(1024).optional(), ad_link: z.string().min(1).max(65_536).optional() }).strict();\nconst inventoryUpdate = inventoryAttributes.partial().refine(value => Object.keys(value).length > 0,'Supply changed attributes');\nexport const inventoryOperation = z.discriminatedUnion('operation', [\n inventoryPair.extend({ operation: z.literal('CREATE'), attributes: inventoryAttributes }), inventoryPair.extend({ operation: z.literal('UPSERT'), attributes: inventoryAttributes }), inventoryPair.extend({ operation: z.literal('UPDATE'), attributes: inventoryUpdate }), inventoryPair.extend({ operation: z.literal('DELETE') }),\n]);\nexport const inventoryRequest = z.object({ operations: z.array(inventoryOperation).min(1).max(1000).refine(rows => unique(rows,inventoryKey),'Duplicate item/store pair'), acknowledge_replacement: z.literal(true).optional(), acknowledge_unconfirmed_existing: z.literal(true).optional() }).strict();\nexport const inventoryContext = localScope.extend(inventoryRequest.shape);\nexport const inventoryList = localScope.extend({ item_filters: z.array(inventoryPair).min(1).max(1000).refine(rows => unique(rows,inventoryKey),'Duplicate item/store pair'), limit: z.number().int().min(1).max(100).default(24), cursor: z.string().min(1).max(8192).optional() });\nconst inventoryWrite = storeWrite.extend(inventoryRequest.shape).superRefine((value,ctx) => { if (value.operations.some(row => row.operation === 'UPSERT') && !value.acknowledge_replacement) ctx.addIssue({ code:'custom',message:'UPSERT requires full replacement acknowledgement' });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' }); });\nexport const inventoryBatch = inventoryWrite.safeExtend({ confirm_permanent_deletion: z.literal(true).optional() });\nexport const inventoryNamed = (operation: z.infer<typeof itemOperation>) => {\n 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});\n return storeWrite.extend({ items: z.array(item).min(1).max(1000), acknowledge_replacement: z.literal(true).optional(), acknowledge_unconfirmed_existing: z.literal(true).optional(), confirm_permanent_deletion: z.literal(true).optional() }).superRefine((value,ctx) => { const { items,...common } = value, result = inventoryBatch.safeParse({ ...common,operations:items.map(row => ({ ...row,operation })) });if (!result.success) for (const issue of result.error.issues) ctx.addIssue({ code:'custom',path:issue.path,message:issue.message }); });\n};\nexport const inventoryWriteTools = { pinterest_create_local_inventory:'CREATE',pinterest_update_local_inventory:'UPDATE',pinterest_upsert_local_inventory:'UPSERT',pinterest_delete_local_inventory:'DELETE' } as const;\nexport const inventoryBatchReference = z.object({ account_id:pinterestId,batch_receipt:z.string().min(100).max(2_000_000) }).strict();\n","import { z } from 'zod';\nimport { AdportError, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestLocalStores } from './local-stores.js';\nimport { groupHash } from './product-group-schemas.js';\nimport { itemOperation, sourceId } from './catalog-item-schemas.js';\nimport { inventoryAttributes, inventoryBatch, inventoryBatchReference, inventoryContext, inventoryKey, inventoryList, inventoryNamed, inventoryPair, inventoryRequest, inventoryWriteTools, localBound, localCanonical, localFailure, localHash, localObject, localScope, publicLocal, type LocalRow, type LocalScope } from './local-catalog-schemas.js';\n\ntype Pair=z.infer<typeof inventoryPair>;\ntype Request=z.infer<typeof inventoryRequest>;\ntype Current={pair:Pair;state:'PRESENT'|'NOT_RETURNED';attributes?:LocalRow;metadata?:LocalRow};\ntype Plan=Omit<WritePreview,'serverValidated'>&{execute():Promise<string[]>;resultDetails?():unknown;resultWarnings?():string[]};\nconst batchId=z.string().regex(/^[A-Za-z0-9_-]{1,100}$/),nativeBatch=z.object({batch_id:batchId,created_time:z.string().min(1).max(100),completed_time:z.string().max(100).optional(),status:z.enum(['PROCESSING','COMPLETED','FAILED']),operation_results:z.array(z.record(z.string(),z.json())).max(1000)});\nconst manifestRow=inventoryPair.extend({operation:itemOperation,desired_keys:z.array(z.enum(['price','sale_price','availability','ad_link'])).max(4),desired_hash:groupHash.optional(),preserved_hash:groupHash.optional()});\nconst receiptSchema=localScope.extend({version:z.literal('pinterest_local_inventory_v1'),scope_id:z.string().min(1).max(200),owner_context_hash:groupHash,batch_id:batchId,expires_at:z.number().int().safe(),manifest:z.array(manifestRow).min(1).max(1000)}).strict();\nconst notes=['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’s processing result, independent readback and final publication/eligibility are separate observations. Native conditional writes and automatic mutation replay are not available.'];\nconst readAttrs=(row:LocalRow)=>Object.fromEntries(Object.entries(row).filter(([key])=>!['item_id','store_metadata','created_at','last_updated_time'].includes(key)));\nconst preserved=(row:LocalRow,keys:string[])=>Object.fromEntries(Object.entries(row).filter(([key])=>!keys.includes(key)));\nconst diagnostics=(value:unknown)=>z.array(z.object({attribute:z.string().max(256),code:z.number().int().min(-2147483648).max(2147483647),message:z.string().max(100_000)})).max(10_000).parse(value??[]).map(({message,...row})=>({...row,message_present:!!message}));\n\nexport class PinterestLocalInventory {\n constructor(private readonly client:PinterestAdsClient,private readonly stores:PinterestLocalStores,private readonly media:MediaResolver) {}\n supports(tool:string){return tool==='pinterest_apply_local_inventory_batch'||Object.hasOwn(inventoryWriteTools,tool);}\n private scopeId(){const value=(this.media as {scopeId?:unknown}).scopeId;return typeof value==='string'&&value?value:'local';}\n private path(catalog:string){return `catalogs/${catalog}/local_inventory_items`;}\n private async selected(selection:LocalScope,pairs:Pair[]){const parent=await this.stores.selected(selection),stores=await this.stores.owned(selection,pairs.map(row=>row.store_id));if(pairs.some(pair=>stores.find(store=>store.id===pair.store_id)?.store_code!==pair.store_code))throw new AdportError('PENDING_MISMATCH','Selected store ID/code does not match the current catalog.');return {...parent,stores};}\n private async readSet(selection:LocalScope,pairs:Pair[]):Promise<Current[]>{\n const data=await this.client.mutate(this.path(selection.catalog_id)+'/query','POST',{item_filters:pairs.map(({item_id,store_code})=>({item_id,store_code}))},z.object({items:z.array(z.record(z.string(),z.json())).max(1000)}),this.stores.params(selection.account_id)).catch(error=>{throw localFailure(error);}),seen=new Map<string,Current>();\n for(const raw of data.items){inventoryAttributes.partial().loose().parse(raw);const item_id=sourceId.parse(raw.item_id),metadata=z.looseObject({store_id:z.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);if(!pair||metadata.store_id!==pair.store_id||seen.has(key)||raw.catalog_id!==undefined&&raw.catalog_id!==selection.catalog_id)throw localFailure();z.number().int().safe().parse(raw.created_at);z.number().int().safe().parse(raw.last_updated_time);seen.set(key,{pair,state:'PRESENT',attributes:readAttrs(raw),metadata});}\n return pairs.map(pair=>seen.get(inventoryKey(pair))??{pair,state:'NOT_RETURNED'});\n }\n private record(row:Current){return {id:localHash([row.pair.item_id,row.pair.store_code]),name:row.pair.item_id+' · '+row.pair.store_code,...row.pair,status:row.state,attributes:publicLocal(row.attributes),store_metadata:row.metadata};}\n async list(value:unknown){\n const input=inventoryList.parse(value),selection=localScope.parse({account_id:input.account_id,catalog_id:input.catalog_id}),key=localHash({selection,pairs:input.item_filters,size:input.limit});let offset=0;\n if(input.cursor){let cursor;try{cursor=z.object({selection:groupHash,offset:z.number().int().min(1).max(999)}).strict().parse(JSON.parse(Buffer.from(input.cursor,'base64url').toString('utf8')));}catch{throw new AdportError('INVALID_INPUT','Invalid local-inventory cursor.');}if(cursor.selection!==key||cursor.offset>=input.item_filters.length)throw new AdportError('PENDING_MISMATCH','Local-inventory selection changed; restart the first page.');offset=cursor.offset;}\n const pairs=input.item_filters.slice(offset,offset+input.limit);await this.selected(selection,pairs);const current=await this.readSet(selection,pairs),next=offset+pairs.length;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:[...notes,'Paging covers only the requested item/store pairs, not all inventory in the catalog.']};\n }\n private manifest(request:Request,current:Current[]){\n const result=request.operations.map(row=>{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:undefined,keys=Object.keys(attributes??{}) as z.infer<typeof manifestRow>['desired_keys'],before=current.find(old=>inventoryKey(old.pair)===inventoryKey(pair))!;return {...pair,operation:row.operation,desired_keys:keys,...(attributes?{desired_hash:localHash(attributes)}:{}),...(row.operation==='UPDATE'?{preserved_hash:localHash(preserved(before.attributes!,keys))}:{})};});\n if(Buffer.byteLength(localCanonical(result))>1_000_000)throw new AdportError('INVALID_INPUT','Local-inventory receipt exceeds its bound; split the batch.');return result;\n }\n async context(value:unknown){\n const input=inventoryContext.parse(value),selection=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});localBound(request);\n const pairs=request.operations.map(row=>inventoryPair.parse({item_id:row.item_id,store_code:row.store_code,store_id:row.store_id})),parent=await this.selected(selection,pairs),current=await this.readSet(selection,pairs);\n for(const row of request.operations){const before=current.find(old=>inventoryKey(old.pair)===inventoryKey(row))!;if(row.operation==='CREATE'&&before.state==='PRESENT')throw new AdportError('INVALID_INPUT','CREATE cannot overwrite a positively read local item/store pair.');if(['UPDATE','DELETE'].includes(row.operation)&&before.state!=='PRESENT')throw new AdportError('INVALID_INPUT','UPDATE/DELETE require a positively read current item/store pair.');if(row.operation==='UPSERT'&&!request.acknowledge_replacement)throw new AdportError('INVALID_INPUT','UPSERT requires acknowledge_replacement.');if(['CREATE','UPSERT'].includes(row.operation)&&before.state!=='PRESENT'&&!request.acknowledge_unconfirmed_existing)throw new AdportError('INVALID_INPUT','Missing query rows do not prove absence; acknowledge_unconfirmed_existing is required.');}\n const scope_id=this.scopeId(),manifest=this.manifest(request,current);return {...parent,request,current,manifest,scope_id,context_hash:localHash({selection,owner:parent.owner,catalog:{id:parent.catalog.id,name:parent.catalog.name,type:parent.catalog.catalog_type},stores:parent.stores.map(({created_at:_created,updated_at:_updated,...row})=>row),request,current,scope_id}),records:current.map(row=>this.record(row)),notes};\n }\n async publicContext(value:unknown){const result=await this.context(value);return {context_hash:result.context_hash,records:result.records,changes:result.request.operations.map(row=>publicLocal(row)),notes:[...notes,'CREATE duplicate handling is native; Adport does not claim atomic absence or promise that a missing query proves a new pair.']};}\n private batchRows(data:z.infer<typeof nativeBatch>,manifest:z.infer<typeof manifestRow>[]){\n const found=new Map<string,LocalRow>();for(const raw of data.operation_results){const pair=z.object({item_id:sourceId,store_code:sourceId,supplemental_type:z.literal('LOCAL_INVENTORY'),status:z.enum(['SUCCESS','FAILURE','PROCESSING'])}).parse(raw),key=inventoryKey(pair),expected=manifest.find(row=>inventoryKey(row)===key),errors=diagnostics(raw.errors),warnings=diagnostics(raw.warnings);if(!expected||found.has(key)||pair.status==='SUCCESS'&&(errors.length||data.status==='FAILED'))throw localFailure();found.set(key,{id:localHash([pair.item_id,pair.store_code]),name:pair.item_id+' · '+pair.store_code,item_id:pair.item_id,store_code:pair.store_code,store_id:expected.store_id,status:pair.status,errors,warnings});}\n return manifest.map(row=>found.get(inventoryKey(row))??{id:localHash([row.item_id,row.store_code]),name:row.item_id+' · '+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:[]});\n }\n private async verifiedReceipt(value:unknown){const input=inventoryBatchReference.parse(value),proof=receiptSchema.parse(this.client.verifyCatalogBatchReceipt(input.batch_receipt));if(proof.account_id!==input.account_id||proof.scope_id!==this.scopeId()||proof.expires_at<=Math.floor(Date.now()/1000)||proof.expires_at>Math.floor(Date.now()/1000)+30*86400)throw new AdportError('INVALID_INPUT','Local-inventory receipt expired or belongs to another advertiser/project.');const parent=await this.stores.selected({account_id:proof.account_id,catalog_id:proof.catalog_id});if(parent.owner!==proof.owner_context_hash)throw new AdportError('POLICY_VIOLATION','Local-inventory catalog ownership changed.');return proof;}\n async status(value:unknown,reconcile=false){\n const proof=await this.verifiedReceipt(value),data=await this.client.get(`catalogs/${proof.catalog_id}/supplemental_items/batch/${proof.batch_id}`,nativeBatch,this.stores.params(proof.account_id)).catch(error=>{throw localFailure(error,[proof.batch_id]);});if(data.batch_id!==proof.batch_id)throw localFailure();const records=this.batchRows(data,proof.manifest);let readback_error:LocalRow|undefined;\n if(reconcile)try{await this.selected({account_id:proof.account_id,catalog_id:proof.catalog_id},proof.manifest);const current=await this.readSet({account_id:proof.account_id,catalog_id:proof.catalog_id},proof.manifest);for(const record of records){const expected=proof.manifest.find(row=>inventoryKey(row)===inventoryKey(record as {item_id:string;store_code:string}))!,actual=current.find(row=>inventoryKey(row.pair)===inventoryKey(expected))!;record.observed_state=actual.state;if(record.status!=='SUCCESS'){record.readback='NATIVE_ITEM_NOT_SUCCESSFUL';continue;}if(expected.operation==='DELETE'){record.readback=actual.state==='PRESENT'?'STILL_PRESENT':'ABSENCE_UNCONFIRMED';continue;}if(!actual.attributes){record.readback='CURRENT_PAIR_UNCONFIRMED';continue;}const attrs=Object.fromEntries(expected.desired_keys.map(key=>[key,actual.attributes![key]])),matches=localHash(attrs)===expected.desired_hash,retains=!expected.preserved_hash||localHash(preserved(actual.attributes,expected.desired_keys))===expected.preserved_hash;record.readback=matches&&retains?'REQUESTED_CONFIGURATION_VERIFIED':'CONFIGURATION_UNCONFIRMED';record.omitted_fields_preserved=expected.preserved_hash?retains:undefined;}}catch(error){const detail=error instanceof AdportError?localObject(error.details):{};readback_error={status:'READBACK_UNAVAILABLE',...(typeof detail.http_status==='number'?{http_status:detail.http_status}:{})};}\n return {batch_id:proof.batch_id,status:data.status,records,submitted_items:proof.manifest.length,terminal_items:records.filter(row=>['SUCCESS','FAILURE','BATCH_FAILED'].includes(String(row.status))).length,all_items_native_successful:data.status==='COMPLETED'&&records.every(row=>row.status==='SUCCESS'),...(readback_error?{readback_error}:{}),publication_verified:false,notes};\n }\n async plan(op:WriteOperation):Promise<Plan>{\n const operation=inventoryWriteTools[op.tool as keyof typeof inventoryWriteTools],kind=operation==='CREATE'?'create':operation==='DELETE'?'remove':'update';if(op.provider!=='pinterest'||!this.supports(op.tool)||op.kind!==kind)throw new AdportError('INVALID_INPUT','Invalid local-inventory mutation kind.');const parsed=operation?inventoryNamed(operation).parse(op.payload):inventoryBatch.parse(op.payload),selection={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});\n const prepare=async()=>{const result=await this.context({...selection,...request});if(result.context_hash!==parsed.expected_context_hash)throw new AdportError('PENDING_MISMATCH','Local inventory, store, owner, project or request changed; preview again.');return result;},before=await prepare();let details:LocalRow|undefined;\n return {summary:`Submit local inventory batch · ${request.operations.length} item/store pairs`,changes:request.operations.map(row=>`${row.operation} ${row.item_id} · ${row.store_code}`),coercions:[],budgetDeltas:[],notes,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+' · '+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:notes},\n execute:async()=>{const fresh=await prepare();let id:string|undefined;try{if(fresh.scope_id!==this.scopeId())throw localFailure();const native=await this.client.mutate(this.path(selection.catalog_id)+'/batch','POST',{operations:request.operations.map(({store_id:_store,...row})=>row)},nativeBatch,this.stores.params(op.accountId));id=native.batch_id;const batch_receipt=this.client.catalogBatchReceipt({...selection,version:'pinterest_local_inventory_v1',scope_id:fresh.scope_id,owner_context_hash:fresh.owner,batch_id:id,expires_at:Math.floor(Date.now()/1000)+30*86400,manifest:fresh.manifest}),records=this.batchRows(native,fresh.manifest);if(native.status==='FAILED'||records.every(row=>row.status==='FAILURE'))throw localFailure(undefined,[id],{batch_receipt,records,native_status:native.status});details={status:'ACCEPTED_FOR_PROCESSING',processed:false,native_status:native.status,batch_id:id,batch_receipt,records,configuration_verified:false,publication_verified:false,next_tool:'pinterest_local_inventory_batch_status',next_arguments:{account_id:op.accountId,batch_receipt}};return [id];}catch(error){const extra=error instanceof AdportError?localObject(error.details):{};throw localFailure(error,id?[id]:Array.isArray(extra.resource_ids)?extra.resource_ids as string[]:[],extra.batch_receipt?{batch_receipt:extra.batch_receipt,records:extra.records,native_status:extra.native_status}:{});}},resultDetails:()=>details,resultWarnings:()=>notes};\n }\n}\n","import { z } from 'zod';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { accountSchema, campaignSchema, createCampaignSchema, pinterestId } from './schemas.js';\nimport { groupHash } from './product-group-schemas.js';\nimport { localCanonical, localHash, localObject, type LocalRow } from './local-catalog-schemas.js';\n\ntype Campaign=z.infer<typeof campaignSchema>;\ntype Plan=Omit<WritePreview,'serverValidated'>&{execute():Promise<string[]>;resultDetails?():unknown;resultWarnings?():string[]};\nexport const campaignBudgetContext=z.object({account_id:pinterestId,campaign_id:pinterestId}).strict();\nexport const campaignDailyBudget=z.object({campaign_id:pinterestId,expected_context_hash:groupHash,daily_budget_mode:z.enum(['FIXED','AVERAGE']),budget_micros:z.number().int().positive().safe().optional(),acknowledge_variable_daily_spend:z.literal(true).optional(),acknowledge_averaging_reset:z.literal(true).optional()}).strict().superRefine((value,ctx)=>{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.'});});\nconst notes=['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.'];\nconst failure=(error?:unknown,ids:string[]=[],extra:LocalRow={})=>(new AdportError('PROVIDER_ERROR','Pinterest campaign budget outcome is unconfirmed. No mutation was retried; reconcile known campaign IDs before another preview. Native bodies are hidden.',{...(ids.length?{resource_ids:[...new Set(ids)]}:{}),...(error instanceof AdportError&&Array.isArray(localObject(error.details).native_errors)?{native_errors:localObject(error.details).native_errors}:{}),...(error instanceof AdportError&&typeof localObject(error.details).verification_phase==='string'?{verification_phase:localObject(error.details).verification_phase}:{}),...extra,...(error instanceof AdportError&&typeof localObject(error.details).api_code==='number'&&Number.isSafeInteger(localObject(error.details).api_code)?{api_code:localObject(error.details).api_code}:{}),...(error instanceof AdportError&&typeof localObject(error.details).http_status==='number'?{http_status:localObject(error.details).http_status}:{})}));\nconst configuration=(campaign: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]));\n\n/** Fixed/average semantics are explicit; the shared cap still checks native nominal micros. */\nexport class PinterestCampaignBudgets{\n constructor(private readonly client:PinterestAdsClient,private readonly campaign:(account:string,id:string)=>Promise<Campaign>,private readonly projectScope:()=>string){}\n supports(tool:string){return tool==='pinterest_set_campaign_daily_budget';}\n private async account(account:string){const result=await this.client.get(`ad_accounts/${pinterestId.parse(account)}`,accountSchema);if(result.id!==account)throw failure();return {id:result.id,currency:result.currency,country:typeof result.country==='string'?result.country:undefined,owner_fingerprint:typeof localObject(result.owner).username==='string'?localHash(String(localObject(result.owner).username).toLowerCase()):undefined};}\n private currency(value:unknown){if(typeof value!=='string'||!/^[A-Z]{3}$/.test(value))throw new AdportError('INVALID_INPUT','Native account currency is unavailable; no monetary mutation is permitted.');return value;}\n private mode(value:Campaign){const daily=value.daily_spend_cap??0,lifetime=value.lifetime_spend_cap??0;if(value.is_campaign_budget_optimization!==true)return 'NOT_CAMPAIGN_BUDGETED';if((daily>0)===(lifetime>0))return 'AMBIGUOUS';if(lifetime>0)return value.is_flexible_daily_budgets===true?'AMBIGUOUS':'LIFETIME';return value.is_flexible_daily_budgets===true?'AVERAGE':value.is_flexible_daily_budgets===false?'FIXED':'DAILY_MODE_UNCONFIRMED';}\n async context(value:unknown){const input=campaignBudgetContext.parse(value),account=await this.account(input.account_id),current=await this.campaign(input.account_id,input.campaign_id),mode=this.mode(current),scope=this.projectScope();return {account,current,mode,scope,context_hash:localHash({input,account,current:configuration(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:account.currency,is_campaign_budget_optimization:current.is_campaign_budget_optimization,is_flexible_daily_budgets:current.is_flexible_daily_budgets}],notes};}\n async publicContext(value:unknown){const result=await this.context(value);return {context_hash:result.context_hash,records:result.records,notes};}\n private async write(account:string,method:'POST'|'PATCH',body:LocalRow):Promise<{id:string}>{\n const ids:string[]=[];if(typeof body.id==='string')ids.push(body.id);\n try{const raw=localObject(await this.client.mutate(`ad_accounts/${pinterestId.parse(account)}/campaigns`,method,[body],z.unknown()));for(const item of Array.isArray(raw.items)?raw.items.slice(0,1000):[]){const id=localObject(localObject(item).data).id;if(pinterestId.safeParse(id).success)ids.push(String(id));}if(!Array.isArray(raw.items)||raw.items.length!==1)throw failure();const item=localObject(raw.items[0]);if(item.exceptions!==undefined&&(!Array.isArray(item.exceptions)||item.exceptions.length)){const errors=Array.isArray(item.exceptions)?item.exceptions.slice(0,100).map(value=>{const row=localObject(value);return {...(typeof row.code==='number'&&Number.isSafeInteger(row.code)?{code:row.code}:{}),message_present:typeof row.message==='string'};}):[];throw failure(undefined,ids,{verification_phase:'NATIVE_BATCH_ERRORS',native_errors:errors});}const data=campaignSchema.partial().extend({id:pinterestId}).parse(item.data);if(data.ad_account_id!==undefined&&data.ad_account_id!==account||body.id!==undefined&&data.id!==body.id||Object.entries(body).some(([key,value])=>data[key]!==undefined&&localCanonical(data[key])!==localCanonical(value)))throw failure(undefined,ids,{verification_phase:'NATIVE_RECEIPT'});return data;}catch(error){throw failure(error,ids);}\n }\n private preserved(before:Campaign,after:Campaign,changed:string[]){const values=configuration(after);return Object.entries(configuration(before)).every(([key,value])=>changed.includes(key)||localCanonical(values[key])===localCanonical(value));}\n async create(input:z.infer<typeof createCampaignSchema>,op:WriteOperation,guard:WriteGuard):Promise<Plan>{\n 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 AdportError('INVALID_INPUT','Invalid average-daily campaign creation.');const account=await this.account(op.accountId),currency=this.currency(account.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};let details:LocalRow|undefined;\n 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}],notes,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},{label:'Status',after:status},{label:'Objective',after:input.objective_type}],notices:notes},execute:async()=>{let id:string|undefined;try{const fresh=await this.account(op.accountId);if(localCanonical(fresh)!==localCanonical(account))throw new AdportError('PENDING_MISMATCH','Account currency/configuration changed.');const created=await this.write(op.accountId,'POST',body);id=created.id;const actual=await this.campaign(op.accountId,id);if(Object.entries(body).some(([key,value])=>localCanonical(actual[key])!==localCanonical(value))||(actual.lifetime_spend_cap??0)!==0)throw failure();details={configuration_readback:'VERIFIED',campaign_id:id,status:actual.status,budget_mode:'AVERAGE',configured_daily_average_micros:actual.daily_spend_cap,currency,daily_delivery_ceiling_verified:false,full_performance_plus_configuration:false};return[id];}catch(error){const known=error instanceof AdportError?localObject(error.details).resource_ids:undefined;throw failure(error,id?[id]:Array.isArray(known)?known as string[]:[]);}},resultDetails:()=>details,resultWarnings:()=>notes};\n }\n async plan(op:WriteOperation):Promise<Plan>{\n if(op.provider!=='pinterest'||!this.supports(op.tool)||op.kind!=='update')throw new AdportError('INVALID_INPUT','Invalid daily-budget mutation kind.');const input=campaignDailyBudget.parse(op.payload),prepare=async()=>{const result=await this.context({account_id:op.accountId,campaign_id:input.campaign_id});if(result.context_hash!==input.expected_context_hash)throw new AdportError('PENDING_MISMATCH','Campaign, budget mode, currency or project changed; preview again.');if(!['FIXED','AVERAGE'].includes(result.mode)||!['PAUSED','ACTIVE','DRAFT'].includes(String(result.current.status)))throw new AdportError('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.');if((result.mode==='AVERAGE'||input.daily_budget_mode==='AVERAGE')&&(!input.acknowledge_variable_daily_spend||!input.acknowledge_averaging_reset))throw new AdportError('INVALID_INPUT','Current or requested average mode requires variable-spend and averaging-reset acknowledgements.');return result;},before=await prepare(),currency=this.currency(before.account.currency),amount=input.budget_micros??before.current.daily_spend_cap!;\n if(before.mode===input.daily_budget_mode&&amount===before.current.daily_spend_cap)throw new AdportError('INVALID_INPUT','No daily-budget change requested.');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'}`;let details:LocalRow|undefined;\n return {summary:`Change Pinterest campaign \"${before.current.name??input.campaign_id}\" daily budget`,changes:[`~ ${input.campaign_id} ${before.mode} → ${input.daily_budget_mode}; ${before.current.daily_spend_cap} → ${amount} micros`],coercions:[],budgetDeltas:[{target,fromMicros:before.current.daily_spend_cap!,toMicros:amount,currency}],notes,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},{label:'Status',before:before.current.status,after:before.current.status}],notices:notes},execute:async()=>{await prepare();try{await this.write(op.accountId,'PATCH',body);const actual=await this.campaign(op.accountId,input.campaign_id);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 failure(undefined,[input.campaign_id],{verification_phase:'INDEPENDENT_READBACK'});details={configuration_readback:'VERIFIED',campaign_id:actual.id,status:actual.status,budget_mode:input.daily_budget_mode,configured_budget_micros:amount,currency,omitted_configuration_preserved:true,daily_delivery_ceiling_verified:false};return[actual.id];}catch(error){const known=error instanceof AdportError?localObject(error.details).resource_ids:undefined;throw failure(error,[input.campaign_id,...(Array.isArray(known)?known as string[]:[])]);}},resultDetails:()=>details,resultWarnings:()=>notes};\n }\n}\n\nexport function pinterestCampaignBudgetTools(provider:PinterestAdsProvider):AnyToolDefinition[]{const catalog={category:'campaigns' as const,exposure:'specialist' as const};return[\n defineTool({name:'pinterest_campaign_budget_context',namespace:'pinterest',catalog,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:z.looseObject({records:z.array(z.record(z.string(),z.unknown()))}),handler:input=>provider.campaignBudgets.publicContext(input)}),\n guardedWriteTool({name:'pinterest_set_campaign_daily_budget',namespace:'pinterest',provider:'pinterest',catalog,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.'}),\n];}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { createCampaignSchema, pinterestId, setBudgetSchema, setStatusSchema } from './schemas.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestCreativeTools } from './creative-tools.js';\nimport { pinterestAssetTools } from './assets.js';\nimport { pinterestKeywordTools } from './keywords.js';\nimport { pinterestAudienceTools } from './audiences.js';\nimport { pinterestMeasurementTools } from './measurement.js';\nimport { pinterestCatalogTools } from './catalogs.js';\nimport { pinterestProductGroupTools } from './product-group-tools.js';\nimport { pinterestCatalogItemTools } from './catalog-item-tools.js';\nimport { pinterestLocalCatalogTools } from './local-catalog-tools.js';\nimport { pinterestCampaignBudgetTools } from './campaign-budgets.js';\n\nexport function pinterestTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n return [\n ...pinterestAssetTools(provider),\n ...pinterestKeywordTools(provider),\n ...pinterestAudienceTools(provider),\n ...pinterestMeasurementTools(provider),\n ...pinterestCatalogTools(provider),\n ...pinterestProductGroupTools(provider),\n ...pinterestCatalogItemTools(provider),\n ...pinterestLocalCatalogTools(provider),\n ...pinterestCampaignBudgetTools(provider),\n ...pinterestCreativeTools(provider),\n defineTool({ name: 'pinterest_list_campaigns', namespace: 'pinterest', description: 'List Pinterest campaigns, including archived and draft entities.', input: z.object({ account_id: pinterestId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n guardedWriteTool({ 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 }),\n guardedWriteTool({ name: 'pinterest_set_campaign_status', namespace: 'pinterest', provider: 'pinterest', kind: 'update', description: 'Pause or activate an existing Pinterest campaign.', payload: setStatusSchema }),\n guardedWriteTool({ 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 }),\n ];\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { filterFields } from './product-group-filter-spec.js';\nimport { catalogType, groupContext, groupCreate, groupDelete, groupList, groupPaging, groupReference, groupUpdate, productGroupFilterSchema } from './product-group-schemas.js';\n\nexport function pinterestProductGroupTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'creatives' as const, exposure: 'specialist' as const }, read = { namespace: 'pinterest', catalog, presentation: 'records' as const, annotations: { readOnly: true }, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) }, write = { namespace: 'pinterest', provider: 'pinterest', catalog };\n return [\n defineTool({ namespace: 'pinterest', catalog, 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: z.object({ catalog_type: catalogType }).strict(), annotations: { readOnly: true, openWorld: false }, handler: async input => ({ catalog_type: input.catalog_type, fields: filterFields[input.catalog_type], schema: z.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.'] }) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n guardedWriteTool({ ...write, 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 }),\n guardedWriteTool({ ...write, 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 }),\n guardedWriteTool({ ...write, 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 }),\n ];\n}\n","import { z } from 'zod';\nimport { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { attributeSchema, batchReference, itemBatchApply, itemContext, itemCopy, itemNamedApply, itemRead, itemSchemaQuery, itemWriteOperations } from './catalog-item-schemas.js';\n\nexport function pinterestCatalogItemTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'creatives' as const, exposure: 'specialist' as const }, read = { namespace: 'pinterest', catalog, annotations: { readOnly: true }, presentation: 'records' as const, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) }, write = { namespace: 'pinterest', provider: 'pinterest', catalog };\n const named = Object.entries(itemWriteOperations).map(([name, operation]) => guardedWriteTool({ ...write, name, 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.` }));\n return [\n defineTool({ namespace: 'pinterest', catalog, 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: z.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.'] }) }),\n defineTool({ ...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: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, handler: input => provider.catalogItems.list(input) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n ...named,\n guardedWriteTool({ ...write, 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.' }),\n guardedWriteTool({ ...write, 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.' }),\n ];\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { inventoryBatch, inventoryBatchReference, inventoryContext, inventoryList, inventoryNamed, inventoryWriteTools, localStoreContext, localStoreCreate, localStoreDelete, localStoreList, localStoreUpdate } from './local-catalog-schemas.js';\n\nexport function pinterestLocalCatalogTools(provider:PinterestAdsProvider):AnyToolDefinition[]{\n const catalog={category:'creatives' as const,exposure:'specialist' as const},read={namespace:'pinterest',catalog,annotations:{readOnly:true},presentation:'records' as const,output:z.looseObject({records:z.array(z.record(z.string(),z.unknown()))})},write={namespace:'pinterest',provider:'pinterest',catalog};\n return [\n defineTool({...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)}),\n defineTool({...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)}),\n guardedWriteTool({...write,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.'}),\n guardedWriteTool({...write,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.'}),\n guardedWriteTool({...write,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.'}),\n defineTool({...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)}),\n defineTool({...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)}),\n defineTool({...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)}),\n defineTool({...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)}),\n ...Object.entries(inventoryWriteTools).map(([name,operation])=>guardedWriteTool({...write,name,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.`})),\n guardedWriteTool({...write,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.'}),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { PinterestAdsClient, type PinterestCredentials } from './client.js';\nimport { PinterestAdsProvider } from './provider.js';\nimport { pinterestTools } from './tools.js';\nexport { PinterestAdsClient, PINTEREST_API_BASE, PINTEREST_TOKEN_URL, PINTEREST_ADS_SCOPES, PINTEREST_PIN_SCOPES, PINTEREST_SECRET_PIN_SCOPES, PINTEREST_CATALOG_SCOPES, pinterestAuthorizationScopes, buildPinterestAuthUrl, exchangePinterestCode, type PinterestCredentials, type PinterestAuthorizationOptions } from './client.js';\nexport { PinterestAdsProvider } from './provider.js';\nexport { pinterestTools } from './tools.js';\nexport { accountSchema, campaignSchema } from './schemas.js';\n\nexport async function resolvePinterestCredentials(store: CredentialStore): Promise<PinterestCredentials | undefined> {\n const data = (await store.get('pinterest'))?.data;\n if (data?.client_id && data.client_secret && data.refresh_token) return {\n clientId: data.client_id, clientSecret: data.client_secret, refreshToken: data.refresh_token,\n onRefreshToken: async refreshToken => {\n const latest = await store.get('pinterest');\n if (latest) await store.set({ provider: 'pinterest', source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });\n },\n };\n if (process.env.PINTEREST_CLIENT_ID && process.env.PINTEREST_CLIENT_SECRET && process.env.PINTEREST_REFRESH_TOKEN) return {\n clientId: process.env.PINTEREST_CLIENT_ID, clientSecret: process.env.PINTEREST_CLIENT_SECRET, refreshToken: process.env.PINTEREST_REFRESH_TOKEN,\n };\n return undefined;\n}\nexport async function createPinterestModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolvePinterestCredentials(store);\n if (!credentials) return undefined;\n const provider = new PinterestAdsProvider(new PinterestAdsClient(credentials));\n return { provider, tools: pinterestTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAC5B,SAAS,SAAS;AAClB,SAAS,YAAY,uBAAuB;AAErC,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB,GAAG,kBAAkB;AACjD,IAAM,uBAAuB,CAAC,YAAY,WAAW;AACrD,IAAM,uBAAuB,CAAC,GAAG,sBAAsB,eAAe,gBAAgB,aAAa,cAAc,oBAAoB;AACrI,IAAM,8BAA8B,CAAC,GAAG,sBAAsB,sBAAsB,uBAAuB,oBAAoB,mBAAmB;AAClJ,IAAM,2BAA2B,CAAC,iBAAiB,gBAAgB;AAMnE,SAAS,6BAA6B,UAAyC,C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AAmQ,SAAS,qBAAqB,CAAC;AAAA,IACpaA,mBAAiB,EAAE,MAAM,iCAAiC,WAAW,aAAa,UAAU,aAAa,MAAM,UAAU,aAAa,qDAAqD,SAAS,gBAAgB,CAAC;AAAA,IACrNA,mBAAiB,EAAE,MAAM,wBAAwB,WAAW,aAAa,UAAU,aAAa,MAAM,UAAU,aAAa,mGAAmG,SAAS,gBAAgB,CAAC;AAAA,EAC5P;AACF;;;AIvBA,eAAsB,4BAA4B,OAAmE;AACnH,QAAM,QAAQ,MAAM,MAAM,IAAI,WAAW,IAAI;AAC7C,MAAI,MAAM,aAAa,KAAK,iBAAiB,KAAK,cAAe,QAAO;AAAA,IACtE,UAAU,KAAK;AAAA,IAAW,cAAc,KAAK;AAAA,IAAe,cAAc,KAAK;AAAA,IAC/E,gBAAgB,OAAM,iBAAgB;AACpC,YAAM,SAAS,MAAM,MAAM,IAAI,WAAW;AAC1C,UAAI,OAAQ,OAAM,MAAM,IAAI,EAAE,UAAU,aAAa,QAAQ,OAAO,QAAQ,MAAM,EAAE,GAAG,OAAO,MAAM,eAAe,aAAa,EAAE,CAAC;AAAA,IACrI;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,uBAAuB,QAAQ,IAAI,2BAA2B,QAAQ,IAAI,wBAAyB,QAAO;AAAA,IACxH,UAAU,QAAQ,IAAI;AAAA,IAAqB,cAAc,QAAQ,IAAI;AAAA,IAAyB,cAAc,QAAQ,IAAI;AAAA,EAC1H;AACA,SAAO;AACT;AACA,eAAsB,sBAAsB,OAA6D;AACvG,QAAMC,eAAc,MAAM,4BAA4B,KAAK;AAC3D,MAAI,CAACA,aAAa,QAAO;AACzB,QAAM,WAAW,IAAI,qBAAqB,IAAI,mBAAmBA,YAAW,CAAC;AAC7E,SAAO,EAAE,UAAU,OAAO,eAAe,QAAQ,EAAE;AACrD;","names":["state","credentials","response","url","name","text","id","z","AdportError","LocalMediaResolver","AdportError","z","z","z","z","name","description","write","z","account","id","AdportError","ids","cursor","type","parent","tag","fields","url","AdportError","creativesOutput","defineTool","guardedWriteTool","z","id","z","url","account","AdportError","pinId","fields","input","current","ids","paging","defineTool","creativesOutput","guardedWriteTool","createHash","AdportError","creativesOutput","defineTool","guardedWriteTool","z","hash","z","createHash","snapshot","account","selected","AdportError","configuration","page","ids","parsed","notes","value","defineTool","creativesOutput","guardedWriteTool","createHash","AdportError","creativesOutput","defineTool","guardedWriteTool","z","hash","z","ids","writes","object","AdportError","digest","createHash","account","page","source","tag","type","targeting","create","input","current","body","fields","name","description","defineTool","write","guardedWriteTool","creativesOutput","createHash","AdportError","defineTool","guardedWriteTool","z","canonical","digest","createHash","hash","z","url","writes","account","AdportError","ids","configuration","input","context","count","name","description","defineTool","guardedWriteTool","createHash","AdportError","defineTool","guardedWriteTool","z","id","z","hash","name","url","account","selected","reference","canonical","digest","createHash","text","location","credentials","catalog","AdportError","ids","page","fields","input","body","current","changes","defineTool","guardedWriteTool","createHash","AdportError","z","z","z","text","strings","type","fields","reference","ids","canonical","hash","createHash","AdportError","cursor","z","product","account","catalog","id","selection","query","selected","page","records","owner","feed","fields","create","createHash","z","AdportError","z","z","z","ids","type","canonical","hash","createHash","object","z","notes","ids","AdportError","name","match","url","type","account","selection","owner","id","state","key","catalog","records","description","source","parent","value","record","copy","z","AdportError","createHash","z","AdportError","createHash","z","ids","AdportError","name","text","common","account","catalog","selection","AdportError","ids","z","parent","cursor","page","unique","create","records","id","preserved","z","AdportError","batchId","z","nativeBatch","manifestRow","receiptSchema","notes","preserved","diagnostics","catalog","selection","parent","AdportError","cursor","records","record","id","z","AdportError","defineTool","guardedWriteTool","z","notes","failure","ids","AdportError","configuration","account","item","id","currency","catalog","defineTool","guardedWriteTool","LocalMediaResolver","account","id","query","z","page","AdportError","fields","plan","z","defineTool","guardedWriteTool","z","defineTool","guardedWriteTool","catalog","z","write","defineTool","guardedWriteTool","z","creativesOutput","defineTool","guardedWriteTool","catalog","z","write","name","guardedWriteTool","defineTool","creativesOutput","z","defineTool","guardedWriteTool","catalog","z","write","defineTool","guardedWriteTool","name","defineTool","z","guardedWriteTool","credentials"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/creatives.ts","../src/creative-tools.ts","../src/schemas.ts","../src/assets.ts","../src/keywords.ts","../src/audiences.ts","../src/measurement.ts","../src/catalogs.ts","../src/product-groups.ts","../src/product-group-schemas.ts","../src/product-group-filter-spec.ts","../src/catalog-items.ts","../src/catalog-item-attributes.ts","../src/catalog-item-schemas.ts","../src/local-stores.ts","../src/local-catalog-schemas.ts","../src/local-inventory.ts","../src/campaign-budgets.ts","../src/tools.ts","../src/product-group-tools.ts","../src/catalog-item-tools.ts","../src/local-catalog-tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\nimport { z } from 'zod';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport const PINTEREST_API_BASE = 'https://api.pinterest.com/v5/';\nexport const PINTEREST_TOKEN_URL = `${PINTEREST_API_BASE}oauth/token`;\nexport const PINTEREST_ADS_SCOPES = ['ads:read', 'ads:write'] as const;\nexport const PINTEREST_PIN_SCOPES = [...PINTEREST_ADS_SCOPES, 'boards:read', 'boards:write', 'pins:read', 'pins:write', 'user_accounts:read'] as const;\nexport const PINTEREST_SECRET_PIN_SCOPES = [...PINTEREST_PIN_SCOPES, 'boards:read_secret', 'boards:write_secret', 'pins:read_secret', 'pins:write_secret'] as const;\nexport const PINTEREST_CATALOG_SCOPES = ['catalogs:read', 'catalogs:write'] as const;\nexport interface PinterestAuthorizationOptions {\n pinManagement?: boolean;\n secretPins?: boolean;\n catalogManagement?: boolean;\n}\nexport function pinterestAuthorizationScopes(options: PinterestAuthorizationOptions = {}): readonly string[] {\n return [...(options.secretPins ? PINTEREST_SECRET_PIN_SCOPES : options.pinManagement ? PINTEREST_PIN_SCOPES : PINTEREST_ADS_SCOPES), ...(options.catalogManagement ? PINTEREST_CATALOG_SCOPES : [])];\n}\nexport interface PinterestCredentials {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n onRefreshToken?: (refreshToken: string) => Promise<void>;\n}\nconst tokenSchema = z.object({\n access_token: z.string().min(1), expires_in: z.number().positive(),\n refresh_token: z.string().min(1).optional(),\n scope: z.string().optional(),\n});\n\nexport function buildPinterestAuthUrl(clientId: string, redirectUri: string, state: string, options: PinterestAuthorizationOptions = {}): string {\n return `https://www.pinterest.com/oauth/?${new URLSearchParams({\n client_id: clientId, response_type: 'code', redirect_uri: redirectUri, state, scope: pinterestAuthorizationScopes(options).join(','),\n })}`;\n}\n\nasync function tokenRequest(credentials: Pick<PinterestCredentials, 'clientId' | 'clientSecret'>, body: URLSearchParams, fetchImpl: typeof fetch) {\n const response = await fetchImpl(PINTEREST_TOKEN_URL, {\n method: 'POST', headers: {\n authorization: `Basic ${Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n }, body, redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `pinterest: OAuth ${body.get('grant_type')} failed (HTTP ${response.status})`);\n const parsed = tokenSchema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'pinterest: malformed OAuth response');\n return parsed.data;\n}\n\nexport async function exchangePinterestCode(input: { clientId: string; clientSecret: string; code: string; redirectUri: string } & PinterestAuthorizationOptions, fetchImpl: typeof fetch = fetch): Promise<string> {\n const token = await tokenRequest(input, new URLSearchParams({\n grant_type: 'authorization_code', code: input.code, redirect_uri: input.redirectUri, continuous_refresh: 'true',\n }), fetchImpl);\n if (!token.refresh_token) throw new AdportError('PROVIDER_ERROR', 'pinterest: OAuth exchange did not return a refresh token');\n if (input.pinManagement || input.secretPins || input.catalogManagement) {\n const granted = new Set(token.scope?.split(/[\\s,]+/).filter(Boolean));\n const requested = pinterestAuthorizationScopes(input);\n 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.`);\n }\n return token.refresh_token;\n}\n\nexport class PinterestAdsClient {\n private token?: { value: string; expiresAt: number; scopes?: ReadonlySet<string> };\n private refreshToken: string;\n private refreshing?: Promise<string>;\n constructor(private readonly credentials: PinterestCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n this.refreshToken = credentials.refreshToken;\n }\n catalogBatchReceipt(value: unknown): string {\n const encoded = Buffer.from(JSON.stringify(value)).toString('base64url');\n if (encoded.length > 1_500_000) throw new AdportError('INVALID_INPUT', 'Catalog batch proof exceeds its bound; split this batch before previewing.');\n return encoded + '.' + createHmac('sha256', this.credentials.clientSecret).update('pinterest_catalog_batch_v1:' + this.credentials.clientId + ':' + encoded).digest('hex');\n }\n verifyCatalogBatchReceipt(value: string): unknown {\n const [encoded, signature, extra] = value.split('.');\n if (extra !== undefined || !encoded || encoded.length > 1_500_000 || !/^[a-f0-9]{64}$/.test(signature ?? '')) throw new AdportError('INVALID_INPUT', 'Invalid catalog batch receipt.');\n const expected = createHmac('sha256', this.credentials.clientSecret).update('pinterest_catalog_batch_v1:' + this.credentials.clientId + ':' + encoded).digest();\n if (!timingSafeEqual(expected, Buffer.from(signature!, 'hex'))) throw new AdportError('INVALID_INPUT', 'Catalog batch receipt belongs to another application or was changed.');\n try { return JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')); } catch { throw new AdportError('INVALID_INPUT', 'Invalid catalog batch receipt.'); }\n }\n async get<T>(path: string, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, 'GET', schema, undefined, params);\n }\n async mutate<T>(path: string, method: 'POST' | 'PATCH' | 'DELETE', body: unknown, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, method, schema, body, params);\n }\n async uploadVideo(url: string, parameters: Record<string, string>, bytes: Uint8Array<ArrayBuffer>, name: string) {\n const destination = new URL(url);\n 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');\n const required = ['Content-Type', 'key', 'policy', 'x-amz-algorithm', 'x-amz-credential', 'x-amz-date', 'x-amz-security-token', 'x-amz-signature'];\n if (Object.keys(parameters).length !== required.length || required.some(key => !parameters[key] || parameters[key]!.length > 32_768) || 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');\n const body = new FormData();\n for (const key of required) body.set(key, parameters[key]!);\n body.set('file', new Blob([bytes], { type: 'video/mp4' }), name);\n // The signed Storage capability replaces OAuth here; never forward a bearer token.\n const response = await this.fetchImpl(destination.href, { method: 'POST', body, redirect: 'error', signal: AbortSignal.timeout(120_000) });\n if (response.status !== 204) throw new AdportError('PROVIDER_ERROR', 'pinterest: video transfer was not confirmed');\n }\n private async request<T>(path: string, method: 'GET' | 'POST' | 'PATCH' | 'DELETE', schema: z.ZodType<T>, body?: unknown, params = new URLSearchParams(), retry = true): Promise<T> {\n if (!/^[a-z_]+(?:\\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'pinterest: invalid API resource path');\n const url = new URL(path, PINTEREST_API_BASE);\n url.search = params.toString();\n const token = await this.accessToken();\n const missingCatalogScope = method === 'GET' && (path === 'catalogs' || path.startsWith('catalogs/'))\n && this.token?.value === token && this.token.scopes !== undefined && !this.token.scopes.has('catalogs:read');\n const response = await this.fetchImpl(url.href, {\n method, headers: { authorization: `Bearer ${token}`, ...(body !== undefined ? { 'content-type': 'application/json' } : {}) },\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}), redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (response.status === 401 && method === 'GET' && retry && !missingCatalogScope) {\n if (this.token?.value === token) this.token = undefined;\n return this.request(path, method, schema, body, params, false);\n }\n if (!response.ok) {\n const advice = response.status === 401 && missingCatalogScope\n ? ' The current token is missing catalogs:read. Ask the connection owner to review catalog access; refreshing the same grant cannot add permissions.'\n : response.status === 403 ? ' Check app Trial/Standard access, endpoint-specific scopes and ad-account permissions; reauthorization alone may not help.' : '';\n const details: Record<string, unknown> = { http_status: response.status };\n if (response.status === 401 && missingCatalogScope) details.missing_scopes = ['catalogs:read'];\n if ([400, 404, 409, 422].includes(response.status)) {\n const error = z.object({ code: z.union([z.string(), z.number()]).optional(), message: z.string().max(2000).optional() }).safeParse(await response.json().catch(() => undefined));\n if (error.success) {\n if (error.data.code !== undefined) details.api_code = error.data.code;\n const payload = body && typeof body === 'object' && !Array.isArray(body) ? body as Record<string, unknown> : {};\n const auth = payload.credentials && typeof payload.credentials === 'object' ? payload.credentials as Record<string, unknown> : {};\n const sourceSecrets = path.startsWith('catalogs/') ? [payload.location, auth.username, auth.password].filter((value): value is string => typeof value === 'string' && value.length > 0) : [];\n if (error.data.message) details.api_message = [...sourceSecrets, this.credentials.clientId, this.credentials.clientSecret, this.credentials.refreshToken, this.refreshToken, token].reduce((text, secret) => secret ? text.replaceAll(secret, '[redacted]') : text, error.data.message);\n }\n }\n throw new AdportError('PROVIDER_ERROR', `pinterest: HTTP ${response.status}.${advice}${details.api_message ? ` ${details.api_message}` : ''}`, details);\n }\n const raw: unknown = response.status === 204 ? undefined : await response.json();\n const parsed = schema.safeParse(raw);\n if (!parsed.success) {\n const value = raw && typeof raw === 'object' ? raw as Record<string, unknown> : {};\n const resourceIds = [value.id, value.media_id].filter((id): id is string => typeof id === 'string' && /^\\d{1,30}$/.test(id));\n 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);\n 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)] } : {}) });\n }\n return parsed.data;\n }\n private async accessToken(): Promise<string> {\n if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.value;\n if (!this.refreshing) this.refreshing = this.refresh().finally(() => { this.refreshing = undefined; });\n return this.refreshing;\n }\n private async refresh(): Promise<string> {\n const token = await tokenRequest(this.credentials, new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.refreshToken }), this.fetchImpl);\n if (token.refresh_token && token.refresh_token !== this.refreshToken) {\n this.refreshToken = token.refresh_token;\n await this.credentials.onRefreshToken?.(token.refresh_token);\n }\n this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1000,\n ...(token.scope?.trim() ? { scopes: new Set(token.scope.split(/[\\s,]+/).filter(Boolean)) } : {}) };\n return token.access_token;\n }\n}\n","import { z } from 'zod';\nimport {\n AdportError, LocalMediaResolver, resolveDateRange, type Account, type AdProvider, type MediaResolver, type MetricName,\n type NormalizedQuery, type Report, type ReportRow, type StandardActions,\n type WriteGuard, type WriteOperation, type WritePreview, type WriteResult,\n} from '@adport/core';\nimport { PinterestAdsClient } from './client.js';\nimport { PinterestCreativeService } from './creatives.js';\nimport { PINTEREST_ASSET_WRITES, PinterestAssetService } from './assets.js';\nimport { PinterestKeywordService } from './keywords.js';\nimport { PinterestAudienceService } from './audiences.js';\nimport { PinterestMeasurementService } from './measurement.js';\nimport { PinterestCatalogService } from './catalogs.js';\nimport { PinterestProductGroups } from './product-groups.js';\nimport { PinterestCatalogItems } from './catalog-items.js';\nimport { PinterestLocalStores } from './local-stores.js';\nimport { PinterestLocalInventory } from './local-inventory.js';\nimport { PinterestCampaignBudgets } from './campaign-budgets.js';\nimport { accountSchema, batchResponseSchema, campaignSchema, createCampaignSchema, entitySchema, entityStatus, pinterestId, setBudgetSchema, setStatusSchema } from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]>; resultDetails?: () => unknown; resultWarnings?: () => string[] }\nconst LEVEL = {\n account: { path: '', id: 'AD_ACCOUNT_ID', filter: '' },\n campaign: { path: 'campaigns', id: 'CAMPAIGN_ID', filter: 'campaign_ids' },\n ad_group: { path: 'ad_groups', id: 'AD_GROUP_ID', filter: 'ad_group_ids' },\n ad: { path: 'ads', id: 'AD_ID', filter: 'ad_ids' },\n} as const;\nconst FIELDS = { spend: 'SPEND_IN_MICRO_DOLLAR', impressions: 'PAID_IMPRESSION', clicks: 'OUTBOUND_CLICK_1', conversions: 'TOTAL_CHECKOUT', conversion_value: 'TOTAL_CHECKOUT_VALUE_IN_MICRO_DOLLAR' } as const;\nconst DERIVED = {\n ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000],\n cpa: ['spend', 'conversions', 1], roas: ['conversion_value', 'spend', 1],\n} as const;\n\nexport class PinterestAdsProvider implements AdProvider {\n readonly id = 'pinterest';\n readonly creatives: PinterestCreativeService;\n readonly assets: PinterestAssetService;\n readonly keywords: PinterestKeywordService;\n readonly audiences: PinterestAudienceService;\n readonly measurement: PinterestMeasurementService;\n readonly catalogs: PinterestCatalogService;\n readonly productGroups: PinterestProductGroups;\n readonly catalogItems: PinterestCatalogItems;\n readonly localStores: PinterestLocalStores;\n readonly localInventory: PinterestLocalInventory;\n readonly campaignBudgets: PinterestCampaignBudgets;\n constructor(private readonly client: PinterestAdsClient, media: MediaResolver = new LocalMediaResolver()) {\n this.creatives = new PinterestCreativeService(client, (account, id) => this.getCampaign(account, id));\n this.assets = new PinterestAssetService(client, media);\n this.keywords = new PinterestKeywordService(client, (account, entity, resource) => this.creatives.getEntity(account, entity, resource));\n this.audiences = new PinterestAudienceService(client, (account, entity, resource) => this.creatives.getEntity(account, entity, resource), (account, resource) => this.assets.getPin(account, resource));\n this.measurement = new PinterestMeasurementService(client);\n this.catalogs = new PinterestCatalogService(client);\n this.productGroups = new PinterestProductGroups(client, this.catalogs);\n this.catalogItems = new PinterestCatalogItems(client, this.catalogs, media);\n this.localStores = new PinterestLocalStores(client, this.catalogs);\n this.localInventory = new PinterestLocalInventory(client, this.localStores, media);\n this.campaignBudgets = new PinterestCampaignBudgets(client, (account, id) => this.getCampaign(account, id), () => { const value = (media as { scopeId?: unknown }).scopeId;return typeof value === 'string' && value ? value : 'local'; });\n }\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions {\n return { pauseCampaign: (accountId, campaignId) => ({ tool: 'pinterest_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) };\n }\n private async collect<T extends { id: string }>(path: string, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T[]> {\n const result: T[] = [], bookmarks = new Set<string>(), entities = new Set<string>();\n const query = new URLSearchParams(params);\n query.set('page_size', '250');\n const pageSchema = z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() });\n while (true) {\n const page = await this.client.get(path, pageSchema, query);\n for (const item of page.items) {\n if (entities.has(item.id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: pagination repeated an entity');\n entities.add(item.id); result.push(item);\n }\n if (!page.bookmark) return result;\n if (bookmarks.has(page.bookmark) || bookmarks.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'pinterest: pagination did not terminate');\n bookmarks.add(page.bookmark); query.set('bookmark', page.bookmark);\n }\n }\n async listAccounts(): Promise<Account[]> {\n return (await this.collect('ad_accounts', accountSchema)).map(a => ({ provider: this.id, id: a.id, name: a.name ?? a.id, ...(a.currency ? { currency: a.currency } : {}) }));\n }\n async listCampaigns(accountId: string) {\n return this.listEntities(accountId, 'campaigns', campaignSchema);\n }\n private async listEntities<T extends z.infer<typeof entitySchema>>(accountId: string, collection: string, schema: z.ZodType<T>) {\n const params = new URLSearchParams();\n // Live v5 requires CSV arrays; repeated status parameters select only the\n // final value despite the specification's omitted explode annotation.\n params.set('entity_statuses', entityStatus.options.join(','));\n const rows = await this.collect(`ad_accounts/${pinterestId.parse(accountId)}/${collection}`, schema, params);\n if (rows.some(row => row.ad_account_id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: entity account mismatch');\n return rows;\n }\n async getCampaign(accountId: string, campaignId: string) {\n const result = await this.client.get(`ad_accounts/${pinterestId.parse(accountId)}/campaigns/${pinterestId.parse(campaignId)}`, campaignSchema);\n if (result.id !== campaignId || result.ad_account_id !== accountId) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign account/ID mismatch');\n return result;\n }\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const start = z.iso.date().parse(range.start), end = z.iso.date().parse(range.end);\n const days = (Date.parse(end) - Date.parse(start)) / 86_400_000;\n if (days < 0 || days > 90) throw new AdportError('INVALID_INPUT', 'pinterest: report end must be on/after start and within 90 days');\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'pinterest: report limit must be a positive integer');\n const level = LEVEL[query.level], fields = new Set<string>();\n for (const metric of query.metrics) {\n if (metric in FIELDS) fields.add(FIELDS[metric as keyof typeof FIELDS]);\n else if (metric in DERIVED) for (const dependency of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) fields.add(FIELDS[dependency as keyof typeof FIELDS]);\n }\n if (!fields.size) throw new AdportError('INVALID_INPUT', 'pinterest: report requires at least one supported metric');\n const rows: ReportRow[] = [];\n for (const id of [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))]) {\n const accountId = pinterestId.parse(id), base = `ad_accounts/${accountId}`;\n const entities = query.level === 'account'\n ? [await this.client.get(base, accountSchema)]\n : await this.listEntities(accountId, level.path, entitySchema);\n if (query.level === 'account' && entities.some(e => e.id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: account ID mismatch');\n const lookup = new Map(entities.map(e => [e.id, e]));\n const seen = new Set<string>();\n for (let offset = 0; offset < entities.length; offset += 250) {\n const batch = entities.slice(offset, offset + 250), allowed = new Set(batch.map(e => e.id));\n const params = new URLSearchParams({\n start_date: start, end_date: end, granularity: 'TOTAL', columns: [level.id, ...fields].join(','),\n click_window_days: '30', view_window_days: '1', conversion_report_time: 'TIME_OF_AD_ACTION',\n });\n if (level.filter) params.set(level.filter, batch.map(entity => entity.id).join(','));\n const data = await this.client.get(`${base}/${level.path ? `${level.path}/` : ''}analytics`, z.array(z.record(z.string(), z.unknown())), params);\n for (const row of data) {\n const entityId = pinterestId.parse(row[level.id]);\n if (!allowed.has(entityId) || seen.has(entityId)) throw new AdportError('PROVIDER_ERROR', 'pinterest: incorrectly scoped or duplicate report row');\n seen.add(entityId);\n const entity = lookup.get(entityId)!;\n rows.push({ provider: this.id, accountId, entity: { level: query.level, id: entityId, name: entity.name ?? entityId, ...(typeof entity.status === 'string' ? { status: entity.status } : {}) }, metrics: normalize(row, query.metrics) });\n if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };\n }\n }\n }\n return { rows };\n }\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, resultDetails: _details, resultWarnings: _warnings, ...preview } = await this.plan(op, guard);\n return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard), resourceIds = await plan.execute();\n return { applied: true, resourceIds, ...(plan.resultDetails ? { details: plan.resultDetails() } : {}), ...(plan.resultWarnings ? { warnings: plan.resultWarnings() } : {}) };\n }\n private async write(accountId: string, method: 'POST' | 'PATCH', body: Record<string, unknown>) {\n const result = await this.client.mutate(`ad_accounts/${accountId}/campaigns`, method, [body], batchResponseSchema);\n const item = result.items[0];\n if (result.items.length !== 1 || !item?.data || item.exceptions?.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign batch item failed; inspect account before retrying');\n const parsed = campaignSchema.safeParse(item.data);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign batch returned incomplete data; inspect account before retrying');\n const data = parsed.data;\n if (data.ad_account_id !== accountId || (body.id && data.id !== body.id)\n || Object.entries(body).some(([key, value]) => ['status', 'daily_spend_cap', 'lifetime_spend_cap'].includes(key) && data[key] !== value)) {\n throw new AdportError('PROVIDER_ERROR', 'pinterest: campaign write response mismatch; inspect before retrying');\n }\n return [data.id];\n }\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const accountId = pinterestId.parse(op.accountId);\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'pinterest: provider mismatch');\n if (this.measurement.supports(op.tool)) return this.measurement.plan(op);\n if (this.catalogs.supports(op.tool)) return this.catalogs.plan(op);\n if (this.catalogItems.supports(op.tool)) return this.catalogItems.plan(op);\n if (this.localStores.supports(op.tool)) return this.localStores.plan(op);\n if (this.localInventory.supports(op.tool)) return this.localInventory.plan(op);\n if (this.campaignBudgets.supports(op.tool)) return this.campaignBudgets.plan(op);\n if (['pinterest_create_product_group', 'pinterest_update_product_group', 'pinterest_delete_product_group'].includes(op.tool)) return this.productGroups.plan(op);\n if (this.keywords.supports(op.tool)) return this.keywords.plan(op, guard);\n if (this.audiences.supports(op.tool)) return this.audiences.plan(op);\n if (PINTEREST_ASSET_WRITES.has(op.tool)) return this.assets.plan(op);\n if (op.tool === 'pinterest_create_campaign' && op.kind === 'create') {\n const input = createCampaignSchema.parse(op.payload);\n if (input.daily_budget_mode === 'AVERAGE') return this.campaignBudgets.create(input, op, guard);\n const { budget_type, budget_micros, daily_budget_mode: _mode, acknowledge_variable_daily_spend: _ack, ...rest } = input;\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const cap = budget_type === 'DAILY' ? 'daily_spend_cap' : 'lifetime_spend_cap';\n const body = { ...rest, status, [cap]: budget_micros, is_campaign_budget_optimization: true, is_flexible_daily_budgets: false };\n return {\n summary: `Create Pinterest campaign \"${input.name}\"`, changes: [`+ ${JSON.stringify(body)}`],\n coercions: status !== input.status ? ['status coerced to PAUSED by policy (paused_creation)'] : [],\n budgetDeltas: [{ target: `new campaign ${budget_type} budget`, toMicros: budget_micros }],\n execute: () => this.write(accountId, 'POST', body),\n };\n }\n if (op.kind === 'update' && ['pinterest_set_campaign_status', 'pinterest_set_budget'].includes(op.tool)) {\n const input = op.tool === 'pinterest_set_budget' ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);\n const current = await this.getCampaign(accountId, input.campaign_id);\n if ('budget_micros' in input) {\n const daily = current.daily_spend_cap ?? 0, lifetime = current.lifetime_spend_cap ?? 0;\n if (!current.is_campaign_budget_optimization || (daily > 0) === (lifetime > 0)) throw new AdportError('INVALID_INPUT', 'pinterest: campaign budget update requires CBO with exactly one existing daily/lifetime cap');\n if (current.is_flexible_daily_budgets) throw new AdportError('INVALID_INPUT', 'pinterest: use pinterest_campaign_budget_context and pinterest_set_campaign_daily_budget with variable-spend/reset acknowledgements for an average daily budget');\n if (daily > 0 && typeof current.is_flexible_daily_budgets !== 'boolean') throw new AdportError('INVALID_INPUT', 'pinterest: daily budget mode is unconfirmed; read pinterest_campaign_budget_context');\n const cap = daily > 0 ? 'daily_spend_cap' : 'lifetime_spend_cap', from = daily || lifetime;\n return {\n summary: `Change Pinterest campaign \"${current.name ?? current.id}\" budget`, changes: [`~ ${current.id} ${cap}: ${from} → ${input.budget_micros} micros`], coercions: [],\n budgetDeltas: [{ target: `campaign ${current.id} ${cap}`, fromMicros: from, toMicros: input.budget_micros }],\n execute: () => this.write(accountId, 'PATCH', { id: current.id, [cap]: input.budget_micros }),\n };\n }\n return {\n summary: `Change Pinterest campaign \"${current.name ?? current.id}\" status`, changes: [`~ ${current.id} status: ${current.status ?? 'unknown'} → ${input.status}`], coercions: [], budgetDeltas: [],\n execute: () => this.write(accountId, 'PATCH', { id: current.id, status: input.status }),\n };\n }\n return this.creatives.plan(op, guard);\n }\n}\n\nfunction normalize(row: Record<string, unknown>, requested: MetricName[]) {\n const mapped: Partial<Record<MetricName, number>> = {};\n for (const [metric, field] of Object.entries(FIELDS)) {\n const value = row[field];\n if (value === null || value === undefined) continue;\n const number = typeof value === 'number' ? value : typeof value === 'string' && /^\\d+(?:\\.\\d+)?$/.test(value) ? Number(value) : NaN;\n if (!Number.isFinite(number) || number < 0) throw new AdportError('PROVIDER_ERROR', `pinterest: malformed ${field} metric`);\n // MICRO_DOLLAR is Pinterest's historical field name; units are always\n // micros of the advertiser's account currency, not necessarily USD.\n mapped[metric as MetricName] = number / (metric === 'spend' || metric === 'conversion_value' ? 1_000_000 : 1);\n }\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) {\n if (mapped[numerator] !== undefined && mapped[denominator] !== undefined) mapped[metric as MetricName] = mapped[denominator] ? mapped[numerator]! / mapped[denominator]! * factor : 0;\n }\n return Object.fromEntries(requested.filter(metric => mapped[metric] !== undefined).map(metric => [metric, mapped[metric]]));\n}\n","import { AdportError, creativeStatusAction, type Creative, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport { createAd, createGroup, updateAd, updateGroup } from './creative-tools.js';\nimport { campaignSchema, pinterestId } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ninterface Page { account_id: string; page_size: number; bookmark?: string }\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst object = z.record(z.string(), z.unknown());\nconst response = z.looseObject({ id: pinterestId, ad_account_id: pinterestId.optional() });\nfunction record(value: unknown): Row { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Row : {}; }\nfunction query(input: Row) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(input)) if (value !== undefined) params.set(key, Array.isArray(value) ? value.map(String).join(',') : String(value)); return params; }\nfunction safeUrl(value: unknown): string[] { if (typeof value !== 'string') return []; try { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password ? [value] : []; } catch { return []; } }\n\n/** Native batch and targeting contracts from Pinterest-owned v5 OpenAPI5.28.0. */\nexport class PinterestCreativeService {\n constructor(private readonly client: PinterestAdsClient, private readonly campaign: (account: string, id: string) => Promise<z.infer<typeof campaignSchema>>) {}\n private base(account: string) { return `ad_accounts/${pinterestId.parse(account)}`; }\n async read(account: string, path: string) { return this.client.get(`${this.base(account)}/${path}`, object); }\n async getEntity(account: string, entity: 'campaigns' | 'ad_groups' | 'ads', id: string) { return this.owned(account, entity, id); }\n async page(input: Page & Row, collection: 'ad_groups' | 'ads' | 'audiences') {\n const { account_id, ...params } = input;\n const data = await this.client.get(`${this.base(account_id)}/${collection}`, z.looseObject({ items: z.array(response), bookmark: z.string().nullable().optional() }), query({ ...params, ...(collection !== 'audiences' && !params.entity_statuses ? { entity_statuses: ['ACTIVE', 'PAUSED', 'ARCHIVED', 'DRAFT', 'DELETED_DRAFT'] } : {}) }));\n if (data.items.some(row => row.ad_account_id !== undefined && row.ad_account_id !== account_id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: collection returned a foreign account');\n if (data.bookmark && data.bookmark === input.bookmark) throw new AdportError('PROVIDER_ERROR', 'pinterest: pagination repeated a bookmark');\n return { ...data, truncated: Boolean(data.bookmark), ...(data.bookmark ? { next_cursor: data.bookmark } : {}) };\n }\n async ads(input: Page & Row) {\n const { include_pin_details, ...filters } = input;\n const data = await this.page(filters, 'ads');\n const pins = new Map<string, Row>(), warnings: Array<{ provider: string; message: string }> = [];\n if (include_pin_details) {\n const ids = [...new Set(data.items.map(ad => typeof ad.pin_id === 'string' && /^\\d{1,30}$/.test(ad.pin_id) ? ad.pin_id : '').filter(Boolean))];\n let cursor = 0, denied = false;\n await Promise.all(Array.from({ length: Math.min(4, ids.length) }, async () => {\n while (cursor < ids.length && !denied) {\n const id = ids[cursor++]!;\n try {\n const pin = await this.client.get(`pins/${id}`, z.looseObject({ id: z.string().regex(/^\\d+$/) }), query({ ad_account_id: input.account_id }));\n if (pin.id !== id) throw new AdportError('PROVIDER_ERROR', 'pinterest: referenced Pin response ID mismatch');\n pins.set(id, pin);\n } catch (error) {\n const forbidden = error instanceof AdportError && record(error.details).http_status === 403;\n if (forbidden) denied = true;\n 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'}`;\n if (!warnings.some(warning => warning.message === message)) warnings.push({ provider: 'pinterest', message });\n }\n }\n }));\n }\n const creatives: Creative[] = data.items.map(ad => {\n const status = typeof ad.status === 'string' ? ad.status : '', args = { account_id: input.account_id, ad_id: ad.id };\n const pin = pins.get(String(ad.pin_id));\n 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) ? [] : [\n ...(['ACTIVE', 'PAUSED'].includes(status) ? [creativeStatusAction('pinterest_set_ad_status', args, status, ['ACTIVE', 'PAUSED'])] : []),\n { 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' as const, value: ad.destination_url, max_length: 2048 }] : [])] },\n ] };\n });\n return { ...data, creatives, warnings };\n }\n async targetingOptions(account: string, type: string) { return this.client.get(`resources/targeting/${type}`, z.array(object), query({ ad_account_id: pinterestId.parse(account) })); }\n async estimate(input: { account_id: string } & Row) { const { account_id, ...body } = input; return this.client.mutate(`${this.base(account_id)}/ad_groups/audience_sizing`, 'POST', body, object); }\n\n private async owned(account: string, collection: 'campaigns' | 'ad_groups' | 'ads', id: string): Promise<Row> {\n if (collection === 'campaigns') return this.campaign(account, id);\n const row = await this.client.get(`${this.base(account)}/${collection}/${pinterestId.parse(id)}`, response);\n if (row.id !== id || (row.ad_account_id !== undefined && row.ad_account_id !== account)) throw new AdportError('PROVIDER_ERROR', 'pinterest: resource ID/account mismatch');\n if (collection === 'ad_groups') await this.campaign(account, pinterestId.parse(row.campaign_id));\n else {\n const parent = await this.owned(account, 'ad_groups', pinterestId.parse(row.ad_group_id));\n if (row.campaign_id !== undefined && row.campaign_id !== parent.campaign_id) throw new AdportError('PROVIDER_ERROR', 'pinterest: ad campaign hierarchy mismatch');\n }\n return row;\n }\n\n private async batch(account: string, collection: string, method: 'POST' | 'PATCH', body: Row) {\n const data = await this.client.mutate(`${this.base(account)}/${collection}`, method, [body], z.object({ items: z.array(z.object({ data: object.nullable().optional(), exceptions: z.array(z.unknown()).optional() })) }));\n const item = data.items[0], parsed = response.safeParse(item?.data);\n const ids = parsed.success ? [parsed.data.id] : [];\n if (data.items.length !== 1 || !parsed.success || item?.exceptions?.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: native batch item failed or returned incomplete data; reconcile before retrying', { resource_ids: ids });\n if ((parsed.data.ad_account_id !== undefined && parsed.data.ad_account_id !== account) || (body.id && parsed.data.id !== body.id) || (body.status !== undefined && parsed.data.status !== body.status)) throw new AdportError('PROVIDER_ERROR', 'pinterest: mutation receipt ID/account/status mismatch; reconcile before retrying', { resource_ids: ids });\n if (['campaign_id', 'ad_group_id', 'budget_in_micro_currency', 'bid_in_micro_currency'].some(key => body[key] !== undefined && parsed.data[key] !== body[key])) throw new AdportError('PROVIDER_ERROR', 'pinterest: mutation receipt parent/money mismatch; read configuration before retrying', { resource_ids: ids });\n const goals = record(body.optimization_goal_metadata), returnedGoals = record(parsed.data.optimization_goal_metadata);\n 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']]) {\n const expected = record(goals[key!])[field!], returned = record(returnedGoals[key!])[field!];\n if (expected !== undefined && (returned == null || !/^\\d+$/.test(String(returned)) || Number(returned) !== Number(expected))) throw new AdportError('PROVIDER_ERROR', 'pinterest: monetary optimization receipt mismatch; read configuration before retrying', { resource_ids: ids });\n }\n return ids;\n }\n\n private async verifyOptimization(account: string, input: unknown) {\n const tag = record(record(input).conversion_tag_v3_goal_metadata).conversion_tag_id;\n if (tag === undefined) return;\n const result = await this.client.get(`${this.base(account)}/conversion_tags/${pinterestId.parse(tag)}`, z.looseObject({ id: pinterestId, ad_account_id: pinterestId }));\n if (result.id !== tag || result.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'pinterest: conversion tag is not owned by the selected advertiser');\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const p = op.payload, account = op.accountId, coercions: string[] = [], budgetDeltas: WritePreview['budgetDeltas'] = [];\n let collection: 'campaigns' | 'ad_groups' | 'ads', body: Row, method: 'POST' | 'PATCH' = 'PATCH';\n const paused = (status: string) => { if (guard.forcePausedCreation && status !== 'PAUSED') { coercions.push('status coerced to PAUSED by policy (paused_creation)'); return 'PAUSED'; } return status; };\n switch (op.tool) {\n case 'pinterest_create_ad_group': {\n const input = createGroup.parse(p), parent = await this.campaign(account, input.campaign_id);\n if (typeof parent.is_campaign_budget_optimization !== 'boolean') throw new AdportError('INVALID_INPUT', 'pinterest: campaign CBO mode is unavailable; cannot determine budget ownership');\n if (parent.is_campaign_budget_optimization && input.budget_in_micro_currency !== undefined) throw new AdportError('INVALID_INPUT', 'pinterest: CBO campaigns own the budget; omit an ad-group budget');\n if (!parent.is_campaign_budget_optimization && input.budget_in_micro_currency === undefined) throw new AdportError('INVALID_INPUT', 'pinterest: non-CBO campaigns require an ad-group budget');\n if (parent.is_campaign_budget_optimization && input.pacing_delivery_type !== 'STANDARD') throw new AdportError('INVALID_INPUT', 'pinterest: CBO permits only STANDARD pacing');\n if (input.budget_type === 'LIFETIME' && !input.end_time) throw new AdportError('INVALID_INPUT', 'pinterest: lifetime budgets require end_time');\n if (input.lifetime_frequency_cap && !input.end_time) throw new AdportError('INVALID_INPUT', 'pinterest: a frequency cap requires end_time');\n checkTargeting(input.targeting_spec);\n await this.verifyOptimization(account, input.optimization_goal_metadata);\n body = { ...input, status: paused(input.status), ...(input.budget_in_micro_currency !== undefined ? { budget_type: input.budget_type ?? 'DAILY' } : {}) };\n collection = 'ad_groups'; method = 'POST'; moneyDeltas(body, {}, `new ad group ${input.name}`, budgetDeltas); break;\n }\n case 'pinterest_create_ad': {\n const input = createAd.parse(p); await this.owned(account, 'ad_groups', input.ad_group_id);\n collection = 'ads'; method = 'POST'; body = { ...input, status: paused(input.status) }; break;\n }\n case 'pinterest_update_ad_group': {\n const input = updateGroup.parse(p), { ad_group_id, ...fields } = input, current = await this.owned(account, 'ad_groups', ad_group_id);\n body = { id: ad_group_id, ...fields };\n if (fields.targeting_spec) { body.targeting_spec = { ...record(current.targeting_spec), ...fields.targeting_spec }; checkTargeting(body.targeting_spec); }\n if (fields.optimization_goal_metadata) {\n await this.verifyOptimization(account, fields.optimization_goal_metadata);\n const previous = record(current.optimization_goal_metadata), merged: Row = { ...previous, ...fields.optimization_goal_metadata };\n for (const [key, value] of Object.entries(fields.optimization_goal_metadata)) merged[key] = { ...record(previous[key]), ...record(value) };\n body.optimization_goal_metadata = merged;\n }\n const effective = { ...current, ...body };\n if (effective.start_time && effective.end_time && Number(effective.end_time) <= Number(effective.start_time)) throw new AdportError('INVALID_INPUT', 'pinterest: end_time must follow start_time');\n moneyDeltas(body, current, `ad group ${ad_group_id}`, budgetDeltas); collection = 'ad_groups'; break;\n }\n case 'pinterest_update_ad': {\n const input = updateAd.parse(p), { ad_id, ...fields } = input, current = await this.owned(account, 'ads', ad_id);\n if (input.pin_id !== undefined && current.status !== 'DRAFT') throw new AdportError('INVALID_INPUT', 'pinterest: pin_id can only be replaced on DRAFT ads. Create a new paused ad for a different Pin.');\n collection = 'ads'; body = { id: ad_id, ...fields }; break;\n }\n case 'pinterest_set_ad_status':\n case 'pinterest_set_ad_group_status': {\n collection = op.tool === 'pinterest_set_ad_status' ? 'ads' : 'ad_groups';\n const id = pinterestId.parse(p[collection === 'ads' ? 'ad_id' : 'ad_group_id']); await this.owned(account, collection, id);\n body = { id, status: z.enum(['ACTIVE', 'PAUSED']).parse(p.status) }; break;\n }\n case 'pinterest_set_ad_group_budget': {\n const id = pinterestId.parse(p.ad_group_id), current = await this.owned(account, 'ad_groups', id), parent = await this.campaign(account, String(current.campaign_id));\n if (parent.is_campaign_budget_optimization) throw new AdportError('INVALID_INPUT', 'pinterest: this ad group uses the campaign’s CBO budget');\n if (!['DAILY', 'LIFETIME'].includes(String(current.budget_type)) || typeof current.budget_in_micro_currency !== 'number') throw new AdportError('INVALID_INPUT', 'pinterest: current ad-group budget/type is unavailable');\n collection = 'ad_groups'; body = { id, budget_in_micro_currency: z.number().int().positive().safe().parse(p.budget_micros) }; moneyDeltas(body, current, `ad group ${id}`, budgetDeltas); break;\n }\n case 'pinterest_set_ad_group_bidding': {\n const id = pinterestId.parse(p.ad_group_id), current = await this.owned(account, 'ad_groups', id);\n body = { id, ...(p.bid_strategy_type !== undefined ? { bid_strategy_type: p.bid_strategy_type } : {}), ...(p.bid_micros !== undefined ? { bid_in_micro_currency: p.bid_micros } : {}) };\n if ((body.bid_strategy_type ?? current.bid_strategy_type) === 'MAX_BID' && !(body.bid_in_micro_currency ?? current.bid_in_micro_currency)) throw new AdportError('INVALID_INPUT', 'pinterest: MAX_BID requires a monetary bid');\n moneyDeltas(body, current, `ad group ${id}`, budgetDeltas); collection = 'ad_groups'; break;\n }\n case 'pinterest_archive_entity': {\n collection = z.enum(['campaigns', 'ad_groups', 'ads']).parse(p.entity); const id = pinterestId.parse(p.resource_id); await this.owned(account, collection, id); body = { id, status: 'ARCHIVED' }; break;\n }\n default: throw new AdportError('INVALID_INPUT', `pinterest: unsupported write ${op.tool}`);\n }\n return { summary: `Pinterest ${op.tool.replace(/^pinterest_/, '').replaceAll('_', ' ')}`, changes: [`${method} ${collection}: ${JSON.stringify(body)}`], coercions, budgetDeltas, execute: () => this.batch(account, collection, method, body) };\n }\n}\n\nfunction checkTargeting(input: unknown) {\n if (!input) return;\n const target = record(input);\n if (!(Array.isArray(target.GEO) && target.GEO.length) && !(Array.isArray(target.LOCATION) && target.LOCATION.length)) throw new AdportError('INVALID_INPUT', 'pinterest: targeting requires GEO or LOCATION');\n if (Array.isArray(target.AGE_BUCKET) && target.AGE_BUCKET.length && (target.MINIMUM_AGE || target.MAXIMUM_AGE)) throw new AdportError('INVALID_INPUT', 'pinterest: choose AGE_BUCKET or minimum/maximum age');\n 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 AdportError('INVALID_INPUT', 'pinterest: minimum and maximum age must be supplied together and ordered');\n}\nexport function pinMedia(input: unknown, depth = 0): Creative['media'] {\n if (depth > 2) return [];\n const media = record(input), result: Creative['media'] = [];\n const variants = (value: unknown) => 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));\n const video = variants(media.video_list).find(item => safeUrl(item.url).some(url => url.startsWith('https:')));\n if (video) result.push({ type: 'video', url: String(video.url) });\n else {\n const image = variants(media.images).find(item => safeUrl(item.url).some(url => url.startsWith('https:')));\n if (image) result.push({ type: 'image', url: String(image.url) });\n }\n for (const item of (Array.isArray(media.items) ? media.items : []).slice(0, 10)) result.push(...pinMedia(item, depth + 1));\n return result.slice(0, 10);\n}\nfunction moneyDeltas(next: Row, current: Row, target: string, deltas: WritePreview['budgetDeltas']) {\n const amount = (label: string, value: unknown, old: unknown) => {\n const parse = (input: unknown) => { const n = typeof input === 'number' ? input : typeof input === 'string' && /^\\d+$/.test(input) ? Number(input) : NaN; if (!Number.isSafeInteger(n) || n < 0) throw new AdportError('PROVIDER_ERROR', `pinterest: invalid ${label} money value`); return n; };\n const to = parse(value);\n if (old !== undefined && old !== null) deltas.push({ target: `${target} ${label}`, fromMicros: parse(old), toMicros: to });\n else deltas.push({ target: `${target} ${label}`, toMicros: to });\n };\n for (const key of ['budget_in_micro_currency', 'bid_in_micro_currency']) if (next[key] !== undefined) amount(key, next[key], current[key]);\n const goals = record(next.optimization_goal_metadata), previous = record(current.optimization_goal_metadata);\n 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!] !== undefined) amount(field!, record(goals[key!])[field!], record(previous[key!])[field!]);\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { entityStatus, pinterestId } from './schemas.js';\n\nconst id = pinterestId, pinId = z.string().regex(/^\\d+$/).max(30), money = z.number().int().positive().safe(), strings = z.array(z.string().min(1)).max(1000);\nconst url = z.string().url().refine(value => { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) URL without embedded credentials');\nconst microsString = z.string().regex(/^\\d+$/).refine(value => Number.isSafeInteger(Number(value)), 'Micro amount must be a safe integer');\nexport const targeting = z.object({ AGE_BUCKET: strings.optional(), APPTYPE: strings.optional(), AUDIENCE_EXCLUDE: z.array(id).optional(), AUDIENCE_INCLUDE: z.array(id).optional(), GENDER: z.array(z.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: z.string().regex(/^\\d+$/).optional(), MAXIMUM_AGE: z.string().regex(/^\\d+\\+?$/).optional(), TARGETING_STRATEGY: strings.optional() }).strict();\nexport const optimization = z.object({ conversion_tag_v3_goal_metadata: z.object({ conversion_tag_id: id.optional(), conversion_event: z.string().min(1).optional(), cpa_goal_value_in_micro_currency: microsString.optional(), is_roas_optimized: z.boolean().optional(), reporting_event: z.string().optional() }).strict().optional(), frequency_goal_metadata: z.object({ frequency: z.number().int().min(2).max(20), timerange: z.enum(['THIRTY_DAY', 'DAY', 'SEVEN_DAY', 'TWENTY_MINUTE', 'TEN_MINUTE', 'TWENTY_FOUR_HOUR']) }).strict().optional(), scrollup_goal_metadata: z.object({ scrollup_goal_value_in_micro_currency: microsString }).strict().optional() }).strict();\nconst bidStrategy = z.enum(['AUTOMATIC_BID', 'MAX_BID', 'TARGET_AVG']);\nconst groupFields = { name: z.string().trim().min(1).max(255).optional(), targeting_spec: targeting.optional(), auto_targeting_enabled: z.boolean().optional(), placement_group: z.enum(['ALL', 'SEARCH', 'BROWSE', 'OTHER']).optional(), start_time: z.number().int().positive().safe().optional(), end_time: z.number().int().positive().safe().optional(), lifetime_frequency_cap: z.number().int().positive().optional(), optimization_goal_metadata: optimization.optional() };\nexport const createGroup = z.object({ ...groupFields, name: z.string().trim().min(1).max(255), targeting_spec: targeting, auto_targeting_enabled: z.boolean().default(false), campaign_id: id, billable_event: z.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: z.enum(['DAILY', 'LIFETIME']).optional(), pacing_delivery_type: z.enum(['STANDARD', 'ACCELERATED']).default('STANDARD'), status: z.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');\nexport const updateGroup = z.object({ ad_group_id: id, ...groupFields }).refine(v => Object.keys(v).length > 1, 'Provide an ad-group field');\nexport const createAd = z.object({ ad_group_id: id, pin_id: pinId, creative_type: z.enum(['REGULAR', 'VIDEO', 'SHOPPING', 'CAROUSEL', 'MAX_VIDEO', 'COLLECTION', 'IDEA', 'SHOWCASE', 'QUIZ', 'COLLAGE', 'MAX_WIDTH_REGULAR_COLLECTION', 'MAX_WIDTH_VIDEO_COLLECTION', 'APP']), name: z.string().min(1).max(255), destination_url: url.optional(), click_tracking_url: url.optional(), view_tracking_url: url.optional(), status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED') });\nexport const updateAd = z.object({ ad_id: id, name: z.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');\nconst page = { page_size: z.number().int().positive().max(250).default(50), bookmark: z.string().min(1).optional() };\nconst account = { account_id: id };\nconst ids = z.array(id).min(1).max(250);\n\nexport function pinterestCreativeTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (input: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'pinterest', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' = 'update') => guardedWriteTool({ name, namespace: 'pinterest', provider: 'pinterest', description, payload, kind });\n return [\n read('pinterest_get_entity', 'Read a campaign, ad group or ad by ID through the native resource endpoint, verifying advertiser and parent ownership.', z.object({ ...account, entity: z.enum(['campaigns', 'ad_groups', 'ads']), resource_id: id }), input => provider.creatives.getEntity(input.account_id, input.entity, input.resource_id)),\n read('pinterest_ad_groups', 'Read advertiser ad-group targeting, budgets, bids and schedules with native bookmark pagination.', z.object({ ...account, campaign_ids: ids.optional(), ad_group_ids: ids.optional(), entity_statuses: z.array(entityStatus).optional(), ...page }), input => provider.creatives.page(input, 'ad_groups')),\n 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: z.object({ ...account, campaign_ids: ids.optional(), ad_group_ids: ids.optional(), ad_ids: ids.optional(), entity_statuses: z.array(entityStatus).optional(), include_pin_details: z.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) }),\n read('pinterest_targeting_options', 'Read native targeting resources for the selected advertiser; returns provider codes and labels.', z.object({ ...account, targeting_type: z.enum(['APPTYPE', 'GENDER', 'LOCALE', 'AGE_BUCKET', 'LOCATION', 'GEO', 'INTEREST', 'KEYWORD', 'AUDIENCE_INCLUDE', 'AUDIENCE_EXCLUDE']) }), input => provider.creatives.targetingOptions(input.account_id, input.targeting_type)),\n read('pinterest_audience_estimate', 'Get a native non-binding audience-size estimate via read-only POST. No targeting or delivery changes.', z.object({ ...account, targeting_spec: targeting, auto_targeting_enabled: z.boolean(), placement_group: z.enum(['ALL', 'SEARCH', 'BROWSE', 'OTHER']).default('ALL') }), input => provider.creatives.estimate(input)),\n write('pinterest_create_ad_group', 'Create a verified campaign’s ad group, paused by policy. Budgets/bids are integer account-currency micros; non-CBO campaigns require an ad-group budget.', createGroup, 'create'),\n write('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),\n write('pinterest_create_ad', 'Create a paused advertiser ad using an existing eligible Pin. This does not edit or publish an organic Pin.', createAd, 'create'),\n write('pinterest_update_ad', 'Patch the verified advertiser ad’s name/destination/tracking fields. Pin replacement is allowed only for DRAFT ads; existing Pins remain unchanged.', updateAd),\n ...(['ad_group', 'ad'] as const).map(entity => write(`pinterest_set_${entity}_status`, 'Pause or activate an account-owned child entity after checking its parent hierarchy.', z.object({ [entity === 'ad' ? 'ad_id' : 'ad_group_id']: id, status: z.enum(['PAUSED', 'ACTIVE']) }))),\n write('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.', z.object({ ad_group_id: id, budget_micros: money })),\n write('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.', z.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')),\n write('pinterest_archive_entity', 'Archive a verified advertiser campaign, ad group or ad through native batch PATCH. This does not delete an original Pin.', z.object({ entity: z.enum(['campaigns', 'ad_groups', 'ads']), resource_id: id })),\n ];\n}\n","import { z } from 'zod';\n\n// Pinterest's official OpenAPI 5.28.0, reviewed 2026-08-31.\nexport const pinterestId = z.string().regex(/^\\d+$/).max(18);\nexport const entityStatus = z.enum(['ACTIVE', 'PAUSED', 'ARCHIVED', 'DRAFT', 'DELETED_DRAFT']);\nconst micros = z.number().int().nonnegative().safe();\nexport const accountSchema = z.looseObject({ id: pinterestId, name: z.string().optional(), currency: z.string().optional() });\nexport const entitySchema = z.looseObject({ id: pinterestId, ad_account_id: pinterestId, name: z.string().nullable().optional(), status: entityStatus.optional() });\nexport const campaignSchema = entitySchema.extend({\n daily_spend_cap: micros.nullable().optional(), lifetime_spend_cap: micros.nullable().optional(),\n is_campaign_budget_optimization: z.boolean().nullable().optional(),\n is_flexible_daily_budgets: z.boolean().nullable().optional(),\n});\nexport const batchResponseSchema = z.object({ items: z.array(z.object({\n data: campaignSchema.partial().optional(), exceptions: z.array(z.unknown()).optional(),\n})) });\nexport const createCampaignSchema = z.object({\n name: z.string().trim().min(1).max(255),\n objective_type: z.enum(['AWARENESS', 'CONSIDERATION', 'WEB_CONVERSION', 'CATALOG_SALES', 'VIDEO_COMPLETION', 'APP_INSTALL', 'SALES', 'LEADS', 'CTV_CONSIDERATION']),\n status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED'),\n budget_type: z.enum(['DAILY', 'LIFETIME']).default('DAILY'),\n daily_budget_mode: z.enum(['FIXED', 'AVERAGE']).default('FIXED'),\n acknowledge_variable_daily_spend: z.literal(true).optional(),\n budget_micros: micros.positive(),\n start_time: z.number().int().positive().safe().optional(),\n end_time: z.number().int().positive().safe().optional(),\n app_id: z.string().min(1).optional(), app_platform: z.enum(['IOS', 'ANDROID']).optional(),\n}).superRefine((value, ctx) => {\n 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.' });\n if (value.budget_type === 'LIFETIME' && !value.end_time) ctx.addIssue({ code: 'custom', path: ['end_time'], message: 'Lifetime campaign budgets require an end time.' });\n 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.' });\n 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.' });\n});\nexport const setStatusSchema = z.object({ campaign_id: pinterestId, status: z.enum(['PAUSED', 'ACTIVE']) });\nexport const setBudgetSchema = z.object({ campaign_id: pinterestId, budget_micros: micros.positive() });\n","import { createHash } from 'node:crypto';\nimport { AdportError, LocalMediaResolver, creativesOutput, defineTool, guardedWriteTool, mediaSourceFields, type AnyToolDefinition, type Creative, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestId } from './schemas.js';\nimport { pinMedia } from './creatives.js';\n\nconst id = z.string().regex(/^\\d+$/).max(30), hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst privacy = z.enum(['PUBLIC', 'PROTECTED', 'SECRET']);\nconst username = z.string().min(1), owner = z.object({ username });\nconst boardSchema = z.looseObject({ id, name: z.string(), description: z.string().nullable().optional(), privacy, owner, is_ads_only: z.boolean().optional(), pin_count: z.number().int().nonnegative().optional(), collaborator_count: z.number().int().nonnegative().optional(), follower_count: z.number().int().nonnegative().optional() });\nconst pinSchema = z.looseObject({ id, board_id: id, title: z.string().nullable().optional(), description: z.string().nullable().optional(), alt_text: z.string().nullable().optional(), link: z.string().nullable().optional(), is_owner: z.boolean().optional(), has_been_promoted: z.boolean().optional() });\nconst mediaSchema = z.object({ media_id: id, media_type: z.literal('video'), status: z.enum(['registered', 'processing', 'succeeded', 'failed']) });\nconst source = z.object(mediaSourceFields).refine(v => Boolean(v.media_id) !== Boolean(v.file_path), 'Choose project media_id or local file_path');\nconst link = z.string().max(2048).url().refine(value => { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password; }, 'Use an HTTP(S) destination without credentials');\nconst copy = { title: z.string().max(100).nullable().optional(), description: z.string().max(800).nullable().optional(), alt_text: z.string().max(500).nullable().optional(), link: link.nullable().optional() };\nconst pinCreation = { board_id: id, expected_board_privacy: privacy, original_content: z.literal(true), confirm_publication: z.boolean().default(false), ...copy };\nconst createImage = source.safeExtend(pinCreation);\nconst createVideo = z.object({ ...pinCreation, native_media_id: id, cover_image_key_frame_time: z.number().int().nonnegative().safe().default(0) });\nconst createBoard = z.object({ name: z.string().trim().min(1).max(180), description: z.string().max(500).optional(), privacy: privacy.default('SECRET'), confirm_publication: z.boolean().default(false) });\nconst boardReference = { board_id: id, expected_snapshot_hash: hash };\nconst updateBoard = z.object({ ...boardReference, name: z.string().trim().min(1).max(180).optional(), description: z.string().max(500).nullable().optional() }).strict().refine(v => v.name !== undefined || v.description !== undefined, 'Provide a board name or description');\nconst deleteEmptyBoard = z.object({ ...boardReference, confirm_permanent_deletion: z.literal(true) }).strict();\nconst updatePin = z.object({ pin_id: id, expected_snapshot_hash: hash, ...copy }).strict().refine(v => Object.keys(copy).some(key => v[key as keyof typeof v] !== undefined), 'Provide Pin copy to update');\nconst deletePin = z.object({ pin_id: id, expected_snapshot_hash: hash }).strict();\nconst 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' } as const;\nexport const PINTEREST_ASSET_WRITES = new Set(Object.keys(kinds));\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]> };\ntype Page = { account_id: string; page_size: number; bookmark?: string };\ntype Pin = z.infer<typeof pinSchema>;\ntype Board = z.infer<typeof boardSchema>;\nfunction boardSnapshot(board: Board) {\n 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');\n}\nfunction snapshot(pin: Pin, board: z.infer<typeof boardSchema>) {\n 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');\n}\nfunction copyFields(input: Record<string, unknown>) { return Object.fromEntries(Object.keys(copy).filter(key => input[key] !== undefined).map(key => [key, input[key]])); }\nfunction plan(summary: string, changes: string[], execute: Plan['execute']): Plan { 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 }; }\n\n/** Contracts from Pinterest-owned v5 OpenAPI 5.28.0, fetched 2026-11-04. */\nexport class PinterestAssetService {\n constructor(private readonly client: PinterestAdsClient, private readonly media: MediaResolver = new LocalMediaResolver()) {}\n private params(account: string) { return new URLSearchParams({ ad_account_id: pinterestId.parse(account) }); }\n private async account(account: string) {\n const current = await this.client.get(`ad_accounts/${pinterestId.parse(account)}`, z.object({ id: pinterestId, owner }));\n if (current.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: advertiser response ID mismatch');\n return current;\n }\n private async ownedBoard(account: string, boardId: string) {\n const current = await this.account(account);\n const board = await this.client.get(`boards/${id.parse(boardId)}`, boardSchema, this.params(account));\n if (board.id !== boardId || board.owner.username.toLowerCase() !== current.owner.username.toLowerCase()) throw new AdportError('INVALID_INPUT', 'pinterest: board is not owned by the selected advertiser; collaborator boards are not writable through this workflow');\n return board;\n }\n private async nativeOwner(account: string) {\n const current = await this.account(account);\n // /media has no ad_account_id parameter: bind this credential-global resource\n // to the selected advertiser, rather than silently using the token user's library.\n const tokenOwner = await this.client.get('user_account', z.object({ username }));\n if (current.owner.username.toLowerCase() !== tokenOwner.username.toLowerCase()) throw new AdportError('INVALID_INPUT', 'pinterest: native video uploads belong to the token user; the selected advertiser must have that same owner');\n }\n private async page<T>(path: string, schema: z.ZodType<T>, input: Page, params: URLSearchParams) {\n params.set('page_size', String(input.page_size));\n if (input.bookmark) params.set('bookmark', input.bookmark);\n const data = await this.client.get(path, z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() }), params);\n if (data.items.length > input.page_size || data.bookmark && (data.bookmark === input.bookmark || !data.items.length)) throw new AdportError('PROVIDER_ERROR', 'pinterest: media pagination did not advance');\n return { ...data, truncated: Boolean(data.bookmark), ...(data.bookmark ? { next_cursor: data.bookmark } : {}) };\n }\n async boards(input: Page & { privacy?: 'ALL' | 'PUBLIC' | 'PROTECTED' | 'SECRET' | 'PUBLIC_AND_SECRET' }) {\n const current = await this.account(input.account_id), params = this.params(input.account_id);\n if (input.privacy) params.set('privacy', input.privacy);\n const result = await this.page('boards', boardSchema, input, params);\n return { ...result, items: result.items.map(board => ({ ...board, owned_by_advertiser: board.owner.username.toLowerCase() === current.owner.username.toLowerCase() })) };\n }\n async getBoard(account: string, boardId: string) {\n const board = await this.ownedBoard(account, boardId), snapshotHash = boardSnapshot(board);\n const creative: Creative = { id: board.id, provider: 'pinterest', account_id: account, 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: account, board_id: board.id, expected_snapshot_hash: snapshotHash }, fields: [...(board.is_ads_only === true || board.privacy === 'PROTECTED' ? [] : [{ key: 'name', label: 'Board name', type: 'text' as const, value: board.name, max_length: 180 }]), { key: 'description', label: 'Description', type: 'text', value: board.description ?? '', max_length: 500 }] }] };\n 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.'] };\n }\n private async requireEmptyBoard(account: string, board: Board) {\n if (board.privacy !== 'SECRET' || board.is_ads_only !== false || board.pin_count !== 0 || board.collaborator_count !== 0 || board.follower_count !== 0) throw new AdportError('INVALID_INPUT', 'pinterest: empty-board deletion requires an explicitly SECRET, non-ad-only board with known zero Pins, collaborators and followers');\n const input = { account_id: account, page_size: 1 };\n const pins = await this.page(`boards/${board.id}/pins`, pinSchema, input, this.params(account));\n const sections = await this.page(`boards/${board.id}/sections`, z.object({ id: id.optional(), name: z.string() }), input, this.params(account));\n if (pins.items.length || pins.truncated || sections.items.length || sections.truncated) throw new AdportError('INVALID_INPUT', 'pinterest: board still contains Pins or sections; empty-board deletion does not remove content');\n }\n async getPin(account: string, pinId: string) {\n const pin = await this.client.get(`pins/${id.parse(pinId)}`, pinSchema, this.params(account));\n if (pin.id !== pinId) throw new AdportError('PROVIDER_ERROR', 'pinterest: Pin response ID mismatch');\n const board = await this.ownedBoard(account, pin.board_id);\n const snapshotHash = snapshot(pin, board);\n const creative: Creative = { id: pin.id, provider: 'pinterest', account_id: account, 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: account, 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' as const, value: pin.link, max_length: 2048 }] : [])] }] : [] };\n return { pin, board, snapshot_hash: snapshotHash, creatives: [creative], truncated: false };\n }\n async pins(input: Page & { board_id?: string }) {\n if (input.board_id) await this.ownedBoard(input.account_id, input.board_id); else await this.account(input.account_id);\n const data = await this.page(input.board_id ? `boards/${input.board_id}/pins` : 'pins', pinSchema, input, this.params(input.account_id));\n if (input.board_id && data.items.some(pin => pin.board_id !== input.board_id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: Pin collection returned another board');\n const creatives: Creative[] = 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: [] }));\n 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.'] };\n }\n async getMedia(account: string, mediaId: string) {\n await this.nativeOwner(account);\n const current = await this.client.get(`media/${id.parse(mediaId)}`, mediaSchema);\n if (current.media_id !== mediaId) throw new AdportError('PROVIDER_ERROR', 'pinterest: media response ID mismatch');\n return current;\n }\n private checkPublication(board: { privacy: string }, expected: string, confirmed: boolean) {\n if (board.privacy !== expected) throw new AdportError('PENDING_MISMATCH', 'pinterest: board privacy changed; read boards and prepare a new preview');\n if (board.privacy === 'PUBLIC' && !confirmed) throw new AdportError('INVALID_INPUT', 'pinterest: a public board publishes organic content; explicit confirm_publication is required');\n }\n private checkPinReceipt(pin: Pin, boardId: string, fields: Record<string, unknown>, pinId?: string) {\n if (pinId && pin.id !== pinId || pin.board_id !== boardId || Object.entries(fields).some(([key, value]) => (pin[key] ?? null) !== value)) throw new AdportError('PROVIDER_ERROR', 'pinterest: Pin write receipt differs from approved content; reconcile before retrying', { resource_ids: [pin.id] });\n return [pin.id];\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'pinterest' || !PINTEREST_ASSET_WRITES.has(op.tool) || op.kind !== kinds[op.tool as keyof typeof kinds]) throw new AdportError('INVALID_INPUT', 'pinterest: invalid asset operation kind');\n const account = pinterestId.parse(op.accountId), params = this.params(account);\n if (op.tool === 'pinterest_create_board') {\n const input = createBoard.parse(op.payload), current = await this.account(account);\n this.checkPublication(input, input.privacy, input.confirm_publication);\n const { confirm_publication: _confirmed, ...body } = input;\n const native = { ...body, ...(input.privacy === 'PROTECTED' ? { is_ads_only: true } : {}) };\n return plan(`Create Pinterest ${input.privacy} board`, [JSON.stringify(native), input.privacy === 'PROTECTED' ? 'Pinterest names ad-only boards “Ad-only Pins”; they are protected, not secret.' : `Board owned by ${current.owner.username}; no Pin or ad is created.`], async () => {\n const created = await this.client.mutate('boards', 'POST', native, boardSchema, params);\n if (created.owner.username.toLowerCase() !== current.owner.username.toLowerCase() || created.privacy !== input.privacy || input.privacy !== 'PROTECTED' && created.name !== input.name || input.privacy === 'PROTECTED' && created.is_ads_only !== true) throw new AdportError('PROVIDER_ERROR', 'pinterest: created board owner/privacy/name mismatch; reconcile before retrying', { resource_ids: [created.id] });\n return [created.id];\n });\n }\n if (op.tool === 'pinterest_update_board' || op.tool === 'pinterest_delete_empty_board') {\n const input = op.tool === 'pinterest_update_board' ? updateBoard.parse(op.payload) : deleteEmptyBoard.parse(op.payload), board = await this.ownedBoard(account, input.board_id);\n if (boardSnapshot(board) !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: board copy, privacy or ownership changed; read the board again');\n if (op.tool === 'pinterest_delete_empty_board') {\n await this.requireEmptyBoard(account, board);\n return plan(`Permanently delete empty Pinterest board “${board.name}”`, [`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 () => {\n // Recheck immediately before DELETE as well as when the apply plan is built.\n const fresh = await this.ownedBoard(account, board.id);\n if (boardSnapshot(fresh) !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: board changed before deletion; read it again');\n await this.requireEmptyBoard(account, fresh);\n const receipt = await this.client.mutate(`boards/${board.id}`, 'DELETE', undefined, boardSchema.optional(), params);\n if (receipt && receipt.id !== board.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: board deletion receipt ID mismatch; reconcile before retrying', { resource_ids: [board.id] });\n return [board.id];\n });\n }\n const patch = updateBoard.parse(input);\n if (patch.name !== undefined && (board.is_ads_only === true || board.privacy === 'PROTECTED')) throw new AdportError('INVALID_INPUT', 'pinterest: ad-only board names are assigned by Pinterest; edit only the description');\n const fields = { ...(patch.name !== undefined ? { name: patch.name } : {}), ...(patch.description !== undefined ? { description: patch.description } : {}) };\n const edit = plan(`Edit Pinterest board “${board.name}”`, [`Board ${board.id}; visibility ${board.privacy} is preserved. Pins, sections and delivery are unchanged.`, ...Object.entries(fields).map(([key, value]) => `${key}: ${JSON.stringify(board[key] ?? null)} → ${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 () => {\n const receipt = await this.client.mutate(`boards/${board.id}`, 'PATCH', fields, boardSchema, params);\n 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(fields).some(([key, value]) => (receipt[key] ?? null) !== value) || patch.name === undefined && receipt.name !== board.name || patch.description === undefined && (receipt.description ?? null) !== (board.description ?? null)) throw new AdportError('PROVIDER_ERROR', 'pinterest: board update receipt differs from approved copy or preserved visibility/ownership; reconcile before retrying', { resource_ids: [board.id] });\n return [board.id];\n });\n return { ...edit, fieldChanges: Object.entries(fields).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)') })) };\n }\n if (op.tool === 'pinterest_upload_video') {\n const input = source.parse(op.payload); await this.nativeOwner(account);\n const file = await this.media.read(input, { maxBytes: 50 * 1024 * 1024, contentTypes: ['video/mp4'] });\n 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 () => {\n let mediaId: string | undefined;\n try {\n const result = await this.client.mutate('media', 'POST', { media_type: 'video' }, z.object({ media_id: id, media_type: z.literal('video'), upload_url: z.string().url().optional(), upload_parameters: z.record(z.string(), z.string()).optional() }));\n mediaId = result.media_id;\n if (!result.upload_url || !result.upload_parameters) throw new Error('incomplete native upload instructions');\n await this.client.uploadVideo(result.upload_url, result.upload_parameters, file.bytes, file.name);\n } catch (error) {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n const ids = mediaId ? [mediaId] : Array.isArray(details.resource_ids) ? details.resource_ids.filter((value): value is string => typeof value === 'string' && /^\\d{1,30}$/.test(value)).slice(0, 2) : [];\n throw new AdportError('PROVIDER_ERROR', 'pinterest: native video registration/transfer was not confirmed; reconcile before retrying. No mutation was retried.', { resource_ids: ids });\n }\n return [mediaId!];\n });\n }\n if (op.tool === 'pinterest_create_image_pin' || op.tool === 'pinterest_create_video_pin') {\n const image = op.tool === 'pinterest_create_image_pin' ? createImage.parse(op.payload) : undefined, video = image ? undefined : createVideo.parse(op.payload), input = image ?? video!;\n const board = await this.ownedBoard(account, input.board_id);\n this.checkPublication(board, input.expected_board_privacy, input.confirm_publication);\n let mediaSource: Record<string, unknown>, mediaNote: string;\n if (image) {\n const file = await this.media.read(image, { maxBytes: 20 * 1024 * 1024, contentTypes: ['image/png', 'image/jpeg'] });\n mediaSource = { source_type: 'image_base64', content_type: file.contentType, data: Buffer.from(file.bytes).toString('base64') };\n mediaNote = `${file.name}; ${file.bytes.length} bytes; SHA-256 ${file.sha256}.`;\n } else {\n const native = await this.getMedia(account, video!.native_media_id);\n if (native.status !== 'succeeded') throw new AdportError('INVALID_INPUT', `pinterest: video processing is ${native.status}; only succeeded media can create a Pin`);\n mediaSource = { source_type: 'video_id', media_id: native.media_id, cover_image_key_frame_time: video!.cover_image_key_frame_time };\n mediaNote = `Native video ${native.media_id}; cover keyframe ${video!.cover_image_key_frame_time}s.`;\n }\n const fields = copyFields(input), body = { board_id: board.id, ...fields, media_source: mediaSource };\n return plan(`Create Pinterest ${image ? 'image' : 'video'} Pin on ${board.privacy} board`, [mediaNote, `Board ${board.id} “${board.name}”; visibility ${board.privacy}.`, JSON.stringify(fields), '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, fields));\n }\n const input = op.tool === 'pinterest_update_pin' ? updatePin.parse(op.payload) : deletePin.parse(op.payload), current = await this.getPin(account, input.pin_id);\n if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: Pin copy, ownership, promotion or board privacy changed; read the Pin again');\n if (current.pin.is_owner !== true || current.pin.has_been_promoted !== false) throw new AdportError('INVALID_INPUT', 'pinterest: only an explicitly owned, never-promoted original Pin can be edited/deleted here. Create a replacement for promoted or unknown usage.');\n 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 () => {\n const receipt = await this.client.mutate(`pins/${input.pin_id}`, 'DELETE', undefined, pinSchema.optional(), params);\n if (receipt && receipt.id !== input.pin_id) throw new AdportError('PROVIDER_ERROR', 'pinterest: deletion receipt ID mismatch; reconcile before retrying', { resource_ids: [input.pin_id] });\n return [input.pin_id];\n });\n const fields = copyFields(input);\n 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(fields).map(([key, value]) => `${key}: ${JSON.stringify(current.pin[key] ?? null)} → ${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', fields, pinSchema, params), current.board.id, fields, input.pin_id));\n }\n}\n\nexport function pinterestAssetTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const account = { account_id: pinterestId }, paging = { page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).optional() };\n return [\n defineTool({ 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: z.object({ ...account, ...paging, privacy: z.enum(['ALL', 'PUBLIC', 'PROTECTED', 'SECRET', 'PUBLIC_AND_SECRET']).optional() }), annotations: { readOnly: true }, handler: input => provider.assets.boards(input) }),\n defineTool({ 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: z.object({ ...account, board_id: id }), output: creativesOutput.passthrough(), presentation: 'records', annotations: { readOnly: true }, handler: input => provider.assets.getBoard(input.account_id, input.board_id) }),\n defineTool({ 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: z.object({ ...account, ...paging, board_id: id.optional() }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: input => provider.assets.pins(input) }),\n defineTool({ 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: z.object({ ...account, pin_id: id }), output: creativesOutput.passthrough(), presentation: 'creatives', annotations: { readOnly: true }, handler: input => provider.assets.getPin(input.account_id, input.pin_id) }),\n defineTool({ 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: z.object({ ...account, native_media_id: id }), annotations: { readOnly: true }, handler: input => provider.assets.getMedia(input.account_id, input.native_media_id) }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, creativesOutput, defineTool, guardedWriteTool, planningViewSchema, type AnyToolDefinition, type Creative, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestId as id } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]> };\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), cursor = z.string().min(1).max(4096);\nconst parent = z.discriminatedUnion('type', [z.object({ type: z.literal('account') }).strict(), z.object({ type: z.literal('campaign'), campaign_id: id }).strict(), z.object({ type: z.literal('ad_group'), ad_group_id: id }).strict()]);\nconst match = z.enum(['BROAD', 'PHRASE', 'EXACT', 'EXACT_NEGATIVE', 'PHRASE_NEGATIVE']);\n// The native metrics endpoint rejects other ISO markets (live verified2026-11-04).\nconst metricsCountry = z.enum(['CA', 'GB', 'US', 'IE', 'AU', 'NZ']);\nconst keyword = z.looseObject({ id, parent_id: id, parent_type: z.string().optional(), match_type: match.nullable(), value: z.string(), archived: z.boolean().optional(), bid: z.number().int().nullable().optional() });\ntype Keyword = z.infer<typeof keyword>;\nconst reference = { parent, expected_parent_hash: hash };\nconst create = z.object({ ...reference, keywords: z.array(z.object({ value: z.string().trim().min(1).max(120), match_type: match }).strict()).min(1).max(100) }).strict().superRefine((v, ctx) => {\n 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' });\n 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' });\n});\nconst archive = z.object({ ...reference, keywords: z.array(z.object({ keyword_id: id, expected_snapshot_hash: hash }).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');\ntype Parent = z.infer<typeof parent>;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');\nconst snapshot = (value: Keyword) => 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 });\nconst writes = new Set(['pinterest_create_keywords', 'pinterest_archive_keywords']);\n\n/** Pinterest-owned v5 OpenAPI5.28.0 /keywords, fetched 2026-11-04. */\nexport class PinterestKeywordService {\n constructor(private readonly client: PinterestAdsClient, private readonly entity: (account: string, type: 'campaigns' | 'ad_groups', resource: string) => Promise<Row>) {}\n supports(tool: string) { return writes.has(tool); }\n private base(account: string) { return `ad_accounts/${id.parse(account)}/keywords`; }\n async context(account: string, selected: Parent) {\n const scope = parent.parse(selected);\n let entity: Row, campaign: Row | undefined;\n if (scope.type === 'account') {\n entity = await this.client.get(`ad_accounts/${id.parse(account)}`, z.looseObject({ id }));\n if (entity.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword account response mismatch');\n } else if (scope.type === 'campaign') entity = await this.entity(account, 'campaigns', scope.campaign_id);\n else { entity = await this.entity(account, 'ad_groups', scope.ad_group_id); campaign = await this.entity(account, 'campaigns', id.parse(entity.campaign_id)); }\n const parentId = id.parse(entity.id), configuration = { account_id: account, parent: scope, parent_id: parentId, status: entity.status ?? null, ...(campaign ? { campaign_id: campaign.id, campaign_status: campaign.status ?? null } : {}) };\n return { ...configuration, entity, ...(campaign ? { campaign } : {}), parent_snapshot_hash: digest(configuration), 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.'] };\n }\n private scoped(value: Keyword, context: { parent: Parent; parent_id: string }) {\n const types = context.parent.type === 'account' ? ['advertiser', 'account', 'adaccount'] : context.parent.type === 'campaign' ? ['campaign'] : ['adgroup'];\n if (value.parent_id !== context.parent_id || value.parent_type && !types.includes(value.parent_type.toLowerCase().replaceAll('_', ''))) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword collection returned another parent');\n return value;\n }\n private async page(account: string, context: Awaited<ReturnType<PinterestKeywordService['context']>>, size: number, bookmark?: string, matches?: z.infer<typeof match>[]) {\n const params = new URLSearchParams({ page_size: String(size) });\n if (context.parent.type === 'campaign') params.set('campaign_id', context.parent_id);\n if (context.parent.type === 'ad_group') params.set('ad_group_id', context.parent_id);\n if (bookmark) params.set('bookmark', bookmark);\n if (matches) params.set('match_types', matches.join(','));\n const data = await this.client.get(this.base(account), z.object({ items: z.array(keyword), bookmark: z.string().nullable().optional() }), params);\n 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 AdportError('PROVIDER_ERROR', 'pinterest: keyword pagination did not advance or returned duplicate/oversized rows');\n if (matches && data.items.some(v => v.match_type === null || !matches.includes(v.match_type))) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword collection ignored the match-type selection');\n return { ...data, items: data.items.map(v => this.scoped(v, context)), truncated: Boolean(data.bookmark), ...(data.bookmark ? { next_cursor: data.bookmark } : {}) };\n }\n private view(account: string, scope: Parent, parentHash: string, item: Keyword): Creative {\n return { id: item.id, provider: 'pinterest', account_id: account, 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: account, parent: scope, expected_parent_hash: parentHash, keywords: [{ keyword_id: item.id, expected_snapshot_hash: snapshot(item) }] }, fields: [] }] : [] };\n }\n async list(input: { account_id: string; parent: Parent; page_size: number; bookmark?: string; match_types?: z.infer<typeof match>[] }) {\n 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);\n 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: snapshot(value) })), creatives: data.items.map(value => this.view(input.account_id, context.parent, context.parent_snapshot_hash, value)), notes: context.notes };\n }\n private async find(account: string, context: Awaited<ReturnType<PinterestKeywordService['context']>>, wanted: Set<string>) {\n const found = new Map<string, Keyword>(), cursors = new Set<string>(), seen = new Set<string>();\n let bookmark: string | undefined;\n for (let page = 0; page < 40; page++) {\n const result = await this.page(account, context, 250, bookmark);\n for (const row of result.items) {\n if (seen.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword inventory repeated an ID'); seen.add(row.id);\n if (wanted.has(row.id)) found.set(row.id, row);\n }\n if (found.size === wanted.size) return found;\n if (!result.next_cursor) throw new AdportError('INVALID_INPUT', 'pinterest: requested keyword is not visible in this parent; archived keywords cannot be safely rediscovered/unarchived through this API');\n if (cursors.has(result.next_cursor)) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword inventory repeated a cursor');\n cursors.add(result.next_cursor); bookmark = result.next_cursor;\n }\n throw new AdportError('INVALID_INPUT', 'pinterest: keyword ownership lookup exceeded 10,000 rows; no write was made');\n }\n async get(account: string, scope: Parent, keywordId: string) {\n const context = await this.context(account, scope), found = (await this.find(account, context, new Set([keywordId]))).get(keywordId)!;\n return { keyword: found, snapshot_hash: snapshot(found), parent_snapshot_hash: context.parent_snapshot_hash, creatives: [this.view(account, scope, context.parent_snapshot_hash, found)], truncated: false, notes: context.notes };\n }\n async metrics(input: { account_id: string; country_code: string; keywords: string[] }) {\n metricsCountry.parse(input.country_code);\n const data = await this.client.get(`${this.base(input.account_id)}/metrics`, z.object({ data: z.array(z.looseObject({ keyword: z.string(), metrics: z.looseObject({ keyword_query_volume: z.string().optional() }).optional() })) }), new URLSearchParams({ country_code: input.country_code, keywords: input.keywords.join(',') }));\n const wanted = new Set(input.keywords), seen = new Set<string>();\n for (const item of data.data) { if (!wanted.has(item.keyword) || seen.has(item.keyword)) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword metrics returned another or repeated keyword'); seen.add(item.keyword); }\n 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.'] } };\n }\n private async batch(account: string, context: Awaited<ReturnType<PinterestKeywordService['context']>>, method: 'POST' | 'PATCH', body: Row, expected: Array<{ id?: string; value?: string; match_type?: string | null; archived?: boolean }>) {\n const data = await this.client.mutate(this.base(account), method, body, z.object({ keywords: z.array(z.unknown()), errors: z.array(z.unknown()) }));\n const ids = data.keywords.flatMap(value => { const parsed = z.object({ id }).safeParse(value); return parsed.success ? [parsed.data.id] : []; });\n const parsed = z.array(keyword).safeParse(data.keywords);\n if (data.errors.length || !parsed.success || parsed.data.length !== expected.length || new Set(ids).size !== ids.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword batch was partial or incomplete; reconcile returned IDs before retrying', { resource_ids: ids });\n const unmatched = [...expected];\n for (const row of parsed.data) {\n try { this.scoped(row, context); } catch { throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword receipt belongs to another parent; reconcile before retrying', { resource_ids: ids }); }\n const index = unmatched.findIndex(item => Object.entries(item).every(([key, value]) => row[key] === value));\n if (index < 0) throw new AdportError('PROVIDER_ERROR', 'pinterest: keyword receipt differs from approved keywords; reconcile before retrying', { resource_ids: ids });\n unmatched.splice(index, 1);\n }\n return ids;\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n if (op.provider !== 'pinterest' || !this.supports(op.tool) || op.kind !== (op.tool === 'pinterest_create_keywords' ? 'create' : 'update')) throw new AdportError('INVALID_INPUT', 'pinterest: invalid keyword operation');\n const input = op.tool === 'pinterest_create_keywords' ? create.parse(op.payload) : archive.parse(op.payload), context = await this.context(op.accountId, input.parent);\n if (context.parent_snapshot_hash !== input.expected_parent_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: keyword parent state changed; read its context again');\n const notes = ['Preview is local; Pinterest has no server dry-run for keyword writes.', ...context.notes];\n if (op.tool === 'pinterest_create_keywords') {\n const value = create.parse(input), positive = value.keywords.some(item => !item.match_type.endsWith('_NEGATIVE'));\n if (guard.forcePausedCreation && positive && context.entity.status !== 'PAUSED' && context.campaign?.status !== 'PAUSED') throw new AdportError('POLICY_VIOLATION', 'pinterest: positive keywords cannot be paused individually; paused_creation requires a paused parent ad group or campaign');\n return { summary: `Create ${value.keywords.length} Pinterest keywords`, changes: [`Parent ${context.parent.type} ${context.parent_id}.`, ...value.keywords.map(item => `${item.match_type}: ${item.value}`), 'Keyword bids are omitted; existing ad-group bidding is preserved.'], coercions: [], budgetDeltas: [], notes, execute: () => this.batch(op.accountId, context, 'POST', { parent_id: context.parent_id, keywords: value.keywords }, value.keywords.map(item => ({ ...item, archived: false }))) };\n }\n const value = archive.parse(input), current = await this.find(op.accountId, context, new Set(value.keywords.map(item => item.keyword_id)));\n for (const item of value.keywords) if (snapshot(current.get(item.keyword_id)!) !== item.expected_snapshot_hash || current.get(item.keyword_id)!.archived !== false) throw new AdportError('PENDING_MISMATCH', 'pinterest: keyword contents or archive state changed; read it again');\n return { summary: `Archive ${value.keywords.length} Pinterest keywords`, changes: [...current.values()].map(item => `${item.match_type}: ${item.value} (${item.id}) → archived`), coercions: [], budgetDeltas: [], notes: [...notes, '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 }))) };\n }\n}\n\nexport function pinterestKeywordTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const account = { account_id: id }, selected = { ...account, parent: parent.default({ type: 'account' }) };\n return [\n defineTool({ 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: z.object(selected), annotations: { readOnly: true }, handler: v => provider.keywords.context(v.account_id, v.parent) }),\n defineTool({ name: 'pinterest_keywords', namespace: 'pinterest', description: 'List one verified parent’s 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: z.object({ ...selected, page_size: z.number().int().min(1).max(250).default(50), bookmark: cursor.optional(), match_types: z.array(match).min(1).max(5).optional() }), output: creativesOutput.passthrough(), presentation: 'records', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: v => provider.keywords.list(v) }),\n defineTool({ 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: z.object({ ...selected, keyword_id: id }), output: creativesOutput.passthrough(), presentation: 'records', annotations: { readOnly: true }, handler: v => provider.keywords.get(v.account_id, v.parent, v.keyword_id) }),\n defineTool({ 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: z.object({ ...account, country_code: metricsCountry, keywords: z.array(z.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: z.object({ planning: planningViewSchema }).passthrough(), presentation: 'planning', annotations: { readOnly: true }, handler: v => provider.keywords.metrics(v) }),\n guardedWriteTool({ 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 }),\n guardedWriteTool({ 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 }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition, type Creative, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestId as id } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute: () => Promise<string[]> };\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), name = z.string().trim().min(1).max(255), description = z.string().max(1000).nullable();\nconst ids = z.array(id).min(1).max(100).refine(v => new Set(v).size === v.length, 'Use unique IDs');\nconst href = z.string().url().max(2048).refine(value => { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) URL without credentials');\nconst domain = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z]{2,63}$/);\nconst customer = z.object({ audience_type: z.literal('CUSTOMER_LIST'), customer_list_id: id, expected_source_hash: hash }).strict();\nconst visitor = z.object({ audience_type: z.literal('VISITOR'), visitor_source_ids: ids, retention_days: z.number().int().min(1).max(540), prefill: z.boolean(), event: z.string().min(1).max(100).optional(), event_source: z.array(z.enum(['web', 'mobile', 'offline'])).min(1).max(3).optional(), ingestion_source: z.array(z.enum(['tag', 'mmp', 'file_upload', 'conversions_api'])).min(1).max(4).optional(), url: z.array(href).min(1).max(100).optional() }).strict();\nconst engagement = z.object({ audience_type: z.literal('ENGAGEMENT'), engagement_domains: z.array(domain).min(1).max(10), engagement_type: z.enum(['click', 'save', 'closeup', 'comment', 'like']).optional(), engager_type: z.number().int().min(1).max(2).optional(), retention_days: z.number().int().min(1).max(540).optional(), campaign_ids: ids.optional(), ad_ids: ids.optional(), pin_ids: z.array(z.string().regex(/^\\d{1,30}$/)).min(1).max(100).optional(), objective_types: z.array(z.enum(['AWARENESS', 'CONSIDERATION', 'WEB_CONVERSION', 'CATALOG_SALES', 'VIDEO_COMPLETION', 'SALES'])).min(1).max(6).optional(), url: z.array(href).min(1).max(100).optional() }).strict();\nconst actalike = z.object({ audience_type: z.literal('ACTALIKE'), seeds: z.array(z.object({ audience_id: id, expected_snapshot_hash: hash }).strict()).min(1).max(100).refine(v => new Set(v.map(s => s.audience_id)).size === v.length, 'Use unique seeds'), country: z.enum(['US', 'CA', 'GB']), percentage: z.number().int().min(1).max(10) }).strict();\nconst definition = z.discriminatedUnion('audience_type', [customer, visitor, engagement, actalike]);\ntype Definition = z.infer<typeof definition>;\nconst audience = z.looseObject({ id, ad_account_id: id.optional(), name: z.string().optional(), description: z.string().nullable().optional(), audience_type: z.string().optional(), rule: z.record(z.string(), z.unknown()).optional(), is_nca: z.boolean().optional(), status: z.string().optional() });\nconst customerList = z.object({ id, name: z.string(), ad_account_id: id.optional(), is_nca: z.boolean().optional(), status: z.string().optional(), created_time: z.number().finite().optional(), updated_time: z.number().finite().optional(), num_batches: z.number().int().nonnegative().optional(), num_uploaded_user_records: z.number().int().nonnegative().optional(), num_removed_user_records: z.number().int().nonnegative().optional(), exceptions: z.record(z.string(), z.unknown()).optional() });\nconst selected = { audience_id: id, expected_snapshot_hash: hash };\nconst createAudience = z.object({ name, description: description.optional(), definition }).strict();\nconst updateAudience = z.object({ ...selected, name: name.optional(), description: description.optional() }).strict().refine(v => v.name !== undefined || v.description !== undefined, 'Supply audience copy');\nconst replaceRule = z.object({ ...selected, expected_context_hash: hash, definition }).strict();\nconst removeAudience = z.object({ audience_id: id, expected_context_hash: hash, confirm_permanent_removal: z.literal(true) }).strict();\nconst records = z.array(hash).min(1).max(10_000).refine(v => new Set(v).size === v.length, 'Use unique SHA-256 records');\nconst createList = z.object({ name, list_type: z.enum(['EMAIL', 'IDFA', 'MAID']).default('EMAIL'), is_nca: z.boolean().default(false), records_sha256: records, confirm_data_rights: z.literal(true) }).strict();\nconst updateRecords = z.object({ customer_list_id: id, expected_snapshot_hash: hash, operation_type: z.enum(['ADD', 'REMOVE']), records_sha256: records, confirm_data_rights: z.literal(true) }).strict();\nconst writes = new Map<string, WriteOperation['kind']>([['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']]);\nconst object = (value: unknown): Row => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\nfunction canonical(value: unknown): unknown {\n if (typeof value === 'number' && Number.isInteger(value) && !Number.isSafeInteger(value)) throw new AdportError('PROVIDER_ERROR', 'pinterest: unsafe native identifier or counter in audience configuration');\n if (Array.isArray(value)) return value.map(canonical);\n return value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\n}\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst audienceSnapshot = (value: z.infer<typeof audience>) => digest(Object.fromEntries(['id', 'ad_account_id', 'name', 'description', 'audience_type', 'rule', 'is_nca'].map(key => [key, value[key] ?? null])));\nconst listSnapshot = (value: z.infer<typeof customerList>) => digest(Object.fromEntries((['id', 'ad_account_id', 'name', 'is_nca', 'updated_time', 'num_batches', 'num_uploaded_user_records', 'num_removed_user_records'] as const).map(key => [key, value[key] ?? null])));\nfunction normalizeRule(value: unknown): Row {\n const rule = { ...object(value) };\n if (rule.percentage !== undefined) rule.percentage = String(rule.percentage);\n if (typeof rule.visitor_source_id === 'string') rule.visitor_source_id = [rule.visitor_source_id];\n if (Array.isArray(rule.seed_id)) { canonical(rule.seed_id); rule.seed_id = rule.seed_id.map(String); }\n return rule;\n}\nfunction includesFields(actual: unknown, expected: unknown): boolean {\n if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every((value, index) => includesFields(actual[index], value));\n if (expected !== null && typeof expected === 'object') return Object.entries(object(expected)).every(([key, value]) => includesFields(object(actual)[key], value));\n return actual === expected;\n}\n\n/** Pinterest-owned v5 OpenAPI5.28.0 audience/customer-list contracts, fetched2026-11-04. */\nexport class PinterestAudienceService {\n constructor(private readonly client: PinterestAdsClient, private readonly entity: (account: string, type: 'campaigns' | 'ads', resource: string) => Promise<Row>, private readonly pin: (account: string, resource: string) => Promise<{ pin: Row }>) {}\n supports(tool: string) { return writes.has(tool); }\n private base(account: string) { return `ad_accounts/${id.parse(account)}`; }\n private async page<T>(account: string, path: string, schema: z.ZodType<T>, size: number, bookmark?: string, extra: Record<string, string> = {}) {\n const data = await this.client.get(`${this.base(account)}/${path}`, z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() }), new URLSearchParams({ ...extra, page_size: String(size), ...(bookmark ? { bookmark } : {}) }));\n if (data.items.length > size || data.bookmark && (!data.items.length || data.bookmark === bookmark)) throw new AdportError('PROVIDER_ERROR', 'pinterest: audience pagination did not advance or exceeded page size');\n return { ...data, truncated: Boolean(data.bookmark), ...(data.bookmark ? { next_cursor: data.bookmark } : {}) };\n }\n async list(input: { account_id: string; ownership_type: 'OWNED' | 'RECEIVED'; page_size: number; bookmark?: string }) {\n const data = await this.page(input.account_id, 'audiences', audience, input.page_size, input.bookmark, { ownership_type: input.ownership_type });\n 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 !== undefined && v.ad_account_id !== input.account_id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: owned audience list returned foreign ownership or duplicate IDs');\n return { ...data, items: data.items.map(v => ({ ...v, owned_by_advertiser: v.ad_account_id === input.account_id, snapshot_hash: audienceSnapshot(v) })) };\n }\n async get(account: string, audienceId: string) {\n const current = await this.client.get(`${this.base(account)}/audiences/${id.parse(audienceId)}`, audience);\n if (current.id !== audienceId || current.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'pinterest: audience ownership was not confirmed for this advertiser; received audiences are not writable');\n const snapshotHash = audienceSnapshot(current);\n const creative: Creative = { id: current.id, provider: 'pinterest', account_id: account, 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: account, 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: 1000 }] }] };\n 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.'] };\n }\n async getCustomerList(account: string, resource: string) {\n const current = await this.client.get(`${this.base(account)}/customer_lists/${id.parse(resource)}`, customerList);\n if (current.id !== resource || current.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'pinterest: customer list is not explicitly owned by this advertiser');\n const { exceptions: _exceptions, ...metadata } = current;\n return { customer_list: metadata, snapshot_hash: listSnapshot(current), has_exceptions: Boolean(current.exceptions && Object.keys(object(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.'] };\n }\n async customerLists(input: { account_id: string; page_size: number; bookmark?: string }) {\n const data = await this.page(input.account_id, 'customer_lists', customerList, input.page_size, input.bookmark);\n 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 AdportError('PROVIDER_ERROR', 'pinterest: customer list returned foreign/missing ownership or duplicate IDs');\n return { ...data, items: data.items.map(value => { const { exceptions: _exceptions, ...metadata } = value; return { ...metadata, snapshot_hash: listSnapshot(value) }; }) };\n }\n async sources(account: string) {\n const current = await this.client.get(this.base(account), z.object({ id, owner: z.object({ username: z.string() }) }));\n if (current.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: audience account ID mismatch');\n const native = await this.client.get('user_account', z.object({ username: z.string() }));\n 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’s domains. Account-scoped tag/list/seed workflows remain available.'] };\n const websites: Array<{ website: string; status?: string; verified_at?: string }> = [], seen = new Set<string>();\n let bookmark: string | undefined;\n for (let page = 0; page < 20; page++) {\n const data = await this.client.get('user_account/websites', z.object({ items: z.array(z.object({ website: z.string(), status: z.string().optional(), verified_at: z.string().optional() })), bookmark: z.string().nullable().optional() }), new URLSearchParams({ page_size: '250', ...(bookmark ? { bookmark } : {}) }));\n if (data.items.length > 250 || data.bookmark && (!data.items.length || seen.has(data.bookmark) || data.bookmark === bookmark)) throw new AdportError('PROVIDER_ERROR', 'pinterest: website pagination did not advance');\n websites.push(...data.items);\n 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.'] };\n seen.add(data.bookmark); bookmark = data.bookmark;\n }\n return { token_owner_matches: true, websites, complete: false, notes: ['Website inventory exceeded 5,000 entries; engagement-domain validation is blocked.'] };\n }\n private async rule(account: string, value: Definition): Promise<Row> {\n if (value.audience_type === 'CUSTOMER_LIST') {\n const source = await this.getCustomerList(account, value.customer_list_id);\n if (source.snapshot_hash !== value.expected_source_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: customer-list source changed; read it again');\n return { customer_list_id: value.customer_list_id };\n }\n if (value.audience_type === 'ACTALIKE') {\n for (const seed of value.seeds) {\n const source = await this.get(account, seed.audience_id);\n if (source.snapshot_hash !== seed.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: seed audience configuration changed; read it again');\n }\n return { seed_id: value.seeds.map(v => v.audience_id), country: value.country, percentage: value.percentage };\n }\n if (value.audience_type === 'VISITOR') {\n for (const source of value.visitor_source_ids) {\n const tag = await this.client.get(`${this.base(account)}/conversion_tags/${source}`, z.object({ id, ad_account_id: id }));\n if (tag.id !== source || tag.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'pinterest: visitor source tag is not owned by this advertiser');\n }\n 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 } : {}) };\n }\n const available = await this.sources(account);\n const hosts = new Set(available.websites.flatMap(v => { try { return [new URL(v.website.includes('://') ? v.website : `https://${v.website}`).hostname]; } catch { return []; } }));\n if (!available.complete || !available.token_owner_matches || value.engagement_domains.some(v => !hosts.has(v))) throw new AdportError('INVALID_INPUT', 'pinterest: engagement domains are not present in the complete advertiser-owner website inventory');\n for (const campaign of value.campaign_ids ?? []) await this.entity(account, 'campaigns', campaign);\n for (const ad of value.ad_ids ?? []) await this.entity(account, 'ads', ad);\n for (const pin of value.pin_ids ?? []) if ((await this.pin(account, pin)).pin.is_owner !== true) throw new AdportError('INVALID_INPUT', 'pinterest: engagement Pin is not explicitly owned');\n 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 } : {}) };\n }\n private async inventory<T>(account: string, path: string, schema: z.ZodType<T>, extra: Record<string, string> = {}) {\n const items: T[] = [], cursors = new Set<string>(); let bookmark: string | undefined;\n for (let page = 0; page < 50; page++) {\n const data = await this.page(account, path, schema, 100, bookmark, extra); items.push(...data.items);\n if (!data.next_cursor) return { items, complete: true };\n if (cursors.has(data.next_cursor)) throw new AdportError('PROVIDER_ERROR', 'pinterest: usage inventory repeated a cursor');\n cursors.add(data.next_cursor); bookmark = data.next_cursor;\n }\n return { items, complete: false };\n }\n async usage(account: string, resource: string) {\n const current = await this.get(account, resource);\n const groups = await this.inventory(account, 'ad_groups', z.looseObject({ id, ad_account_id: id.optional(), status: z.string().optional(), targeting_spec: z.record(z.string(), z.unknown()).optional() }), { entity_statuses: 'ACTIVE,PAUSED,ARCHIVED,DRAFT,DELETED_DRAFT' });\n const audiences = await this.inventory(account, 'audiences', audience, { ownership_type: 'OWNED' });\n const sharing = [];\n for (const type of ['AD_ACCOUNT', 'BUSINESS_ACCOUNT']) {\n const data = await this.inventory(account, 'audiences/shared/accounts', z.object({ account_id: id, account_type: z.enum(['AD_ACCOUNT', 'BUSINESS_ACCOUNT']) }), { audience_id: resource, account_type: type });\n if (data.items.some(v => v.account_type !== type) || new Set(data.items.map(v => v.account_id)).size !== data.items.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: sharing returned the wrong account type or repeated accounts');\n sharing.push(data);\n }\n const seen = new Set<string>(), references: Array<{ kind: string; id: string; status?: string; targeting_dimensions?: string[]; snapshot_hash?: string }> = [];\n let configurationComplete = true;\n for (const group of groups.items) {\n if (seen.has(group.id) || group.ad_account_id !== undefined && group.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: usage returned a foreign or repeated ad group'); seen.add(group.id);\n if (!group.targeting_spec) configurationComplete = false;\n const targeting = group.targeting_spec ?? {};\n for (const key of ['AUDIENCE_INCLUDE', 'AUDIENCE_EXCLUDE']) if (targeting[key] !== undefined && !z.array(id).safeParse(targeting[key]).success) throw new AdportError('PROVIDER_ERROR', 'pinterest: audience targeting references could not be inspected');\n const dimensions = ['AUDIENCE_INCLUDE', 'AUDIENCE_EXCLUDE'].filter(key => Array.isArray(targeting[key]) && (targeting[key] as string[]).includes(resource));\n if (dimensions.length) references.push({ kind: 'ad_group', id: group.id, ...(typeof group.status === 'string' ? { status: group.status } : {}), targeting_dimensions: dimensions });\n }\n seen.clear();\n for (const source of audiences.items) {\n if (seen.has(source.id) || source.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: usage returned a foreign or repeated owned audience'); seen.add(source.id);\n const seed = source.rule?.seed_id; canonical(seed);\n if (!['CUSTOMER_LIST', 'VISITOR', 'ENGAGEMENT', 'ACTALIKE'].includes(source.audience_type ?? '') || source.audience_type === 'ACTALIKE' && !Array.isArray(seed)) configurationComplete = false;\n if (source.id !== resource && Array.isArray(seed) && seed.some(v => String(v) === resource)) references.push({ kind: 'derived_audience', id: source.id, snapshot_hash: audienceSnapshot(source) });\n }\n const shared_accounts = sharing.flatMap(v => v.items).filter(v => v.account_type !== 'AD_ACCOUNT' || v.account_id !== account), scan_complete = configurationComplete && groups.complete && audiences.complete && sharing.every(v => v.complete);\n references.sort((a, b) => `${a.kind}:${a.id}`.localeCompare(`${b.kind}:${b.id}`)); shared_accounts.sort((a, b) => `${a.account_type}:${a.account_id}`.localeCompare(`${b.account_type}:${b.account_id}`));\n const context = { snapshot_hash: current.snapshot_hash, references, shared_accounts, scan_complete };\n return { ...current, ...context, context_hash: digest(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.'] };\n }\n private planWrite(summary: string, changes: string[], execute: Plan['execute'], fieldChanges?: WritePreview['fieldChanges']): Plan {\n 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 };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'pinterest' || writes.get(op.tool) !== op.kind) throw new AdportError('INVALID_INPUT', 'pinterest: invalid audience operation');\n const account = id.parse(op.accountId);\n if (op.tool === 'pinterest_create_customer_list' || op.tool === 'pinterest_update_customer_list_records') {\n const create = op.tool === 'pinterest_create_customer_list', input = create ? createList.parse(op.payload) : updateRecords.parse(op.payload);\n let resource: string | undefined;\n if ('customer_list_id' in input) { resource = input.customer_list_id; const current = await this.getCustomerList(account, resource); if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: customer-list batches or metadata changed; read it again'); }\n const recordsDigest = digest(input.records_sha256), body = create ? { name: createList.parse(input).name, list_type: createList.parse(input).list_type, is_nca: createList.parse(input).is_nca, records: input.records_sha256.join(',') } : { operation_type: updateRecords.parse(input).operation_type, records: input.records_sha256.join(',') };\n return this.planWrite(`${create ? 'Create' : 'Update'} Pinterest customer list`, [`${input.records_sha256.length} unique SHA-256 identifiers; batch digest ${recordsDigest}. Identifiers are not included in this preview.`, create ? `New ${createList.parse(input).list_type} list “${createList.parse(input).name}”; expanded matching is_nca=${createList.parse(input).is_nca}.` : `${updateRecords.parse(input).operation_type} membership records on ${resource}.`, 'Native processing is asynchronous. This does not confirm matched users; read customer-list status.'], async () => {\n let result: z.infer<typeof customerList>;\n try { result = await this.client.mutate(`${this.base(account)}/customer_lists${resource ? `/${resource}` : ''}`, create ? 'POST' : 'PATCH', body, customerList); }\n catch (error) {\n const details = error instanceof AdportError ? object(error.details) : {}, ids = Array.isArray(details.resource_ids) ? details.resource_ids.filter(v => id.safeParse(v).success) : resource ? [resource] : [];\n throw new AdportError('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: ids });\n }\n if (result.ad_account_id !== account || resource && result.id !== resource || create && (result.name !== createList.parse(input).name || result.is_nca !== createList.parse(input).is_nca)) throw new AdportError('PROVIDER_ERROR', 'pinterest: customer-list receipt ownership/name/matching mode mismatch; reconcile before retrying', { resource_ids: [result.id] });\n return [result.id];\n });\n }\n if (op.tool === 'pinterest_create_audience') {\n const input = createAudience.parse(op.payload), rule = await this.rule(account, input.definition), body = { ad_account_id: account, name: input.name, ...(input.description !== undefined ? { description: input.description } : {}), audience_type: input.definition.audience_type, rule };\n return this.planWrite(`Create Pinterest ${input.definition.audience_type} audience “${input.name}”`, [JSON.stringify(body), '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(account, undefined, body, await this.client.mutate(`${this.base(account)}/audiences`, 'POST', body, audience)));\n }\n if (op.tool === 'pinterest_remove_audience') {\n const input = removeAudience.parse(op.payload), current = await this.usage(account, input.audience_id);\n if (current.context_hash !== input.expected_context_hash || !current.scan_complete) throw new AdportError('PENDING_MISMATCH', 'pinterest: audience usage changed or is incomplete; read it again');\n if (current.references.length || current.shared_accounts.length) throw new AdportError('INVALID_INPUT', 'pinterest: audience still has targeting, derived audiences or sharing references');\n return this.planWrite(`Remove Pinterest audience “${current.audience.name ?? input.audience_id}”`, [`Native operation_type REMOVE on ${input.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(account, input.audience_id, {}, await this.client.mutate(`${this.base(account)}/audiences/${input.audience_id}`, 'PATCH', { operation_type: 'REMOVE' }, audience)));\n }\n const replacement = op.tool === 'pinterest_replace_audience_rule', input = replacement ? replaceRule.parse(op.payload) : updateAudience.parse(op.payload), current = replacement ? await this.usage(account, input.audience_id) : await this.get(account, input.audience_id);\n if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('PENDING_MISMATCH', 'pinterest: audience copy/configuration changed; read it again');\n const body: Row = { operation_type: 'UPDATE' }, changes: NonNullable<WritePreview['fieldChanges']> = [];\n if (replacement) {\n const value = replaceRule.parse(input), context = current as Awaited<ReturnType<PinterestAudienceService['usage']>>;\n if (context.context_hash !== value.expected_context_hash || !context.scan_complete) throw new AdportError('PENDING_MISMATCH', 'pinterest: audience usage changed or is incomplete; read it again');\n if (context.shared_accounts.length) throw new AdportError('INVALID_INPUT', 'pinterest: shared audience rules cannot be replaced through this workflow');\n if (value.definition.audience_type !== current.audience.audience_type) throw new AdportError('INVALID_INPUT', 'pinterest: rule replacement must preserve audience type');\n 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 AdportError('INVALID_INPUT', 'pinterest: an audience cannot use itself or a direct derived audience as a seed');\n body.rule = await this.rule(account, value.definition); changes.push({ field: 'Rule', before: JSON.stringify(current.audience.rule ?? null), after: JSON.stringify(body.rule) });\n } else {\n const value = updateAudience.parse(input);\n for (const key of ['name', 'description'] as const) if (value[key] !== undefined) { body[key] = value[key]; 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)') }); }\n }\n return this.planWrite(`Edit Pinterest audience “${current.audience.name ?? input.audience_id}”`, [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(account, input.audience_id, body, await this.client.mutate(`${this.base(account)}/audiences/${input.audience_id}`, 'PATCH', body, audience), current.audience), changes);\n }\n private receipt(account: string, resource: string | undefined, expected: Row, current: z.infer<typeof audience>, previous?: z.infer<typeof audience>) {\n const fields = Object.entries(expected).filter(([key]) => key !== 'operation_type');\n if (current.ad_account_id !== account || resource && current.id !== resource || fields.some(([key, value]) => key === 'rule' ? !includesFields(normalizeRule(current.rule), normalizeRule(value)) : digest(current[key] ?? null) !== digest(value)) || previous && ['name', 'description', 'rule', 'audience_type', 'is_nca'].some(key => expected[key] === undefined && digest(current[key] ?? null) !== digest(previous[key] ?? null))) throw new AdportError('PROVIDER_ERROR', 'pinterest: audience receipt differs from approved fields or preserved ownership/configuration; reconcile before retrying', { resource_ids: [current.id] });\n return [current.id];\n }\n}\n\nexport function pinterestAudienceTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const account = { account_id: id }, page = { page_size: z.number().int().min(1).max(250).default(50), bookmark: z.string().min(1).max(4096).optional() };\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (input: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'pinterest', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: WriteOperation['kind']) => guardedWriteTool({ name, namespace: 'pinterest', provider: 'pinterest', description, payload, kind });\n return [\n 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.', z.object({ ...account, ...page, ownership_type: z.enum(['OWNED', 'RECEIVED']).default('OWNED') }), v => provider.audiences.list(v)),\n defineTool({ 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: z.object({ ...account, audience_id: id }), output: creativesOutput.passthrough(), presentation: 'records', annotations: { readOnly: true }, handler: v => provider.audiences.get(v.account_id, v.audience_id) }),\n 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.', z.object({ ...account, audience_id: id }), v => provider.audiences.usage(v.account_id, v.audience_id)),\n read('pinterest_audience_sources', 'Read the advertiser owner’s 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.', z.object(account), v => provider.audiences.sources(v.account_id)),\n read('pinterest_customer_lists', 'Read selected advertiser customer-list metadata, counts, processing status and snapshots with pagination. Never returns records or native exception contents.', z.object({ ...account, ...page }), v => provider.audiences.customerLists(v)),\n 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.', z.object({ ...account, customer_list_id: id }), v => provider.audiences.getCustomerList(v.account_id, v.customer_list_id)),\n write('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'),\n write('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'),\n write('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'),\n write('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'),\n write('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'),\n write('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'),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { isIP } from 'node:net';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestId as id } from './schemas.js';\n\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]>; resultDetails?(): unknown; resultWarnings?(): string[] };\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), text = z.string().min(1).max(4096), decimal = z.string().regex(/^\\d+(?:\\.\\d+)?$/);\nconst optionalText = text.nullable().optional(), integer = z.number().int().nonnegative().safe();\nconst aem = { aem_db_enabled: z.boolean().default(false), aem_enabled: z.boolean().default(false), aem_external_id_enabled: z.boolean().default(false), aem_fnln_enabled: z.boolean().default(false), aem_ge_enabled: z.boolean().default(false), aem_loc_enabled: z.boolean().default(false), aem_ph_enabled: z.boolean().default(false) };\nconst tag = z.looseObject({ id: id.optional(), ad_account_id: id, name: z.string(), status: z.string().optional(), configs: z.record(z.string(), z.unknown()).optional(), last_fired_time_ms: z.number().nullable().optional() });\nconst tagCreate = z.object({ name: z.string().trim().min(1).max(255), ...aem, md_frequency: z.number().default(1), expected_context_hash: hash, confirm_enhanced_match_consent: z.boolean().default(false) }).strict().refine(value => !Object.keys(aem).some(key => value[key as keyof typeof aem]) || value.confirm_enhanced_match_consent, 'Enabling enhanced match requires explicit consent confirmation');\nconst eventMetadata = z.looseObject({ ad_account_id: id.optional(), conversion_tag_id: id.optional(), conversion_event: z.string().optional(), created_time: z.number().int().optional(), reporting_conversion_event: z.string().optional() });\nconst sourcePlatform = z.enum(['WEB', 'MOBILE', 'MOBILE_ANDROID', 'MOBILE_IOS', 'OFFLINE', 'PINTEREST_WEB', 'PINTEREST_ANDROID', 'PINTEREST_IOS', 'POINT_OF_SALE']);\nconst ingestionSource = z.enum(['TAG', 'MMP', 'FILE_UPLOAD', 'CONVERSIONS_API', 'NATIVE']);\nconst qualityInput = z.object({ account_id: id, lookback_period: z.enum(['1d', '14d']), source_platform: sourcePlatform.optional(), ingestion_source: ingestionSource.optional() }).strict();\nconst component = z.looseObject({ coverage: z.number(), overlap: z.number().optional(), issues: z.array(z.looseObject({ id: z.string(), name: z.string(), reason: z.string() })).optional() });\nconst quality = z.looseObject({ overall_status: z.enum(['NEEDS_IMPROVEMENT', 'FAIR', 'GOOD']), quality_components: z.record(z.string(), z.record(z.string(), component)), ingestion_source: ingestionSource, source_platform: sourcePlatform, lookback_period: z.enum(['1d', '14d']) });\nconst hashedValues = z.array(hash).min(1).max(100);\nconst userData = z.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: z.string().refine(value => isIP(value) !== 0 && !['0.0.0.0', '::'].includes(value), 'Use a valid, non-unspecified IP address').optional(), client_user_agent: z.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');\nconst product = z.object({ id: text.optional(), item_brand: text.optional(), item_brand_id: z.string().max(64).optional(), item_category: text.optional(), item_name: text.optional(), item_price: decimal.optional(), quantity: integer.optional() }).strict();\nconst customData = z.object({ content_brand: optionalText, content_category: optionalText, content_ids: z.array(text).max(1000).optional(), content_name: optionalText, contents: z.array(product).max(1000).optional(), currency: z.string().regex(/^[A-Z]{3}$/).nullable().optional(), external_measurement_id: optionalText, external_measurement_vendor_id: z.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');\nconst appInfo = z.object({ app_id: z.string().max(200).optional(), app_name: z.string().max(200).optional(), app_package_name: z.string().max(200).optional(), app_store: z.string().max(100).optional(), app_version: z.string().max(100).optional(), install_time: integer.optional(), user_agent: z.string().max(16384).optional(), window_height: integer.max(30720).optional(), window_width: integer.max(30720).optional() }).strict();\nconst deviceInfo = z.object({ battery_level: integer.max(100).optional(), brand: z.string().max(100).optional(), carrier: z.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: z.enum(['desktop', 'laptop', 'cellphone', 'tablet', 'smartwatch', 'tv', 'vr', 'console', 'other']).optional(), kernel_version: z.string().max(100).optional(), languages: z.array(z.string()).max(100).optional(), locale: z.string().max(35).optional(), model: z.string().max(100).optional(), network_type: z.enum(['wifi', 'cellular_2g', 'cellular_3g', 'cellular_4g', 'cellular_5g', 'cellular_6g', 'ethernet', 'unknown']).optional(), os_family: z.enum(['ios', 'android', 'macos', 'windows', 'linux', 'bsd', 'other']).optional(), os_name: z.string().max(100).optional(), os_release_name: z.string().max(100).optional(), os_version: z.string().max(100).optional(), screen_density: integer.max(100000).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: z.string().max(40).optional(), timezone_abbr: z.string().max(5).optional(), type: z.string().max(100).optional() }).strict();\nconst sourceUrl = z.string().url().max(16384).refine(value => { const url = new URL(value); return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password; }, 'Use an HTTP(S) source URL without credentials');\nconst event = z.object({ action_source: z.enum(['web', 'app_android', 'app_ios', 'offline']), event_id: z.string().min(1).max(512), event_name: z.string().regex(/^[A-Za-z0-9_-]{1,100}$/), event_time: integer.refine(value => value <= Math.floor(Date.now() / 1000) + 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: z.boolean().optional(), os_version: optionalText, partner_name: optionalText, wifi: z.boolean().optional() }).strict();\nconst sendEvents = z.object({ expected_context_hash: hash, test: z.boolean().default(true), confirm_data_rights: z.literal(true), confirm_live_events: z.boolean().default(false), data: z.array(event).min(1).max(1000) }).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');\nconst eventResponse = z.object({ num_events_received: integer, num_events_processed: integer, events: z.array(z.object({ status: z.enum(['failed', 'processed']), error_message: z.string().nullable().optional(), warning_message: z.string().nullable().optional() })) });\nconst writes = new Set(['pinterest_create_conversion_tag', 'pinterest_send_conversion_events']);\n\n/** Native wire contracts: Pinterest-owned v5 OpenAPI5.28.0 and Conversions API guide, checked2026-11-04. */\nexport class PinterestMeasurementService {\n constructor(private readonly client: PinterestAdsClient) {}\n supports(tool: string) { return writes.has(tool); }\n private base(account: string) { return `ad_accounts/${id.parse(account)}`; }\n private owned<T extends { ad_account_id?: string }>(account: string, row: T): T {\n if (row.ad_account_id !== undefined && row.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: measurement response belongs to another advertiser');\n return row;\n }\n async tags(account: string, filterDeleted = false) {\n const result = await this.client.get(`${this.base(account)}/conversion_tags`, z.object({ items: z.array(tag) }), new URLSearchParams({ filter_deleted: String(filterDeleted) }));\n result.items.forEach(row => this.owned(account, row));\n const ids = result.items.flatMap(row => row.id ? [row.id] : []);\n if (new Set(ids).size !== ids.length) throw new AdportError('PROVIDER_ERROR', 'pinterest: duplicate conversion-tag IDs');\n return { ...result, account_id: account, truncated: false };\n }\n async context(account: string) {\n const advertiser = await this.client.get(this.base(account), z.looseObject({ id, name: z.string().optional(), currency: z.string().optional() }));\n if (advertiser.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: measurement account ID mismatch');\n const tags = await this.tags(account);\n const configuration = 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)));\n return { account_id: account, advertiser, tags: tags.items, snapshot_hash: digest({ account_id: account, currency: advertiser.currency ?? null, tags: configuration }), 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.'] };\n }\n async getTag(account: string, tagId: string) {\n const row = await this.client.get(`${this.base(account)}/conversion_tags/${id.parse(tagId)}`, tag);\n this.owned(account, row);\n if (row.id !== tagId) throw new AdportError('PROVIDER_ERROR', 'pinterest: conversion-tag ID mismatch');\n return row;\n }\n async eligible(account: string) {\n const result = await this.client.get(`${this.base(account)}/conversion_tags/ocpm_eligible`, z.record(z.string(), z.array(eventMetadata)));\n if (Object.keys(result).some(key => key !== account)) throw new AdportError('PROVIDER_ERROR', 'pinterest: eligible-event mapping belongs to another advertiser');\n return { account_id: account, events: (result[account] ?? []).map(row => this.owned(account, row)) };\n }\n async visits(input: { account_id: string; page_size: number; bookmark?: string; order: 'ASCENDING' | 'DESCENDING' }) {\n const params = new URLSearchParams({ page_size: String(input.page_size), order: input.order });\n if (input.bookmark) params.set('bookmark', input.bookmark);\n const result = await this.client.get(`${this.base(input.account_id)}/conversion_tags/page_visit`, z.object({ items: z.array(eventMetadata), bookmark: z.string().nullable().optional() }), params);\n if (result.items.length > input.page_size || result.bookmark && (!result.items.length || result.bookmark === input.bookmark)) throw new AdportError('PROVIDER_ERROR', 'pinterest: page-visit pagination did not advance');\n result.items.forEach(row => this.owned(input.account_id, row));\n return { ...result, account_id: input.account_id, truncated: Boolean(result.bookmark), ...(result.bookmark ? { next_cursor: result.bookmark } : {}) };\n }\n async quality(input: z.infer<typeof qualityInput>) {\n const parsed = qualityInput.parse(input), params = new URLSearchParams({ lookback_period: parsed.lookback_period });\n if (parsed.source_platform) params.set('source_platform', parsed.source_platform);\n if (parsed.ingestion_source) params.set('ingestion_source', parsed.ingestion_source);\n const result = await this.client.get(`${this.base(parsed.account_id)}/conversion_eqs`, z.array(quality), params);\n 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 AdportError('PROVIDER_ERROR', 'pinterest: event-quality response ignored the selected filters');\n return { account_id: parsed.account_id, items: result };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.kind !== 'create') throw new AdportError('INVALID_INPUT', 'pinterest: measurement writes require create kind');\n if (op.tool === 'pinterest_create_conversion_tag') {\n const input = tagCreate.parse(op.payload), context = await this.context(op.accountId);\n this.checkContext(input.expected_context_hash, context.snapshot_hash);\n if (context.tags.some(row => !row.id) || context.tags.some(row => row.name.toLowerCase() === input.name.toLowerCase())) throw new AdportError('INVALID_INPUT', 'pinterest: conversion tag already exists or tag identity is incomplete; inspect existing tags');\n const { expected_context_hash: _hash, confirm_enhanced_match_consent: _consent, ...body } = input;\n return { summary: `Create Pinterest conversion tag \"${input.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 () => {\n const row = await this.client.mutate(`${this.base(op.accountId)}/conversion_tags`, 'POST', body, tag);\n const resourceIds = row.id ? [row.id] : [];\n if (row.ad_account_id !== op.accountId || !row.id || row.name !== input.name || row.configs && Object.entries(body).some(([key, value]) => key !== 'name' && row.configs![key] !== undefined && row.configs![key] !== value)) throw new AdportError('PROVIDER_ERROR', 'pinterest: conversion-tag creation not confirmed; inspect before any retry', { resource_ids: resourceIds });\n return resourceIds;\n } };\n }\n if (op.tool !== 'pinterest_send_conversion_events') throw new AdportError('INVALID_INPUT', 'pinterest: unsupported measurement write');\n const input = sendEvents.parse(op.payload), context = await this.context(op.accountId);\n this.checkContext(input.expected_context_hash, context.snapshot_hash);\n const count = input.data.length, batchHash = digest(input.data), mode = input.test ? 'TEST' : 'LIVE';\n let details: unknown, warnings: string[] = [];\n 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.'];\n return { summary: `Send ${count} Pinterest conversion events (${mode})`, changes: [`+ ${count} 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: count }, { label: 'Batch SHA-256', after: batchHash }], notices }, resultDetails: () => details, resultWarnings: () => warnings, execute: async () => {\n let result: z.infer<typeof eventResponse>;\n try { result = await this.client.mutate(`${this.base(op.accountId)}/events`, 'POST', { data: input.data }, eventResponse, new URLSearchParams({ test: String(input.test) })); }\n catch (error) {\n const native = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n throw new AdportError('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: count, ...(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 } : {}) });\n }\n const rows = result.events.map((row, index) => ({ index, status: row.status, has_error: Boolean(row.error_message), has_warning: Boolean(row.warning_message) }));\n const processed = rows.filter(row => row.status === 'processed').length;\n if (result.num_events_received !== count || result.events.length !== count || result.num_events_processed !== processed) throw new AdportError('PROVIDER_ERROR', 'pinterest: conversion-event receipt counts disagree; no automatic retry', { status: 'UNCONFIRMED', mode, batch_sha256: batchHash, record_count: count, num_events_received: result.num_events_received, num_events_processed: result.num_events_processed, rows });\n const complete = processed === count && rows.every(row => !row.has_error);\n details = { status: complete ? 'COMPLETE' : 'PARTIAL_OR_UNCONFIRMED', mode, batch_sha256: batchHash, record_count: count, num_events_received: result.num_events_received, num_events_processed: result.num_events_processed, failed_count: count - processed, rows };\n if (!processed) throw new AdportError('PROVIDER_ERROR', 'pinterest: no conversion events were processed; inspect row outcomes before any new submission', details);\n if (!complete || rows.some(row => row.has_warning)) warnings.push(`${processed} of ${count} events processed; ${count - processed} failed. Inspect result.details and native diagnostics before submitting again.`);\n if (input.test) warnings.push('Test-mode validation only; these events were not recorded for reporting or optimization.');\n return [];\n } };\n }\n private checkContext(expected: string, actual: string) {\n if (expected !== actual) throw new AdportError('INVALID_INPUT', 'pinterest: measurement context changed; read it again before requesting a new preview');\n }\n}\n\nexport function pinterestMeasurementTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (input: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'pinterest', description, input, annotations: { readOnly: true }, handler });\n return [\n read('pinterest_measurement_context', 'Read advertiser identity, conversion tags and a stable snapshot_hash for guarded measurement writes.', z.object({ account_id: id }), input => provider.measurement.context(input.account_id)),\n read('pinterest_conversion_tags', 'Read advertiser-owned conversion tags and code snippets as data. Unpaged native collection; does not install tracking or send events.', z.object({ account_id: id, filter_deleted: z.boolean().default(false) }), input => provider.measurement.tags(input.account_id, input.filter_deleted)),\n read('pinterest_get_conversion_tag', 'Read one advertiser-owned conversion tag by ID. Code snippets are returned as text only.', z.object({ account_id: id, conversion_tag_id: id }), input => provider.measurement.getTag(input.account_id, input.conversion_tag_id)),\n read('pinterest_conversion_tag_eligible_events', 'Read the advertiser’s native OCPM-eligible conversion-tag events without changing optimization.', z.object({ account_id: id }), input => provider.measurement.eligible(input.account_id)),\n defineTool({ name: 'pinterest_conversion_tag_page_visits', namespace: 'pinterest', description: 'Read native conversion-tag page-visit metadata with bookmark pagination.', input: z.object({ account_id: id, page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).max(4096).optional(), order: z.enum(['ASCENDING', 'DESCENDING']).default('ASCENDING') }), annotations: { readOnly: true }, pagination: { cursorInput: 'bookmark' }, handler: input => provider.measurement.visits(input) }),\n read('pinterest_event_quality', 'Read Pinterest’s native conversion-event quality diagnostics for explicit lookback/source filters. No derived score or delivery change.', qualityInput, input => provider.measurement.quality(input)),\n guardedWriteTool({ 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 }),\n guardedWriteTool({ name: 'pinterest_send_conversion_events', namespace: 'pinterest', provider: 'pinterest', kind: 'create', description: 'Send 1–1000 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 }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, defineTool, guardedWriteTool, hostedFeedUrl, type AnyToolDefinition, type ReviewField, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport { pinterestId } from './schemas.js';\nimport type { PinterestAdsProvider } from './provider.js';\n\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]>; resultDetails?(): unknown; resultWarnings?(): string[] };\nconst id = z.string().regex(/^\\d{1,30}$/), hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst type = z.enum(['RETAIL', 'HOTEL', 'CREATIVE_ASSETS']), format = z.enum(['TSV', 'CSV', 'XML', 'INTEGRATION']);\nconst state = z.enum(['ACTIVE', 'INACTIVE']);\nconst name = z.string().trim().min(1).max(1024), currency = z.string().regex(/^[A-Z]{3}$/).nullable();\nconst credentials = z.object({ username: z.string().min(1).max(4096), password: z.string().min(1).max(8192) }).strict().nullable();\nconst location = z.string().url().max(16384).refine(value => { const url = new URL(value); return ['http:', 'https:', 'ftp:', 'sftp:'].includes(url.protocol) && !url.username && !url.password && !url.hash; }, 'Use an HTTP(S), FTP or SFTP URL without inline credentials or fragments');\nconst schedule = z.object({ time: z.string().regex(/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/), timezone: z.string().min(1).max(100) }).strict().nullable();\nconst availability = z.enum(['IN_STOCK', 'OUT_OF_STOCK', 'PREORDER']).nullable();\nconst account = { account_id: pinterestId }, selected = { catalog_id: id }, reference = { ...selected, feed_id: id }, bound = { ...reference, expected_snapshot_hash: hash };\nconst paging = { page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).max(4096).optional() };\nconst catalog = z.looseObject({ id, name: z.string(), catalog_type: type, created_at: z.string(), updated_at: z.string() });\nconst feed = z.looseObject({ id, catalog_type: type, catalog_id: id.nullable().optional(), name: z.string().nullable(), status: z.string(), format, default_locale: z.string(), default_country: z.string().optional(), default_currency: z.string().nullable().optional(), default_availability: availability.optional(), preferred_processing_schedule: schedule.optional(), location: z.string(), credentials: z.unknown().optional(), created_at: z.string(), updated_at: z.string() });\nconst common = { catalog_id: id, name, location, format, default_locale: z.string().min(2).max(40), default_currency: currency.optional(), credentials: credentials.optional(), preferred_processing_schedule: schedule.optional(), status: state.default('INACTIVE') };\nconst feedCreate = z.discriminatedUnion('catalog_type', [\n z.object({ ...common, catalog_type: z.literal('RETAIL'), default_country: z.string().regex(/^[A-Z]{2}$/), default_availability: availability.optional() }).strict(),\n z.object({ ...common, catalog_type: z.literal('HOTEL') }).strict(),\n z.object({ ...common, catalog_type: z.literal('CREATIVE_ASSETS'), default_country: z.string().regex(/^[A-Z]{2}$/) }).strict(),\n]);\nconst feedChangeFields = z.object({ name: name.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();\nconst feedChanges = feedChangeFields.refine(value => Object.keys(value).length > 0, 'Supply at least one feed setting');\nconst createCatalog = z.object({ expected_context_hash: hash, name, catalog_type: type }).strict();\nconst createFeed = z.object({ expected_context_hash: hash, feed: feedCreate, confirm_source_access: z.literal(true), confirm_publication: z.boolean().default(false) }).strict();\nconst updateFeed = z.object({ ...bound, changes: feedChanges, confirm_source_access: z.boolean().default(false), confirm_publication: z.boolean().default(false) }).strict();\nconst [retailFeed, hotelFeed, creativeAssetsFeed] = feedCreate.options;\nconst hostedSource = { location: hostedFeedUrl };\nconst hostedCreateFeed = createFeed.extend({ feed: z.discriminatedUnion('catalog_type', [\n retailFeed.omit({ credentials: true }).extend(hostedSource),\n hotelFeed.omit({ credentials: true }).extend(hostedSource),\n creativeAssetsFeed.omit({ credentials: true }).extend(hostedSource),\n]) });\nconst hostedUpdateFeed = updateFeed.extend({ changes: feedChangeFields.omit({ credentials: true }).extend({ location: hostedFeedUrl.optional() }) });\nconst deleteFeed = z.object({ ...bound, confirm_permanent_deletion: z.literal(true) }).strict();\nconst ingestFeed = z.object({ ...bound, confirm_source_access: z.literal(true), confirm_publication: z.literal(true) }).strict();\nconst processing = z.looseObject({ id, status: z.enum(['COMPLETED', 'FAILED', 'PROCESSING']), created_at: z.string(), updated_at: z.string(), ingestion_details: z.record(z.string(), z.unknown()), product_counts: z.record(z.string(), z.unknown()), validation_details: z.record(z.string(), z.unknown()) });\nconst ingestion = z.object({ id, feed_id: id, status: z.enum(['COMPLETED', 'FAILED', 'PROCESSING']), created_at: z.string() });\nconst writeKinds = { pinterest_create_catalog: 'create', pinterest_create_feed: 'create', pinterest_update_feed: 'update', pinterest_delete_feed: 'remove', pinterest_ingest_feed: 'update' } as const;\nconst isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value);\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : isObject(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value)) ?? 'undefined').digest('hex');\nconst same = (a: unknown, b: unknown) => digest(a) === digest(b);\nfunction sourceOrigin(value: string): string { try { const url = new URL(value); return `${url.protocol}//${url.host}`; } catch { return 'Unavailable'; } }\nfunction privateValues(value: z.infer<typeof feed>) { const auth = isObject(value.credentials) ? value.credentials : {}; return [value.location, auth.username, auth.password].filter((v): v is string => typeof v === 'string' && v.length > 0); }\nfunction redact(value: unknown, secrets: string[]): unknown {\n if (typeof value === 'string') return secrets.reduce((text, secret) => text.replaceAll(secret, '[redacted]'), value);\n if (Array.isArray(value)) return value.map(item => redact(item, secrets));\n 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;\n}\nfunction publicFeed(value: z.infer<typeof feed>) {\n const { location, credentials, ...rest } = value;\n 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'];\n const selected = Object.fromEntries(keys.filter(key => Object.hasOwn(rest, key)).map(key => [key, rest[key]]));\n const { created_at: _created, updated_at: _updated, ...settings } = selected;\n const config = { ...settings, location, credentials_configured: credentials != null };\n return { ...selected, source_origin: sourceOrigin(location), source_fingerprint: digest(location), credentials_configured: credentials != null, snapshot_hash: digest(config) };\n}\nconst output = z.object({ account_id: pinterestId, context_hash: hash, records: z.array(z.record(z.string(), z.unknown())), truncated: z.boolean() }).passthrough();\nconst labels: Record<string, string> = { 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' };\nfunction fields(before: Record<string, unknown> | undefined, requested: Record<string, unknown>): ReviewField[] {\n return Object.entries(requested).filter(([key]) => key !== 'catalog_id').map(([key, value]) => key === 'location'\n ? { label: 'Source', ...(before ? { before: { origin: sourceOrigin(String(before.location)), fingerprint: digest(before.location) } } : {}), after: { origin: sourceOrigin(String(value)), fingerprint: digest(value) } }\n : key === 'credentials' ? { label: 'Feed authentication', ...(before ? { before: before.credentials != null ? 'Configured; values hidden' : 'Not configured' } : {}), after: value === null ? 'Remove credentials' : 'Configure credentials; values hidden' }\n : { label: labels[key] ?? key, ...(before && Object.hasOwn(before, key) ? { before: before[key] } : {}), after: value });\n}\n\n/** Pinterest-owned OpenAPI 5.28.0, commit 2503147; contracts fetched 2026-11-05. */\nexport class PinterestCatalogService {\n constructor(private readonly client: PinterestAdsClient) {}\n supports(tool: string) { return Object.hasOwn(writeKinds, tool); }\n private params(account: string, catalog?: string) { return new URLSearchParams({ ad_account_id: pinterestId.parse(account), ...(catalog ? { catalog_id: id.parse(catalog) } : {}) }); }\n private async context(account: string) {\n const value = await this.client.get(`ad_accounts/${pinterestId.parse(account)}`, z.object({ id: pinterestId, owner: z.object({ username: z.string().min(1) }) }));\n if (value.id !== account) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog advertiser ID mismatch');\n return { account_id: account, context_hash: digest({ account, owner: value.owner.username.toLowerCase() }) };\n }\n private async page<T>(path: string, schema: z.ZodType<T>, params: URLSearchParams, input: { page_size: number; bookmark?: string }) {\n params.set('page_size', String(input.page_size)); if (input.bookmark) params.set('bookmark', input.bookmark);\n const value = await this.client.get(path, z.object({ items: z.array(schema), bookmark: z.string().nullable().optional() }), params);\n const ids = value.items.flatMap(row => isObject(row) && typeof row.id === 'string' ? [row.id] : []);\n if (value.items.length > input.page_size || new Set(ids).size !== ids.length || value.bookmark && (value.bookmark === input.bookmark || !value.items.length)) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog pagination did not advance consistently');\n return { ...value, truncated: Boolean(value.bookmark), ...(value.bookmark ? { next_cursor: value.bookmark } : {}) };\n }\n private async find<T extends { id?: string }>(path: string, schema: z.ZodType<T>, params: URLSearchParams, wanted: string): Promise<T | undefined> {\n const seen = new Set<string>(), ids = new Set<string>(); let bookmark: string | undefined;\n for (let pages = 0; pages < 40; pages++) {\n const page = await this.page(path, schema, new URLSearchParams(params), { page_size: 250, bookmark });\n for (const row of page.items) { if (row.id && ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog finder repeated an identity'); if (row.id) ids.add(row.id); if (row.id === wanted) return row; }\n if (!page.next_cursor) return undefined;\n if (seen.has(page.next_cursor)) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog finder repeated a bookmark');\n seen.add(page.next_cursor); bookmark = page.next_cursor;\n }\n throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog membership lookup exceeded 10,000 rows; membership is unconfirmed');\n }\n private async ownedCatalog(account: string, catalogId: string) {\n const value = await this.find('catalogs', catalog, this.params(account), id.parse(catalogId));\n if (!value) throw new AdportError('INVALID_INPUT', 'pinterest: catalog was not found for the selected advertiser owner');\n return value;\n }\n private validateFeed(value: z.infer<typeof feed>, selected: z.infer<typeof catalog>) {\n if (value.catalog_type !== selected.catalog_type || value.catalog_id != null && value.catalog_id !== selected.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: feed catalog/type mismatch');\n return value;\n }\n private async ownedFeed(account: string, catalogId: string, feedId: string) {\n const selected = await this.ownedCatalog(account, catalogId), member = await this.find('catalogs/feeds', feed, this.params(account, catalogId), id.parse(feedId));\n if (!member) throw new AdportError('INVALID_INPUT', 'pinterest: feed was not found in the selected advertiser catalog');\n this.validateFeed(member, selected);\n const value = await this.client.get(`catalogs/feeds/${feedId}`, feed, this.params(account));\n if (value.id !== feedId) throw new AdportError('PROVIDER_ERROR', 'pinterest: feed ID mismatch');\n return this.validateFeed(value, selected);\n }\n async catalogs(input: { account_id: string; page_size: number; bookmark?: string }) {\n const context = await this.context(input.account_id), page = await this.page('catalogs', catalog, this.params(input.account_id), input);\n return { ...context, ...page, records: page.items.map(value => ({ ...value, snapshot_hash: digest({ id: value.id, name: value.name, catalog_type: value.catalog_type }) })) };\n }\n async getCatalog(account: string, catalogId: string) {\n const context = await this.context(account), value = await this.ownedCatalog(account, catalogId);\n return { ...context, catalog: value, records: [value], truncated: false };\n }\n async feeds(input: { account_id: string; catalog_id: string; page_size: number; bookmark?: string }) {\n const context = await this.context(input.account_id), selected = await this.ownedCatalog(input.account_id, input.catalog_id), page = await this.page('catalogs/feeds', feed, this.params(input.account_id, input.catalog_id), input);\n const items = page.items.map(value => publicFeed(this.validateFeed(value, selected)));\n return { ...context, ...page, items, records: items, catalog_id: selected.id };\n }\n async getFeed(account: string, catalogId: string, feedId: string) {\n const context = await this.context(account), value = publicFeed(await this.ownedFeed(account, catalogId, feedId));\n return { ...context, feed: value, records: [value], truncated: false };\n }\n async results(input: { account_id: string; catalog_id: string; feed_id: string; page_size: number; bookmark?: string }) {\n const context = await this.context(input.account_id), current = await this.ownedFeed(input.account_id, input.catalog_id, input.feed_id);\n const page = await this.safe(current, () => this.page(`catalogs/feeds/${current.id}/processing_results`, processing, this.params(input.account_id), input));\n const items = page.items.map(value => redact(value, privateValues(current)) as Record<string, unknown>);\n return { ...context, ...page, items, records: items, feed_id: current.id };\n }\n async issues(input: { account_id: string; catalog_id: string; feed_id: string; processing_result_id: string; page_size: number; bookmark?: string; item_numbers?: number[]; item_validation_issue?: string }) {\n const context = await this.context(input.account_id), current = await this.ownedFeed(input.account_id, input.catalog_id, input.feed_id);\n const result = await this.safe(current, () => this.find(`catalogs/feeds/${current.id}/processing_results`, processing, this.params(input.account_id), input.processing_result_id));\n if (!result) throw new AdportError('INVALID_INPUT', 'pinterest: processing result was not found for this feed');\n const params = this.params(input.account_id);\n if (input.item_numbers) params.set('item_numbers', input.item_numbers.join(','));\n if (input.item_validation_issue) params.set('item_validation_issue', input.item_validation_issue);\n const page = await this.safe(current, () => this.page(`catalogs/processing_results/${result.id}/item_issues`, z.record(z.string(), z.unknown()), params, input));\n const items = page.items.map(value => redact(value, privateValues(current)) as Record<string, unknown>);\n return { ...context, ...page, 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.'] };\n }\n private async safe<T>(current: z.infer<typeof feed>, fn: () => Promise<T>): Promise<T> {\n try { return await fn(); } catch (error) {\n if (!(error instanceof AdportError)) throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog request was not confirmed; reconcile before retrying');\n throw new AdportError(error.code, redact(error.message, privateValues(current)) as string, redact(error.details, privateValues(current)));\n }\n }\n private async verify(resource: string, fn: () => Promise<boolean>) {\n try { if (!await fn()) throw new Error('readback mismatch'); }\n catch { throw new AdportError('PROVIDER_ERROR', 'pinterest: catalog write readback unconfirmed; reconcile the resource ID before a new approval', { resource_ids: [resource] }); }\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'pinterest' || !this.supports(op.tool) || op.kind !== writeKinds[op.tool as keyof typeof writeKinds]) throw new AdportError('INVALID_INPUT', 'pinterest: catalog operation kind mismatch');\n const context = await this.context(op.accountId), base = { coercions: [], budgetDeltas: [], notes: [] };\n const review = (title: string, subject: string, fields: ReviewField[], notices: string[]) => ({ provider: 'pinterest', accountId: op.accountId, kind: op.kind, title, subject, fields, notices });\n if (op.tool === 'pinterest_create_catalog') {\n const input = createCatalog.parse(op.payload);\n if (input.expected_context_hash !== context.context_hash) throw new AdportError('INVALID_INPUT', 'pinterest: catalog advertiser context changed; read catalogs again');\n const body = { name: input.name, catalog_type: input.catalog_type };\n return { ...base, summary: `Create Pinterest ${input.catalog_type} catalog \"${input.name}\"`, changes: [`+ ${JSON.stringify(body)}`], review: review('Create catalog', input.name, fields(undefined, body), ['Creates an empty catalog. No feed, products, Pins or ads are created. Native catalog-program eligibility is still required.']), execute: async () => {\n const value = await this.client.mutate('catalogs', 'POST', body, catalog, this.params(op.accountId));\n await this.verify(value.id, async () => { const current = await this.ownedCatalog(op.accountId, value.id); return current.name === body.name && current.catalog_type === body.catalog_type; });\n return [value.id];\n } };\n }\n if (op.tool === 'pinterest_create_feed') {\n const input = createFeed.parse(op.payload), body = input.feed, selected = await this.ownedCatalog(op.accountId, body.catalog_id);\n if (input.expected_context_hash !== context.context_hash || selected.catalog_type !== body.catalog_type) throw new AdportError('INVALID_INPUT', 'pinterest: catalog advertiser context/type changed; read catalogs again');\n if (body.status === 'ACTIVE' && !input.confirm_publication) throw new AdportError('INVALID_INPUT', 'pinterest: active feeds may create public product Pins; confirm publication and source access');\n const changes = fields(undefined, body);\n return { ...base, summary: `Create Pinterest feed \"${body.name}\"`, changes: changes.map(field => `+ ${field.label}: ${JSON.stringify(field.after)}`), review: review('Create feed', body.name, changes, ['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 () => {\n const value = await this.client.mutate('catalogs/feeds', 'POST', body, feed, this.params(op.accountId));\n await this.verify(value.id, async () => this.matches(await this.ownedFeed(op.accountId, selected.id, value.id), body));\n return [value.id];\n }, resultWarnings: () => ['Saved feed configuration is not proof of source authentication or imported products; read processing results.'] };\n }\n const input = op.tool === 'pinterest_update_feed' ? updateFeed.parse(op.payload) : op.tool === 'pinterest_delete_feed' ? deleteFeed.parse(op.payload) : ingestFeed.parse(op.payload);\n const current = await this.ownedFeed(op.accountId, input.catalog_id, input.feed_id);\n if (publicFeed(current).snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('INVALID_INPUT', 'pinterest: feed configuration changed; read the feed again');\n if (current.status === 'DELETED') throw new AdportError('INVALID_INPUT', 'pinterest: this feed is deleted');\n 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 () => {\n const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}`, 'DELETE', undefined, z.union([feed, z.undefined()]), this.params(op.accountId)));\n if (result && result.id !== current.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: feed delete receipt ID mismatch', { resource_ids: [current.id] });\n await this.verify(current.id, async () => { const remaining = await this.find('catalogs/feeds', feed, this.params(op.accountId, input.catalog_id), current.id); return !remaining || remaining.status === 'DELETED'; });\n return [current.id];\n } };\n if (op.tool === 'pinterest_ingest_feed') {\n let details: unknown, warning: string[] = [];\n 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: digest(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 () => {\n const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}/ingest`, 'POST', undefined, ingestion, this.params(op.accountId)));\n if (result.feed_id !== current.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: ingestion receipt feed mismatch', { resource_ids: [current.id, result.id] });\n 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' };\n if (result.status === 'FAILED') warning = ['Pinterest reports that the requested ingestion failed. Read processing results; do not automatically retry.'];\n return [result.id];\n }, resultDetails: () => details, resultWarnings: () => warning };\n }\n const update = updateFeed.parse(op.payload), changes = update.changes;\n if (current.catalog_type !== 'RETAIL' && Object.hasOwn(changes, 'default_availability')) throw new AdportError('INVALID_INPUT', 'pinterest: default availability is retail-only');\n if ((changes.location !== undefined || changes.credentials != null || changes.status === 'ACTIVE') && !update.confirm_source_access) throw new AdportError('INVALID_INPUT', 'pinterest: changing feed source/authentication or activating processing requires source-access confirmation');\n if ((changes.status ?? current.status) === 'ACTIVE' && Object.keys(changes).some(key => key !== 'name') && !update.confirm_publication) throw new AdportError('INVALID_INPUT', 'pinterest: changes to an active feed may affect public product Pins; confirm publication');\n if (!Object.entries(changes).some(([key, value]) => key === 'credentials' || !same(current[key], value))) throw new AdportError('INVALID_INPUT', 'pinterest: no supplied feed settings would change');\n const body = { catalog_type: current.catalog_type, ...changes }, visible = fields(current, changes);\n return { ...base, summary: `Update Pinterest feed ${current.id}`, changes: visible.map(field => `~ ${field.label}: ${JSON.stringify(field.before)} → ${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 () => {\n const result = await this.safe(current, () => this.client.mutate(`catalogs/feeds/${current.id}`, 'PATCH', body, feed, this.params(op.accountId)));\n if (result.id !== current.id) throw new AdportError('PROVIDER_ERROR', 'pinterest: feed update receipt ID mismatch', { resource_ids: [current.id] });\n await this.verify(current.id, async () => this.matches(await this.ownedFeed(op.accountId, input.catalog_id, current.id), changes));\n return [current.id];\n }, resultWarnings: () => changes.location !== undefined || changes.credentials != null ? ['Source downloading/authentication is unverified until native processing results confirm success.'] : [] };\n }\n private matches(current: z.infer<typeof feed>, wanted: Record<string, unknown>) {\n return Object.entries(wanted).every(([key, value]) => {\n if (key === 'catalog_id' && current.catalog_id == null) return true;\n if (key === 'credentials') return value === null ? current.credentials == null : current.credentials != null;\n return same(current[key], value);\n });\n }\n}\n\nexport function pinterestCatalogTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ 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: z.object({ ...account, ...paging }).strict(), output, presentation: 'records', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: input => provider.catalogs.catalogs(input) }),\n defineTool({ 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: z.object({ ...account, ...selected }).strict(), output, presentation: 'records', annotations: { readOnly: true }, handler: input => provider.catalogs.getCatalog(input.account_id, input.catalog_id) }),\n defineTool({ name: 'pinterest_feeds', namespace: 'pinterest', description: 'List one advertiser-owned catalog’s feeds and configuration snapshots. Native bookmarks; source paths/query values and feed credentials stay hidden.', input: z.object({ ...account, ...selected, ...paging }).strict(), output, presentation: 'records', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: input => provider.catalogs.feeds(input) }),\n defineTool({ 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: z.object({ ...account, ...reference }).strict(), output, presentation: 'records', annotations: { readOnly: true }, handler: input => provider.catalogs.getFeed(input.account_id, input.catalog_id, input.feed_id) }),\n defineTool({ 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: z.object({ ...account, ...reference, ...paging }).strict(), output, presentation: 'records', pagination: { cursorInput: 'bookmark' }, annotations: { readOnly: true }, handler: input => provider.catalogs.results(input) }),\n defineTool({ 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: z.object({ ...account, ...reference, processing_result_id: id, ...paging, item_numbers: z.array(z.number().int().nonnegative().safe()).min(1).max(1000).optional(), item_validation_issue: z.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) }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ name: 'pinterest_create_feed', namespace: 'pinterest', provider: 'pinterest', kind: 'create', payload: createFeed, hosted: { payload: hostedCreateFeed, description: 'Create a feed with a public HTTPS source in the selected Pinterest catalog. Defaults to INACTIVE. Confirm access to the source. ACTIVE also requires confirmation that processing can publish product Pins.' }, 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.' }),\n guardedWriteTool({ name: 'pinterest_update_feed', namespace: 'pinterest', provider: 'pinterest', kind: 'update', payload: updateFeed, hosted: { payload: hostedUpdateFeed, description: 'Update selected settings on an owned Pinterest catalog feed. A replacement source must be a public HTTPS URL. Source changes require access confirmation. Active feeds require confirmation that processing can publish product Pins.' }, 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.' }),\n guardedWriteTool({ 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.' }),\n guardedWriteTool({ 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.' }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestCatalogService } from './catalogs.js';\nimport { pinterestId } from './schemas.js';\nimport { catalogType, groupAction, groupChanges, groupContext, groupCreate, groupDelete, groupId, groupList, groupPaging, groupReference, groupUpdate, nativeGroup, productGroupFilterSchema } from './product-group-schemas.js';\n\ntype Group = z.infer<typeof nativeGroup>;\ntype Action = z.infer<typeof groupAction>;\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]>; resultDetails?(): unknown; resultWarnings?(): string[] };\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst hash = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst normalizeFilters = (filters: unknown): unknown => {\n if (!filters || typeof filters !== 'object' || Array.isArray(filters)) return filters;\n return Object.fromEntries(Object.entries(filters).map(([key, raw]) => {\n // Pinterest explicitly defaults these two pricing criteria to inclusion:true.\n const value = ['MIN_PRICE', 'MAX_PRICE'].includes(key) && raw && typeof raw === 'object' && !Array.isArray(raw) ? { inclusion: true, ...raw } : raw;\n 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) => canonical(a).localeCompare(canonical(b))) : normalizeFilters(value)];\n }));\n};\nconst configuration = (value: Group): Row => ({ ...Object.fromEntries(Object.entries(value).filter(([key]) => !['created_at', 'updated_at'].includes(key))), filters: normalizeFilters(value.filters) });\nconst mismatch = () => new AdportError('PROVIDER_ERROR', 'pinterest: product group scope, native response or pagination could not be verified.');\nconst 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.'];\nconst cursor = z.object({ selection: z.string().regex(/^[a-f0-9]{64}$/), native: z.string().min(1).max(4096) }).strict();\nconst count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst counts = z.discriminatedUnion('catalog_type', [z.object({ catalog_type: z.literal('RETAIL'), in_stock: count, out_of_stock: count, preorder: count, total: count, videos: count.optional() }).strict(), z.object({ catalog_type: z.literal('HOTEL'), total: count }).strict(), z.object({ catalog_type: z.literal('CREATIVE_ASSETS'), total: count, videos: count, images: count, app_links: count }).strict()]);\nconst product = z.object({ catalog_type: catalogType, metadata: z.record(z.string(), z.json()), pin: z.record(z.string(), z.json()) });\n\n/** Pinterest-owned OpenAPI 5.28.0 at 51aca009, fetched 2026-11-06. */\nexport class PinterestProductGroups {\n constructor(private readonly client: PinterestAdsClient, private readonly catalogs: PinterestCatalogService) {}\n private params(account: string, extra: Record<string, string> = {}) { return new URLSearchParams({ ad_account_id: pinterestId.parse(account), ...extra }); }\n private scope(group: Group, catalog: { id: string; catalog_type: string }, wanted?: string) {\n if (group.catalog_id !== catalog.id || group.catalog_type !== catalog.catalog_type || wanted && group.id !== wanted || group.catalog_type !== 'RETAIL' && group.feed_id != null) throw mismatch();return group;\n }\n private snapshot(account: string, group: Group) { return hash({ account_id: account, configuration: configuration(group) }); }\n private async read(account: string, catalog: { id: string; catalog_type: string }, id: string) { return this.scope(await this.client.get(`catalogs/product_groups/${groupId.parse(id)}`, nativeGroup, this.params(account)), catalog, id); }\n private async page<S extends z.ZodType>(path: string, schema: S, account: string, selection: Row, input: { page_size: number; bookmark?: string }, query: Record<string, string>) {\n const key = hash({ account, selection, page_size: input.page_size });let native: string | undefined;\n if (input.bookmark) { let parsed: z.infer<typeof cursor>;try { parsed = cursor.parse(JSON.parse(Buffer.from(input.bookmark, 'base64url').toString('utf8'))); } catch { throw new AdportError('INVALID_INPUT', 'Invalid product group cursor; restart this selection.'); }if (parsed.selection !== key) throw new AdportError('PENDING_MISMATCH', 'Product group selection changed; restart its first page.');native = parsed.native; }\n const params = this.params(account, { ...query, page_size: String(input.page_size), ...(native ? { bookmark: native } : {}) }), value = await this.client.get(path, z.object({ items: z.array(schema).max(250), bookmark: z.string().min(1).max(4096).nullable().optional() }), params);\n if (value.items.length > input.page_size || value.bookmark && (value.bookmark === native || !value.items.length)) throw mismatch();\n const complete = value.bookmark === null ? true : value.bookmark === undefined ? null : false;\n return { items: value.items, complete, truncated: complete !== true, ...(value.bookmark ? { next_cursor: Buffer.from(JSON.stringify({ selection: key, native: value.bookmark })).toString('base64url') } : {}) };\n }\n async list(value: unknown) {\n const input = groupList.parse(value), context = await this.catalogs.getCatalog(input.account_id, input.catalog_id);\n if (input.feed_id) { if (context.catalog.catalog_type !== 'RETAIL') throw new AdportError('INVALID_INPUT', 'Feed-based groups are RETAIL only.');await this.catalogs.getFeed(input.account_id, input.catalog_id, input.feed_id); }\n const selected = { catalog_id: input.catalog_id, feed_id: input.feed_id, product_group_ids: input.product_group_ids ? [...input.product_group_ids].sort() : undefined }, page = await this.page('catalogs/product_groups', nativeGroup, input.account_id, selected, input, { catalog_id: input.catalog_id, ...(input.feed_id ? { feed_id: input.feed_id } : {}), ...(input.product_group_ids ? { id: input.product_group_ids.join(',') } : {}) });\n if (new Set(page.items.map(row => row.id)).size !== page.items.length || page.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();\n const items = page.items.map(row => ({ ...this.scope(row, context.catalog), snapshot_hash: this.snapshot(input.account_id, row) }));return { ...page, items, records: items, notes };\n }\n async get(value: unknown) { 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) };return { group, records: [group], notes }; }\n async counts(value: unknown) {\n 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));if (data.catalog_type !== group.catalog_type) throw mismatch();\n 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.'] };\n }\n async products(value: unknown) {\n 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 }), page = await this.page(`catalogs/product_groups/${group.id}/products`, product, input.account_id, { catalog_id: input.catalog_id, product_group_id: group.id, snapshot_hash: group.snapshot_hash }, input, {});\n const records = page.items.map(row => { const key = row.catalog_type === 'RETAIL' ? 'item_id' : row.catalog_type === 'HOTEL' ? 'hotel_id' : 'creative_assets_id', nativeId = row.metadata[key];if (row.catalog_type !== group.catalog_type || typeof nativeId !== 'string' || !nativeId || nativeId.length > 1024) throw mismatch();return { id: `${row.catalog_type}:${nativeId}:${hash(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 }; });\n if (new Set(records.map(row => row.id)).size !== records.length) throw mismatch();return { ...page, records, 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.'] };\n }\n private mutable(row: Group) { if (row.catalog_type !== 'CREATIVE_ASSETS' && row.type !== 'MERCHANT_CREATED') throw new AdportError('INVALID_INPUT', 'Only merchant-created retail/hotel product groups can be edited or deleted; automatic groups are read-only.'); }\n private references(filters: unknown): string[] {\n const result = new Set<string>();\n const walk = (value: unknown) => { if (!value || typeof value !== 'object') return;if (Array.isArray(value)) { value.forEach(walk);return; }for (const [key, item] of Object.entries(value)) { if (key === 'PRODUCT_GROUP') { const parsed = z.object({ values: z.array(groupId).min(1).max(100) }).safeParse(item);if (!parsed.success) throw mismatch();parsed.data.values.forEach(id => result.add(id)); }else walk(item); } };walk(filters);return [...result].sort();\n }\n async context(value: unknown) {\n const input = groupContext.parse(value), owner = await this.catalogs.getCatalog(input.account_id, input.catalog_id), catalog = owner.catalog, action = input.action;\n const current = action.kind === 'create' ? undefined : await this.read(input.account_id, catalog, action.product_group_id);if (current) this.mutable(current);\n let body: Row = {}, feed: unknown;\n if (action.kind === 'create') {\n const { mode, catalog_type, feed_id, confirm_all_products: _all, ...fields } = action.definition;if (catalog_type !== catalog.catalog_type) throw new AdportError('INVALID_INPUT', 'Product group type differs from selected catalog.');\n if (mode === 'FEED') { const currentFeed = (await this.catalogs.getFeed(input.account_id, catalog.id, feed_id!)).feed;feed = { id: feed_id, snapshot_hash: currentFeed.snapshot_hash }; }\n body = mode === 'FEED' ? { feed_id, ...fields } : { catalog_id: catalog.id, catalog_type, ...fields };\n } else if (action.kind === 'update') {\n const { confirm_all_products, ...changes } = groupChanges.parse(action.changes);\n if ((current!.catalog_type !== 'RETAIL' || current!.feed_id != null) && (changes.country !== undefined || changes.locale !== undefined)) throw new AdportError('INVALID_INPUT', 'Country/locale apply only to catalog-based RETAIL groups.');\n if (changes.filters && !productGroupFilterSchema(current!.catalog_type, current!.catalog_type !== 'RETAIL' && confirm_all_products === true).safeParse(changes.filters).success) throw new AdportError('INVALID_INPUT', 'Invalid filter selection; use pinterest_product_group_filter_schema.');\n body = { ...(current!.feed_id != null ? {} : { catalog_type: current!.catalog_type }), ...changes };\n } else if (!current!.name || current!.name !== action.confirm_name) throw new AdportError('INVALID_INPUT', 'Permanent deletion requires the exact current product group name.');\n const referenced = new Map<string, Group>(), visit = async (id: string, stack: Set<string>): Promise<void> => {\n if (id === current?.id || stack.has(id)) throw new AdportError('INVALID_INPUT', 'Product group filter references contain a cycle.');if (referenced.has(id)) return;if (referenced.size >= 40) throw new AdportError('INVALID_INPUT', 'Reference proof exceeds the 40-group Adport bound.');\n const row = await this.read(input.account_id, catalog, id);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 AdportError('INVALID_INPUT', 'Referenced groups must belong to the selected retail feed.');\n referenced.set(id, row);for (const next of this.references(row.filters)) await visit(next, new Set([...stack, id]));\n };\n // Deletion does not resolve outgoing filter references; it verifies only the\n // exact owned resource being removed, including all current configuration.\n if (action.kind !== 'delete') for (const id of this.references(body.filters ?? current?.filters)) await visit(id, new Set());\n const context_hash = hash({ account_id: input.account_id, owner: owner.context_hash, catalog: { id: catalog.id, name: catalog.name, catalog_type: catalog.catalog_type }, action, current: current ? configuration(current) : undefined, body, feed, references: [...referenced.values()].map(row => configuration(row)).sort((a, b) => String(a.id).localeCompare(String(b.id))) });\n return { context_hash, catalog, current, body, records: [current ? { ...current, snapshot_hash: this.snapshot(input.account_id, current) } : { id: catalog.id, name: catalog.name, catalog_type: catalog.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 };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const create = op.tool === 'pinterest_create_product_group', update = op.tool === 'pinterest_update_product_group', remove = op.tool === 'pinterest_delete_product_group';\n if (op.provider !== 'pinterest' || !(create || update || remove) || op.kind !== (create ? 'create' : update ? 'update' : 'remove')) throw new AdportError('INVALID_INPUT', 'Invalid Pinterest product group operation.');\n const input = create ? groupCreate.parse(op.payload) : update ? groupUpdate.parse(op.payload) : groupDelete.parse(op.payload);\n const action: 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 };\n const prepare = async () => { const context = await this.context({ account_id: op.accountId, catalog_id: input.catalog_id, action });if (context.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'Product group context, references or source settings changed; read context and preview again.');return context; }, before = await prepare();\n const title = create ? 'Create product group' : update ? 'Update product group' : 'Delete product group permanently', subject = create ? String(before.body.name) : before.current!.name ?? before.current!.id;let receipt: Row | undefined;\n return { summary: `${title} · ${subject}`, changes: [remove ? '- ' + subject : `${create ? '+' : '~'} ${canonical(before.body)}`], coercions: [], budgetDeltas: [], notes,\n 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' } as Record<string, string>)[key] ?? key, ...(before.current && Object.hasOwn(before.current, key) ? { before: before.current[key] } : {}), after }))), { label: 'Verified filter references', after: before.reference_count }], notices: notes },\n execute: async () => { const fresh = await prepare();let id = fresh.current?.id;try {\n const path = `catalogs/product_groups${id ? '/' + id : ''}`;\n const result = await this.client.mutate(path, create ? 'POST' : update ? 'PATCH' : 'DELETE', remove ? undefined : fresh.body, remove ? z.union([nativeGroup, z.undefined()]) : nativeGroup, this.params(op.accountId));\n if (result) { if (id && result.id !== id) throw mismatch();id = result.id;this.scope(result, fresh.catalog, id); }if (!id) throw mismatch();\n if (remove) {\n const absence = await this.list({ account_id: op.accountId, catalog_id: input.catalog_id, product_group_ids: [id], page_size: 1 });if (absence.complete !== true || absence.items.length) throw mismatch();receipt = { deletion_readback: 'ABSENT_FROM_COMPLETE_FILTERED_LIST', items_deleted: false };\n } else {\n const actual = await this.read(op.accountId, fresh.catalog, id);\n if (create && !fresh.body.feed_id && actual.feed_id != null) throw mismatch();\n 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' }) };\n if (Object.entries(wanted).some(([key, value]) => canonical(configuration(actual)[key]) !== canonical(value))) throw mismatch();\n 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: id } };\n }\n return [id];\n } catch (error) { const data = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Row : {}, returned = Array.isArray(data.resource_ids) ? data.resource_ids.filter((value): value is string => typeof value === 'string' && groupId.safeParse(value).success) : [];throw new AdportError('PROVIDER_ERROR', 'Pinterest product group mutation is unconfirmed. No write was retried; reconcile known IDs before another preview.', { resource_ids: [...new Set([...(id ? [id] : []), ...returned])], ...(typeof data.http_status === 'number' ? { http_status: data.http_status } : {}) }); }\n }, resultDetails: () => receipt, resultWarnings: () => notes.slice(1) };\n }\n}\n","import { z } from 'zod';\nimport { pinterestId } from './schemas.js';\nimport { filterEnums, filterFields } from './product-group-filter-spec.js';\n\nexport const catalogType = z.enum(['RETAIL', 'HOTEL', 'CREATIVE_ASSETS']);\nexport const groupId = z.string().regex(/^\\d{1,30}$/), groupHash = z.string().regex(/^[a-f0-9]{64}$/);\nconst text = z.string().min(1).max(1024), negated = z.boolean().optional();\nconst strings = z.array(text).min(1).max(100), numericOperator = z.enum(['GREATER_THAN', 'GREATER_THAN_OR_EQUALS', 'LESS_THAN', 'LESS_THAN_OR_EQUALS']);\nconst criteria: Record<string, z.ZodType> = {\n CatalogsProductGroupMultipleStringCriteria: z.object({ values: strings, negated }).strict(),\n CatalogsProductGroupMultipleStringListCriteria: z.object({ values: z.array(strings).min(1).max(100), negated }).strict(),\n CatalogsProductGroupFilterOperatorTypeCriteria: z.object({ values: strings, negated, filter_operator_type: z.enum(['IS', 'CONTAINS']).optional() }).strict(),\n CatalogsProductGroupPricingCriteria: z.object({ values: z.number().nonnegative().max(Number.MAX_SAFE_INTEGER), negated, inclusion: z.boolean().optional() }).strict(),\n CatalogsProductGroupUint32Criteria: z.object({ value: z.number().int().min(0).max(4_294_967_295), negated, operator: numericOperator }).strict(),\n CatalogsProductGroupCurrencyCriteria: z.object({ values: z.enum(filterEnums.NonNullableCatalogsCurrency), negated: z.literal(false).optional() }).strict(),\n CatalogsProductGroupMultipleGenderCriteria: z.object({ values: z.array(z.enum(filterEnums.Gender)).min(1).max(100), negated }).strict(),\n CatalogsProductGroupMultipleCountriesCriteria: z.object({ values: z.array(z.enum(filterEnums.Country)).min(1).max(100), negated }).strict(),\n CatalogsProductGroupMultipleMediaTypesCriteria: z.object({ values: z.array(z.enum(filterEnums.MediaType)).min(1).max(100), negated }).strict(),\n CatalogsProductGroupMultiplePinterestProductCategoryCriteria: z.object({ values: z.array(z.enum(filterEnums.ProductCategoryEnum)).min(1).max(100), negated }).strict(),\n PriceFilterPrice: z.object({ currency: z.enum(filterEnums.NonNullableCatalogsCurrency), negated, operator: numericOperator, value: z.number().nonnegative().max(Number.MAX_SAFE_INTEGER) }).strict(),\n};\nexport function productGroupFilterSchema(type: z.infer<typeof catalogType>, allowEmpty = false) {\n const fields = Object.entries(filterFields[type]).map(([key, value]) => z.object({ [key]: criteria[value]! }).strict());\n const clause = z.union([fields[0]!, fields[1]!, ...fields.slice(2)]);\n const list = z.array(clause).min(allowEmpty ? 0 : 1).max(32);\n return z.union([z.object({ any_of: list }).strict(), z.object({ all_of: list }).strict()]);\n}\n// Keep large native enums on demand; every supplied filter is validated against\n// the same pinned Zod schema before preview or native use, never silently dropped.\nexport const groupFilters = z.record(z.string(), z.json()).refine(value => Buffer.byteLength(JSON.stringify(value), 'utf8') <= 262_144, 'Filters exceed the 256 KiB Adport bound');\nexport const groupDefinition = z.object({\n mode: z.enum(['FEED', 'CATALOG']), catalog_type: catalogType, feed_id: groupId.optional(),\n name: text, description: z.string().max(10_000).nullable().optional(), filters: groupFilters,\n country: z.enum(filterEnums.Country).optional(), locale: z.enum(filterEnums.CatalogsLocale).optional(),\n confirm_all_products: z.literal(true).optional(),\n}).strict().superRefine((value, ctx) => {\n if (value.mode === 'FEED' ? value.catalog_type !== 'RETAIL' || !value.feed_id || value.country !== undefined || value.locale !== undefined : value.feed_id !== undefined || value.catalog_type !== 'RETAIL' && (value.country !== undefined || value.locale !== undefined)) 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' });\n validateGroupFilters(value.catalog_type, value.filters, value.confirm_all_products, ctx);\n});\nexport function validateGroupFilters(type: z.infer<typeof catalogType>, filters: z.infer<typeof groupFilters>, all: boolean | undefined, ctx: z.RefinementCtx) {\n if (!productGroupFilterSchema(type, type !== '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.' });\n}\nexport const groupChanges = z.object({ name: text.optional(), description: z.string().max(10_000).nullable().optional(), filters: groupFilters.optional(), country: z.enum(filterEnums.Country).optional(), locale: z.enum(filterEnums.CatalogsLocale).optional(), confirm_all_products: z.literal(true).optional() }).strict().refine(value => Object.keys(value).some(key => key !== 'confirm_all_products'), 'Supply at least one setting');\nconst selection = { catalog_id: groupId }, reference = { ...selection, product_group_id: groupId };\nexport const groupCreate = z.object({ ...selection, expected_context_hash: groupHash, definition: groupDefinition }).strict();\nexport const groupUpdate = z.object({ ...reference, expected_context_hash: groupHash, changes: groupChanges, acknowledge_live_effects: z.literal(true) }).strict();\nexport const groupDelete = z.object({ ...reference, expected_context_hash: groupHash, confirm_name: z.string().min(1).max(1024), acknowledge_live_effects: z.literal(true), confirm_permanent_deletion: z.literal(true) }).strict();\nexport const groupAction = z.discriminatedUnion('kind', [\n z.object({ kind: z.literal('create'), definition: groupDefinition }).strict(),\n z.object({ kind: z.literal('update'), product_group_id: groupId, changes: groupChanges }).strict(),\n z.object({ kind: z.literal('delete'), product_group_id: groupId, confirm_name: z.string().min(1).max(1024) }).strict(),\n]);\nexport const groupContext = z.object({ account_id: pinterestId, ...selection, action: groupAction }).strict();\nexport const groupPaging = { page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).max(8192).optional() };\nexport const groupList = z.object({ account_id: pinterestId, ...selection, feed_id: groupId.optional(), product_group_ids: z.array(groupId).min(1).max(100).refine(ids => new Set(ids).size === ids.length).optional(), ...groupPaging }).strict();\nexport const groupReference = z.object({ account_id: pinterestId, ...reference }).strict();\nexport const nativeGroup = z.looseObject({ id: groupId, catalog_id: groupId, catalog_type: catalogType, name: z.string().max(1024).optional(), description: z.string().max(10_000).nullable().optional(), filters: groupFilters, feed_id: groupId.nullable().optional(), type: z.string().optional(), country: z.string().nullable().optional(), locale: z.string().nullable().optional(), created_at: z.number().int().safe().optional(), updated_at: z.number().int().safe().optional() }).superRefine((value, ctx) => {\n 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' });\n});\n","// Pinterest-owned OpenAPI 5.28.0, 51aca009f10a90283ccdf3956d509fc995ebac23.\n// Pinned native field/enum data for on-demand filter discovery and shared validation.\nexport const filterFields = {\n \"RETAIL\": {\n \"MIN_PRICE\": \"CatalogsProductGroupPricingCriteria\",\n \"MAX_PRICE\": \"CatalogsProductGroupPricingCriteria\",\n \"CURRENCY\": \"CatalogsProductGroupCurrencyCriteria\",\n \"ITEM_ID\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"AVAILABILITY\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"BRAND\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"CONDITION\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"CUSTOM_LABEL_0\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_1\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_2\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_3\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_4\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"ITEM_GROUP_ID\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"GENDER\": \"CatalogsProductGroupMultipleGenderCriteria\",\n \"MEDIA_TYPE\": \"CatalogsProductGroupMultipleMediaTypesCriteria\",\n \"PRODUCT_TYPE_4\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"PRODUCT_TYPE_3\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"PRODUCT_TYPE_2\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"PRODUCT_TYPE_1\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"PRODUCT_TYPE_0\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_6\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_5\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_4\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_3\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_2\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_1\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_0\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"CUSTOM_NUMBER_0\": \"CatalogsProductGroupUint32Criteria\",\n \"CUSTOM_NUMBER_1\": \"CatalogsProductGroupUint32Criteria\",\n \"CUSTOM_NUMBER_2\": \"CatalogsProductGroupUint32Criteria\",\n \"CUSTOM_NUMBER_3\": \"CatalogsProductGroupUint32Criteria\",\n \"CUSTOM_NUMBER_4\": \"CatalogsProductGroupUint32Criteria\",\n \"TITLE_KEYWORDS\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"PINTEREST_PRODUCT_CATEGORIES\": \"CatalogsProductGroupMultiplePinterestProductCategoryCriteria\",\n \"PRODUCT_GROUP\": \"CatalogsProductGroupMultipleStringCriteria\"\n },\n \"HOTEL\": {\n \"PRICE\": \"PriceFilterPrice\",\n \"HOTEL_ID\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"BRAND\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"CUSTOM_LABEL_0\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_1\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_2\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_3\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_4\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"COUNTRY\": \"CatalogsProductGroupMultipleCountriesCriteria\",\n \"TITLE_KEYWORDS\": \"CatalogsProductGroupMultipleStringCriteria\"\n },\n \"CREATIVE_ASSETS\": {\n \"CREATIVE_ASSETS_ID\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"CUSTOM_LABEL_0\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_1\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_2\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_3\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"CUSTOM_LABEL_4\": \"CatalogsProductGroupFilterOperatorTypeCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_6\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_5\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_4\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_3\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_2\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_1\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"GOOGLE_PRODUCT_CATEGORY_0\": \"CatalogsProductGroupMultipleStringListCriteria\",\n \"MEDIA_TYPE\": \"CatalogsProductGroupMultipleMediaTypesCriteria\",\n \"TITLE_KEYWORDS\": \"CatalogsProductGroupMultipleStringCriteria\",\n \"LINK\": \"CatalogsProductGroupFilterOperatorTypeCriteria\"\n }\n} as const;\nexport const 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\"]} as const;\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError, MAX_PROJECT_MEDIA_BYTES, verifyMedia, type Creative, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestCatalogService } from './catalogs.js';\nimport { catalogType, groupHash } from './product-group-schemas.js';\nimport { itemUpdateMask } from './catalog-item-attributes.js';\nimport { attributeSchema, batchReference, itemBatchApply, itemContext, itemCopy, itemIdField, itemIdsField, itemNamedApply, itemOperation, itemRead, itemRequest, itemSelection, itemWriteOperations, sourceId } from './catalog-item-schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Selection = z.infer<typeof itemSelection>;\ntype Request = z.infer<typeof itemRequest>;\ntype Kind = z.infer<typeof catalogType>;\ntype Current = { id: string; state: 'PRESENT' | 'NATIVE_ITEM_ERROR' | 'NOT_RETURNED'; attributes?: Row; pins?: unknown[] | null; diagnostics: unknown; diagnostic_hash?: string };\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]>; resultDetails?(): unknown; resultWarnings?(): string[] };\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst hash = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst object = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\nconst batchId = z.string().regex(/^[A-Za-z0-9_-]{1,100}$/);\nconst diagnostic = z.object({ code: z.number().int().safe().optional(), attribute: z.string().max(256).optional(), message: z.string().max(100_000).optional() });\nconst diagnostics = (value: unknown) => z.array(diagnostic).max(10_000).parse(value ?? []).map(({ message, ...row }) => ({ ...row, message_present: !!message }));\nconst nativeBatch = z.object({ catalog_type: catalogType, batch_id: batchId.optional(), created_time: z.string().max(100).nullable().optional(), completed_time: z.string().max(100).nullable().optional(), status: z.enum(['PROCESSING', 'COMPLETED', 'FAILED']).optional(), items: z.array(z.record(z.string(), z.json())).max(1000).optional() });\nconst manifestRow = z.object({ source_id: sourceId, operation: itemOperation, desired_keys: z.array(z.string()).max(108), clear_keys: z.array(z.string()).max(100), desired_hash: groupHash.optional(), preserved_hash: groupHash.optional() }).strict();\nconst receiptSchema = itemSelection.extend({ version: z.literal('pinterest_items_v1'), scope_id: z.string().min(1).max(200), catalog_type: catalogType, owner_context_hash: groupHash, batch_id: batchId, expires_at: z.number().int().safe(), manifest: z.array(manifestRow).min(1).max(1000), media_expires_at: z.string().max(100).optional() }).strict();\nconst notes = ['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.'];\nconst failure = (error: unknown, ids: string[] = [], extra: Row = {}) => { const data = error instanceof AdportError ? object(error.details) : {};return new AdportError('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.', { ...(ids.length ? { resource_ids: ids } : {}), ...(typeof data.http_status === 'number' ? { http_status: data.http_status } : {}), ...extra }); };\nfunction bounded(value: unknown) { if (Buffer.byteLength(canonical(value)) > 2 * 1024 * 1024) throw new AdportError('INVALID_INPUT', 'Catalog batch exceeds the 2 MiB Adport bound; use smaller batches.'); }\nfunction publicValue(value: unknown, key = ''): unknown {\n if (Array.isArray(value)) return value.map(item => publicValue(item, key));\n if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, publicValue(item, name)]));\n if (typeof value === 'string' && /link|url/i.test(key)) {\n const match = value.match(/^https:\\/\\/adport\\.invalid\\/media\\/([a-f0-9-]+)\\/([a-f0-9]+)$/);if (match) return { media_id: match[1], sha256: match[2] };\n try { const url = new URL(value);return { origin: url.origin, fingerprint: hash(value) }; } catch { return { fingerprint: hash(value) }; }\n }\n return value;\n}\nfunction normalized(type: Kind, values: Row) { return { ...values, ...(type === 'RETAIL' && typeof values.image_link === 'string' ? { image_link: [values.image_link] } : {}) }; }\nfunction wantedValues(type: Kind, attrs: Row, keys: string[], clears: string[]) { return normalized(type, Object.fromEntries(keys.map(key => [key, clears.includes(key) ? null : attrs[key] ?? null]))); }\nfunction preserved(attrs: Row, keys: string[]) { return Object.fromEntries(Object.entries(attrs).filter(([key]) => !keys.includes(key) && key !== 'last_updated_time')); }\nconst safeMediaUrl = (value: string) => { try { const url = new URL(value);return url.protocol === 'https:' && !url.username && !url.password && !url.hash; } catch { return false; } };\n\n/** Native vertical item batches, Pinterest OpenAPI 5.28.0 at 51aca009. */\nexport class PinterestCatalogItems {\n constructor(private readonly client: PinterestAdsClient, private readonly catalogs: PinterestCatalogService, private readonly media: MediaResolver) {}\n supports(tool: string) { return tool === 'pinterest_apply_catalog_items_batch' || tool === 'pinterest_update_catalog_item_copy' || Object.hasOwn(itemWriteOperations, tool); }\n private scopeId() { const value = (this.media as { scopeId?: unknown }).scopeId;return typeof value === 'string' && value ? value : 'local'; }\n private params(account: string) { return new URLSearchParams({ ad_account_id: account }); }\n private snapshot(selection: Selection, type: Kind, owner: string, row: Current) { return hash({ selection, catalog_type: type, owner, id: row.id, state: row.state, attributes: row.attributes, diagnostic_hash: row.diagnostic_hash }); }\n private async selected(selection: Selection) { const result = await this.catalogs.getCatalog(selection.account_id, selection.catalog_id);return { catalog: result.catalog, owner: result.context_hash }; }\n private async readSet(selection: Selection, type: Kind, ids: string[]): Promise<Current[]> {\n const result = await this.client.mutate('catalogs/items', 'POST', { country: selection.country, language: selection.language, filters: { catalog_id: selection.catalog_id, catalog_type: type, [itemIdsField[type]]: ids } }, z.object({ items: z.array(z.record(z.string(), z.json())).max(1000) }), this.params(selection.account_id)).catch(error => { throw failure(error); });\n const found = new Map<string, Current>();\n for (const raw of result.items) {\n const id = sourceId.parse(raw[itemIdField[type]]), errors = diagnostics(raw.errors), kind = raw.item_response_kind, family = type === 'RETAIL' ? 'retail' : type === 'HOTEL' ? 'hotel' : 'creative_assets';\n if (!ids.includes(id) || found.has(id) || raw.catalog_type !== type || raw.catalog_id !== undefined && raw.catalog_id !== selection.catalog_id || kind !== undefined && ![family + '_item', family + '_item_error'].includes(String(kind)) || errors.length && raw.attributes !== undefined || kind === family + '_item_error' && raw.attributes !== undefined) throw failure(undefined);\n const attrs = raw.attributes === undefined ? undefined : z.record(z.string(), z.json()).parse(raw.attributes), state = attrs ? 'PRESENT' : 'NATIVE_ITEM_ERROR';\n found.set(id, { id, state, attributes: attrs, pins: raw.pins === null ? null : raw.pins === undefined ? undefined : z.array(z.unknown()).max(11).parse(raw.pins), diagnostics: errors, diagnostic_hash: errors.length ? hash(raw.errors) : undefined });\n }\n return ids.map(id => found.get(id) ?? { id, state: 'NOT_RETURNED', diagnostics: [] });\n }\n private previewMedia(pins: unknown[] | null | undefined): Creative['media'] {\n const result: Creative['media'] = [];\n for (const pin of pins ?? []) for (const image of Object.values(object(object(object(pin).media).images))) {\n const url = object(image).url;if (typeof url !== 'string') continue;let parsed: URL;try { parsed = new URL(url); } catch { continue; }\n if (safeMediaUrl(url) && (parsed.hostname === 'i.pinimg.com' || parsed.hostname.endsWith('.pinimg.com'))) { result.push({ type: 'image', url });break; }\n }\n return result.slice(0, 11);\n }\n async list(value: unknown) {\n const input = itemRead.parse(value), selection = itemSelection.parse(Object.fromEntries(Object.entries(input).filter(([key]) => ['account_id', 'catalog_id', 'country', 'language'].includes(key)))), { catalog, owner } = await this.selected(selection), key = hash({ selection, ids: input.item_ids, limit: input.limit });let offset = 0;\n if (input.cursor) { let navigation;try { navigation = z.object({ selection: groupHash, offset: z.number().int().min(1).max(999) }).strict().parse(JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8'))); } catch { throw new AdportError('INVALID_INPUT', 'Invalid catalog item cursor.'); }if (navigation.selection !== key || navigation.offset >= input.item_ids.length) throw new AdportError('PENDING_MISMATCH', 'Catalog item selection changed; restart its first page.');offset = navigation.offset; }\n const ids = input.item_ids.slice(offset, offset + input.limit), current = await this.readSet(selection, catalog.catalog_type, ids), records = 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(selection, catalog.catalog_type, owner, row) }));\n const creatives: Creative[] = current.map((row, index) => { const title = row.attributes?.title ?? row.attributes?.name, description = row.attributes?.description;return { id: row.id, provider: 'pinterest', account_id: input.account_id, name: records[index]!.name, type: 'CATALOG_' + catalog.catalog_type, status: row.state, headlines: typeof title === 'string' ? [title] : [], descriptions: typeof description === 'string' ? [description] : [], landing_urls: [], media: this.previewMedia(row.pins), actions: row.state === 'PRESENT' ? [{ label: 'Edit copy', tool: 'pinterest_update_catalog_item_copy', arguments: { ...selection, source_id: row.id, expected_snapshot_hash: records[index]!.snapshot_hash, confirm_publication: true, acknowledge_catalog_effects: true }, fields: [{ key: 'title', label: catalog.catalog_type === 'HOTEL' ? 'Name' : 'Title', type: 'text', value: typeof title === 'string' ? title : '' }, { key: 'description', label: 'Description', type: 'text', value: typeof description === 'string' ? description : '' }] }] : [] }; });\n const next = offset + ids.length;return { records, creatives, catalog_type: catalog.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.'] };\n }\n private async materialize(request: Request, type: Kind, mint: boolean) {\n const rows = structuredClone(request.operations), targets = new Set<string>(), resolved = new Map<string, string>(), sources: Row[] = [];let expires: string | undefined;\n if (request.media_assets.length && !this.media.providerUrl) throw new AdportError('INVALID_INPUT', 'Upload project media first; this runtime has no private provider URL staging.');\n for (const asset of request.media_assets) {\n const row = rows[asset.item_index], key = `${asset.item_index}:${asset.field}:${asset.image_index ?? ''}`;if (!row?.attributes || row.operation === 'DELETE' || targets.has(key)) throw new AdportError('INVALID_INPUT', 'Media references require distinct existing non-delete item slots.');targets.add(key);\n const options = { maxBytes: MAX_PROJECT_MEDIA_BYTES, contentTypes: /video/.test(asset.field) ? ['video/mp4'] : ['image/png', 'image/jpeg', 'image/webp'] }, source = { media_id: asset.media_id, expected_sha256: asset.expected_sha256 }, file = await this.media.read(source, options), verified = verifyMedia(file.bytes, file.name, source.expected_sha256, { ...options, contentType: file.contentType });\n const cacheKey = canonical({ source, type: verified.contentType });let url = resolved.get(cacheKey);\n if (!url) {\n url = `https://adport.invalid/media/${asset.media_id}/${asset.expected_sha256}`;\n if (mint) { const grant = await this.media.providerUrl!(source, options);if (!safeMediaUrl(grant.url) || grant.sha256 !== verified.sha256 || !(Date.parse(grant.expires_at) > Date.now() + 10 * 60_000)) throw new AdportError('PROVIDER_ERROR', 'Media staging returned an invalid or short-lived grant.');url = grant.url;if (!expires || Date.parse(grant.expires_at) < Date.parse(expires)) expires = grant.expires_at; }\n resolved.set(cacheKey, url);\n }\n const parts = asset.field.split('.'), attrs = parts.length === 2 ? object(row.attributes[parts[0]!]) : row.attributes, field = parts.at(-1)!;\n if (parts.length === 2) { const parent = row.attributes[parts[0]!];if (parent !== undefined && (!parent || typeof parent !== 'object' || Array.isArray(parent))) throw new AdportError('INVALID_INPUT', 'A nested media reference requires an object field.');row.attributes[parts[0]!] = attrs as typeof row.attributes; }\n const array = field === 'additional_image_link' || field === 'image_link' && type === 'RETAIL';\n if (array) { if (asset.image_index === undefined) throw new AdportError('INVALID_INPUT', 'An array media field requires image_index.');const values = attrs[field] === undefined ? [] : Array.isArray(attrs[field]) ? attrs[field] as unknown[] : [attrs[field]];if (values[asset.image_index] != null) throw new AdportError('INVALID_INPUT', 'A media slot already has a native URL.');values[asset.image_index] = url;attrs[field] = values; }\n else { if (asset.image_index !== undefined || attrs[field] !== undefined) throw new AdportError('INVALID_INPUT', 'Scalar media fields cannot have image_index or an existing URL.');attrs[field] = url; }\n 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 });\n }\n for (const row of rows) {\n if (row.operation === 'DELETE') { if (type !== 'RETAIL' && row.last_updated_time !== undefined) throw new AdportError('INVALID_INPUT', 'Only RETAIL deletion supports last_updated_time.');continue; }\n if (!attributeSchema(type, row.operation).safeParse(row.attributes).success) throw new AdportError('INVALID_INPUT', 'Attributes do not match this native catalog type/operation. Use pinterest_catalog_item_schema; no field is silently dropped.');\n if (row.attributes?.id !== undefined && row.attributes.id !== row.source_id) throw new AdportError('INVALID_INPUT', 'Deprecated attribute id cannot differ from the selected source_id.');\n if (row.clear_fields?.length && (type !== 'RETAIL' || Object.keys(row.attributes!).some(key => !itemUpdateMask.safeParse(key).success))) throw new AdportError('INVALID_INPUT', 'Explicit unsetting is RETAIL-only; all supplied fields must be native update-mask fields when combined with clears.');\n }\n bounded(rows);return { rows, sources, expires };\n }\n private manifest(type: Kind, rows: Request['operations'], before: Current[]) {\n const result = rows.map(row => { const desired_keys = [...new Set([...Object.keys(row.attributes ?? {}), ...(row.clear_fields ?? [])])].sort(), clear_keys = row.clear_fields ?? [], current = before.find(value => value.id === row.source_id)!;return { source_id: row.source_id, operation: row.operation, desired_keys, clear_keys, ...(row.operation !== 'DELETE' ? { desired_hash: hash(wantedValues(type, row.attributes!, desired_keys, clear_keys)) } : {}), ...(row.operation === 'UPDATE' ? { preserved_hash: hash(preserved(normalized(type, current.attributes!), desired_keys)) } : {}) }; });\n if (Buffer.byteLength(canonical(result)) > 1_000_000) throw new AdportError('INVALID_INPUT', 'Batch proof exceeds its bound; split this batch before previewing.');return result;\n }\n async context(value: unknown) {\n const input = itemContext.parse(value), selection = 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))));bounded(request);\n const { catalog, owner } = await this.selected(selection), current = await this.readSet(selection, catalog.catalog_type, request.operations.map(row => row.source_id));\n for (const row of request.operations) {\n const before = current.find(value => value.id === row.source_id)!;\n if (row.operation === 'CREATE' && before.state === 'PRESENT') throw new AdportError('INVALID_INPUT', 'CREATE cannot overwrite an existing item.');\n if (['UPDATE', 'DELETE'].includes(row.operation) && before.state !== 'PRESENT') throw new AdportError('INVALID_INPUT', 'UPDATE/DELETE require a positively read current item; native item errors cannot establish ownership/configuration.');\n if (row.operation === 'UPSERT' && (!request.acknowledge_replacement || before.state !== 'PRESENT' && !request.acknowledge_unconfirmed_existing)) throw new AdportError('INVALID_INPUT', 'UPSERT requires replacement acknowledgement and, for unconfirmed current items, acknowledge_unconfirmed_existing.');\n }\n const prepared = await this.materialize(request, catalog.catalog_type, false);this.manifest(catalog.catalog_type, prepared.rows, current);\n const scope_id = this.scopeId();return { context_hash: hash({ selection, owner, catalog: { id: catalog.id, name: catalog.name, type: catalog.catalog_type }, scope: scope_id, request, current: current.map(({ pins: _pins, ...row }) => row) }), scope_id, selection, request, catalog, owner, 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(selection, catalog.catalog_type, owner, row), diagnostics: row.diagnostics })), notes };\n }\n async publicContext(value: unknown) { const result = await this.context(value);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 }; }\n private batchRows(data: z.infer<typeof nativeBatch>, manifest: z.infer<typeof manifestRow>[]) {\n const seen = new Set<string>(), values = new Map<string, Row>();\n for (const row of data.items ?? []) {\n const id = sourceId.parse(row[itemIdField[data.catalog_type]]);if (seen.has(id) || !manifest.some(value => value.source_id === id)) throw failure(undefined);seen.add(id);\n const status = z.enum(['SUCCESS', 'FAILURE', 'PROCESSING']).optional().parse(row.status), errors = diagnostics(row.errors), warnings = diagnostics(row.warnings);if (status === 'SUCCESS' && errors.length) throw failure(undefined);\n values.set(id, { id, source_id: id, status: status ?? 'UNCONFIRMED', errors, warnings });\n }\n 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: [] });\n }\n private async verifiedReceipt(value: unknown) {\n const input = batchReference.parse(value), proof = receiptSchema.parse(this.client.verifyCatalogBatchReceipt(input.batch_receipt));if (proof.account_id !== input.account_id || proof.scope_id !== this.scopeId() || proof.expires_at <= Math.floor(Date.now() / 1000) || proof.expires_at > Math.floor(Date.now() / 1000) + 30 * 86400) throw new AdportError('INVALID_INPUT', 'Batch receipt is expired or belongs to another advertiser/project.');\n const { catalog, owner } = await this.selected(proof);if (catalog.catalog_type !== proof.catalog_type || owner !== proof.owner_context_hash) throw new AdportError('POLICY_VIOLATION', 'Current catalog ownership/type differs from the batch receipt.');return proof;\n }\n async status(value: unknown, reconcile = false) {\n 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 => { throw failure(error, [proof.batch_id]); });if (data.batch_id !== proof.batch_id || data.catalog_type !== proof.catalog_type) throw failure(undefined);\n const records = this.batchRows(data, proof.manifest);let readback_error: Row | undefined;\n if (reconcile) {\n try {\n const current = await this.readSet(proof, proof.catalog_type, proof.manifest.map(row => row.source_id));\n for (const record of records) {\n const expected = proof.manifest.find(row => row.source_id === record.id)!, actual = current.find(row => row.id === record.id)!;\n record.observed_state = actual.state;\n if (record.status !== 'SUCCESS') { record.readback = 'NATIVE_ITEM_NOT_SUCCESSFUL';continue; }\n if (expected.operation === 'DELETE') { record.readback = actual.state === 'PRESENT' ? 'STILL_PRESENT' : 'ABSENCE_UNCONFIRMED';continue; }\n if (!actual.attributes) { record.readback = 'CURRENT_ITEM_UNCONFIRMED';continue; }\n const matches = hash(wantedValues(proof.catalog_type, actual.attributes, expected.desired_keys, expected.clear_keys)) === expected.desired_hash, retains = !expected.preserved_hash || hash(preserved(normalized(proof.catalog_type, actual.attributes), expected.desired_keys)) === expected.preserved_hash;\n record.readback = matches && retains ? 'REQUESTED_CONFIGURATION_VERIFIED' : 'CONFIGURATION_UNCONFIRMED';record.omitted_fields_preserved = expected.preserved_hash ? retains : undefined;\n }\n } catch (error) { const details = error instanceof AdportError ? object(error.details) : {};readback_error = { status: 'READBACK_UNAVAILABLE', ...(typeof details.http_status === 'number' ? { http_status: details.http_status } : {}) }; }\n }\n return { batch_id: proof.batch_id, catalog_type: proof.catalog_type, status: data.status ?? 'UNCONFIRMED', records, submitted_items: proof.manifest.length, terminal_items: records.filter(row => ['SUCCESS', 'FAILURE', 'BATCH_FAILED'].includes(String(row.status))).length, all_items_native_successful: data.status === 'COMPLETED' && records.every(row => row.status === 'SUCCESS'), ...(readback_error ? { readback_error } : {}), media_expires_at: proof.media_expires_at, notes: [...notes, 'A native SUCCESS is not proof of Pin publication, ad eligibility or permanent media hosting. Missing/error item reads never independently certify deletion.'] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const copy = op.tool === 'pinterest_update_catalog_item_copy', operation = itemWriteOperations[op.tool as keyof typeof itemWriteOperations], expectedKind = operation === 'CREATE' ? 'create' : operation === 'DELETE' ? 'remove' : 'update';\n if (op.provider !== 'pinterest' || !this.supports(op.tool) || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'Invalid catalog item mutation/provider kind.');\n const parsed = copy ? itemCopy.parse(op.payload) : operation ? itemNamedApply(operation).parse(op.payload) : itemBatchApply.parse(op.payload);\n const selection = itemSelection.parse({ account_id: op.accountId, catalog_id: parsed.catalog_id, country: parsed.country, language: parsed.language });\n const request: 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 });\n if (copy) { const input = parsed as z.infer<typeof itemCopy>, parent = await this.selected(selection);request.operations[0]!.attributes = { ...(input.title !== undefined ? { [parent.catalog.catalog_type === 'HOTEL' ? 'name' : 'title']: input.title } : {}), ...(input.description !== undefined ? { description: input.description } : {}) }; }\n const prepare = async () => { const result = await this.context({ ...selection, ...request });\n if (copy ? result.records[0]!.snapshot_hash !== (parsed as z.infer<typeof itemCopy>).expected_snapshot_hash : result.context_hash !== (parsed as z.infer<typeof itemBatchApply>).expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog items, selection, owner or media changed; read context and preview again.');return result; }, before = await prepare();let receipt: Row | undefined;\n const title = copy ? 'Update catalog item copy' : 'Submit catalog item batch';\n return { summary: `${title} · ${request.operations.length} items`, changes: before.prepared.rows.map(row => `${row.operation} ${row.source_id}`), coercions: [], budgetDeltas: [], notes,\n review: { provider: 'pinterest', accountId: op.accountId, kind: op.kind, title, subject: before.catalog.name, fields: [{ label: 'Catalog and market', after: { id: selection.catalog_id, type: before.catalog.catalog_type, country: selection.country, language: selection.language } }, ...before.prepared.rows.map(row => ({ label: row.source_id + ' · ' + 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: [...notes, ...(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.'] : [])] },\n execute: async () => { const fresh = await prepare();let id: string | undefined;try {\n const materialized = await this.materialize(request, fresh.catalog.catalog_type, true), manifest = this.manifest(fresh.catalog.catalog_type, materialized.rows, fresh.current);if (this.scopeId() !== fresh.scope_id) throw new AdportError('PENDING_MISMATCH', 'Media scope changed before batch submission.');\n const items = materialized.rows.map(row => ({ [itemIdField[fresh.catalog.catalog_type]]: row.source_id, operation: row.operation, ...(row.attributes !== undefined ? { attributes: row.attributes } : {}), ...(row.clear_fields?.length ? { update_mask: [...new Set([...Object.keys(row.attributes!), ...row.clear_fields])] } : {}), ...(row.last_updated_time !== undefined ? { last_updated_time: row.last_updated_time } : {}) }));\n const data = await this.client.mutate('catalogs/items/batch', 'POST', { catalog_id: selection.catalog_id, catalog_type: fresh.catalog.catalog_type, country: selection.country, language: selection.language, items }, nativeBatch, this.params(op.accountId));id = data.batch_id;\n if (!id || !data.status || data.catalog_type !== fresh.catalog.catalog_type || data.created_time === null) throw failure(undefined, id ? [id] : []);\n const batch_receipt = this.client.catalogBatchReceipt({ ...selection, version: 'pinterest_items_v1', scope_id: fresh.scope_id, catalog_type: fresh.catalog.catalog_type, owner_context_hash: fresh.owner, batch_id: id, expires_at: Math.floor(Date.now() / 1000) + 30 * 86400, manifest, ...(materialized.expires ? { media_expires_at: materialized.expires } : {}) }), results = this.batchRows(data, manifest);\n if (data.status === 'FAILED' || results.every(row => row.status === 'FAILURE')) throw failure(undefined, [id], { batch_receipt, item_results: results, native_status: data.status });\n receipt = { status: 'ACCEPTED_FOR_PROCESSING', processed: false, native_status: data.status, batch_id: id, 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 } };return [id];\n } catch (error) { const details = error instanceof AdportError ? object(error.details) : {};throw failure(error, id ? [id] : Array.isArray(details.resource_ids) ? details.resource_ids as string[] : [], details.batch_receipt ? { batch_receipt: details.batch_receipt, item_results: details.item_results, native_status: details.native_status } : {}); }\n }, resultDetails: () => receipt, resultWarnings: () => notes };\n }\n}\n","// Native attribute facts: Pinterest OpenAPI 5.28.0, 51aca009f10a90283ccdf3956d509fc995ebac23.\n// Strict known fields; native defaults are not inserted into mutation payloads.\nimport { z } from 'zod';\nexport const itemAttributeSchemas = {\n retailCreate: z.object({\"ad_image_0_link\": z.string().max(2000).nullable().optional(), \"ad_image_0_tag\": z.string().max(511).nullable().optional(), \"ad_image_10_link\": z.string().max(2000).nullable().optional(), \"ad_image_10_tag\": z.string().max(511).nullable().optional(), \"ad_image_11_link\": z.string().max(2000).nullable().optional(), \"ad_image_11_tag\": z.string().max(511).nullable().optional(), \"ad_image_12_link\": z.string().max(2000).nullable().optional(), \"ad_image_12_tag\": z.string().max(511).nullable().optional(), \"ad_image_13_link\": z.string().max(2000).nullable().optional(), \"ad_image_13_tag\": z.string().max(511).nullable().optional(), \"ad_image_14_link\": z.string().max(2000).nullable().optional(), \"ad_image_14_tag\": z.string().max(511).nullable().optional(), \"ad_image_15_link\": z.string().max(2000).nullable().optional(), \"ad_image_15_tag\": z.string().max(511).nullable().optional(), \"ad_image_16_link\": z.string().max(2000).nullable().optional(), \"ad_image_16_tag\": z.string().max(511).nullable().optional(), \"ad_image_17_link\": z.string().max(2000).nullable().optional(), \"ad_image_17_tag\": z.string().max(511).nullable().optional(), \"ad_image_18_link\": z.string().max(2000).nullable().optional(), \"ad_image_18_tag\": z.string().max(511).nullable().optional(), \"ad_image_19_link\": z.string().max(2000).nullable().optional(), \"ad_image_19_tag\": z.string().max(511).nullable().optional(), \"ad_image_1_link\": z.string().max(2000).nullable().optional(), \"ad_image_1_tag\": z.string().max(511).nullable().optional(), \"ad_image_2_link\": z.string().max(2000).nullable().optional(), \"ad_image_2_tag\": z.string().max(511).nullable().optional(), \"ad_image_3_link\": z.string().max(2000).nullable().optional(), \"ad_image_3_tag\": z.string().max(511).nullable().optional(), \"ad_image_4_link\": z.string().max(2000).nullable().optional(), \"ad_image_4_tag\": z.string().max(511).nullable().optional(), \"ad_image_5_link\": z.string().max(2000).nullable().optional(), \"ad_image_5_tag\": z.string().max(511).nullable().optional(), \"ad_image_6_link\": z.string().max(2000).nullable().optional(), \"ad_image_6_tag\": z.string().max(511).nullable().optional(), \"ad_image_7_link\": z.string().max(2000).nullable().optional(), \"ad_image_7_tag\": z.string().max(511).nullable().optional(), \"ad_image_8_link\": z.string().max(2000).nullable().optional(), \"ad_image_8_tag\": z.string().max(511).nullable().optional(), \"ad_image_9_link\": z.string().max(2000).nullable().optional(), \"ad_image_9_tag\": z.string().max(511).nullable().optional(), \"ad_link\": z.string().max(65536).nullable().optional(), \"ad_video_0_link\": z.string().max(2000).nullable().optional(), \"ad_video_0_tag\": z.string().max(511).nullable().optional(), \"ad_video_1_link\": z.string().max(2000).nullable().optional(), \"ad_video_1_tag\": z.string().max(511).nullable().optional(), \"ad_video_2_link\": z.string().max(2000).nullable().optional(), \"ad_video_2_tag\": z.string().max(511).nullable().optional(), \"additional_image_link\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"adult\": z.boolean().nullable().optional(), \"age_group\": z.string().max(65536).nullable().optional(), \"ai_disclosures\": z.array(z.object({\"disclosure\": z.array(z.enum([\"ai_modified\",\"synthetic_performer\"])).min(1).max(1000), \"url\": z.string().max(2000)}).strict()).max(1000).optional(), \"android_deep_link\": z.string().max(65536).optional(), \"availability\": z.string().max(65536).optional(), \"average_review_rating\": z.number().nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"checkout_enabled\": z.boolean().nullable().optional(), \"color\": z.string().max(65536).nullable().optional(), \"condition\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(511).nullable().optional(), \"custom_label_1\": z.string().max(511).nullable().optional(), \"custom_label_2\": z.string().max(511).nullable().optional(), \"custom_label_3\": z.string().max(511).nullable().optional(), \"custom_label_4\": z.string().max(511).nullable().optional(), \"custom_number_0\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_1\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_2\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_3\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_4\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"description\": z.string().max(65536).optional(), \"free_shipping_label\": z.boolean().nullable().optional(), \"free_shipping_limit\": z.string().max(65536).nullable().optional(), \"gender\": z.string().max(65536).nullable().optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"gtin\": z.union([z.string().max(65536).nullable(), z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), \"id\": z.string().max(65536).optional(), \"image_link\": z.union([z.string().max(65536), z.array(z.string().max(65536)).min(1).max(1)]).optional(), \"installment_price\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).optional(), \"item_group_id\": z.string().max(65536).nullable().optional(), \"last_updated_time\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"link\": z.string().max(65536).optional(), \"material\": z.string().max(65536).nullable().optional(), \"min_ad_price\": z.string().max(65536).nullable().optional(), \"mobile_link\": z.string().max(65536).nullable().optional(), \"mpn\": z.string().max(65536).nullable().optional(), \"number_of_ratings\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"number_of_reviews\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"pattern\": z.string().max(65536).nullable().optional(), \"price\": z.string().max(65536).optional(), \"product_type\": z.string().max(65536).nullable().optional(), \"promotion_id\": z.string().max(65536).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional(), \"sale_price_effective_date\": z.string().max(65536).nullable().optional(), \"save_pin_disabled\": z.boolean().optional(), \"shipping\": z.string().max(65536).nullable().optional(), \"shipping_height\": z.string().max(65536).nullable().optional(), \"shipping_weight\": z.string().max(65536).nullable().optional(), \"shipping_width\": z.string().max(65536).nullable().optional(), \"size\": z.string().max(65536).nullable().optional(), \"size_system\": z.string().max(65536).nullable().optional(), \"size_type\": z.string().max(65536).nullable().optional(), \"tax\": z.string().max(65536).nullable().optional(), \"title\": z.string().max(65536).optional(), \"unit_pricing_base_measure\": z.string().max(65536).nullable().optional(), \"unit_pricing_measure\": z.string().max(65536).nullable().optional(), \"variant_names\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"variant_values\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"video_link\": z.string().max(65536).nullable().optional()}).strict(),\n retailUpdate: z.object({\"ad_image_0_link\": z.string().max(2000).nullable().optional(), \"ad_image_0_tag\": z.string().max(511).nullable().optional(), \"ad_image_10_link\": z.string().max(2000).nullable().optional(), \"ad_image_10_tag\": z.string().max(511).nullable().optional(), \"ad_image_11_link\": z.string().max(2000).nullable().optional(), \"ad_image_11_tag\": z.string().max(511).nullable().optional(), \"ad_image_12_link\": z.string().max(2000).nullable().optional(), \"ad_image_12_tag\": z.string().max(511).nullable().optional(), \"ad_image_13_link\": z.string().max(2000).nullable().optional(), \"ad_image_13_tag\": z.string().max(511).nullable().optional(), \"ad_image_14_link\": z.string().max(2000).nullable().optional(), \"ad_image_14_tag\": z.string().max(511).nullable().optional(), \"ad_image_15_link\": z.string().max(2000).nullable().optional(), \"ad_image_15_tag\": z.string().max(511).nullable().optional(), \"ad_image_16_link\": z.string().max(2000).nullable().optional(), \"ad_image_16_tag\": z.string().max(511).nullable().optional(), \"ad_image_17_link\": z.string().max(2000).nullable().optional(), \"ad_image_17_tag\": z.string().max(511).nullable().optional(), \"ad_image_18_link\": z.string().max(2000).nullable().optional(), \"ad_image_18_tag\": z.string().max(511).nullable().optional(), \"ad_image_19_link\": z.string().max(2000).nullable().optional(), \"ad_image_19_tag\": z.string().max(511).nullable().optional(), \"ad_image_1_link\": z.string().max(2000).nullable().optional(), \"ad_image_1_tag\": z.string().max(511).nullable().optional(), \"ad_image_2_link\": z.string().max(2000).nullable().optional(), \"ad_image_2_tag\": z.string().max(511).nullable().optional(), \"ad_image_3_link\": z.string().max(2000).nullable().optional(), \"ad_image_3_tag\": z.string().max(511).nullable().optional(), \"ad_image_4_link\": z.string().max(2000).nullable().optional(), \"ad_image_4_tag\": z.string().max(511).nullable().optional(), \"ad_image_5_link\": z.string().max(2000).nullable().optional(), \"ad_image_5_tag\": z.string().max(511).nullable().optional(), \"ad_image_6_link\": z.string().max(2000).nullable().optional(), \"ad_image_6_tag\": z.string().max(511).nullable().optional(), \"ad_image_7_link\": z.string().max(2000).nullable().optional(), \"ad_image_7_tag\": z.string().max(511).nullable().optional(), \"ad_image_8_link\": z.string().max(2000).nullable().optional(), \"ad_image_8_tag\": z.string().max(511).nullable().optional(), \"ad_image_9_link\": z.string().max(2000).nullable().optional(), \"ad_image_9_tag\": z.string().max(511).nullable().optional(), \"ad_link\": z.string().max(65536).nullable().optional(), \"ad_video_0_link\": z.string().max(2000).nullable().optional(), \"ad_video_0_tag\": z.string().max(511).nullable().optional(), \"ad_video_1_link\": z.string().max(2000).nullable().optional(), \"ad_video_1_tag\": z.string().max(511).nullable().optional(), \"ad_video_2_link\": z.string().max(2000).nullable().optional(), \"ad_video_2_tag\": z.string().max(511).nullable().optional(), \"adult\": z.boolean().nullable().optional(), \"age_group\": z.string().max(65536).nullable().optional(), \"android_deep_link\": z.string().max(65536).optional(), \"availability\": z.string().max(65536).optional(), \"average_review_rating\": z.number().nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"checkout_enabled\": z.boolean().nullable().optional(), \"color\": z.string().max(65536).nullable().optional(), \"condition\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(511).nullable().optional(), \"custom_label_1\": z.string().max(511).nullable().optional(), \"custom_label_2\": z.string().max(511).nullable().optional(), \"custom_label_3\": z.string().max(511).nullable().optional(), \"custom_label_4\": z.string().max(511).nullable().optional(), \"custom_number_0\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_1\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_2\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_3\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_4\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"description\": z.string().max(65536).optional(), \"free_shipping_label\": z.boolean().nullable().optional(), \"free_shipping_limit\": z.string().max(65536).nullable().optional(), \"gender\": z.string().max(65536).nullable().optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"gtin\": z.union([z.string().max(65536).nullable(), z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), \"id\": z.string().max(65536).optional(), \"installment_price\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).optional(), \"item_group_id\": z.string().max(65536).nullable().optional(), \"last_updated_time\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"link\": z.string().max(65536).optional(), \"material\": z.string().max(65536).nullable().optional(), \"min_ad_price\": z.string().max(65536).nullable().optional(), \"mobile_link\": z.string().max(65536).nullable().optional(), \"mpn\": z.string().max(65536).nullable().optional(), \"number_of_ratings\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"number_of_reviews\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"pattern\": z.string().max(65536).nullable().optional(), \"price\": z.string().max(65536).optional(), \"product_type\": z.string().max(65536).nullable().optional(), \"promotion_id\": z.string().max(65536).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional(), \"sale_price_effective_date\": z.string().max(65536).nullable().optional(), \"shipping\": z.string().max(65536).nullable().optional(), \"shipping_height\": z.string().max(65536).nullable().optional(), \"shipping_weight\": z.string().max(65536).nullable().optional(), \"shipping_width\": z.string().max(65536).nullable().optional(), \"size\": z.string().max(65536).nullable().optional(), \"size_system\": z.string().max(65536).nullable().optional(), \"size_type\": z.string().max(65536).nullable().optional(), \"tax\": z.string().max(65536).nullable().optional(), \"title\": z.string().max(65536).optional(), \"unit_pricing_base_measure\": z.string().max(65536).nullable().optional(), \"unit_pricing_measure\": z.string().max(65536).nullable().optional(), \"variant_names\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"variant_values\": z.array(z.string().max(65536)).max(1000).nullable().optional()}).strict(),\n retailRead: z.object({\"ad_image_0_link\": z.string().max(2000).nullable().optional(), \"ad_image_0_tag\": z.string().max(511).nullable().optional(), \"ad_image_10_link\": z.string().max(2000).nullable().optional(), \"ad_image_10_tag\": z.string().max(511).nullable().optional(), \"ad_image_11_link\": z.string().max(2000).nullable().optional(), \"ad_image_11_tag\": z.string().max(511).nullable().optional(), \"ad_image_12_link\": z.string().max(2000).nullable().optional(), \"ad_image_12_tag\": z.string().max(511).nullable().optional(), \"ad_image_13_link\": z.string().max(2000).nullable().optional(), \"ad_image_13_tag\": z.string().max(511).nullable().optional(), \"ad_image_14_link\": z.string().max(2000).nullable().optional(), \"ad_image_14_tag\": z.string().max(511).nullable().optional(), \"ad_image_15_link\": z.string().max(2000).nullable().optional(), \"ad_image_15_tag\": z.string().max(511).nullable().optional(), \"ad_image_16_link\": z.string().max(2000).nullable().optional(), \"ad_image_16_tag\": z.string().max(511).nullable().optional(), \"ad_image_17_link\": z.string().max(2000).nullable().optional(), \"ad_image_17_tag\": z.string().max(511).nullable().optional(), \"ad_image_18_link\": z.string().max(2000).nullable().optional(), \"ad_image_18_tag\": z.string().max(511).nullable().optional(), \"ad_image_19_link\": z.string().max(2000).nullable().optional(), \"ad_image_19_tag\": z.string().max(511).nullable().optional(), \"ad_image_1_link\": z.string().max(2000).nullable().optional(), \"ad_image_1_tag\": z.string().max(511).nullable().optional(), \"ad_image_2_link\": z.string().max(2000).nullable().optional(), \"ad_image_2_tag\": z.string().max(511).nullable().optional(), \"ad_image_3_link\": z.string().max(2000).nullable().optional(), \"ad_image_3_tag\": z.string().max(511).nullable().optional(), \"ad_image_4_link\": z.string().max(2000).nullable().optional(), \"ad_image_4_tag\": z.string().max(511).nullable().optional(), \"ad_image_5_link\": z.string().max(2000).nullable().optional(), \"ad_image_5_tag\": z.string().max(511).nullable().optional(), \"ad_image_6_link\": z.string().max(2000).nullable().optional(), \"ad_image_6_tag\": z.string().max(511).nullable().optional(), \"ad_image_7_link\": z.string().max(2000).nullable().optional(), \"ad_image_7_tag\": z.string().max(511).nullable().optional(), \"ad_image_8_link\": z.string().max(2000).nullable().optional(), \"ad_image_8_tag\": z.string().max(511).nullable().optional(), \"ad_image_9_link\": z.string().max(2000).nullable().optional(), \"ad_image_9_tag\": z.string().max(511).nullable().optional(), \"ad_link\": z.string().max(65536).nullable().optional(), \"ad_video_0_link\": z.string().max(2000).nullable().optional(), \"ad_video_0_tag\": z.string().max(511).nullable().optional(), \"ad_video_1_link\": z.string().max(2000).nullable().optional(), \"ad_video_1_tag\": z.string().max(511).nullable().optional(), \"ad_video_2_link\": z.string().max(2000).nullable().optional(), \"ad_video_2_tag\": z.string().max(511).nullable().optional(), \"adult\": z.boolean().nullable().optional(), \"age_group\": z.string().max(65536).nullable().optional(), \"android_deep_link\": z.string().max(65536).optional(), \"availability\": z.string().max(65536).optional(), \"average_review_rating\": z.number().nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"checkout_enabled\": z.boolean().nullable().optional(), \"color\": z.string().max(65536).nullable().optional(), \"condition\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(511).nullable().optional(), \"custom_label_1\": z.string().max(511).nullable().optional(), \"custom_label_2\": z.string().max(511).nullable().optional(), \"custom_label_3\": z.string().max(511).nullable().optional(), \"custom_label_4\": z.string().max(511).nullable().optional(), \"custom_number_0\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_1\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_2\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_3\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"custom_number_4\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"description\": z.string().max(65536).optional(), \"free_shipping_label\": z.boolean().nullable().optional(), \"free_shipping_limit\": z.string().max(65536).nullable().optional(), \"gender\": z.string().max(65536).nullable().optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"gtin\": z.union([z.string().max(65536).nullable(), z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable()]).nullable().optional(), \"id\": z.string().max(65536).optional(), \"installment_price\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).optional(), \"item_group_id\": z.string().max(65536).nullable().optional(), \"last_updated_time\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"link\": z.string().max(65536).optional(), \"material\": z.string().max(65536).nullable().optional(), \"min_ad_price\": z.string().max(65536).nullable().optional(), \"mobile_link\": z.string().max(65536).nullable().optional(), \"mpn\": z.string().max(65536).nullable().optional(), \"number_of_ratings\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"number_of_reviews\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"pattern\": z.string().max(65536).nullable().optional(), \"price\": z.string().max(65536).optional(), \"product_type\": z.string().max(65536).nullable().optional(), \"promotion_id\": z.string().max(65536).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional(), \"sale_price_effective_date\": z.string().max(65536).nullable().optional(), \"shipping\": z.string().max(65536).nullable().optional(), \"shipping_height\": z.string().max(65536).nullable().optional(), \"shipping_weight\": z.string().max(65536).nullable().optional(), \"shipping_width\": z.string().max(65536).nullable().optional(), \"size\": z.string().max(65536).nullable().optional(), \"size_system\": z.string().max(65536).nullable().optional(), \"size_type\": z.string().max(65536).nullable().optional(), \"tax\": z.string().max(65536).nullable().optional(), \"title\": z.string().max(65536).optional(), \"unit_pricing_base_measure\": z.string().max(65536).nullable().optional(), \"unit_pricing_measure\": z.string().max(65536).nullable().optional(), \"variant_names\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"variant_values\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"additional_image_link\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"ai_disclosures\": z.array(z.object({\"disclosure\": z.array(z.enum([\"ai_modified\",\"synthetic_performer\"])).min(1).max(1000), \"url\": z.string().max(2000)}).strict()).max(1000).optional(), \"image_link\": z.array(z.string().max(65536)).min(1).max(1000).optional(), \"video_link\": z.string().max(65536).nullable().optional()}).strict(),\n hotelCreate: z.object({\"address\": z.object({\"addr1\": z.string().max(65536).optional(), \"city\": z.string().max(65536).optional(), \"country\": z.string().max(65536).optional(), \"postal_code\": z.string().max(65536).optional(), \"region\": z.string().max(65536).optional()}).strict().optional(), \"base_price\": z.string().max(65536).nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"category\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(65536).nullable().optional(), \"custom_label_1\": z.string().max(65536).nullable().optional(), \"custom_label_2\": z.string().max(65536).nullable().optional(), \"custom_label_3\": z.string().max(65536).nullable().optional(), \"custom_label_4\": z.string().max(65536).nullable().optional(), \"description\": z.string().max(65536).nullable().optional(), \"guest_ratings\": z.object({\"max_score\": z.number().nullable().optional(), \"number_of_reviewers\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"rating_system\": z.string().max(65536).nullable().optional(), \"score\": z.number().nullable().optional()}).strict().optional(), \"latitude\": z.number().optional(), \"link\": z.string().max(65536).nullable().optional(), \"longitude\": z.number().nullable().optional(), \"name\": z.string().max(65536).nullable().optional(), \"neighborhood\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional(), \"additional_image_link\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"ai_disclosures\": z.array(z.object({\"disclosure\": z.array(z.enum([\"ai_modified\",\"synthetic_performer\"])).min(1).max(1000), \"url\": z.string().max(2000)}).strict()).max(1000).optional(), \"main_image\": z.object({\"link\": z.string().max(65536).optional(), \"tag\": z.array(z.string().max(65536)).max(1000).nullable().optional()}).strict().optional()}).strict(),\n hotelUpdate: z.object({\"address\": z.object({\"addr1\": z.string().max(65536).optional(), \"city\": z.string().max(65536).optional(), \"country\": z.string().max(65536).optional(), \"postal_code\": z.string().max(65536).optional(), \"region\": z.string().max(65536).optional()}).strict().optional(), \"base_price\": z.string().max(65536).nullable().optional(), \"brand\": z.string().max(65536).nullable().optional(), \"category\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(65536).nullable().optional(), \"custom_label_1\": z.string().max(65536).nullable().optional(), \"custom_label_2\": z.string().max(65536).nullable().optional(), \"custom_label_3\": z.string().max(65536).nullable().optional(), \"custom_label_4\": z.string().max(65536).nullable().optional(), \"description\": z.string().max(65536).nullable().optional(), \"guest_ratings\": z.object({\"max_score\": z.number().nullable().optional(), \"number_of_reviewers\": z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).nullable().optional(), \"rating_system\": z.string().max(65536).nullable().optional(), \"score\": z.number().nullable().optional()}).strict().optional(), \"latitude\": z.number().optional(), \"link\": z.string().max(65536).nullable().optional(), \"longitude\": z.number().nullable().optional(), \"name\": z.string().max(65536).nullable().optional(), \"neighborhood\": z.array(z.string().max(65536)).max(1000).nullable().optional(), \"sale_price\": z.string().max(65536).nullable().optional()}).strict(),\n creativeCreate: z.object({\"android_deep_link\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(65536).nullable().optional(), \"custom_label_1\": z.string().max(65536).nullable().optional(), \"custom_label_2\": z.string().max(65536).nullable().optional(), \"custom_label_3\": z.string().max(65536).nullable().optional(), \"custom_label_4\": z.string().max(65536).nullable().optional(), \"description\": z.string().max(65536).optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).nullable().optional(), \"link\": z.string().max(65536).optional(), \"title\": z.string().max(65536).optional(), \"visibility\": z.string().max(65536).nullable().optional(), \"ai_disclosures\": z.array(z.object({\"disclosure\": z.array(z.enum([\"ai_modified\",\"synthetic_performer\"])).min(1).max(1000), \"url\": z.string().max(2000)}).strict()).max(1000).optional(), \"image_link\": z.string().max(65536).optional(), \"video_link\": z.string().max(65536).optional()}).strict(),\n creativeUpdate: z.object({\"android_deep_link\": z.string().max(65536).nullable().optional(), \"custom_label_0\": z.string().max(65536).nullable().optional(), \"custom_label_1\": z.string().max(65536).nullable().optional(), \"custom_label_2\": z.string().max(65536).nullable().optional(), \"custom_label_3\": z.string().max(65536).nullable().optional(), \"custom_label_4\": z.string().max(65536).nullable().optional(), \"description\": z.string().max(65536).optional(), \"google_product_category\": z.string().max(65536).nullable().optional(), \"ios_deep_link\": z.string().max(65536).nullable().optional(), \"link\": z.string().max(65536).optional(), \"title\": z.string().max(65536).optional(), \"visibility\": z.string().max(65536).nullable().optional()}).strict(),\n} as const;\nexport const itemUpdateMask = z.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\"]);\nexport const 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\"] as const;\n","import { z } from 'zod';\nimport { pinterestId } from './schemas.js';\nimport { groupId, groupHash, catalogType } from './product-group-schemas.js';\nimport { filterEnums } from './product-group-filter-spec.js';\nimport { itemAttributeSchemas, itemLanguages, itemUpdateMask } from './catalog-item-attributes.js';\n\nexport const itemOperation = z.enum(['CREATE', 'UPDATE', 'UPSERT', 'DELETE']);\nexport const sourceId = z.string().min(1).max(1024).regex(/^[^\\x00-\\x1f\\x7f]+$/);\nexport const itemObject = z.record(z.string(), z.json());\nexport const itemSelection = z.object({ account_id: pinterestId, catalog_id: groupId, country: z.enum(filterEnums.Country), language: z.enum(itemLanguages) }).strict();\nexport const itemRead = itemSelection.extend({ item_ids: z.array(sourceId).min(1).max(1000).refine(ids => new Set(ids).size === ids.length), limit: z.number().int().min(1).max(100).default(24), cursor: z.string().min(1).max(8192).optional() });\nconst itemMutationBase = z.object({ source_id: sourceId, operation: itemOperation, attributes: itemObject.optional(), clear_fields: z.array(itemUpdateMask).min(1).max(100).refine(values => new Set(values).size === values.length).optional(), last_updated_time: z.number().int().nonnegative().safe().optional() }).strict();\nexport const itemMutation = itemMutationBase.superRefine((value, ctx) => {\n if (value.operation === 'DELETE' ? value.attributes !== undefined || value.clear_fields !== undefined : value.attributes === undefined || value.last_updated_time !== undefined || value.operation !== 'UPDATE' && value.clear_fields !== undefined) ctx.addIssue({ code: 'custom', message: 'CREATE/UPSERT/UPDATE require attributes; only UPDATE supports clear_fields; only DELETE accepts last_updated_time' });\n 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' });\n if (value.clear_fields?.some(key => Object.hasOwn(value.attributes ?? {}, key))) ctx.addIssue({ code: 'custom', message: 'A field cannot be both supplied and cleared' });\n});\nexport const itemMedia = z.object({ item_index: z.number().int().min(0).max(999), field: z.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: z.number().int().min(0).max(999).optional(), media_id: z.string().uuid(), expected_sha256: groupHash }).strict();\nexport const itemRequest = z.object({ operations: z.array(itemMutation).min(1).max(1000).refine(rows => new Set(rows.map(row => row.source_id)).size === rows.length, 'Each item may appear only once in a batch'), media_assets: z.array(itemMedia).max(1000).default([]), acknowledge_replacement: z.literal(true).optional(), acknowledge_unconfirmed_existing: z.literal(true).optional() }).strict();\nexport const itemContext = itemSelection.extend(itemRequest.shape);\nconst write = itemSelection.omit({ account_id: true }).extend({ expected_context_hash: groupHash, confirm_publication: z.literal(true), acknowledge_catalog_effects: z.literal(true), confirm_permanent_deletion: z.literal(true).optional() });\nexport const itemBatchApply = write.extend(itemRequest.shape).superRefine((value, ctx) => {\n 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' });\n 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' });\n});\nexport const itemNamedApply = (operation: z.infer<typeof itemOperation>) => write.extend({\n items: z.array(itemMutationBase.omit({ operation: true })).min(1).max(1000), media_assets: itemRequest.shape.media_assets,\n acknowledge_replacement: z.literal(true).optional(), acknowledge_unconfirmed_existing: z.literal(true).optional(),\n}).superRefine((value, ctx) => {\n const result = itemBatchApply.safeParse({ ...Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'items')), operations: value.items.map(row => ({ ...row, operation })) });\n if (!result.success) for (const issue of result.error.issues) ctx.addIssue({ code: 'custom', path: issue.path, message: issue.message });\n});\nexport const itemCopy = itemSelection.omit({ account_id: true }).extend({ source_id: sourceId, expected_snapshot_hash: groupHash, title: z.string().max(65_536).optional(), description: z.string().max(65_536).optional(), confirm_publication: z.literal(true), acknowledge_catalog_effects: z.literal(true) }).strict().refine(value => value.title !== undefined || value.description !== undefined, 'Supply copy to change');\nexport const batchReference = z.object({ account_id: pinterestId, batch_receipt: z.string().min(100).max(2_000_000) }).strict();\nexport const itemSchemaQuery = z.object({ catalog_type: catalogType, operation: itemOperation }).strict();\nexport function attributeSchema(type: z.infer<typeof catalogType>, operation: z.infer<typeof itemOperation>) {\n if (operation === 'DELETE') return z.object({}).strict();\n return type === 'RETAIL' ? operation === 'UPDATE' ? itemAttributeSchemas.retailUpdate : itemAttributeSchemas.retailCreate : type === 'HOTEL' ? operation === 'UPDATE' ? itemAttributeSchemas.hotelUpdate : itemAttributeSchemas.hotelCreate : operation === 'UPDATE' ? itemAttributeSchemas.creativeUpdate : itemAttributeSchemas.creativeCreate;\n}\nexport const itemIdField = { RETAIL: 'item_id', HOTEL: 'hotel_id', CREATIVE_ASSETS: 'creative_assets_id' } as const;\nexport const itemIdsField = { RETAIL: 'item_ids', HOTEL: 'hotel_ids', CREATIVE_ASSETS: 'creative_assets_ids' } as const;\nexport const itemWriteOperations = { pinterest_create_catalog_items: 'CREATE', pinterest_update_catalog_items: 'UPDATE', pinterest_upsert_catalog_items: 'UPSERT', pinterest_delete_catalog_items: 'DELETE' } as const;\n","import { z } from 'zod';\nimport { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestCatalogService } from './catalogs.js';\nimport { groupHash } from './product-group-schemas.js';\nimport { localBound, localCanonical, localFailure, localHash, localObject, localScope, localStoreContext, localStoreCreate, localStoreDelete, localStoreList, localStoreUpdate, nativeLocalStore, publicLocal, type LocalRow, type LocalScope } from './local-catalog-schemas.js';\n\ntype Store = z.infer<typeof nativeLocalStore>;\ntype Action = z.infer<typeof localStoreContext>['action'];\ntype Plan = Omit<WritePreview,'serverValidated'> & { execute(): Promise<string[]>;resultDetails?():unknown;resultWarnings?():string[] };\nconst storeValue = (value: Store) => Object.fromEntries(Object.entries(value).filter(([key]) => !['created_at','updated_at'].includes(key)));\nconst 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.'];\n\nexport class PinterestLocalStores {\n constructor(private readonly client:PinterestAdsClient,private readonly catalogs:PinterestCatalogService) {}\n supports(tool:string) { return ['pinterest_create_local_stores','pinterest_update_local_stores','pinterest_delete_local_stores'].includes(tool); }\n params(account:string,extra:Record<string,string> = {}) { return new URLSearchParams({ ad_account_id:account,...extra }); }\n path(catalog:string) { return `catalogs/${catalog}/local_stores`; }\n async selected(value:LocalScope) { const selection = localScope.parse(value), result = await this.catalogs.getCatalog(selection.account_id,selection.catalog_id);if (result.catalog.catalog_type !== 'RETAIL') throw new AdportError('INVALID_INPUT','Local stores/inventory require a RETAIL catalog.');return { selection,catalog:result.catalog,owner:result.context_hash }; }\n private async page(selection:LocalScope,ids:string[]|undefined,size:number,bookmark?:string) {\n const data = await this.client.get(this.path(selection.catalog_id),z.object({ items:z.array(nativeLocalStore).max(250),bookmark:z.string().max(8192).nullable().optional() }),this.params(selection.account_id,{ page_size:String(size),...(ids?{ids:ids.join(',')}:{}),...(bookmark?{bookmark}:{}) })).catch(error=>{throw localFailure(error);});\n 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 || ids && data.items.some(row=>!ids.includes(row.id))) throw localFailure();return data;\n }\n async list(value:unknown) {\n const input = localStoreList.parse(value),selection = localScope.parse({account_id:input.account_id,catalog_id:input.catalog_id}),parent = await this.selected(selection),key = localHash({selection,ids:input.store_ids,size:input.page_size});let bookmark:string|undefined;\n if (input.bookmark) { let cursor;try { cursor = z.object({ selection:groupHash,native:z.string().min(1).max(8192) }).strict().parse(JSON.parse(Buffer.from(input.bookmark,'base64url').toString('utf8'))); } catch {throw new AdportError('INVALID_INPUT','Invalid local-store cursor.');}if (cursor.selection!==key) throw new AdportError('PENDING_MISMATCH','Local-store selection changed; restart the first page.');bookmark=cursor.native; }\n const page = await this.page(selection,input.store_ids,input.page_size,bookmark),complete = page.bookmark===null?true:page.bookmark===undefined?null:false;\n return { records:page.items.map(row=>({...row,...publicLocal(row) as LocalRow,snapshot_hash:localHash({selection,owner:parent.owner,store:storeValue(row)})})),complete,truncated:complete!==true,...(page.bookmark?{next_cursor:Buffer.from(JSON.stringify({selection:key,native:page.bookmark})).toString('base64url')} : {}),notes:['Only stores in the selected advertiser-owned RETAIL catalog. Missing native bookmarks leave completeness unknown.'] };\n }\n private async gather(selection:LocalScope,ids?:string[]) {\n const rows:Store[] = [],seen=new Set<string>();let bookmark:string|undefined;\n for (let page=0;page<40;page++) { const data = await this.page(selection,ids,250,bookmark);rows.push(...data.items);if(rows.length>10_000 || new Set(rows.map(row=>row.id)).size!==rows.length || new Set(rows.map(row=>row.store_code)).size!==rows.length) throw localFailure();if(data.bookmark===null) return rows;if(!data.bookmark||seen.has(data.bookmark)) throw new AdportError('PROVIDER_ERROR','Complete store inventory is unavailable; no absence or unique-code proof is inferred.');seen.add(data.bookmark);bookmark=data.bookmark; }\n throw new AdportError('INVALID_INPUT','Store lookup exceeded10,000 rows; no mutation is permitted.');\n }\n async owned(selection:LocalScope,ids:string[]) { const unique=[...new Set(ids)],stores:Store[]=[];for(let offset=0;offset<unique.length;offset+=100) stores.push(...await this.gather(selection,unique.slice(offset,offset+100)));if(stores.length!==unique.length) throw new AdportError('INVALID_INPUT','Selected local store was not positively read in this catalog.');return stores.sort((a,b)=>a.id.localeCompare(b.id)); }\n async context(value:unknown) {\n const input=localStoreContext.parse(value),parent=await this.selected({account_id:input.account_id,catalog_id:input.catalog_id}),{selection}=parent,action=input.action;localBound(action);\n const inventory = action.kind==='create' || action.kind==='update' && action.stores.some(row=>row.store_code!==undefined) ? await this.gather(selection) : undefined,current=action.kind==='create'?[]:inventory?inventory.filter(row=>action.stores.some(item=>item.id===row.id)):await this.owned(selection,action.stores.map(row=>row.id));\n if(action.kind!=='create'&&current.length!==action.stores.length) throw new AdportError('INVALID_INPUT','A selected store is outside the current catalog.');\n if(action.kind==='create') {if(inventory!.length+action.stores.length>10_000) throw new AdportError('INVALID_INPUT','Catalog would exceed10,000 local stores.');if(action.stores.some(row=>inventory!.some(old=>old.store_code===row.store_code))) throw new AdportError('INVALID_INPUT','CREATE cannot overwrite an existing store code.');}\n if(action.kind==='update') {const desired=(inventory??current).map(row=>({id:row.id,code:action.stores.find(item=>item.id===row.id)?.store_code??row.store_code}));if(new Set(desired.map(row=>row.code)).size!==desired.length) throw new AdportError('INVALID_INPUT','Store code would collide with another store.');if(action.stores.some(row=>row.store_code!==undefined&&row.store_code!==current.find(old=>old.id===row.id)!.store_code)&&!action.acknowledge_store_code_change) throw new AdportError('INVALID_INPUT','Store-code changes require acknowledge_store_code_change.');const changed=action.stores.filter(row=>row.store_code!==undefined&&row.store_code!==current.find(old=>old.id===row.id)!.store_code);if(changed.some(row=>current.some(old=>old.id!==row.id&&old.store_code===row.store_code))) throw new AdportError('INVALID_INPUT','Store-code swaps require separate reviewed operations; transient native collisions are not assumed safe.');}\n 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 AdportError('PENDING_MISMATCH','Store name/code changed; read context again.');\n return {...parent,action,current,occupied_ids:inventory?.map(row=>row.id)??[],context_hash:localHash({selection,owner:parent.owner,catalog:{id:parent.catalog.id,name:parent.catalog.name,type:parent.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) as LocalRow,snapshot_hash:localHash({selection,owner:parent.owner,store:storeValue(row)})})),notes:storeNotes};\n }\n async publicContext(value:unknown) {const data=await this.context(value);return {context_hash:data.context_hash,records:data.records,action:data.action,notes:data.notes};}\n async plan(op:WriteOperation):Promise<Plan> {\n const create=op.tool==='pinterest_create_local_stores',remove=op.tool==='pinterest_delete_local_stores',kind=create?'create':remove?'remove':'update';if(op.provider!=='pinterest'||!this.supports(op.tool)||op.kind!==kind) throw new AdportError('INVALID_INPUT','Invalid local-store mutation kind.');\n const input=create?localStoreCreate.parse(op.payload):remove?localStoreDelete.parse(op.payload):localStoreUpdate.parse(op.payload),selection={account_id:op.accountId,catalog_id:input.catalog_id},action= {kind:create?'create':remove?'delete':'update',stores:input.stores,...('acknowledge_store_code_change'in input?{acknowledge_store_code_change:input.acknowledge_store_code_change}:{})} as Action;\n const prepare=async()=>{const data=await this.context({...selection,action});if(data.context_hash!==input.expected_context_hash) throw new AdportError('PENDING_MISMATCH','Local store selection, owner or configuration changed; preview again.');return data;},before=await prepare();let details:LocalRow|undefined;\n const title=create?'Create local stores':remove?'Delete local stores permanently':'Update local stores';\n return {summary:`${title} · ${action.stores.length}`,changes:action.stores.map(row=>create?`CREATE ${'store_code'in row?row.store_code:''}`:`${remove?'DELETE':'UPDATE'} ${'id'in row?row.id:''}`),coercions:[],budgetDeltas:[],notes:storeNotes,review:{provider:'pinterest',accountId:op.accountId,kind:op.kind,title,subject:before.catalog.name,fields:action.stores.map(row=>({label:create?String('store_code'in row?row.store_code:''):String('id'in row?row.id:''),...(create?{}:{before:publicLocal(storeValue(before.current.find(old=>old.id===('id'in row?row.id:''))!))}),after:remove?'Remove local store':row})),notices:storeNotes},\n execute:async()=>{const fresh=await prepare(),known=new Set(fresh.current.map(row=>row.id));let records:LocalRow[]=[];try{\n const raw=await this.client.mutate(this.path(selection.catalog_id),create?'POST':remove?'DELETE':'PATCH',remove?undefined:input.stores,z.unknown(),this.params(op.accountId,remove?{ids:(input.stores as z.infer<typeof localStoreDelete>['stores']).map(row=>row.id).join(',')}:{}));\n if(remove){\n if(raw!==undefined){if(!Array.isArray(raw)||raw.length!==action.stores.length) throw localFailure();const seen=new Set<string>();for(const value of raw){const row=localObject(value),id=z.string().regex(/^\\d{1,30}$/).parse(row.id);if(!known.has(id)||seen.has(id)) throw localFailure();seen.add(id);const status=localObject(row.status);records.push({id,native_status:status.statusCode===204&&status.code===undefined&&status.message===undefined?'SUCCESS':'FAILURE'});}}\n const remaining=await this.gather(selection,[...known]);records=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===undefined?'HTTP204':records.find(value=>value.id===row.id)?.native_status??'UNCONFIRMED'}));if(records.some(row=>row.status!=='ABSENT_FROM_COMPLETE_FILTERED_LIST'||row.native_status==='FAILURE')) throw localFailure(undefined,[...known],{records});\n }else{\n if(!Array.isArray(raw)||raw.length!==action.stores.length) {if(Array.isArray(raw)) for(const value of raw){const id=localObject(localObject(value).data??value).id;if(typeof id==='string'&&/^\\d{1,30}$/.test(id))known.add(id);}throw localFailure();}\n const returned:Store[]=[],seen=new Set<string>();for(const value of raw){const row=localObject(localObject(value).data??value),id=typeof row.id==='string'&&/^\\d{1,30}$/.test(row.id)?row.id:undefined;if(id)known.add(id);if(row.exceptions!==undefined){const code=localObject(row.exceptions).code;records.push({id:id??'UNCONFIRMED',status:'FAILURE',native_error:true,...(typeof code==='number'&&Number.isSafeInteger(code)?{error_code:code}:{})});continue;}const store=nativeLocalStore.parse(row);if(create&&fresh.occupied_ids.includes(store.id)||seen.has(store.id)||returned.some(old=>old.store_code===store.store_code)||!create&&!fresh.current.some(old=>old.id===store.id)||create&&!(action.stores as z.infer<typeof localStoreCreate>['stores']).some(item=>item.store_code===store.store_code))throw localFailure();seen.add(store.id);returned.push(store);}\n const actual=returned.length?await this.owned(selection,returned.map(row=>row.id)):[];\n for(const store of actual){const expected=create?(action.stores as z.infer<typeof localStoreCreate>['stores']).find(row=>row.store_code===store.store_code):(action.stores as z.infer<typeof localStoreUpdate>['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)),preserved=!previous||Object.entries(storeValue(previous)).every(([key,value])=>expected&&Object.hasOwn(expected,key)||localCanonical(store[key])===localCanonical(value));records.push({id:store.id,name:store.name,store_code:store.store_code,status:matches&&preserved?'REQUESTED_CONFIGURATION_VERIFIED':'CONFIGURATION_UNCONFIRMED',omitted_fields_preserved:previous?preserved:undefined});}\n if(records.length!==action.stores.length||records.some(row=>row.status!=='REQUESTED_CONFIGURATION_VERIFIED'))throw localFailure(undefined,[...known],{records});\n }\n details={status:'COMPLETE',records,configuration_verified:true,publication_verified:false};return records.map(row=>String(row.id));\n }catch(error){const data=error instanceof AdportError?localObject(error.details):{};throw localFailure(error,[...known],{...(data.records?{records:data.records}:records.length?{records}:{} )});}},resultDetails:()=>publicLocal(details),resultWarnings:()=>storeNotes};\n }\n}\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\nimport { pinterestId } from './schemas.js';\nimport { groupHash, groupId } from './product-group-schemas.js';\nimport { filterEnums } from './product-group-filter-spec.js';\nimport { sourceId, itemOperation } from './catalog-item-schemas.js';\n\n// Pinterest-owned OpenAPI5.28.0 at51aca009, inspected2026-11-06. The guide\n// contains older route examples; current OpenAPI path/field shapes are used.\nexport type LocalRow = Record<string, unknown>;\nexport const localCanonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nexport const localHash = (value: unknown) => createHash('sha256').update(localCanonical(value)).digest('hex');\nexport const localObject = (value: unknown): LocalRow => value && typeof value === 'object' && !Array.isArray(value) ? value as LocalRow : {};\nexport const localScope = z.object({ account_id: pinterestId, catalog_id: groupId }).strict();\nexport type LocalScope = z.infer<typeof localScope>;\nexport const localFailure = (error?: unknown, ids: string[] = [], extra: LocalRow = {}) => { const detail = error instanceof AdportError ? localObject(error.details) : {};return new AdportError('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 } : {}), ...(ids.length ? { resource_ids: [...new Set(ids)] } : {}), ...extra }); };\nexport function localBound(value: unknown) { if (Buffer.byteLength(localCanonical(value)) > 2 * 1024 * 1024) throw new AdportError('INVALID_INPUT', 'Local catalog request exceeds2MiB; split the batch.'); }\nexport function publicLocal(value: unknown, key = ''): unknown {\n if (Array.isArray(value)) return value.map(item => publicLocal(item,key));\n if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([name,item]) => [name,publicLocal(item,name)]));\n if (typeof value === 'string' && /url|link/i.test(key)) { try { return { origin: new URL(value).origin, fingerprint: localHash(value) }; } catch { return { fingerprint: localHash(value) }; } }\n return value;\n}\nconst text = z.string().min(1).max(1024), address = z.string().max(4096);\nexport const localStoreDefinition = z.object({ store_code: sourceId, name: text, country: z.enum(filterEnums.Country), address_primary: address.optional(), address_secondary: address.optional(), city: address.optional(), region: address.optional(), postal_code: address.optional(), latitude: z.number().min(-90).max(90).optional(), longitude: z.number().min(-180).max(180).optional() }).strict();\nexport const localStoreChanges = localStoreDefinition.partial().extend({ id: groupId }).strict().refine(value => Object.keys(value).length > 1,'Supply a store setting');\nexport const nativeLocalStore = localStoreDefinition.extend({ id: groupId, created_at: z.string().min(1).max(100), updated_at: z.string().min(1).max(100) }).loose();\nexport const localStoreRemoval = z.object({ id: groupId, confirm_store_code: sourceId, confirm_name: text }).strict();\nconst unique = <T>(values: T[], key: (value: T) => string) => new Set(values.map(key)).size === values.length;\nconst createStores = z.array(localStoreDefinition).min(1).max(100).refine(rows => unique(rows,row => row.store_code),'Duplicate store code');\nconst updateStores = z.array(localStoreChanges).min(1).max(100).refine(rows => unique(rows,row => row.id),'Duplicate store ID');\nconst deleteStores = z.array(localStoreRemoval).min(1).max(100).refine(rows => unique(rows,row => row.id),'Duplicate store ID');\nexport const localStoreAction = z.discriminatedUnion('kind', [z.object({ kind: z.literal('create'), stores: createStores }).strict(), z.object({ kind: z.literal('update'), stores: updateStores, acknowledge_store_code_change: z.literal(true).optional() }).strict(), z.object({ kind: z.literal('delete'), stores: deleteStores }).strict()]);\nexport const localStoreContext = localScope.extend({ action: localStoreAction });\nconst storeWrite = localScope.omit({ account_id: true }).extend({ expected_context_hash: groupHash, acknowledge_catalog_effects: z.literal(true), confirm_publication: z.literal(true) });\nexport const localStoreCreate = storeWrite.extend({ stores: createStores });\nexport const localStoreUpdate = storeWrite.extend({ stores: updateStores, acknowledge_store_code_change: z.literal(true).optional() });\nexport const localStoreDelete = storeWrite.extend({ stores: deleteStores, confirm_permanent_deletion: z.literal(true) });\nexport const localStoreList = localScope.extend({ store_ids: z.array(groupId).min(1).max(100).refine(ids => new Set(ids).size === ids.length).optional(), page_size: z.number().int().min(1).max(250).default(25), bookmark: z.string().min(1).max(16_384).optional() });\nexport const inventoryPair = z.object({ item_id: sourceId, store_code: sourceId, store_id: groupId }).strict();\nexport const inventoryKey = (value: { item_id: string; store_code: string }) => localCanonical([value.item_id,value.store_code]);\nexport const inventoryAttributes = z.object({ price: z.string().min(1).max(1024), availability: z.enum(['in stock','out of stock','preorder']), sale_price: z.string().min(1).max(1024).optional(), ad_link: z.string().min(1).max(65_536).optional() }).strict();\nconst inventoryUpdate = inventoryAttributes.partial().refine(value => Object.keys(value).length > 0,'Supply changed attributes');\nexport const inventoryOperation = z.discriminatedUnion('operation', [\n inventoryPair.extend({ operation: z.literal('CREATE'), attributes: inventoryAttributes }), inventoryPair.extend({ operation: z.literal('UPSERT'), attributes: inventoryAttributes }), inventoryPair.extend({ operation: z.literal('UPDATE'), attributes: inventoryUpdate }), inventoryPair.extend({ operation: z.literal('DELETE') }),\n]);\nexport const inventoryRequest = z.object({ operations: z.array(inventoryOperation).min(1).max(1000).refine(rows => unique(rows,inventoryKey),'Duplicate item/store pair'), acknowledge_replacement: z.literal(true).optional(), acknowledge_unconfirmed_existing: z.literal(true).optional() }).strict();\nexport const inventoryContext = localScope.extend(inventoryRequest.shape);\nexport const inventoryList = localScope.extend({ item_filters: z.array(inventoryPair).min(1).max(1000).refine(rows => unique(rows,inventoryKey),'Duplicate item/store pair'), limit: z.number().int().min(1).max(100).default(24), cursor: z.string().min(1).max(8192).optional() });\nconst inventoryWrite = storeWrite.extend(inventoryRequest.shape).superRefine((value,ctx) => { if (value.operations.some(row => row.operation === 'UPSERT') && !value.acknowledge_replacement) ctx.addIssue({ code:'custom',message:'UPSERT requires full replacement acknowledgement' });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' }); });\nexport const inventoryBatch = inventoryWrite.safeExtend({ confirm_permanent_deletion: z.literal(true).optional() });\nexport const inventoryNamed = (operation: z.infer<typeof itemOperation>) => {\n 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});\n return storeWrite.extend({ items: z.array(item).min(1).max(1000), acknowledge_replacement: z.literal(true).optional(), acknowledge_unconfirmed_existing: z.literal(true).optional(), confirm_permanent_deletion: z.literal(true).optional() }).superRefine((value,ctx) => { const { items,...common } = value, result = inventoryBatch.safeParse({ ...common,operations:items.map(row => ({ ...row,operation })) });if (!result.success) for (const issue of result.error.issues) ctx.addIssue({ code:'custom',path:issue.path,message:issue.message }); });\n};\nexport const inventoryWriteTools = { pinterest_create_local_inventory:'CREATE',pinterest_update_local_inventory:'UPDATE',pinterest_upsert_local_inventory:'UPSERT',pinterest_delete_local_inventory:'DELETE' } as const;\nexport const inventoryBatchReference = z.object({ account_id:pinterestId,batch_receipt:z.string().min(100).max(2_000_000) }).strict();\n","import { z } from 'zod';\nimport { AdportError, type MediaResolver, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestLocalStores } from './local-stores.js';\nimport { groupHash } from './product-group-schemas.js';\nimport { itemOperation, sourceId } from './catalog-item-schemas.js';\nimport { inventoryAttributes, inventoryBatch, inventoryBatchReference, inventoryContext, inventoryKey, inventoryList, inventoryNamed, inventoryPair, inventoryRequest, inventoryWriteTools, localBound, localCanonical, localFailure, localHash, localObject, localScope, publicLocal, type LocalRow, type LocalScope } from './local-catalog-schemas.js';\n\ntype Pair=z.infer<typeof inventoryPair>;\ntype Request=z.infer<typeof inventoryRequest>;\ntype Current={pair:Pair;state:'PRESENT'|'NOT_RETURNED';attributes?:LocalRow;metadata?:LocalRow};\ntype Plan=Omit<WritePreview,'serverValidated'>&{execute():Promise<string[]>;resultDetails?():unknown;resultWarnings?():string[]};\nconst batchId=z.string().regex(/^[A-Za-z0-9_-]{1,100}$/),nativeBatch=z.object({batch_id:batchId,created_time:z.string().min(1).max(100),completed_time:z.string().max(100).optional(),status:z.enum(['PROCESSING','COMPLETED','FAILED']),operation_results:z.array(z.record(z.string(),z.json())).max(1000)});\nconst manifestRow=inventoryPair.extend({operation:itemOperation,desired_keys:z.array(z.enum(['price','sale_price','availability','ad_link'])).max(4),desired_hash:groupHash.optional(),preserved_hash:groupHash.optional()});\nconst receiptSchema=localScope.extend({version:z.literal('pinterest_local_inventory_v1'),scope_id:z.string().min(1).max(200),owner_context_hash:groupHash,batch_id:batchId,expires_at:z.number().int().safe(),manifest:z.array(manifestRow).min(1).max(1000)}).strict();\nconst notes=['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’s processing result, independent readback and final publication/eligibility are separate observations. Native conditional writes and automatic mutation replay are not available.'];\nconst readAttrs=(row:LocalRow)=>Object.fromEntries(Object.entries(row).filter(([key])=>!['item_id','store_metadata','created_at','last_updated_time'].includes(key)));\nconst preserved=(row:LocalRow,keys:string[])=>Object.fromEntries(Object.entries(row).filter(([key])=>!keys.includes(key)));\nconst diagnostics=(value:unknown)=>z.array(z.object({attribute:z.string().max(256),code:z.number().int().min(-2147483648).max(2147483647),message:z.string().max(100_000)})).max(10_000).parse(value??[]).map(({message,...row})=>({...row,message_present:!!message}));\n\nexport class PinterestLocalInventory {\n constructor(private readonly client:PinterestAdsClient,private readonly stores:PinterestLocalStores,private readonly media:MediaResolver) {}\n supports(tool:string){return tool==='pinterest_apply_local_inventory_batch'||Object.hasOwn(inventoryWriteTools,tool);}\n private scopeId(){const value=(this.media as {scopeId?:unknown}).scopeId;return typeof value==='string'&&value?value:'local';}\n private path(catalog:string){return `catalogs/${catalog}/local_inventory_items`;}\n private async selected(selection:LocalScope,pairs:Pair[]){const parent=await this.stores.selected(selection),stores=await this.stores.owned(selection,pairs.map(row=>row.store_id));if(pairs.some(pair=>stores.find(store=>store.id===pair.store_id)?.store_code!==pair.store_code))throw new AdportError('PENDING_MISMATCH','Selected store ID/code does not match the current catalog.');return {...parent,stores};}\n private async readSet(selection:LocalScope,pairs:Pair[]):Promise<Current[]>{\n const data=await this.client.mutate(this.path(selection.catalog_id)+'/query','POST',{item_filters:pairs.map(({item_id,store_code})=>({item_id,store_code}))},z.object({items:z.array(z.record(z.string(),z.json())).max(1000)}),this.stores.params(selection.account_id)).catch(error=>{throw localFailure(error);}),seen=new Map<string,Current>();\n for(const raw of data.items){inventoryAttributes.partial().loose().parse(raw);const item_id=sourceId.parse(raw.item_id),metadata=z.looseObject({store_id:z.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);if(!pair||metadata.store_id!==pair.store_id||seen.has(key)||raw.catalog_id!==undefined&&raw.catalog_id!==selection.catalog_id)throw localFailure();z.number().int().safe().parse(raw.created_at);z.number().int().safe().parse(raw.last_updated_time);seen.set(key,{pair,state:'PRESENT',attributes:readAttrs(raw),metadata});}\n return pairs.map(pair=>seen.get(inventoryKey(pair))??{pair,state:'NOT_RETURNED'});\n }\n private record(row:Current){return {id:localHash([row.pair.item_id,row.pair.store_code]),name:row.pair.item_id+' · '+row.pair.store_code,...row.pair,status:row.state,attributes:publicLocal(row.attributes),store_metadata:row.metadata};}\n async list(value:unknown){\n const input=inventoryList.parse(value),selection=localScope.parse({account_id:input.account_id,catalog_id:input.catalog_id}),key=localHash({selection,pairs:input.item_filters,size:input.limit});let offset=0;\n if(input.cursor){let cursor;try{cursor=z.object({selection:groupHash,offset:z.number().int().min(1).max(999)}).strict().parse(JSON.parse(Buffer.from(input.cursor,'base64url').toString('utf8')));}catch{throw new AdportError('INVALID_INPUT','Invalid local-inventory cursor.');}if(cursor.selection!==key||cursor.offset>=input.item_filters.length)throw new AdportError('PENDING_MISMATCH','Local-inventory selection changed; restart the first page.');offset=cursor.offset;}\n const pairs=input.item_filters.slice(offset,offset+input.limit);await this.selected(selection,pairs);const current=await this.readSet(selection,pairs),next=offset+pairs.length;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:[...notes,'Paging covers only the requested item/store pairs, not all inventory in the catalog.']};\n }\n private manifest(request:Request,current:Current[]){\n const result=request.operations.map(row=>{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:undefined,keys=Object.keys(attributes??{}) as z.infer<typeof manifestRow>['desired_keys'],before=current.find(old=>inventoryKey(old.pair)===inventoryKey(pair))!;return {...pair,operation:row.operation,desired_keys:keys,...(attributes?{desired_hash:localHash(attributes)}:{}),...(row.operation==='UPDATE'?{preserved_hash:localHash(preserved(before.attributes!,keys))}:{})};});\n if(Buffer.byteLength(localCanonical(result))>1_000_000)throw new AdportError('INVALID_INPUT','Local-inventory receipt exceeds its bound; split the batch.');return result;\n }\n async context(value:unknown){\n const input=inventoryContext.parse(value),selection=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});localBound(request);\n const pairs=request.operations.map(row=>inventoryPair.parse({item_id:row.item_id,store_code:row.store_code,store_id:row.store_id})),parent=await this.selected(selection,pairs),current=await this.readSet(selection,pairs);\n for(const row of request.operations){const before=current.find(old=>inventoryKey(old.pair)===inventoryKey(row))!;if(row.operation==='CREATE'&&before.state==='PRESENT')throw new AdportError('INVALID_INPUT','CREATE cannot overwrite a positively read local item/store pair.');if(['UPDATE','DELETE'].includes(row.operation)&&before.state!=='PRESENT')throw new AdportError('INVALID_INPUT','UPDATE/DELETE require a positively read current item/store pair.');if(row.operation==='UPSERT'&&!request.acknowledge_replacement)throw new AdportError('INVALID_INPUT','UPSERT requires acknowledge_replacement.');if(['CREATE','UPSERT'].includes(row.operation)&&before.state!=='PRESENT'&&!request.acknowledge_unconfirmed_existing)throw new AdportError('INVALID_INPUT','Missing query rows do not prove absence; acknowledge_unconfirmed_existing is required.');}\n const scope_id=this.scopeId(),manifest=this.manifest(request,current);return {...parent,request,current,manifest,scope_id,context_hash:localHash({selection,owner:parent.owner,catalog:{id:parent.catalog.id,name:parent.catalog.name,type:parent.catalog.catalog_type},stores:parent.stores.map(({created_at:_created,updated_at:_updated,...row})=>row),request,current,scope_id}),records:current.map(row=>this.record(row)),notes};\n }\n async publicContext(value:unknown){const result=await this.context(value);return {context_hash:result.context_hash,records:result.records,changes:result.request.operations.map(row=>publicLocal(row)),notes:[...notes,'CREATE duplicate handling is native; Adport does not claim atomic absence or promise that a missing query proves a new pair.']};}\n private batchRows(data:z.infer<typeof nativeBatch>,manifest:z.infer<typeof manifestRow>[]){\n const found=new Map<string,LocalRow>();for(const raw of data.operation_results){const pair=z.object({item_id:sourceId,store_code:sourceId,supplemental_type:z.literal('LOCAL_INVENTORY'),status:z.enum(['SUCCESS','FAILURE','PROCESSING'])}).parse(raw),key=inventoryKey(pair),expected=manifest.find(row=>inventoryKey(row)===key),errors=diagnostics(raw.errors),warnings=diagnostics(raw.warnings);if(!expected||found.has(key)||pair.status==='SUCCESS'&&(errors.length||data.status==='FAILED'))throw localFailure();found.set(key,{id:localHash([pair.item_id,pair.store_code]),name:pair.item_id+' · '+pair.store_code,item_id:pair.item_id,store_code:pair.store_code,store_id:expected.store_id,status:pair.status,errors,warnings});}\n return manifest.map(row=>found.get(inventoryKey(row))??{id:localHash([row.item_id,row.store_code]),name:row.item_id+' · '+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:[]});\n }\n private async verifiedReceipt(value:unknown){const input=inventoryBatchReference.parse(value),proof=receiptSchema.parse(this.client.verifyCatalogBatchReceipt(input.batch_receipt));if(proof.account_id!==input.account_id||proof.scope_id!==this.scopeId()||proof.expires_at<=Math.floor(Date.now()/1000)||proof.expires_at>Math.floor(Date.now()/1000)+30*86400)throw new AdportError('INVALID_INPUT','Local-inventory receipt expired or belongs to another advertiser/project.');const parent=await this.stores.selected({account_id:proof.account_id,catalog_id:proof.catalog_id});if(parent.owner!==proof.owner_context_hash)throw new AdportError('POLICY_VIOLATION','Local-inventory catalog ownership changed.');return proof;}\n async status(value:unknown,reconcile=false){\n const proof=await this.verifiedReceipt(value),data=await this.client.get(`catalogs/${proof.catalog_id}/supplemental_items/batch/${proof.batch_id}`,nativeBatch,this.stores.params(proof.account_id)).catch(error=>{throw localFailure(error,[proof.batch_id]);});if(data.batch_id!==proof.batch_id)throw localFailure();const records=this.batchRows(data,proof.manifest);let readback_error:LocalRow|undefined;\n if(reconcile)try{await this.selected({account_id:proof.account_id,catalog_id:proof.catalog_id},proof.manifest);const current=await this.readSet({account_id:proof.account_id,catalog_id:proof.catalog_id},proof.manifest);for(const record of records){const expected=proof.manifest.find(row=>inventoryKey(row)===inventoryKey(record as {item_id:string;store_code:string}))!,actual=current.find(row=>inventoryKey(row.pair)===inventoryKey(expected))!;record.observed_state=actual.state;if(record.status!=='SUCCESS'){record.readback='NATIVE_ITEM_NOT_SUCCESSFUL';continue;}if(expected.operation==='DELETE'){record.readback=actual.state==='PRESENT'?'STILL_PRESENT':'ABSENCE_UNCONFIRMED';continue;}if(!actual.attributes){record.readback='CURRENT_PAIR_UNCONFIRMED';continue;}const attrs=Object.fromEntries(expected.desired_keys.map(key=>[key,actual.attributes![key]])),matches=localHash(attrs)===expected.desired_hash,retains=!expected.preserved_hash||localHash(preserved(actual.attributes,expected.desired_keys))===expected.preserved_hash;record.readback=matches&&retains?'REQUESTED_CONFIGURATION_VERIFIED':'CONFIGURATION_UNCONFIRMED';record.omitted_fields_preserved=expected.preserved_hash?retains:undefined;}}catch(error){const detail=error instanceof AdportError?localObject(error.details):{};readback_error={status:'READBACK_UNAVAILABLE',...(typeof detail.http_status==='number'?{http_status:detail.http_status}:{})};}\n return {batch_id:proof.batch_id,status:data.status,records,submitted_items:proof.manifest.length,terminal_items:records.filter(row=>['SUCCESS','FAILURE','BATCH_FAILED'].includes(String(row.status))).length,all_items_native_successful:data.status==='COMPLETED'&&records.every(row=>row.status==='SUCCESS'),...(readback_error?{readback_error}:{}),publication_verified:false,notes};\n }\n async plan(op:WriteOperation):Promise<Plan>{\n const operation=inventoryWriteTools[op.tool as keyof typeof inventoryWriteTools],kind=operation==='CREATE'?'create':operation==='DELETE'?'remove':'update';if(op.provider!=='pinterest'||!this.supports(op.tool)||op.kind!==kind)throw new AdportError('INVALID_INPUT','Invalid local-inventory mutation kind.');const parsed=operation?inventoryNamed(operation).parse(op.payload):inventoryBatch.parse(op.payload),selection={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});\n const prepare=async()=>{const result=await this.context({...selection,...request});if(result.context_hash!==parsed.expected_context_hash)throw new AdportError('PENDING_MISMATCH','Local inventory, store, owner, project or request changed; preview again.');return result;},before=await prepare();let details:LocalRow|undefined;\n return {summary:`Submit local inventory batch · ${request.operations.length} item/store pairs`,changes:request.operations.map(row=>`${row.operation} ${row.item_id} · ${row.store_code}`),coercions:[],budgetDeltas:[],notes,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+' · '+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:notes},\n execute:async()=>{const fresh=await prepare();let id:string|undefined;try{if(fresh.scope_id!==this.scopeId())throw localFailure();const native=await this.client.mutate(this.path(selection.catalog_id)+'/batch','POST',{operations:request.operations.map(({store_id:_store,...row})=>row)},nativeBatch,this.stores.params(op.accountId));id=native.batch_id;const batch_receipt=this.client.catalogBatchReceipt({...selection,version:'pinterest_local_inventory_v1',scope_id:fresh.scope_id,owner_context_hash:fresh.owner,batch_id:id,expires_at:Math.floor(Date.now()/1000)+30*86400,manifest:fresh.manifest}),records=this.batchRows(native,fresh.manifest);if(native.status==='FAILED'||records.every(row=>row.status==='FAILURE'))throw localFailure(undefined,[id],{batch_receipt,records,native_status:native.status});details={status:'ACCEPTED_FOR_PROCESSING',processed:false,native_status:native.status,batch_id:id,batch_receipt,records,configuration_verified:false,publication_verified:false,next_tool:'pinterest_local_inventory_batch_status',next_arguments:{account_id:op.accountId,batch_receipt}};return [id];}catch(error){const extra=error instanceof AdportError?localObject(error.details):{};throw localFailure(error,id?[id]:Array.isArray(extra.resource_ids)?extra.resource_ids as string[]:[],extra.batch_receipt?{batch_receipt:extra.batch_receipt,records:extra.records,native_status:extra.native_status}:{});}},resultDetails:()=>details,resultWarnings:()=>notes};\n }\n}\n","import { z } from 'zod';\nimport { AdportError, defineTool, guardedWriteTool, type AnyToolDefinition, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { PinterestAdsClient } from './client.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { accountSchema, campaignSchema, createCampaignSchema, pinterestId } from './schemas.js';\nimport { groupHash } from './product-group-schemas.js';\nimport { localCanonical, localHash, localObject, type LocalRow } from './local-catalog-schemas.js';\n\ntype Campaign=z.infer<typeof campaignSchema>;\ntype Plan=Omit<WritePreview,'serverValidated'>&{execute():Promise<string[]>;resultDetails?():unknown;resultWarnings?():string[]};\nexport const campaignBudgetContext=z.object({account_id:pinterestId,campaign_id:pinterestId}).strict();\nexport const campaignDailyBudget=z.object({campaign_id:pinterestId,expected_context_hash:groupHash,daily_budget_mode:z.enum(['FIXED','AVERAGE']),budget_micros:z.number().int().positive().safe().optional(),acknowledge_variable_daily_spend:z.literal(true).optional(),acknowledge_averaging_reset:z.literal(true).optional()}).strict().superRefine((value,ctx)=>{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.'});});\nconst notes=['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.'];\nconst failure=(error?:unknown,ids:string[]=[],extra:LocalRow={})=>(new AdportError('PROVIDER_ERROR','Pinterest campaign budget outcome is unconfirmed. No mutation was retried; reconcile known campaign IDs before another preview. Native bodies are hidden.',{...(ids.length?{resource_ids:[...new Set(ids)]}:{}),...(error instanceof AdportError&&Array.isArray(localObject(error.details).native_errors)?{native_errors:localObject(error.details).native_errors}:{}),...(error instanceof AdportError&&typeof localObject(error.details).verification_phase==='string'?{verification_phase:localObject(error.details).verification_phase}:{}),...extra,...(error instanceof AdportError&&typeof localObject(error.details).api_code==='number'&&Number.isSafeInteger(localObject(error.details).api_code)?{api_code:localObject(error.details).api_code}:{}),...(error instanceof AdportError&&typeof localObject(error.details).http_status==='number'?{http_status:localObject(error.details).http_status}:{})}));\nconst configuration=(campaign: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]));\n\n/** Fixed/average semantics are explicit; the shared cap still checks native nominal micros. */\nexport class PinterestCampaignBudgets{\n constructor(private readonly client:PinterestAdsClient,private readonly campaign:(account:string,id:string)=>Promise<Campaign>,private readonly projectScope:()=>string){}\n supports(tool:string){return tool==='pinterest_set_campaign_daily_budget';}\n private async account(account:string){const result=await this.client.get(`ad_accounts/${pinterestId.parse(account)}`,accountSchema);if(result.id!==account)throw failure();return {id:result.id,currency:result.currency,country:typeof result.country==='string'?result.country:undefined,owner_fingerprint:typeof localObject(result.owner).username==='string'?localHash(String(localObject(result.owner).username).toLowerCase()):undefined};}\n private currency(value:unknown){if(typeof value!=='string'||!/^[A-Z]{3}$/.test(value))throw new AdportError('INVALID_INPUT','Native account currency is unavailable; no monetary mutation is permitted.');return value;}\n private mode(value:Campaign){const daily=value.daily_spend_cap??0,lifetime=value.lifetime_spend_cap??0;if(value.is_campaign_budget_optimization!==true)return 'NOT_CAMPAIGN_BUDGETED';if((daily>0)===(lifetime>0))return 'AMBIGUOUS';if(lifetime>0)return value.is_flexible_daily_budgets===true?'AMBIGUOUS':'LIFETIME';return value.is_flexible_daily_budgets===true?'AVERAGE':value.is_flexible_daily_budgets===false?'FIXED':'DAILY_MODE_UNCONFIRMED';}\n async context(value:unknown){const input=campaignBudgetContext.parse(value),account=await this.account(input.account_id),current=await this.campaign(input.account_id,input.campaign_id),mode=this.mode(current),scope=this.projectScope();return {account,current,mode,scope,context_hash:localHash({input,account,current:configuration(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:account.currency,is_campaign_budget_optimization:current.is_campaign_budget_optimization,is_flexible_daily_budgets:current.is_flexible_daily_budgets}],notes};}\n async publicContext(value:unknown){const result=await this.context(value);return {context_hash:result.context_hash,records:result.records,notes};}\n private async write(account:string,method:'POST'|'PATCH',body:LocalRow):Promise<{id:string}>{\n const ids:string[]=[];if(typeof body.id==='string')ids.push(body.id);\n try{const raw=localObject(await this.client.mutate(`ad_accounts/${pinterestId.parse(account)}/campaigns`,method,[body],z.unknown()));for(const item of Array.isArray(raw.items)?raw.items.slice(0,1000):[]){const id=localObject(localObject(item).data).id;if(pinterestId.safeParse(id).success)ids.push(String(id));}if(!Array.isArray(raw.items)||raw.items.length!==1)throw failure();const item=localObject(raw.items[0]);if(item.exceptions!==undefined&&(!Array.isArray(item.exceptions)||item.exceptions.length)){const errors=Array.isArray(item.exceptions)?item.exceptions.slice(0,100).map(value=>{const row=localObject(value);return {...(typeof row.code==='number'&&Number.isSafeInteger(row.code)?{code:row.code}:{}),message_present:typeof row.message==='string'};}):[];throw failure(undefined,ids,{verification_phase:'NATIVE_BATCH_ERRORS',native_errors:errors});}const data=campaignSchema.partial().extend({id:pinterestId}).parse(item.data);if(data.ad_account_id!==undefined&&data.ad_account_id!==account||body.id!==undefined&&data.id!==body.id||Object.entries(body).some(([key,value])=>data[key]!==undefined&&localCanonical(data[key])!==localCanonical(value)))throw failure(undefined,ids,{verification_phase:'NATIVE_RECEIPT'});return data;}catch(error){throw failure(error,ids);}\n }\n private preserved(before:Campaign,after:Campaign,changed:string[]){const values=configuration(after);return Object.entries(configuration(before)).every(([key,value])=>changed.includes(key)||localCanonical(values[key])===localCanonical(value));}\n async create(input:z.infer<typeof createCampaignSchema>,op:WriteOperation,guard:WriteGuard):Promise<Plan>{\n 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 AdportError('INVALID_INPUT','Invalid average-daily campaign creation.');const account=await this.account(op.accountId),currency=this.currency(account.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};let details:LocalRow|undefined;\n 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}],notes,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},{label:'Status',after:status},{label:'Objective',after:input.objective_type}],notices:notes},execute:async()=>{let id:string|undefined;try{const fresh=await this.account(op.accountId);if(localCanonical(fresh)!==localCanonical(account))throw new AdportError('PENDING_MISMATCH','Account currency/configuration changed.');const created=await this.write(op.accountId,'POST',body);id=created.id;const actual=await this.campaign(op.accountId,id);if(Object.entries(body).some(([key,value])=>localCanonical(actual[key])!==localCanonical(value))||(actual.lifetime_spend_cap??0)!==0)throw failure();details={configuration_readback:'VERIFIED',campaign_id:id,status:actual.status,budget_mode:'AVERAGE',configured_daily_average_micros:actual.daily_spend_cap,currency,daily_delivery_ceiling_verified:false,full_performance_plus_configuration:false};return[id];}catch(error){const known=error instanceof AdportError?localObject(error.details).resource_ids:undefined;throw failure(error,id?[id]:Array.isArray(known)?known as string[]:[]);}},resultDetails:()=>details,resultWarnings:()=>notes};\n }\n async plan(op:WriteOperation):Promise<Plan>{\n if(op.provider!=='pinterest'||!this.supports(op.tool)||op.kind!=='update')throw new AdportError('INVALID_INPUT','Invalid daily-budget mutation kind.');const input=campaignDailyBudget.parse(op.payload),prepare=async()=>{const result=await this.context({account_id:op.accountId,campaign_id:input.campaign_id});if(result.context_hash!==input.expected_context_hash)throw new AdportError('PENDING_MISMATCH','Campaign, budget mode, currency or project changed; preview again.');if(!['FIXED','AVERAGE'].includes(result.mode)||!['PAUSED','ACTIVE','DRAFT'].includes(String(result.current.status)))throw new AdportError('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.');if((result.mode==='AVERAGE'||input.daily_budget_mode==='AVERAGE')&&(!input.acknowledge_variable_daily_spend||!input.acknowledge_averaging_reset))throw new AdportError('INVALID_INPUT','Current or requested average mode requires variable-spend and averaging-reset acknowledgements.');return result;},before=await prepare(),currency=this.currency(before.account.currency),amount=input.budget_micros??before.current.daily_spend_cap!;\n if(before.mode===input.daily_budget_mode&&amount===before.current.daily_spend_cap)throw new AdportError('INVALID_INPUT','No daily-budget change requested.');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'}`;let details:LocalRow|undefined;\n return {summary:`Change Pinterest campaign \"${before.current.name??input.campaign_id}\" daily budget`,changes:[`~ ${input.campaign_id} ${before.mode} → ${input.daily_budget_mode}; ${before.current.daily_spend_cap} → ${amount} micros`],coercions:[],budgetDeltas:[{target,fromMicros:before.current.daily_spend_cap!,toMicros:amount,currency}],notes,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},{label:'Status',before:before.current.status,after:before.current.status}],notices:notes},execute:async()=>{await prepare();try{await this.write(op.accountId,'PATCH',body);const actual=await this.campaign(op.accountId,input.campaign_id);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 failure(undefined,[input.campaign_id],{verification_phase:'INDEPENDENT_READBACK'});details={configuration_readback:'VERIFIED',campaign_id:actual.id,status:actual.status,budget_mode:input.daily_budget_mode,configured_budget_micros:amount,currency,omitted_configuration_preserved:true,daily_delivery_ceiling_verified:false};return[actual.id];}catch(error){const known=error instanceof AdportError?localObject(error.details).resource_ids:undefined;throw failure(error,[input.campaign_id,...(Array.isArray(known)?known as string[]:[])]);}},resultDetails:()=>details,resultWarnings:()=>notes};\n }\n}\n\nexport function pinterestCampaignBudgetTools(provider:PinterestAdsProvider):AnyToolDefinition[]{const catalog={category:'campaigns' as const,exposure:'specialist' as const};return[\n defineTool({name:'pinterest_campaign_budget_context',namespace:'pinterest',catalog,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:z.looseObject({records:z.array(z.record(z.string(),z.unknown()))}),handler:input=>provider.campaignBudgets.publicContext(input)}),\n guardedWriteTool({name:'pinterest_set_campaign_daily_budget',namespace:'pinterest',provider:'pinterest',catalog,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.'}),\n];}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { createCampaignSchema, pinterestId, setBudgetSchema, setStatusSchema } from './schemas.js';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { pinterestCreativeTools } from './creative-tools.js';\nimport { pinterestAssetTools } from './assets.js';\nimport { pinterestKeywordTools } from './keywords.js';\nimport { pinterestAudienceTools } from './audiences.js';\nimport { pinterestMeasurementTools } from './measurement.js';\nimport { pinterestCatalogTools } from './catalogs.js';\nimport { pinterestProductGroupTools } from './product-group-tools.js';\nimport { pinterestCatalogItemTools } from './catalog-item-tools.js';\nimport { pinterestLocalCatalogTools } from './local-catalog-tools.js';\nimport { pinterestCampaignBudgetTools } from './campaign-budgets.js';\n\nexport function pinterestTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n return [\n ...pinterestAssetTools(provider),\n ...pinterestKeywordTools(provider),\n ...pinterestAudienceTools(provider),\n ...pinterestMeasurementTools(provider),\n ...pinterestCatalogTools(provider),\n ...pinterestProductGroupTools(provider),\n ...pinterestCatalogItemTools(provider),\n ...pinterestLocalCatalogTools(provider),\n ...pinterestCampaignBudgetTools(provider),\n ...pinterestCreativeTools(provider),\n defineTool({ name: 'pinterest_list_campaigns', namespace: 'pinterest', description: 'List Pinterest campaigns, including archived and draft entities.', input: z.object({ account_id: pinterestId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n guardedWriteTool({ 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 }),\n guardedWriteTool({ name: 'pinterest_set_campaign_status', namespace: 'pinterest', provider: 'pinterest', kind: 'update', description: 'Pause or activate an existing Pinterest campaign.', payload: setStatusSchema }),\n guardedWriteTool({ 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 }),\n ];\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { filterFields } from './product-group-filter-spec.js';\nimport { catalogType, groupContext, groupCreate, groupDelete, groupList, groupPaging, groupReference, groupUpdate, productGroupFilterSchema } from './product-group-schemas.js';\n\nexport function pinterestProductGroupTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'creatives' as const, exposure: 'specialist' as const }, read = { namespace: 'pinterest', catalog, presentation: 'records' as const, annotations: { readOnly: true }, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) }, write = { namespace: 'pinterest', provider: 'pinterest', catalog };\n return [\n defineTool({ namespace: 'pinterest', catalog, 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: z.object({ catalog_type: catalogType }).strict(), annotations: { readOnly: true, openWorld: false }, handler: async input => ({ catalog_type: input.catalog_type, fields: filterFields[input.catalog_type], schema: z.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.'] }) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n guardedWriteTool({ ...write, 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 }),\n guardedWriteTool({ ...write, 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 }),\n guardedWriteTool({ ...write, 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 }),\n ];\n}\n","import { z } from 'zod';\nimport { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { attributeSchema, batchReference, itemBatchApply, itemContext, itemCopy, itemNamedApply, itemRead, itemSchemaQuery, itemWriteOperations } from './catalog-item-schemas.js';\n\nexport function pinterestCatalogItemTools(provider: PinterestAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'creatives' as const, exposure: 'specialist' as const }, read = { namespace: 'pinterest', catalog, annotations: { readOnly: true }, presentation: 'records' as const, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) }, write = { namespace: 'pinterest', provider: 'pinterest', catalog };\n const named = Object.entries(itemWriteOperations).map(([name, operation]) => guardedWriteTool({ ...write, name, 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.` }));\n return [\n defineTool({ namespace: 'pinterest', catalog, 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: z.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.'] }) }),\n defineTool({ ...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: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, handler: input => provider.catalogItems.list(input) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n defineTool({ ...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) }),\n ...named,\n guardedWriteTool({ ...write, 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.' }),\n guardedWriteTool({ ...write, name: 'pinterest_update_catalog_item_copy', kind: 'update', destructive: true, 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.' }),\n ];\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { PinterestAdsProvider } from './provider.js';\nimport { inventoryBatch, inventoryBatchReference, inventoryContext, inventoryList, inventoryNamed, inventoryWriteTools, localStoreContext, localStoreCreate, localStoreDelete, localStoreList, localStoreUpdate } from './local-catalog-schemas.js';\n\nexport function pinterestLocalCatalogTools(provider:PinterestAdsProvider):AnyToolDefinition[]{\n const catalog={category:'creatives' as const,exposure:'specialist' as const},read={namespace:'pinterest',catalog,annotations:{readOnly:true},presentation:'records' as const,output:z.looseObject({records:z.array(z.record(z.string(),z.unknown()))})},write={namespace:'pinterest',provider:'pinterest',catalog};\n return [\n defineTool({...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)}),\n defineTool({...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)}),\n guardedWriteTool({...write,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.'}),\n guardedWriteTool({...write,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.'}),\n guardedWriteTool({...write,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.'}),\n defineTool({...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)}),\n defineTool({...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)}),\n defineTool({...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)}),\n defineTool({...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)}),\n ...Object.entries(inventoryWriteTools).map(([name,operation])=>guardedWriteTool({...write,name,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.`})),\n guardedWriteTool({...write,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.'}),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { PinterestAdsClient, type PinterestCredentials } from './client.js';\nimport { PinterestAdsProvider } from './provider.js';\nimport { pinterestTools } from './tools.js';\nexport { PinterestAdsClient, PINTEREST_API_BASE, PINTEREST_TOKEN_URL, PINTEREST_ADS_SCOPES, PINTEREST_PIN_SCOPES, PINTEREST_SECRET_PIN_SCOPES, PINTEREST_CATALOG_SCOPES, pinterestAuthorizationScopes, buildPinterestAuthUrl, exchangePinterestCode, type PinterestCredentials, type PinterestAuthorizationOptions } from './client.js';\nexport { PinterestAdsProvider } from './provider.js';\nexport { pinterestTools } from './tools.js';\nexport { accountSchema, campaignSchema } from './schemas.js';\n\nexport async function resolvePinterestCredentials(store: CredentialStore): Promise<PinterestCredentials | undefined> {\n const data = (await store.get('pinterest'))?.data;\n if (data?.client_id && data.client_secret && data.refresh_token) return {\n clientId: data.client_id, clientSecret: data.client_secret, refreshToken: data.refresh_token,\n onRefreshToken: async refreshToken => {\n const latest = await store.get('pinterest');\n if (latest) await store.set({ provider: 'pinterest', source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });\n },\n };\n if (process.env.PINTEREST_CLIENT_ID && process.env.PINTEREST_CLIENT_SECRET && process.env.PINTEREST_REFRESH_TOKEN) return {\n clientId: process.env.PINTEREST_CLIENT_ID, clientSecret: process.env.PINTEREST_CLIENT_SECRET, refreshToken: process.env.PINTEREST_REFRESH_TOKEN,\n };\n return undefined;\n}\nexport async function createPinterestModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolvePinterestCredentials(store);\n if (!credentials) return undefined;\n const provider = new PinterestAdsProvider(new PinterestAdsClient(credentials));\n return { provider, tools: pinterestTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAC5B,SAAS,SAAS;AAClB,SAAS,YAAY,uBAAuB;AAErC,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB,GAAG,kBAAkB;AACjD,IAAM,uBAAuB,CAAC,YAAY,WAAW;AACrD,IAAM,uBAAuB,CAAC,GAAG,sBAAsB,eAAe,gBAAgB,aAAa,cAAc,oBAAoB;AACrI,IAAM,8BAA8B,CAAC,GAAG,sBAAsB,sBAAsB,uBAAuB,oBAAoB,mBAAmB;AAClJ,IAAM,2BAA2B,CAAC,iBAAiB,gBAAgB;AAMnE,SAAS,6BAA6B,UAAyC,CAAC,GAAsB;AAC3G,SAAO,CAAC,GAAI,QAAQ,aAAa,8BAA8B,QAAQ,gBAAgB,uBAAuB,sBAAuB,GAAI,QAAQ,oBAAoB,2BAA2B,CAAC,CAAE;AACrM;AAOA,IAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAAG,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EACjE,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA,EAC1C,OAAO,EAAE,OAAO,EAAE,SAAS;AAC7B,CAAC;AAEM,SAAS,sBAAsB,UAAkB,aAAqBA,QAAe,UAAyC,CAAC,GAAW;AAC/I,SAAO,oCAAoC,IAAI,gBAAgB;AAAA,IAC7D,WAAW;AAAA,IAAU,eAAe;AAAA,IAAQ,cAAc;AAAA,IAAa,OAAAA;AAAA,IAAO,OAAO,6BAA6B,OAAO,EAAE,KAAK,GAAG;AAAA,EACrI,CAAC,CAAC;AACJ;AAEA,eAAe,aAAaC,cAAsE,MAAuB,WAAyB;AAChJ,QAAMC,YAAW,MAAM,UAAU,qBAAqB;AAAA,IACpD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AW,aAAa,UAAU,aAAa,MAAM,UAAU,aAAa,qDAAqD,SAAS,gBAAgB,CAAC;AAAA,IACrNA,mBAAiB,EAAE,MAAM,wBAAwB,WAAW,aAAa,UAAU,aAAa,MAAM,UAAU,aAAa,mGAAmG,SAAS,gBAAgB,CAAC;AAAA,EAC5P;AACF;;;AIvBA,eAAsB,4BAA4B,OAAmE;AACnH,QAAM,QAAQ,MAAM,MAAM,IAAI,WAAW,IAAI;AAC7C,MAAI,MAAM,aAAa,KAAK,iBAAiB,KAAK,cAAe,QAAO;AAAA,IACtE,UAAU,KAAK;AAAA,IAAW,cAAc,KAAK;AAAA,IAAe,cAAc,KAAK;AAAA,IAC/E,gBAAgB,OAAM,iBAAgB;AACpC,YAAM,SAAS,MAAM,MAAM,IAAI,WAAW;AAC1C,UAAI,OAAQ,OAAM,MAAM,IAAI,EAAE,UAAU,aAAa,QAAQ,OAAO,QAAQ,MAAM,EAAE,GAAG,OAAO,MAAM,eAAe,aAAa,EAAE,CAAC;AAAA,IACrI;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,uBAAuB,QAAQ,IAAI,2BAA2B,QAAQ,IAAI,wBAAyB,QAAO;AAAA,IACxH,UAAU,QAAQ,IAAI;AAAA,IAAqB,cAAc,QAAQ,IAAI;AAAA,IAAyB,cAAc,QAAQ,IAAI;AAAA,EAC1H;AACA,SAAO;AACT;AACA,eAAsB,sBAAsB,OAA6D;AACvG,QAAMC,eAAc,MAAM,4BAA4B,KAAK;AAC3D,MAAI,CAACA,aAAa,QAAO;AACzB,QAAM,WAAW,IAAI,qBAAqB,IAAI,mBAAmBA,YAAW,CAAC;AAC7E,SAAO,EAAE,UAAU,OAAO,eAAe,QAAQ,EAAE;AACrD;","names":["state","credentials","response","url","name","text","id","z","AdportError","LocalMediaResolver","AdportError","z","z","z","z","name","description","write","z","account","id","AdportError","ids","cursor","type","parent","tag","fields","url","AdportError","creativesOutput","defineTool","guardedWriteTool","z","id","z","url","account","AdportError","pinId","fields","input","current","ids","paging","defineTool","creativesOutput","guardedWriteTool","createHash","AdportError","creativesOutput","defineTool","guardedWriteTool","z","hash","z","createHash","snapshot","account","selected","AdportError","configuration","page","ids","parsed","notes","value","defineTool","creativesOutput","guardedWriteTool","createHash","AdportError","creativesOutput","defineTool","guardedWriteTool","z","hash","z","ids","writes","object","AdportError","digest","createHash","account","page","source","tag","type","targeting","create","input","current","body","fields","name","description","defineTool","write","guardedWriteTool","creativesOutput","createHash","AdportError","defineTool","guardedWriteTool","z","canonical","digest","createHash","hash","z","url","writes","account","AdportError","ids","configuration","input","context","count","name","description","defineTool","guardedWriteTool","createHash","AdportError","defineTool","guardedWriteTool","z","id","z","hash","name","url","account","selected","reference","canonical","digest","createHash","text","location","credentials","catalog","AdportError","ids","page","fields","input","body","current","changes","defineTool","guardedWriteTool","createHash","AdportError","z","z","z","text","strings","type","fields","reference","ids","canonical","hash","createHash","AdportError","cursor","z","product","account","catalog","id","selection","query","selected","page","records","owner","feed","fields","create","createHash","z","AdportError","z","z","z","ids","type","canonical","hash","createHash","object","z","notes","ids","AdportError","name","match","url","type","account","selection","owner","id","state","key","catalog","records","description","source","parent","value","record","copy","z","AdportError","createHash","z","AdportError","createHash","z","ids","AdportError","name","text","common","account","catalog","selection","AdportError","ids","z","parent","cursor","page","unique","create","records","id","preserved","z","AdportError","batchId","z","nativeBatch","manifestRow","receiptSchema","notes","preserved","diagnostics","catalog","selection","parent","AdportError","cursor","records","record","id","z","AdportError","defineTool","guardedWriteTool","z","notes","failure","ids","AdportError","configuration","account","item","id","currency","catalog","defineTool","guardedWriteTool","LocalMediaResolver","account","id","query","z","page","AdportError","fields","plan","z","defineTool","guardedWriteTool","z","defineTool","guardedWriteTool","catalog","z","write","defineTool","guardedWriteTool","z","creativesOutput","defineTool","guardedWriteTool","catalog","z","write","name","guardedWriteTool","defineTool","creativesOutput","z","defineTool","guardedWriteTool","catalog","z","write","defineTool","guardedWriteTool","name","defineTool","z","guardedWriteTool","credentials"]}